File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1486: download - view: text, annotated - select for diffs
Wed Jun 8 01:42:20 2022 UTC (2 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain's trust settings are checked when determining if course requests
  are permitted in a domain belonging to another institution, in case they
  changed since reqcrsotherdom.* was last updated in user's environment.db

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1486 2022/06/08 01:42:20 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:     }
 4922:     return @lines;
 4923: }
 4924: 
 4925: sub removeuploadedurl {
 4926:     my ($url)=@_;	
 4927:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4928:     return &removeuserfile($uname,$udom,$fname);
 4929: }
 4930: 
 4931: sub removeuserfile {
 4932:     my ($docuname,$docudom,$fname)=@_;
 4933:     my $home=&homeserver($docuname,$docudom);    
 4934:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4935:     if ($result eq 'ok') {	
 4936:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4937:             my $metafile = $fname.'.meta';
 4938:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4939: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4940:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4941:             my $sqlresult = 
 4942:                 &update_portfolio_table($docuname,$docudom,$file,
 4943:                                         'portfolio_metadata',$group,
 4944:                                         'delete');
 4945:         }
 4946:     }
 4947:     return $result;
 4948: }
 4949: 
 4950: sub mkdiruserfile {
 4951:     my ($docuname,$docudom,$dir)=@_;
 4952:     my $home=&homeserver($docuname,$docudom);
 4953:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4954: }
 4955: 
 4956: sub renameuserfile {
 4957:     my ($docuname,$docudom,$old,$new)=@_;
 4958:     my $home=&homeserver($docuname,$docudom);
 4959:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4960:                         &escape("$old").':'.&escape("$new"),$home);
 4961:     if ($result eq 'ok') {
 4962:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4963:             my $oldmeta = $old.'.meta';
 4964:             my $newmeta = $new.'.meta';
 4965:             my $metaresult = 
 4966:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4967: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4968:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4969:             my $sqlresult = 
 4970:                 &update_portfolio_table($docuname,$docudom,$file,
 4971:                                         'portfolio_metadata',$group,
 4972:                                         'delete');
 4973:         }
 4974:     }
 4975:     return $result;
 4976: }
 4977: 
 4978: # ------------------------------------------------------------------------- Log
 4979: 
 4980: sub log {
 4981:     my ($dom,$nam,$hom,$what)=@_;
 4982:     return critical("log:$dom:$nam:$what",$hom);
 4983: }
 4984: 
 4985: # ------------------------------------------------------------------ Course Log
 4986: #
 4987: # This routine flushes several buffers of non-mission-critical nature
 4988: #
 4989: 
 4990: sub flushcourselogs {
 4991:     &logthis('Flushing log buffers');
 4992: #
 4993: # course logs
 4994: # This is a log of all transactions in a course, which can be used
 4995: # for data mining purposes
 4996: #
 4997: # It also collects the courseid database, which lists last transaction
 4998: # times and course titles for all courseids
 4999: #
 5000:     my %courseidbuffer=();
 5001:     foreach my $crsid (keys(%courselogs)) {
 5002:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5003: 		          &escape($courselogs{$crsid}),
 5004: 		          $coursehombuf{$crsid}) eq 'ok') {
 5005: 	    delete $courselogs{$crsid};
 5006:         } else {
 5007:             &logthis('Failed to flush log buffer for '.$crsid);
 5008:             if (length($courselogs{$crsid})>40000) {
 5009:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5010:                         " exceeded maximum size, deleting.</font>");
 5011:                delete $courselogs{$crsid};
 5012:             }
 5013:         }
 5014:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5015:             'description' => $coursedescrbuf{$crsid},
 5016:             'inst_code'    => $courseinstcodebuf{$crsid},
 5017:             'type'        => $coursetypebuf{$crsid},
 5018:             'owner'       => $courseownerbuf{$crsid},
 5019:         };
 5020:     }
 5021: #
 5022: # Write course id database (reverse lookup) to homeserver of courses 
 5023: # Is used in pickcourse
 5024: #
 5025:     foreach my $crs_home (keys(%courseidbuffer)) {
 5026:         my $response = &courseidput(&host_domain($crs_home),
 5027:                                     $courseidbuffer{$crs_home},
 5028:                                     $crs_home,'timeonly');
 5029:     }
 5030: #
 5031: # File accesses
 5032: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5033: #
 5034:     foreach my $entry (keys(%accesshash)) {
 5035:         if ($entry =~ /___count$/) {
 5036:             my ($dom,$name);
 5037:             ($dom,$name,undef)=
 5038: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5039:             if (! defined($dom) || $dom eq '' || 
 5040:                 ! defined($name) || $name eq '') {
 5041:                 my $cid = $env{'request.course.id'};
 5042: #
 5043: # FIXME 11/29/2021
 5044: # Typo in rev. 1.458 (2003/12/09)??
 5045: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5046: #
 5047: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5048: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5049: # in a nohist_accesscount.db file for the user rather than the course.
 5050: #
 5051: # That said there is a lot of noise in the data being stored.
 5052: # So counts for prtspool/  and adm/ etc. are recorded.
 5053: #
 5054: # A review of which items ending '___count' are written to %accesshash should likely be 
 5055: # made before deciding whether to set these to 'course.' instead of 'request.'
 5056: #
 5057: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5058: # accesses for things which are not published resources, regardless of course, and
 5059: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5060: # anyone in the course for things which are not published resources.
 5061: #
 5062: # For an author, nohist_accesscount.db ends up having records for other items
 5063: # mixed up with the legitimate access counts for the author's published resources.
 5064: #
 5065:                 $dom  = $env{'request.'.$cid.'.domain'};
 5066:                 $name = $env{'request.'.$cid.'.num'};
 5067:             }
 5068:             my $value = $accesshash{$entry};
 5069:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5070:             my %temphash=($url => $value);
 5071:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5072:             if ($result eq 'ok') {
 5073:                 delete $accesshash{$entry};
 5074:             }
 5075:         } else {
 5076:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5077:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5078:             my %temphash=($entry => $accesshash{$entry});
 5079:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5080:                 delete $accesshash{$entry};
 5081:             }
 5082:         }
 5083:     }
 5084: #
 5085: # Roles
 5086: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5087: #
 5088:     foreach my $entry (keys(%userrolehash)) {
 5089:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5090: 	    split(/\:/,$entry);
 5091:         if (&Apache::lonnet::put('nohist_userroles',
 5092:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5093:                 $rudom,$runame) eq 'ok') {
 5094: 	    delete $userrolehash{$entry};
 5095:         }
 5096:     }
 5097: #
 5098: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5099: #
 5100:     my %domrolebuffer = ();
 5101:     foreach my $entry (keys(%domainrolehash)) {
 5102:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5103:         if ($domrolebuffer{$rudom}) {
 5104:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5105:                       '='.&escape($domainrolehash{$entry});
 5106:         } else {
 5107:             $domrolebuffer{$rudom}.=&escape($entry).
 5108:                       '='.&escape($domainrolehash{$entry});
 5109:         }
 5110:         delete $domainrolehash{$entry};
 5111:     }
 5112:     foreach my $dom (keys(%domrolebuffer)) {
 5113: 	my %servers;
 5114: 	if (defined(&domain($dom,'primary'))) {
 5115: 	    my $primary=&domain($dom,'primary');
 5116: 	    my $hostname=&hostname($primary);
 5117: 	    $servers{$primary} = $hostname;
 5118: 	} else { 
 5119: 	    %servers = &get_servers($dom,'library');
 5120: 	}
 5121: 	foreach my $tryserver (keys(%servers)) {
 5122: 	    if (&reply('domroleput:'.$dom.':'.
 5123: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5124: 		last;
 5125: 	    } else {  
 5126: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5127: 	    }
 5128:         }
 5129:     }
 5130:     $dumpcount++;
 5131: }
 5132: 
 5133: sub courselog {
 5134:     my $what=shift;
 5135:     $what=time.':'.$what;
 5136:     unless ($env{'request.course.id'}) { return ''; }
 5137:     $coursedombuf{$env{'request.course.id'}}=
 5138:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5139:     $coursenumbuf{$env{'request.course.id'}}=
 5140:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5141:     $coursehombuf{$env{'request.course.id'}}=
 5142:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5143:     $coursedescrbuf{$env{'request.course.id'}}=
 5144:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5145:     $courseinstcodebuf{$env{'request.course.id'}}=
 5146:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5147:     $courseownerbuf{$env{'request.course.id'}}=
 5148:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5149:     $coursetypebuf{$env{'request.course.id'}}=
 5150:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5151:     if (defined $courselogs{$env{'request.course.id'}}) {
 5152: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5153:     } else {
 5154: 	$courselogs{$env{'request.course.id'}}.=$what;
 5155:     }
 5156:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5157: 	&flushcourselogs();
 5158:     }
 5159: }
 5160: 
 5161: sub courseacclog {
 5162:     my $fnsymb=shift;
 5163:     unless ($env{'request.course.id'}) { return ''; }
 5164:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5165:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5166:         $what.=':POST';
 5167:         # FIXME: Probably ought to escape things....
 5168: 	foreach my $key (keys(%env)) {
 5169:             if ($key=~/^form\.(.*)/) {
 5170:                 my $formitem = $1;
 5171:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5172:                     $what.=':'.$formitem.'='.$env{$key};
 5173:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5174:                     if ($formitem eq 'proctorpassword') {
 5175:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5176:                     } else {
 5177:                         $what.=':'.$formitem.'='.$env{$key};
 5178:                     }
 5179:                 }
 5180:             }
 5181:         }
 5182:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5183:         # FIXME: We should not be depending on a form parameter that someone
 5184:         # editing lonsearchcat.pm might change in the future.
 5185:         if ($env{'form.phase'} eq 'course_search') {
 5186:             $what.= ':POST';
 5187:             # FIXME: Probably ought to escape things....
 5188:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5189:                                  'crsdiscuss') {
 5190:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5191:             }
 5192:         }
 5193:     }
 5194:     &courselog($what);
 5195: }
 5196: 
 5197: sub countacc {
 5198:     my $url=&declutter(shift);
 5199:     return if (! defined($url) || $url eq '');
 5200:     unless ($env{'request.course.id'}) { return ''; }
 5201: #
 5202: # Mark that this url was used in this course
 5203: #
 5204:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5205: #
 5206: # Increase the access count for this resource in this child process
 5207: #
 5208:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5209:     $accesshash{$key}++;
 5210: }
 5211: 
 5212: sub linklog {
 5213:     my ($from,$to)=@_;
 5214:     $from=&declutter($from);
 5215:     $to=&declutter($to);
 5216:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5217:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5218: }
 5219: 
 5220: sub statslog {
 5221:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5222:     if ($users<2) { return; }
 5223:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5224:             'course'       => $env{'request.course.id'},
 5225:             'sections'     => '"all"',
 5226:             'num_students' => $users,
 5227:             'part'         => $part,
 5228:             'symb'         => $symb,
 5229:             'mean_tries'   => $av_attempts,
 5230:             'deg_of_diff'  => $degdiff});
 5231:     foreach my $key (keys(%dynstore)) {
 5232:         $accesshash{$key}=$dynstore{$key};
 5233:     }
 5234: }
 5235:   
 5236: sub userrolelog {
 5237:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5238:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5239:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5240:        $userrolehash
 5241:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5242:                     =$tend.':'.$tstart;
 5243:     }
 5244:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5245:        $userrolehash
 5246:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5247:                     =$tend.':'.$tstart;
 5248:     }
 5249:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5250:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5251:        $domainrolehash
 5252:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5253:                     = $tend.':'.$tstart;
 5254:     }
 5255: }
 5256: 
 5257: sub courserolelog {
 5258:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5259:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5260:         my $cdom = $1;
 5261:         my $cnum = $2;
 5262:         my $sec = $3;
 5263:         my $namespace = 'rolelog';
 5264:         my %storehash = (
 5265:                            role    => $trole,
 5266:                            start   => $tstart,
 5267:                            end     => $tend,
 5268:                            selfenroll => $selfenroll,
 5269:                            context    => $context,
 5270:                         );
 5271:         if ($trole eq 'gr') {
 5272:             $namespace = 'groupslog';
 5273:             $storehash{'group'} = $sec;
 5274:         } else {
 5275:             $storehash{'section'} = $sec;
 5276:         }
 5277:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5278:                    $domain,$cnum,$cdom);
 5279:         if (($trole ne 'st') || ($sec ne '')) {
 5280:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5281:         }
 5282:     }
 5283:     return;
 5284: }
 5285: 
 5286: sub domainrolelog {
 5287:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5288:     if ($area =~ m{^/($match_domain)/$}) {
 5289:         my $cdom = $1;
 5290:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5291:         my $namespace = 'rolelog';
 5292:         my %storehash = (
 5293:                            role    => $trole,
 5294:                            start   => $tstart,
 5295:                            end     => $tend,
 5296:                            context => $context,
 5297:                         );
 5298:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5299:                    $domain,$domconfiguser,$cdom);
 5300:     }
 5301:     return;
 5302: 
 5303: }
 5304: 
 5305: sub coauthorrolelog {
 5306:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5307:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5308:         my $audom = $1;
 5309:         my $auname = $2;
 5310:         my $namespace = 'rolelog';
 5311:         my %storehash = (
 5312:                            role    => $trole,
 5313:                            start   => $tstart,
 5314:                            end     => $tend,
 5315:                            context => $context,
 5316:                         );
 5317:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5318:                    $domain,$auname,$audom);
 5319:     }
 5320:     return;
 5321: }
 5322: 
 5323: sub get_course_adv_roles {
 5324:     my ($cid,$codes) = @_;
 5325:     $cid=$env{'request.course.id'} unless (defined($cid));
 5326:     my %coursehash=&coursedescription($cid);
 5327:     my $crstype = &Apache::loncommon::course_type($cid);
 5328:     my %nothide=();
 5329:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5330:         if ($user !~ /:/) {
 5331: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5332:         } else {
 5333:             $nothide{$user}=1;
 5334:         }
 5335:     }
 5336:     my @possdoms = ($coursehash{'domain'});
 5337:     if ($coursehash{'checkforpriv'}) {
 5338:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5339:     }
 5340:     my %returnhash=();
 5341:     my %dumphash=
 5342:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5343:     my $now=time;
 5344:     my %privileged;
 5345:     foreach my $entry (keys(%dumphash)) {
 5346: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5347:         if (($tstart) && ($tstart<0)) { next; }
 5348:         if (($tend) && ($tend<$now)) { next; }
 5349:         if (($tstart) && ($now<$tstart)) { next; }
 5350:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5351: 	if ($username eq '' || $domain eq '') { next; }
 5352:         if ((&privileged($username,$domain,\@possdoms)) &&
 5353:             (!$nothide{$username.':'.$domain})) { next; }
 5354: 	if ($role eq 'cr') { next; }
 5355:         if ($codes) {
 5356:             if ($section) { $role .= ':'.$section; }
 5357:             if ($returnhash{$role}) {
 5358:                 $returnhash{$role}.=','.$username.':'.$domain;
 5359:             } else {
 5360:                 $returnhash{$role}=$username.':'.$domain;
 5361:             }
 5362:         } else {
 5363:             my $key=&plaintext($role,$crstype);
 5364:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5365:             if ($returnhash{$key}) {
 5366: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5367:             } else {
 5368:                 $returnhash{$key}=$username.':'.$domain;
 5369:             }
 5370:         }
 5371:     }
 5372:     return %returnhash;
 5373: }
 5374: 
 5375: sub get_my_roles {
 5376:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5377:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5378:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5379:     my (%dumphash,%nothide);
 5380:     if ($context eq 'userroles') {
 5381:         %dumphash = &dump('roles',$udom,$uname);
 5382:     } else {
 5383:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5384:         if ($hidepriv) {
 5385:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5386:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5387:                 if ($user !~ /:/) {
 5388:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5389:                 } else {
 5390:                     $nothide{$user} = 1;
 5391:                 }
 5392:             }
 5393:         }
 5394:     }
 5395:     my %returnhash=();
 5396:     my $now=time;
 5397:     my %privileged;
 5398:     foreach my $entry (keys(%dumphash)) {
 5399:         my ($role,$tend,$tstart);
 5400:         if ($context eq 'userroles') {
 5401:             next if ($entry =~ /^rolesdef/);
 5402: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5403:         } else {
 5404:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5405:         }
 5406:         if (($tstart) && ($tstart<0)) { next; }
 5407:         my $status = 'active';
 5408:         if (($tend) && ($tend<=$now)) {
 5409:             $status = 'previous';
 5410:         } 
 5411:         if (($tstart) && ($now<$tstart)) {
 5412:             $status = 'future';
 5413:         }
 5414:         if (ref($types) eq 'ARRAY') {
 5415:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5416:                 next;
 5417:             } 
 5418:         } else {
 5419:             if ($status ne 'active') {
 5420:                 next;
 5421:             }
 5422:         }
 5423:         my ($rolecode,$username,$domain,$section,$area);
 5424:         if ($context eq 'userroles') {
 5425:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5426:             (undef,$domain,$username,$section) = split(/\//,$area);
 5427:         } else {
 5428:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5429:         }
 5430:         if (ref($roledoms) eq 'ARRAY') {
 5431:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5432:                 next;
 5433:             }
 5434:         }
 5435:         if (ref($roles) eq 'ARRAY') {
 5436:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5437:                 if ($role =~ /^cr\//) {
 5438:                     if (!grep(/^cr$/,@{$roles})) {
 5439:                         next;
 5440:                     }
 5441:                 } elsif ($role =~ /^gr\//) {
 5442:                     if (!grep(/^gr$/,@{$roles})) {
 5443:                         next;
 5444:                     }
 5445:                 } else {
 5446:                     next;
 5447:                 }
 5448:             }
 5449:         }
 5450:         if ($hidepriv) {
 5451:             my @privroles = ('dc','su');
 5452:             if ($context eq 'userroles') {
 5453:                 next if (grep(/^\Q$role\E$/,@privroles));
 5454:             } else {
 5455:                 my $possdoms = [$domain];
 5456:                 if (ref($roledoms) eq 'ARRAY') {
 5457:                    push(@{$possdoms},@{$roledoms}); 
 5458:                 }
 5459:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5460:                     if (!$nothide{$username.':'.$domain}) {
 5461:                         next;
 5462:                     }
 5463:                 }
 5464:             }
 5465:         }
 5466:         if ($withsec) {
 5467:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5468:                 $tstart.':'.$tend;
 5469:         } else {
 5470:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5471:         }
 5472:     }
 5473:     return %returnhash;
 5474: }
 5475: 
 5476: sub get_all_adhocroles {
 5477:     my ($dom) = @_;
 5478:     my @roles_by_num = ();
 5479:     my %domdefaults = &get_domain_defaults($dom);
 5480:     my (%description,%access_in_dom,%access_info);
 5481:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5482:         my $count = 0;
 5483:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5484:         my %ordered;
 5485:         foreach my $role (sort(keys(%domcurrent))) {
 5486:             my ($order,$desc,$access_in_dom);
 5487:             if (ref($domcurrent{$role}) eq 'HASH') {
 5488:                 $order = $domcurrent{$role}{'order'};
 5489:                 $desc = $domcurrent{$role}{'desc'};
 5490:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5491:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5492:             }
 5493:             if ($order eq '') {
 5494:                 $order = $count;
 5495:             }
 5496:             $ordered{$order} = $role;
 5497:             if ($desc ne '') {
 5498:                 $description{$role} = $desc;
 5499:             } else {
 5500:                 $description{$role}= $role;
 5501:             }
 5502:             $count++;
 5503:         }
 5504:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5505:             push(@roles_by_num,$ordered{$item});
 5506:         }
 5507:     }
 5508:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5509: }
 5510: 
 5511: sub get_my_adhocroles {
 5512:     my ($cid,$checkreg) = @_;
 5513:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5514:     if ($env{'request.course.id'} eq $cid) {
 5515:         $cdom = $env{'course.'.$cid.'.domain'};
 5516:         $cnum = $env{'course.'.$cid.'.num'};
 5517:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5518:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5519:         $cdom = $1;
 5520:         $cnum = $2;
 5521:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5522:                                      $cdom,$cnum);
 5523:     }
 5524:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5525:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5526:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5527:         if ($rosterhash{$user} ne '') {
 5528:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5529:             return ([],{}) if ($type eq 'auto');
 5530:         }
 5531:     }
 5532:     if (($cdom ne '') && ($cnum ne ''))  {
 5533:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5534:             my $then=$env{'user.login.time'};
 5535:             my $update=$env{'user.update.time'};
 5536:             if (!$update) {
 5537:                 $update = $then;
 5538:             }
 5539:             my @liveroles;
 5540:             foreach my $role ('dh','da') {
 5541:                 if ($env{"user.role.$role./$cdom/"}) {
 5542:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5543:                     my $limit = $update;
 5544:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5545:                         $limit = $then;
 5546:                     }
 5547:                     my $activerole = 1;
 5548:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5549:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5550:                     if ($activerole) {
 5551:                         push(@liveroles,$role);
 5552:                     }
 5553:                 }
 5554:             }
 5555:             if (@liveroles) {
 5556:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5557:                     my ($accessref,$accessinfo,%access_in_dom);
 5558:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5559:                     if (ref($roles_by_num) eq 'ARRAY') {
 5560:                         if (@{$roles_by_num}) {
 5561:                             my %settings;
 5562:                             if ($env{'request.course.id'} eq $cid) {
 5563:                                 foreach my $envkey (keys(%env)) {
 5564:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5565:                                         $settings{$1} = $env{$envkey};
 5566:                                     }
 5567:                                 }
 5568:                             } else {
 5569:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5570:                             }
 5571:                             my %setincrs;
 5572:                             if ($settings{'internal.adhocaccess'}) {
 5573:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5574:                             }
 5575:                             my @statuses;
 5576:                             if ($env{'environment.inststatus'}) {
 5577:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5578:                             }
 5579:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5580:                             if (ref($accessref) eq 'HASH') {
 5581:                                 %access_in_dom = %{$accessref};
 5582:                             }
 5583:                             foreach my $role (@{$roles_by_num}) {
 5584:                                 my ($curraccess,@okstatus,@personnel);
 5585:                                 if ($setincrs{$role}) {
 5586:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5587:                                     if ($curraccess eq 'status') {
 5588:                                         @okstatus = split(/\&/,$rest);
 5589:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5590:                                         @personnel = split(/\&/,$rest);
 5591:                                     }
 5592:                                 } else {
 5593:                                     $curraccess = $access_in_dom{$role};
 5594:                                     if (ref($accessinfo) eq 'HASH') {
 5595:                                         if ($curraccess eq 'status') {
 5596:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5597:                                                 @okstatus = @{$accessinfo->{$role}};
 5598:                                             }
 5599:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5600:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5601:                                                 @personnel = @{$accessinfo->{$role}};
 5602:                                             }
 5603:                                         }
 5604:                                     }
 5605:                                 }
 5606:                                 if ($curraccess eq 'none') {
 5607:                                     next;
 5608:                                 } elsif ($curraccess eq 'all') {
 5609:                                     push(@possroles,$role);
 5610:                                 } elsif ($curraccess eq 'dh') {
 5611:                                     if (grep(/^dh$/,@liveroles)) {
 5612:                                         push(@possroles,$role);
 5613:                                     } else {
 5614:                                         next;
 5615:                                     }
 5616:                                 } elsif ($curraccess eq 'da') {
 5617:                                     if (grep(/^da$/,@liveroles)) {
 5618:                                         push(@possroles,$role);
 5619:                                     } else {
 5620:                                         next;
 5621:                                     }
 5622:                                 } elsif ($curraccess eq 'status') {
 5623:                                     if (@okstatus) {
 5624:                                         if (!@statuses) {
 5625:                                             if (grep(/^default$/,@okstatus)) {
 5626:                                                 push(@possroles,$role);
 5627:                                             }
 5628:                                         } else {
 5629:                                             foreach my $status (@okstatus) {
 5630:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5631:                                                     push(@possroles,$role);
 5632:                                                     last;
 5633:                                                 }
 5634:                                             }
 5635:                                         }
 5636:                                     }
 5637:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5638:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5639:                                         if ($curraccess eq 'exc') {
 5640:                                             push(@possroles,$role);
 5641:                                         }
 5642:                                     } elsif ($curraccess eq 'inc') {
 5643:                                         push(@possroles,$role);
 5644:                                     }
 5645:                                 }
 5646:                             }
 5647:                         }
 5648:                     }
 5649:                 }
 5650:             }
 5651:         }
 5652:     }
 5653:     unless (ref($description) eq 'HASH') {
 5654:         if (ref($roles_by_num) eq 'ARRAY') {
 5655:             my %desc;
 5656:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5657:             $description = \%desc;
 5658:         } else {
 5659:             $description = {};
 5660:         }
 5661:     }
 5662:     return (\@possroles,$description);
 5663: }
 5664: 
 5665: # ----------------------------------------------------- Frontpage Announcements
 5666: #
 5667: #
 5668: 
 5669: sub postannounce {
 5670:     my ($server,$text)=@_;
 5671:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5672:     unless ($text=~/\w/) { $text=''; }
 5673:     return &reply('setannounce:'.&escape($text),$server);
 5674: }
 5675: 
 5676: sub getannounce {
 5677: 
 5678:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5679: 	my $announcement='';
 5680: 	while (my $line = <$fh>) { $announcement .= $line; }
 5681: 	close($fh);
 5682: 	if ($announcement=~/\w/) { 
 5683: 	    return 
 5684:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5685:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5686: 	} else {
 5687: 	    return '';
 5688: 	}
 5689:     } else {
 5690: 	return '';
 5691:     }
 5692: }
 5693: 
 5694: # ---------------------------------------------------------- Course ID routines
 5695: # Deal with domain's nohist_courseid.db files
 5696: #
 5697: 
 5698: sub courseidput {
 5699:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5700:     return unless (ref($storehash) eq 'HASH');
 5701:     my $outcome;
 5702:     if ($caller eq 'timeonly') {
 5703:         my $cids = '';
 5704:         foreach my $item (keys(%$storehash)) {
 5705:             $cids.=&escape($item).'&';
 5706:         }
 5707:         $cids=~s/\&$//;
 5708:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5709:                           $coursehome);       
 5710:     } else {
 5711:         my $items = '';
 5712:         foreach my $item (keys(%$storehash)) {
 5713:             $items.= &escape($item).'='.
 5714:                      &freeze_escape($$storehash{$item}).'&';
 5715:         }
 5716:         $items=~s/\&$//;
 5717:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5718:                           $coursehome);
 5719:     }
 5720:     if ($outcome eq 'unknown_cmd') {
 5721:         my $what;
 5722:         foreach my $cid (keys(%$storehash)) {
 5723:             $what .= &escape($cid).'=';
 5724:             foreach my $item ('description','inst_code','owner','type') {
 5725:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5726:             }
 5727:             $what =~ s/\:$/&/;
 5728:         }
 5729:         $what =~ s/\&$//;  
 5730:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5731:     } else {
 5732:         return $outcome;
 5733:     }
 5734: }
 5735: 
 5736: sub courseiddump {
 5737:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5738:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5739:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5740:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5741:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5742:     my $as_hash = 1;
 5743:     my %returnhash;
 5744:     if (!$domfilter) { $domfilter=''; }
 5745:     my %libserv = &all_library();
 5746:     foreach my $tryserver (keys(%libserv)) {
 5747:         if ( (  $hostidflag == 1 
 5748: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5749: 	     || (!defined($hostidflag)) ) {
 5750: 
 5751: 	    if (($domfilter eq '') ||
 5752: 		(&host_domain($tryserver) eq $domfilter)) {
 5753:                 my $rep;
 5754:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5755:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5756:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5757:                                 &escape($descfilter), &escape($instcodefilter), 
 5758:                                 &escape($ownerfilter), &escape($coursefilter),
 5759:                                 &escape($typefilter), &escape($regexp_ok), 
 5760:                                 $as_hash, &escape($selfenrollonly), 
 5761:                                 &escape($catfilter), $showhidden, $caller, 
 5762:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5763:                                 &escape($createdbefore), &escape($createdafter), 
 5764:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5765:                                 $reqcrsdom,&escape($reqinstcode))));
 5766:                 } else {
 5767:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5768:                              $sincefilter.':'.&escape($descfilter).':'.
 5769:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5770:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5771:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5772:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5773:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5774:                              &escape($cc_clone).':'.$cloneonly.':'.
 5775:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5776:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5777:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5778:                 }
 5779:                      
 5780:                 my @pairs=split(/\&/,$rep);
 5781:                 foreach my $item (@pairs) {
 5782:                     my ($key,$value)=split(/\=/,$item,2);
 5783:                     $key = &unescape($key);
 5784:                     next if ($key =~ /^error: 2 /);
 5785:                     my $result = &thaw_unescape($value);
 5786:                     if (ref($result) eq 'HASH') {
 5787:                         $returnhash{$key}=$result;
 5788:                     } else {
 5789:                         my @responses = split(/:/,$value);
 5790:                         my @items = ('description','inst_code','owner','type');
 5791:                         for (my $i=0; $i<@responses; $i++) {
 5792:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5793:                         }
 5794:                     }
 5795:                 }
 5796:             }
 5797:         }
 5798:     }
 5799:     return %returnhash;
 5800: }
 5801: 
 5802: sub courselastaccess {
 5803:     my ($cdom,$cnum,$hostidref) = @_;
 5804:     my %returnhash;
 5805:     if ($cdom && $cnum) {
 5806:         my $chome = &homeserver($cnum,$cdom);
 5807:         if ($chome ne 'no_host') {
 5808:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5809:             &extract_lastaccess(\%returnhash,$rep);
 5810:         }
 5811:     } else {
 5812:         if (!$cdom) { $cdom=''; }
 5813:         my %libserv = &all_library();
 5814:         foreach my $tryserver (keys(%libserv)) {
 5815:             if (ref($hostidref) eq 'ARRAY') {
 5816:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5817:             } 
 5818:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5819:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5820:                 &extract_lastaccess(\%returnhash,$rep);
 5821:             }
 5822:         }
 5823:     }
 5824:     return %returnhash;
 5825: }
 5826: 
 5827: sub extract_lastaccess {
 5828:     my ($returnhash,$rep) = @_;
 5829:     if (ref($returnhash) eq 'HASH') {
 5830:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5831:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5832:                  $rep eq '') {
 5833:             my @pairs=split(/\&/,$rep);
 5834:             foreach my $item (@pairs) {
 5835:                 my ($key,$value)=split(/\=/,$item,2);
 5836:                 $key = &unescape($key);
 5837:                 next if ($key =~ /^error: 2 /);
 5838:                 $returnhash->{$key} = &thaw_unescape($value);
 5839:             }
 5840:         }
 5841:     }
 5842:     return;
 5843: }
 5844: 
 5845: # ---------------------------------------------------------- DC e-mail
 5846: 
 5847: sub dcmailput {
 5848:     my ($domain,$msgid,$message,$server)=@_;
 5849:     my $status = &Apache::lonnet::critical(
 5850:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5851:        &escape($message),$server);
 5852:     return $status;
 5853: }
 5854: 
 5855: sub dcmaildump {
 5856:     my ($dom,$startdate,$enddate,$senders) = @_;
 5857:     my %returnhash=();
 5858: 
 5859:     if (defined(&domain($dom,'primary'))) {
 5860:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5861:                                                          &escape($enddate).':';
 5862: 	my @esc_senders=map { &escape($_)} @$senders;
 5863: 	$cmd.=&escape(join('&',@esc_senders));
 5864: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5865:             my ($key,$value) = split(/\=/,$line,2);
 5866:             if (($key) && ($value)) {
 5867:                 $returnhash{&unescape($key)} = &unescape($value);
 5868:             }
 5869:         }
 5870:     }
 5871:     return %returnhash;
 5872: }
 5873: # ---------------------------------------------------------- Domain roles
 5874: 
 5875: sub get_domain_roles {
 5876:     my ($dom,$roles,$startdate,$enddate)=@_;
 5877:     if ((!defined($startdate)) || ($startdate eq '')) {
 5878:         $startdate = '.';
 5879:     }
 5880:     if ((!defined($enddate)) || ($enddate eq '')) {
 5881:         $enddate = '.';
 5882:     }
 5883:     my $rolelist;
 5884:     if (ref($roles) eq 'ARRAY') {
 5885:         $rolelist = join('&',@{$roles});
 5886:     }
 5887:     my %personnel = ();
 5888: 
 5889:     my %servers = &get_servers($dom,'library');
 5890:     foreach my $tryserver (keys(%servers)) {
 5891: 	%{$personnel{$tryserver}}=();
 5892: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5893: 					    &escape($startdate).':'.
 5894: 					    &escape($enddate).':'.
 5895: 					    &escape($rolelist), $tryserver))) {
 5896: 	    my ($key,$value) = split(/\=/,$line,2);
 5897: 	    if (($key) && ($value)) {
 5898: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5899: 	    }
 5900: 	}
 5901:     }
 5902:     return %personnel;
 5903: }
 5904: 
 5905: sub get_active_domroles {
 5906:     my ($dom,$roles) = @_;
 5907:     return () unless (ref($roles) eq 'ARRAY');
 5908:     my $now = time;
 5909:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5910:     my %domroles;
 5911:     foreach my $server (keys(%dompersonnel)) {
 5912:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5913:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5914:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5915:         }
 5916:     }
 5917:     return %domroles;
 5918: }
 5919: 
 5920: # ----------------------------------------------------------- Interval timing 
 5921: 
 5922: {
 5923: # Caches needed for speedup of navmaps
 5924: # We don't want to cache this for very long at all (5 seconds at most)
 5925: # 
 5926: # The user for whom we cache
 5927: my $cachedkey='';
 5928: # The cached times for this user
 5929: my %cachedtimes=();
 5930: # When this was last done
 5931: my $cachedtime='';
 5932: 
 5933: sub load_all_first_access {
 5934:     my ($uname,$udom,$ignorecache)=@_;
 5935:     if (($cachedkey eq $uname.':'.$udom) &&
 5936:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5937:         (!$ignorecache)) {
 5938:         return;
 5939:     }
 5940:     $cachedtime=time;
 5941:     $cachedkey=$uname.':'.$udom;
 5942:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5943: }
 5944: 
 5945: sub get_first_access {
 5946:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5947:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5948:     if ($argsymb) { $symb=$argsymb; }
 5949:     my ($map,$id,$res)=&decode_symb($symb);
 5950:     if ($argmap) { $map = $argmap; }
 5951:     if ($type eq 'course') {
 5952: 	$res='course';
 5953:     } elsif ($type eq 'map') {
 5954: 	$res=&symbread($map);
 5955:     } else {
 5956: 	$res=$symb;
 5957:     }
 5958:     &load_all_first_access($uname,$udom,$ignorecache);
 5959:     return $cachedtimes{"$courseid\0$res"};
 5960: }
 5961: 
 5962: sub set_first_access {
 5963:     my ($type,$interval)=@_;
 5964:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5965:     my ($map,$id,$res)=&decode_symb($symb);
 5966:     if ($type eq 'course') {
 5967: 	$res='course';
 5968:     } elsif ($type eq 'map') {
 5969: 	$res=&symbread($map);
 5970:     } else {
 5971: 	$res=$symb;
 5972:     }
 5973:     $cachedkey='';
 5974:     my $firstaccess=&get_first_access($type,$symb,$map);
 5975:     if ($firstaccess) {
 5976:         &logthis("First access time already set ($firstaccess) when attempting ".
 5977:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5978:                  "in $courseid");
 5979:         return 'already_set';
 5980:     } else {
 5981:         my $start = time;
 5982: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5983:                           $udom,$uname);
 5984:         if ($putres eq 'ok') {
 5985:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5986:                  $udom,$uname); 
 5987:             &appenv(
 5988:                      {
 5989:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5990:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5991:                      }
 5992:                   );
 5993:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5994:                 $cachedtimes{"$courseid\0$res"} = $start;
 5995:             }
 5996:         } elsif ($putres ne 'refused') {
 5997:             &logthis("Result: $putres when attempting to set first access time ".
 5998:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5999:         }
 6000:         return $putres;
 6001:     }
 6002:     return 'already_set';
 6003: }
 6004: }
 6005: 
 6006: # --------------------------------------------- Set Expire Date for Spreadsheet
 6007: 
 6008: sub expirespread {
 6009:     my ($uname,$udom,$stype,$usymb)=@_;
 6010:     my $cid=$env{'request.course.id'}; 
 6011:     if ($cid) {
 6012:        my $now=time;
 6013:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6014:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6015:                             $env{'course.'.$cid.'.num'}.
 6016: 	        	    ':nohist_expirationdates:'.
 6017:                             &escape($key).'='.$now,
 6018:                             $env{'course.'.$cid.'.home'})
 6019:     }
 6020:     return 'ok';
 6021: }
 6022: 
 6023: # ----------------------------------------------------- Devalidate Spreadsheets
 6024: 
 6025: sub devalidate {
 6026:     my ($symb,$uname,$udom)=@_;
 6027:     my $cid=$env{'request.course.id'}; 
 6028:     if ($cid) {
 6029:         # delete the stored spreadsheets for
 6030:         # - the student level sheet of this user in course's homespace
 6031:         # - the assessment level sheet for this resource 
 6032:         #   for this user in user's homespace
 6033: 	# - current conditional state info
 6034: 	my $key=$uname.':'.$udom.':';
 6035:         my $status=
 6036: 	    &del('nohist_calculatedsheets',
 6037: 		 [$key.'studentcalc:'],
 6038: 		 $env{'course.'.$cid.'.domain'},
 6039: 		 $env{'course.'.$cid.'.num'})
 6040: 		.' '.
 6041: 	    &del('nohist_calculatedsheets_'.$cid,
 6042: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6043:         unless ($status eq 'ok ok') {
 6044:            &logthis('Could not devalidate spreadsheet '.
 6045:                     $uname.' at '.$udom.' for '.
 6046: 		    $symb.': '.$status);
 6047:         }
 6048: 	&delenv('user.state.'.$cid);
 6049:     }
 6050: }
 6051: 
 6052: sub get_scalar {
 6053:     my ($string,$end) = @_;
 6054:     my $value;
 6055:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6056: 	$value = $1;
 6057:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6058: 	$value = $1;
 6059:     }
 6060:     return &unescape($value);
 6061: }
 6062: 
 6063: sub array2str {
 6064:   my (@array) = @_;
 6065:   my $result=&arrayref2str(\@array);
 6066:   $result=~s/^__ARRAY_REF__//;
 6067:   $result=~s/__END_ARRAY_REF__$//;
 6068:   return $result;
 6069: }
 6070: 
 6071: sub arrayref2str {
 6072:   my ($arrayref) = @_;
 6073:   my $result='__ARRAY_REF__';
 6074:   foreach my $elem (@$arrayref) {
 6075:     if(ref($elem) eq 'ARRAY') {
 6076:       $result.=&arrayref2str($elem).'&';
 6077:     } elsif(ref($elem) eq 'HASH') {
 6078:       $result.=&hashref2str($elem).'&';
 6079:     } elsif(ref($elem)) {
 6080:       #print("Got a ref of ".(ref($elem))." skipping.");
 6081:     } else {
 6082:       $result.=&escape($elem).'&';
 6083:     }
 6084:   }
 6085:   $result=~s/\&$//;
 6086:   $result .= '__END_ARRAY_REF__';
 6087:   return $result;
 6088: }
 6089: 
 6090: sub hash2str {
 6091:   my (%hash) = @_;
 6092:   my $result=&hashref2str(\%hash);
 6093:   $result=~s/^__HASH_REF__//;
 6094:   $result=~s/__END_HASH_REF__$//;
 6095:   return $result;
 6096: }
 6097: 
 6098: sub hashref2str {
 6099:   my ($hashref)=@_;
 6100:   my $result='__HASH_REF__';
 6101:   foreach my $key (sort(keys(%$hashref))) {
 6102:     if (ref($key) eq 'ARRAY') {
 6103:       $result.=&arrayref2str($key).'=';
 6104:     } elsif (ref($key) eq 'HASH') {
 6105:       $result.=&hashref2str($key).'=';
 6106:     } elsif (ref($key)) {
 6107:       $result.='=';
 6108:       #print("Got a ref of ".(ref($key))." skipping.");
 6109:     } else {
 6110: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6111:     }
 6112: 
 6113:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6114:       $result.=&arrayref2str($hashref->{$key}).'&';
 6115:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6116:       $result.=&hashref2str($hashref->{$key}).'&';
 6117:     } elsif(ref($hashref->{$key})) {
 6118:        $result.='&';
 6119:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6120:     } else {
 6121:       $result.=&escape($hashref->{$key}).'&';
 6122:     }
 6123:   }
 6124:   $result=~s/\&$//;
 6125:   $result .= '__END_HASH_REF__';
 6126:   return $result;
 6127: }
 6128: 
 6129: sub str2hash {
 6130:     my ($string)=@_;
 6131:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6132:     return %$hash;
 6133: }
 6134: 
 6135: sub str2hashref {
 6136:   my ($string) = @_;
 6137: 
 6138:   my %hash;
 6139: 
 6140:   if($string !~ /^__HASH_REF__/) {
 6141:       if (! ($string eq '' || !defined($string))) {
 6142: 	  $hash{'error'}='Not hash reference';
 6143:       }
 6144:       return (\%hash, $string);
 6145:   }
 6146: 
 6147:   $string =~ s/^__HASH_REF__//;
 6148: 
 6149:   while($string !~ /^__END_HASH_REF__/) {
 6150:       #key
 6151:       my $key='';
 6152:       if($string =~ /^__HASH_REF__/) {
 6153:           ($key, $string)=&str2hashref($string);
 6154:           if(defined($key->{'error'})) {
 6155:               $hash{'error'}='Bad data';
 6156:               return (\%hash, $string);
 6157:           }
 6158:       } elsif($string =~ /^__ARRAY_REF__/) {
 6159:           ($key, $string)=&str2arrayref($string);
 6160:           if($key->[0] eq 'Array reference error') {
 6161:               $hash{'error'}='Bad data';
 6162:               return (\%hash, $string);
 6163:           }
 6164:       } else {
 6165:           $string =~ s/^(.*?)=//;
 6166: 	  $key=&unescape($1);
 6167:       }
 6168:       $string =~ s/^=//;
 6169: 
 6170:       #value
 6171:       my $value='';
 6172:       if($string =~ /^__HASH_REF__/) {
 6173:           ($value, $string)=&str2hashref($string);
 6174:           if(defined($value->{'error'})) {
 6175:               $hash{'error'}='Bad data';
 6176:               return (\%hash, $string);
 6177:           }
 6178:       } elsif($string =~ /^__ARRAY_REF__/) {
 6179:           ($value, $string)=&str2arrayref($string);
 6180:           if($value->[0] eq 'Array reference error') {
 6181:               $hash{'error'}='Bad data';
 6182:               return (\%hash, $string);
 6183:           }
 6184:       } else {
 6185: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6186:       }
 6187:       $string =~ s/^&//;
 6188: 
 6189:       $hash{$key}=$value;
 6190:   }
 6191: 
 6192:   $string =~ s/^__END_HASH_REF__//;
 6193: 
 6194:   return (\%hash, $string);
 6195: }
 6196: 
 6197: sub str2array {
 6198:     my ($string)=@_;
 6199:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6200:     return @$array;
 6201: }
 6202: 
 6203: sub str2arrayref {
 6204:   my ($string) = @_;
 6205:   my @array;
 6206: 
 6207:   if($string !~ /^__ARRAY_REF__/) {
 6208:       if (! ($string eq '' || !defined($string))) {
 6209: 	  $array[0]='Array reference error';
 6210:       }
 6211:       return (\@array, $string);
 6212:   }
 6213: 
 6214:   $string =~ s/^__ARRAY_REF__//;
 6215: 
 6216:   while($string !~ /^__END_ARRAY_REF__/) {
 6217:       my $value='';
 6218:       if($string =~ /^__HASH_REF__/) {
 6219:           ($value, $string)=&str2hashref($string);
 6220:           if(defined($value->{'error'})) {
 6221:               $array[0] ='Array reference error';
 6222:               return (\@array, $string);
 6223:           }
 6224:       } elsif($string =~ /^__ARRAY_REF__/) {
 6225:           ($value, $string)=&str2arrayref($string);
 6226:           if($value->[0] eq 'Array reference error') {
 6227:               $array[0] ='Array reference error';
 6228:               return (\@array, $string);
 6229:           }
 6230:       } else {
 6231: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6232:       }
 6233:       $string =~ s/^&//;
 6234: 
 6235:       push(@array, $value);
 6236:   }
 6237: 
 6238:   $string =~ s/^__END_ARRAY_REF__//;
 6239: 
 6240:   return (\@array, $string);
 6241: }
 6242: 
 6243: # -------------------------------------------------------------------Temp Store
 6244: 
 6245: sub tmpreset {
 6246:   my ($symb,$namespace,$domain,$stuname) = @_;
 6247:   if (!$symb) {
 6248:     $symb=&symbread();
 6249:     if (!$symb) { $symb= $env{'request.url'}; }
 6250:   }
 6251:   $symb=escape($symb);
 6252: 
 6253:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6254:   $namespace=~s/\//\_/g;
 6255:   $namespace=~s/\W//g;
 6256: 
 6257:   if (!$domain) { $domain=$env{'user.domain'}; }
 6258:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6259:   if ($domain eq 'public' && $stuname eq 'public') {
 6260:       $stuname=&get_requestor_ip();
 6261:   }
 6262:   my $path=LONCAPA::tempdir();
 6263:   my %hash;
 6264:   if (tie(%hash,'GDBM_File',
 6265: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6266: 	  &GDBM_WRCREAT(),0640)) {
 6267:     foreach my $key (keys(%hash)) {
 6268:       if ($key=~ /:$symb/) {
 6269: 	delete($hash{$key});
 6270:       }
 6271:     }
 6272:   }
 6273: }
 6274: 
 6275: sub tmpstore {
 6276:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6277: 
 6278:   if (!$symb) {
 6279:     $symb=&symbread();
 6280:     if (!$symb) { $symb= $env{'request.url'}; }
 6281:   }
 6282:   $symb=escape($symb);
 6283: 
 6284:   if (!$namespace) {
 6285:     # I don't think we would ever want to store this for a course.
 6286:     # it seems this will only be used if we don't have a course.
 6287:     #$namespace=$env{'request.course.id'};
 6288:     #if (!$namespace) {
 6289:       $namespace=$env{'request.state'};
 6290:     #}
 6291:   }
 6292:   $namespace=~s/\//\_/g;
 6293:   $namespace=~s/\W//g;
 6294:   if (!$domain) { $domain=$env{'user.domain'}; }
 6295:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6296:   if ($domain eq 'public' && $stuname eq 'public') {
 6297:       $stuname=&get_requestor_ip();
 6298:   }
 6299:   my $now=time;
 6300:   my %hash;
 6301:   my $path=LONCAPA::tempdir();
 6302:   if (tie(%hash,'GDBM_File',
 6303: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6304: 	  &GDBM_WRCREAT(),0640)) {
 6305:     $hash{"version:$symb"}++;
 6306:     my $version=$hash{"version:$symb"};
 6307:     my $allkeys=''; 
 6308:     foreach my $key (keys(%$storehash)) {
 6309:       $allkeys.=$key.':';
 6310:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6311:     }
 6312:     $hash{"$version:$symb:timestamp"}=$now;
 6313:     $allkeys.='timestamp';
 6314:     $hash{"$version:keys:$symb"}=$allkeys;
 6315:     if (untie(%hash)) {
 6316:       return 'ok';
 6317:     } else {
 6318:       return "error:$!";
 6319:     }
 6320:   } else {
 6321:     return "error:$!";
 6322:   }
 6323: }
 6324: 
 6325: # -----------------------------------------------------------------Temp Restore
 6326: 
 6327: sub tmprestore {
 6328:   my ($symb,$namespace,$domain,$stuname) = @_;
 6329: 
 6330:   if (!$symb) {
 6331:     $symb=&symbread();
 6332:     if (!$symb) { $symb= $env{'request.url'}; }
 6333:   }
 6334:   $symb=escape($symb);
 6335: 
 6336:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6337: 
 6338:   if (!$domain) { $domain=$env{'user.domain'}; }
 6339:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6340:   if ($domain eq 'public' && $stuname eq 'public') {
 6341:       $stuname=&get_requestor_ip();
 6342:   }
 6343:   my %returnhash;
 6344:   $namespace=~s/\//\_/g;
 6345:   $namespace=~s/\W//g;
 6346:   my %hash;
 6347:   my $path=LONCAPA::tempdir();
 6348:   if (tie(%hash,'GDBM_File',
 6349: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6350: 	  &GDBM_READER(),0640)) {
 6351:     my $version=$hash{"version:$symb"};
 6352:     $returnhash{'version'}=$version;
 6353:     my $scope;
 6354:     for ($scope=1;$scope<=$version;$scope++) {
 6355:       my $vkeys=$hash{"$scope:keys:$symb"};
 6356:       my @keys=split(/:/,$vkeys);
 6357:       my $key;
 6358:       $returnhash{"$scope:keys"}=$vkeys;
 6359:       foreach $key (@keys) {
 6360: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6361: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6362:       }
 6363:     }
 6364:     if (!(untie(%hash))) {
 6365:       return "error:$!";
 6366:     }
 6367:   } else {
 6368:     return "error:$!";
 6369:   }
 6370:   return %returnhash;
 6371: }
 6372: 
 6373: # ----------------------------------------------------------------------- Store
 6374: 
 6375: sub store {
 6376:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6377:     my $home='';
 6378: 
 6379:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6380: 
 6381:     $symb=&symbclean($symb);
 6382:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6383: 
 6384:     if (!$domain) { $domain=$env{'user.domain'}; }
 6385:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6386: 
 6387:     &devalidate($symb,$stuname,$domain);
 6388: 
 6389:     $symb=escape($symb);
 6390:     if (!$namespace) { 
 6391:        unless ($namespace=$env{'request.course.id'}) { 
 6392:           return ''; 
 6393:        } 
 6394:     }
 6395:     if (!$home) { $home=$env{'user.home'}; }
 6396: 
 6397:     $$storehash{'ip'}=&get_requestor_ip();
 6398:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6399: 
 6400:     my $namevalue='';
 6401:     foreach my $key (keys(%$storehash)) {
 6402:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6403:     }
 6404:     $namevalue=~s/\&$//;
 6405:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6406:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6407: }
 6408: 
 6409: # -------------------------------------------------------------- Critical Store
 6410: 
 6411: sub cstore {
 6412:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6413:     my $home='';
 6414: 
 6415:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6416: 
 6417:     $symb=&symbclean($symb);
 6418:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6419: 
 6420:     if (!$domain) { $domain=$env{'user.domain'}; }
 6421:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6422: 
 6423:     &devalidate($symb,$stuname,$domain);
 6424: 
 6425:     $symb=escape($symb);
 6426:     if (!$namespace) { 
 6427:        unless ($namespace=$env{'request.course.id'}) { 
 6428:           return ''; 
 6429:        } 
 6430:     }
 6431:     if (!$home) { $home=$env{'user.home'}; }
 6432: 
 6433:     $$storehash{'ip'}=&get_requestor_ip();
 6434:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6435: 
 6436:     my $namevalue='';
 6437:     foreach my $key (keys(%$storehash)) {
 6438:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6439:     }
 6440:     $namevalue=~s/\&$//;
 6441:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6442:     return critical
 6443:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6444: }
 6445: 
 6446: # --------------------------------------------------------------------- Restore
 6447: 
 6448: sub restore {
 6449:     my ($symb,$namespace,$domain,$stuname) = @_;
 6450:     my $home='';
 6451: 
 6452:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6453: 
 6454:     if (!$symb) {
 6455:         return if ($namespace eq 'courserequests');
 6456:         unless ($symb=escape(&symbread())) { return ''; }
 6457:     } else {
 6458:         unless ($namespace eq 'courserequests') {
 6459:             $symb=&escape(&symbclean($symb));
 6460:         }
 6461:     }
 6462:     if (!$namespace) { 
 6463:        unless ($namespace=$env{'request.course.id'}) { 
 6464:           return ''; 
 6465:        } 
 6466:     }
 6467:     if (!$domain) { $domain=$env{'user.domain'}; }
 6468:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6469:     if (!$home) { $home=$env{'user.home'}; }
 6470:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6471: 
 6472:     my %returnhash=();
 6473:     foreach my $line (split(/\&/,$answer)) {
 6474: 	my ($name,$value)=split(/\=/,$line);
 6475:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6476:     }
 6477:     my $version;
 6478:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6479:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6480:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6481:        }
 6482:     }
 6483:     return %returnhash;
 6484: }
 6485: 
 6486: # ---------------------------------------------------------- Course Description
 6487: #
 6488: #  
 6489: 
 6490: sub coursedescription {
 6491:     my ($courseid,$args)=@_;
 6492:     $courseid=~s/^\///;
 6493:     $courseid=~s/\_/\//g;
 6494:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6495:     my $chome=&homeserver($cnum,$cdomain);
 6496:     my $normalid=$cdomain.'_'.$cnum;
 6497:     # need to always cache even if we get errors otherwise we keep 
 6498:     # trying and trying and trying to get the course description.
 6499:     my %envhash=();
 6500:     my %returnhash=();
 6501:     
 6502:     my $expiretime=600;
 6503:     if ($env{'request.course.id'} eq $normalid) {
 6504: 	$expiretime=120;
 6505:     }
 6506: 
 6507:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6508:     if (!$args->{'freshen_cache'}
 6509: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6510: 	foreach my $key (keys(%env)) {
 6511: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6512: 	    my ($setting) = $1;
 6513: 	    $returnhash{$setting} = $env{$key};
 6514: 	}
 6515: 	return %returnhash;
 6516:     }
 6517: 
 6518:     # get the data again
 6519: 
 6520:     if (!$args->{'one_time'}) {
 6521: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6522:     }
 6523: 
 6524:     if ($chome ne 'no_host') {
 6525:        %returnhash=&dump('environment',$cdomain,$cnum);
 6526:        if (!exists($returnhash{'con_lost'})) {
 6527: 	   my $username = $env{'user.name'}; # Defult username
 6528: 	   if(defined $args->{'user'}) {
 6529: 	       $username = $args->{'user'};
 6530: 	   }
 6531:            $returnhash{'home'}= $chome;
 6532: 	   $returnhash{'domain'} = $cdomain;
 6533: 	   $returnhash{'num'} = $cnum;
 6534:            if (!defined($returnhash{'type'})) {
 6535:                $returnhash{'type'} = 'Course';
 6536:            }
 6537:            while (my ($name,$value) = each %returnhash) {
 6538:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6539:            }
 6540:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6541:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6542: 	       $username.'_'.$cdomain.'_'.$cnum;
 6543:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6544:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6545:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6546:        }
 6547:     }
 6548:     if (!$args->{'one_time'}) {
 6549: 	&appenv(\%envhash);
 6550:     }
 6551:     return %returnhash;
 6552: }
 6553: 
 6554: sub update_released_required {
 6555:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6556:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6557:         $cid = $env{'request.course.id'};
 6558:         $cdom = $env{'course.'.$cid.'.domain'};
 6559:         $cnum = $env{'course.'.$cid.'.num'};
 6560:         $chome = $env{'course.'.$cid.'.home'};
 6561:     }
 6562:     if ($needsrelease) {
 6563:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6564:         my $needsupdate;
 6565:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6566:             $needsupdate = 1;
 6567:         } else {
 6568:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6569:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6570:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6571:                 $needsupdate = 1;
 6572:             }
 6573:         }
 6574:         if ($needsupdate) {
 6575:             my %needshash = (
 6576:                              'internal.releaserequired' => $needsrelease,
 6577:                             );
 6578:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6579:             if ($putresult eq 'ok') {
 6580:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6581:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6582:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6583:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6584:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6585:                 }
 6586:             }
 6587:         }
 6588:     }
 6589:     return;
 6590: }
 6591: 
 6592: # -------------------------------------------------See if a user is privileged
 6593: 
 6594: sub privileged {
 6595:     my ($username,$domain,$possdomains,$possroles)=@_;
 6596:     my $now = time;
 6597:     my $roles;
 6598:     if (ref($possroles) eq 'ARRAY') {
 6599:         $roles = $possroles; 
 6600:     } else {
 6601:         $roles = ['dc','su'];
 6602:     }
 6603:     if (ref($possdomains) eq 'ARRAY') {
 6604:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6605:         foreach my $dom (@{$possdomains}) {
 6606:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6607:                 (ref($privileged{$dom}) eq 'HASH')) {
 6608:                 foreach my $role (@{$roles}) {
 6609:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6610:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6611:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6612:                             return 1 unless (($end && $end < $now) ||
 6613:                                              ($start && $start > $now));
 6614:                         }
 6615:                     }
 6616:                 }
 6617:             }
 6618:         }
 6619:     } else {
 6620:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6621:         my $now = time;
 6622: 
 6623:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6624:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6625:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6626:                 return 1 unless ($tend && $tend < $now) 
 6627:                         or ($tstart && $tstart > $now);
 6628:             }
 6629:         }
 6630:     }
 6631:     return 0;
 6632: }
 6633: 
 6634: sub privileged_by_domain {
 6635:     my ($domains,$roles) = @_;
 6636:     my %privileged = ();
 6637:     my $cachetime = 60*60*24;
 6638:     my $now = time;
 6639:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6640:         return %privileged;
 6641:     }
 6642:     foreach my $dom (@{$domains}) {
 6643:         next if (ref($privileged{$dom}) eq 'HASH');
 6644:         my $needroles;
 6645:         foreach my $role (@{$roles}) {
 6646:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6647:             if (defined($cached)) {
 6648:                 if (ref($result) eq 'HASH') {
 6649:                     $privileged{$dom}{$role} = $result;
 6650:                 }
 6651:             } else {
 6652:                 $needroles = 1;
 6653:             }
 6654:         }
 6655:         if ($needroles) {
 6656:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6657:             $privileged{$dom} = {};
 6658:             foreach my $server (keys(%dompersonnel)) {
 6659:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6660:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6661:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6662:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6663:                         next if ($end && $end < $now);
 6664:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6665:                             $dompersonnel{$server}{$item};
 6666:                     }
 6667:                 }
 6668:             }
 6669:             if (ref($privileged{$dom}) eq 'HASH') {
 6670:                 foreach my $role (@{$roles}) {
 6671:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6672:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6673:                     } else {
 6674:                         my %hash = ();
 6675:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6676:                     }
 6677:                 }
 6678:             }
 6679:         }
 6680:     }
 6681:     return %privileged;
 6682: }
 6683: 
 6684: # -------------------------------------------------------- Get user privileges
 6685: 
 6686: sub rolesinit {
 6687:     my ($domain, $username) = @_;
 6688:     my %userroles = ('user.login.time' => time);
 6689:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6690: 
 6691:     # firstaccess and timerinterval are related to timed maps/resources. 
 6692:     # also, blocking can be triggered by an activating timer
 6693:     # it's saved in the user's %env.
 6694:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6695:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6696:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6697:         %timerintchk, %timerintenv);
 6698: 
 6699:     foreach my $key (keys(%firstaccess)) {
 6700:         my ($cid, $rest) = split(/\0/, $key);
 6701:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6702:     }
 6703: 
 6704:     foreach my $key (keys(%timerinterval)) {
 6705:         my ($cid,$rest) = split(/\0/,$key);
 6706:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6707:     }
 6708: 
 6709:     my %allroles=();
 6710:     my %allgroups=();
 6711: 
 6712:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6713:         my $role = $rolesdump{$area};
 6714:         $area =~ s/\_\w\w$//;
 6715: 
 6716:         my ($trole, $tend, $tstart, $group_privs);
 6717: 
 6718:         if ($role =~ /^cr/) {
 6719:         # Custom role, defined by a user 
 6720:         # e.g., user.role.cr/msu/smith/mynewrole
 6721:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6722:                 $trole = $1;
 6723:                 ($tend, $tstart) = split('_', $2);
 6724:             } else {
 6725:                 $trole = $role;
 6726:             }
 6727:         } elsif ($role =~ m|^gr/|) {
 6728:         # Role of member in a group, defined within a course/community
 6729:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6730:             ($trole, $tend, $tstart) = split(/_/, $role);
 6731:             next if $tstart eq '-1';
 6732:             ($trole, $group_privs) = split(/\//, $trole);
 6733:             $group_privs = &unescape($group_privs);
 6734:         } else {
 6735:         # Just a normal role, defined in roles.tab
 6736:             ($trole, $tend, $tstart) = split(/_/,$role);
 6737:         }
 6738: 
 6739:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6740:                  $username);
 6741:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6742: 
 6743:         # role expired or not available yet?
 6744:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6745:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6746: 
 6747:         next if $area eq '' or $trole eq '';
 6748: 
 6749:         my $spec = "$trole.$area";
 6750:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6751: 
 6752:         if ($trole =~ /^cr\//) {
 6753:         # Custom role, defined by a user
 6754:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6755:         } elsif ($trole eq 'gr') {
 6756:         # Role of a member in a group, defined within a course/community
 6757:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6758:             next;
 6759:         } else {
 6760:         # Normal role, defined in roles.tab
 6761:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6762:         }
 6763: 
 6764:         my $cid = $tdomain.'_'.$trest;
 6765:         unless ($firstaccchk{$cid}) {
 6766:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6767:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6768:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6769:                         $coursetimerstarts{$cid}{$item}; 
 6770:                 }
 6771:             }
 6772:             $firstaccchk{$cid} = 1;
 6773:         }
 6774:         unless ($timerintchk{$cid}) {
 6775:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6776:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6777:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6778:                        $coursetimerintervals{$cid}{$item};
 6779:                 }
 6780:             }
 6781:             $timerintchk{$cid} = 1;
 6782:         }
 6783:     }
 6784: 
 6785:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6786:                                                           \%allroles, \%allgroups);
 6787:     $env{'user.adv'} = $userroles{'user.adv'};
 6788:     $env{'user.rar'} = $userroles{'user.rar'};
 6789: 
 6790:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6791: }
 6792: 
 6793: sub set_arearole {
 6794:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6795:     unless ($nolog) {
 6796: # log the associated role with the area
 6797:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6798:     }
 6799:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6800: }
 6801: 
 6802: sub custom_roleprivs {
 6803:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6804:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6805:     my $homsvr = &homeserver($rauthor,$rdomain);
 6806:     if (&hostname($homsvr) ne '') {
 6807:         my ($rdummy,$roledef)=
 6808:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6809:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6810:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6811:             if (defined($syspriv)) {
 6812:                 if ($trest =~ /^$match_community$/) {
 6813:                     $syspriv =~ s/bre\&S//; 
 6814:                 }
 6815:                 $$allroles{'cm./'}.=':'.$syspriv;
 6816:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6817:             }
 6818:             if ($tdomain ne '') {
 6819:                 if (defined($dompriv)) {
 6820:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6821:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6822:                 }
 6823:                 if (($trest ne '') && (defined($coursepriv))) {
 6824:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6825:                         my $rolename = $1;
 6826:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6827:                     }
 6828:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6829:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6830:                 }
 6831:             }
 6832:         }
 6833:     }
 6834: }
 6835: 
 6836: sub course_adhocrole_privs {
 6837:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6838:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6839:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6840:         my (%currprivs,%storeprivs);
 6841:         foreach my $item (split(/:/,$coursepriv)) {
 6842:             my ($priv,$restrict) = split(/\&/,$item);
 6843:             $currprivs{$priv} = $restrict;
 6844:         }
 6845:         my (%possadd,%possremove,%full);
 6846:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6847:             my ($priv,$restrict)=split(/\&/,$item);
 6848:             $full{$priv} = $restrict;
 6849:         }
 6850:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6851:              next if ($item eq '');
 6852:              my ($rule,$rest) = split(/=/,$item);
 6853:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6854:              foreach my $priv (split(/:/,$rest)) {
 6855:                  if ($priv ne '') {
 6856:                      if ($rule eq 'off') {
 6857:                          $possremove{$priv} = 1;
 6858:                      } else {
 6859:                          $possadd{$priv} = 1;
 6860:                      }
 6861:                  }
 6862:              }
 6863:          }
 6864:          foreach my $priv (sort(keys(%full))) {
 6865:              if (exists($currprivs{$priv})) {
 6866:                  unless (exists($possremove{$priv})) {
 6867:                      $storeprivs{$priv} = $currprivs{$priv};
 6868:                  }
 6869:              } elsif (exists($possadd{$priv})) {
 6870:                  $storeprivs{$priv} = $full{$priv};
 6871:              }
 6872:          }
 6873:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6874:      }
 6875:      return $coursepriv;
 6876: }
 6877: 
 6878: sub group_roleprivs {
 6879:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6880:     my $access = 1;
 6881:     my $now = time;
 6882:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6883:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6884:     if ($access) {
 6885:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6886:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6887:     }
 6888: }
 6889: 
 6890: sub standard_roleprivs {
 6891:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6892:     if (defined($pr{$trole.':s'})) {
 6893:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6894:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6895:     }
 6896:     if ($tdomain ne '') {
 6897:         if (defined($pr{$trole.':d'})) {
 6898:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6899:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6900:         }
 6901:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6902:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6903:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6904:         }
 6905:     }
 6906: }
 6907: 
 6908: sub set_userprivs {
 6909:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6910:     my $author=0;
 6911:     my $adv=0;
 6912:     my $rar=0;
 6913:     my %grouproles = ();
 6914:     if (keys(%{$allgroups}) > 0) {
 6915:         my @groupkeys; 
 6916:         foreach my $role (keys(%{$allroles})) {
 6917:             push(@groupkeys,$role);
 6918:         }
 6919:         if (ref($groups_roles) eq 'HASH') {
 6920:             foreach my $key (keys(%{$groups_roles})) {
 6921:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6922:                     push(@groupkeys,$key);
 6923:                 }
 6924:             }
 6925:         }
 6926:         if (@groupkeys > 0) {
 6927:             foreach my $role (@groupkeys) {
 6928:                 my ($trole,$area,$sec,$extendedarea);
 6929:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6930:                     $trole = $1;
 6931:                     $area = $2;
 6932:                     $sec = $3;
 6933:                     $extendedarea = $area.$sec;
 6934:                     if (exists($$allgroups{$area})) {
 6935:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6936:                             my $spec = $trole.'.'.$extendedarea;
 6937:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6938:                                                 $$allgroups{$area}{$group};
 6939:                         }
 6940:                     }
 6941:                 }
 6942:             }
 6943:         }
 6944:     }
 6945:     foreach my $group (keys(%grouproles)) {
 6946:         $$allroles{$group} = $grouproles{$group};
 6947:     }
 6948:     foreach my $role (keys(%{$allroles})) {
 6949:         my %thesepriv;
 6950:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6951:         foreach my $item (split(/:/,$$allroles{$role})) {
 6952:             if ($item ne '') {
 6953:                 my ($privilege,$restrictions)=split(/&/,$item);
 6954:                 if ($restrictions eq '') {
 6955:                     $thesepriv{$privilege}='F';
 6956:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6957:                     $thesepriv{$privilege}.=$restrictions;
 6958:                 }
 6959:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6960:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6961:             }
 6962:         }
 6963:         my $thesestr='';
 6964:         foreach my $priv (sort(keys(%thesepriv))) {
 6965: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6966: 	}
 6967:         $userroles->{'user.priv.'.$role} = $thesestr;
 6968:     }
 6969:     return ($author,$adv,$rar);
 6970: }
 6971: 
 6972: sub role_status {
 6973:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6974:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6975:         my ($one,$two) = split(m{\./},$rolekey,2);
 6976:         (undef,undef,$$role) = split(/\./,$one,3);
 6977:         unless (!defined($$role) || $$role eq '') {
 6978:             $$where = '/'.$two;
 6979:             $$trolecode=$$role.'.'.$$where;
 6980:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6981:             $$tstatus='is';
 6982:             if ($$tstart && $$tstart>$update) {
 6983:                 $$tstatus='future';
 6984:                 if ($$tstart<$now) {
 6985:                     if ($$tstart && $$tstart>$refresh) {
 6986:                         if (($$where ne '') && ($$role ne '')) {
 6987:                             my (%allroles,%allgroups,$group_privs,
 6988:                                 %groups_roles,@rolecodes);
 6989:                             my %userroles = (
 6990:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6991:                             );
 6992:                             @rolecodes = ('cm'); 
 6993:                             my $spec=$$role.'.'.$$where;
 6994:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6995:                             if ($$role =~ /^cr\//) {
 6996:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6997:                                 push(@rolecodes,'cr');
 6998:                             } elsif ($$role eq 'gr') {
 6999:                                 push(@rolecodes,$$role);
 7000:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7001:                                                     $env{'user.name'});
 7002:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7003:                                 (undef,my $group_privs) = split(/\//,$trole);
 7004:                                 $group_privs = &unescape($group_privs);
 7005:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7006:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7007:                                 &get_groups_roles($tdomain,$trest,
 7008:                                                   \%course_roles,\@rolecodes,
 7009:                                                   \%groups_roles);
 7010:                             } else {
 7011:                                 push(@rolecodes,$$role);
 7012:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7013:                             }
 7014:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7015:                                                                    \%groups_roles);
 7016:                             &appenv(\%userroles,\@rolecodes);
 7017:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7018:                         }
 7019:                     }
 7020:                     $$tstatus = 'is';
 7021:                 }
 7022:             }
 7023:             if ($$tend) {
 7024:                 if ($$tend<$update) {
 7025:                     $$tstatus='expired';
 7026:                 } elsif ($$tend<$now) {
 7027:                     $$tstatus='will_not';
 7028:                 }
 7029:             }
 7030:         }
 7031:     }
 7032: }
 7033: 
 7034: sub get_groups_roles {
 7035:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7036:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7037:                   (ref($rolecodes) eq 'ARRAY') && 
 7038:                   (ref($groups_roles) eq 'HASH')); 
 7039:     if (keys(%{$cdom_courseroles}) > 0) {
 7040:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7041:         if ($cdom ne '' && $cnum ne '') {
 7042:             foreach my $key (keys(%{$cdom_courseroles})) {
 7043:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7044:                     my $crsrole = $1;
 7045:                     my $crssec = $2;
 7046:                     if ($crsrole =~ /^cr/) {
 7047:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7048:                             push(@{$rolecodes},'cr');
 7049:                         }
 7050:                     } else {
 7051:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7052:                             push(@{$rolecodes},$crsrole);
 7053:                         }
 7054:                     }
 7055:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7056:                     if ($crssec ne '') {
 7057:                         $rolekey .= "/$crssec";
 7058:                     }
 7059:                     $rolekey .= './';
 7060:                     $groups_roles->{$rolekey} = $rolecodes;
 7061:                 }
 7062:             }
 7063:         }
 7064:     }
 7065:     return;
 7066: }
 7067: 
 7068: sub delete_env_groupprivs {
 7069:     my ($where,$courseroles,$possroles) = @_;
 7070:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7071:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7072:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7073:         %{$courseroles->{$udom}} =
 7074:             &get_my_roles('','','userroles',['active'],
 7075:                           $possroles,[$udom],1);
 7076:     }
 7077:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7078:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7079:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7080:             my $area = '/'.$cdom.'/'.$cnum;
 7081:             my $privkey = "user.priv.$crsrole.$area";
 7082:             if ($crssec ne '') {
 7083:                 $privkey .= '/'.$crssec;
 7084:             }
 7085:             $privkey .= ".$area/$group";
 7086:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7087:         }
 7088:     }
 7089:     return;
 7090: }
 7091: 
 7092: sub check_adhoc_privs {
 7093:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7094:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7095:     if ($sec) {
 7096:         $cckey .= '/'.$sec;
 7097:     } 
 7098:     my $setprivs;
 7099:     if ($env{$cckey}) {
 7100:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7101:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7102:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7103:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7104:             $setprivs = 1;
 7105:         }
 7106:     } else {
 7107:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7108:         $setprivs = 1;
 7109:     }
 7110:     return $setprivs;
 7111: }
 7112: 
 7113: sub set_adhoc_privileges {
 7114: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7115:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7116:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7117:     if ($sec ne '') {
 7118:         $area .= '/'.$sec;
 7119:     }
 7120:     my $spec = $role.'.'.$area;
 7121:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7122:                                   $env{'user.name'},1);
 7123:     my %rolehash = ();
 7124:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7125:         my $rolename = $1;
 7126:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7127:         my %domdef = &get_domain_defaults($dcdom);
 7128:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7129:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7130:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7131:             }
 7132:         }
 7133:     } else {
 7134:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7135:     }
 7136:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7137:     &appenv(\%userroles,[$role,'cm']);
 7138:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7139:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7140:             ($caller eq 'tiny')) {
 7141:         &appenv( {'request.role'        => $spec,
 7142:                   'request.role.domain' => $dcdom,
 7143:                   'request.course.sec'  => $sec,
 7144:                  }
 7145:                );
 7146:         my $tadv=0;
 7147:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7148:         &appenv({'request.role.adv'    => $tadv});
 7149:     }
 7150: }
 7151: 
 7152: # --------------------------------------------------------------- get interface
 7153: 
 7154: sub get {
 7155:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7156:    my $items='';
 7157:    foreach my $item (@$storearr) {
 7158:        $items.=&escape($item).'&';
 7159:    }
 7160:    $items=~s/\&$//;
 7161:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7162:    if (!$uname) { $uname=$env{'user.name'}; }
 7163:    my $uhome=&homeserver($uname,$udomain);
 7164: 
 7165:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7166:    my @pairs=split(/\&/,$rep);
 7167:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7168:      return @pairs;
 7169:    }
 7170:    my %returnhash=();
 7171:    my $i=0;
 7172:    foreach my $item (@$storearr) {
 7173:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7174:       $i++;
 7175:    }
 7176:    return %returnhash;
 7177: }
 7178: 
 7179: # --------------------------------------------------------------- del interface
 7180: 
 7181: sub del {
 7182:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7183:    my $items='';
 7184:    foreach my $item (@$storearr) {
 7185:        $items.=&escape($item).'&';
 7186:    }
 7187: 
 7188:    $items=~s/\&$//;
 7189:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7190:    if (!$uname) { $uname=$env{'user.name'}; }
 7191:    my $uhome=&homeserver($uname,$udomain);
 7192:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7193: }
 7194: 
 7195: # -------------------------------------------------------------- dump interface
 7196: 
 7197: sub unserialize {
 7198:     my ($rep, $escapedkeys) = @_;
 7199: 
 7200:     return {} if $rep =~ /^error/;
 7201: 
 7202:     my %returnhash=();
 7203: 	foreach my $item (split(/\&/,$rep)) {
 7204: 	    my ($key, $value) = split(/=/, $item, 2);
 7205: 	    $key = unescape($key) unless $escapedkeys;
 7206: 	    next if $key =~ /^error: 2 /;
 7207: 	    $returnhash{$key} = &thaw_unescape($value);
 7208: 	}
 7209:     #return %returnhash;
 7210:     return \%returnhash;
 7211: }        
 7212: 
 7213: # see Lond::dump_with_regexp
 7214: # if $escapedkeys hash keys won't get unescaped.
 7215: sub dump {
 7216:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7217:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7218:     if (!$uname) { $uname=$env{'user.name'}; }
 7219:     my $uhome=&homeserver($uname,$udomain);
 7220: 
 7221:     if ($regexp) {
 7222:         $regexp=&escape($regexp);
 7223:     } else {
 7224:         $regexp='.';
 7225:     }
 7226:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7227:         # user is hosted on this machine
 7228:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7229:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7230:         return %{unserialize($reply, $escapedkeys)};
 7231:     }
 7232:     my $rep;
 7233:     if ($encrypt) {
 7234:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7235:     } else {
 7236:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7237:     }
 7238:     my @pairs=split(/\&/,$rep);
 7239:     my %returnhash=();
 7240:     if (!($rep =~ /^error/ )) {
 7241: 	foreach my $item (@pairs) {
 7242: 	    my ($key,$value)=split(/=/,$item,2);
 7243:         $key = unescape($key) unless $escapedkeys;
 7244:         #$key = &unescape($key);
 7245: 	    next if ($key =~ /^error: 2 /);
 7246: 	    $returnhash{$key}=&thaw_unescape($value);
 7247: 	}
 7248:     }
 7249:     return %returnhash;
 7250: }
 7251: 
 7252: 
 7253: # --------------------------------------------------------- dumpstore interface
 7254: 
 7255: sub dumpstore {
 7256:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7257:    # same as dump but keys must be escaped. They may contain colon separated
 7258:    # lists of values that may themself contain colons (e.g. symbs).
 7259:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7260: }
 7261: 
 7262: # -------------------------------------------------------------- keys interface
 7263: 
 7264: sub getkeys {
 7265:    my ($namespace,$udomain,$uname)=@_;
 7266:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7267:    if (!$uname) { $uname=$env{'user.name'}; }
 7268:    my $uhome=&homeserver($uname,$udomain);
 7269:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7270:    my @keyarray=();
 7271:    foreach my $key (split(/\&/,$rep)) {
 7272:       next if ($key =~ /^error: 2 /);
 7273:       push(@keyarray,&unescape($key));
 7274:    }
 7275:    return @keyarray;
 7276: }
 7277: 
 7278: # --------------------------------------------------------------- currentdump
 7279: sub currentdump {
 7280:    my ($courseid,$sdom,$sname)=@_;
 7281:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7282:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7283:    $sname    = $env{'user.name'}         if (! defined($sname));
 7284:    my $uhome = &homeserver($sname,$sdom);
 7285:    my $rep;
 7286: 
 7287:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7288:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7289:                    $courseid)));
 7290:    } else {
 7291:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7292:    }
 7293: 
 7294:    return if ($rep =~ /^(error:|no_such_host)/);
 7295:    #
 7296:    my %returnhash=();
 7297:    #
 7298:    if ($rep eq 'unknown_cmd') {
 7299:        # an old lond will not know currentdump
 7300:        # Do a dump and make it look like a currentdump
 7301:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7302:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7303:        my %hash = @tmp;
 7304:        @tmp=();
 7305:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7306:    } else {
 7307:        my @pairs=split(/\&/,$rep);
 7308:        foreach my $pair (@pairs) {
 7309:            my ($key,$value)=split(/=/,$pair,2);
 7310:            my ($symb,$param) = split(/:/,$key);
 7311:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7312:                                                         &thaw_unescape($value);
 7313:        }
 7314:    }
 7315:    return %returnhash;
 7316: }
 7317: 
 7318: sub convert_dump_to_currentdump{
 7319:     my %hash = %{shift()};
 7320:     my %returnhash;
 7321:     # Code ripped from lond, essentially.  The only difference
 7322:     # here is the unescaping done by lonnet::dump().  Conceivably
 7323:     # we might run in to problems with parameter names =~ /^v\./
 7324:     while (my ($key,$value) = each(%hash)) {
 7325:         my ($v,$symb,$param) = split(/:/,$key);
 7326: 	$symb  = &unescape($symb);
 7327: 	$param = &unescape($param);
 7328:         next if ($v eq 'version' || $symb eq 'keys');
 7329:         next if (exists($returnhash{$symb}) &&
 7330:                  exists($returnhash{$symb}->{$param}) &&
 7331:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7332:         $returnhash{$symb}->{$param}=$value;
 7333:         $returnhash{$symb}->{'v.'.$param}=$v;
 7334:     }
 7335:     #
 7336:     # Remove all of the keys in the hashes which keep track of
 7337:     # the version of the parameter.
 7338:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7339:         # use a foreach because we are going to delete from the hash.
 7340:         foreach my $key (keys(%$param_hash)) {
 7341:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7342:         }
 7343:     }
 7344:     return \%returnhash;
 7345: }
 7346: 
 7347: # ------------------------------------------------------ critical inc interface
 7348: 
 7349: sub cinc {
 7350:     return &inc(@_,'critical');
 7351: }
 7352: 
 7353: # --------------------------------------------------------------- inc interface
 7354: 
 7355: sub inc {
 7356:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7357:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7358:     if (!$uname) { $uname=$env{'user.name'}; }
 7359:     my $uhome=&homeserver($uname,$udomain);
 7360:     my $items='';
 7361:     if (! ref($store)) {
 7362:         # got a single value, so use that instead
 7363:         $items = &escape($store).'=&';
 7364:     } elsif (ref($store) eq 'SCALAR') {
 7365:         $items = &escape($$store).'=&';        
 7366:     } elsif (ref($store) eq 'ARRAY') {
 7367:         $items = join('=&',map {&escape($_);} @{$store});
 7368:     } elsif (ref($store) eq 'HASH') {
 7369:         while (my($key,$value) = each(%{$store})) {
 7370:             $items.= &escape($key).'='.&escape($value).'&';
 7371:         }
 7372:     }
 7373:     $items=~s/\&$//;
 7374:     if ($critical) {
 7375: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7376:     } else {
 7377: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7378:     }
 7379: }
 7380: 
 7381: # --------------------------------------------------------------- put interface
 7382: 
 7383: sub put {
 7384:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7385:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7386:    if (!$uname) { $uname=$env{'user.name'}; }
 7387:    my $uhome=&homeserver($uname,$udomain);
 7388:    my $items='';
 7389:    foreach my $item (keys(%$storehash)) {
 7390:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7391:    }
 7392:    $items=~s/\&$//;
 7393:    if ($encrypt) {
 7394:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7395:    } else {
 7396:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7397:    }
 7398: }
 7399: 
 7400: # ------------------------------------------------------------ newput interface
 7401: 
 7402: sub newput {
 7403:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7404:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7405:    if (!$uname) { $uname=$env{'user.name'}; }
 7406:    my $uhome=&homeserver($uname,$udomain);
 7407:    my $items='';
 7408:    foreach my $key (keys(%$storehash)) {
 7409:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7410:    }
 7411:    $items=~s/\&$//;
 7412:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7413: }
 7414: 
 7415: # ---------------------------------------------------------  putstore interface
 7416: 
 7417: sub putstore {
 7418:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7419:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7420:    if (!$uname) { $uname=$env{'user.name'}; }
 7421:    my $uhome=&homeserver($uname,$udomain);
 7422:    my $items='';
 7423:    foreach my $key (keys(%$storehash)) {
 7424:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7425:    }
 7426:    $items=~s/\&$//;
 7427:    my $esc_symb=&escape($symb);
 7428:    my $esc_v=&escape($version);
 7429:    my $reply =
 7430:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7431: 	      $uhome);
 7432:    if (($tolog) && ($reply eq 'ok')) {
 7433:        my $namevalue='';
 7434:        foreach my $key (keys(%{$storehash})) {
 7435:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7436:        }
 7437:        my $ip = &get_requestor_ip();
 7438:        $namevalue .= 'ip='.&escape($ip).
 7439:                      '&host='.&escape($perlvar{'lonHostID'}).
 7440:                      '&version='.$esc_v.
 7441:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7442:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7443:    }
 7444:    if ($reply eq 'unknown_cmd') {
 7445:        # gfall back to way things use to be done
 7446:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7447: 			    $uname);
 7448:    }
 7449:    return $reply;
 7450: }
 7451: 
 7452: sub old_putstore {
 7453:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7454:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7455:     if (!$uname) { $uname=$env{'user.name'}; }
 7456:     my $uhome=&homeserver($uname,$udomain);
 7457:     my %newstorehash;
 7458:     foreach my $item (keys(%$storehash)) {
 7459: 	my $key = $version.':'.&escape($symb).':'.$item;
 7460: 	$newstorehash{$key} = $storehash->{$item};
 7461:     }
 7462:     my $items='';
 7463:     my %allitems = ();
 7464:     foreach my $item (keys(%newstorehash)) {
 7465: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7466: 	    my $key = $1.':keys:'.$2;
 7467: 	    $allitems{$key} .= $3.':';
 7468: 	}
 7469: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7470:     }
 7471:     foreach my $item (keys(%allitems)) {
 7472: 	$allitems{$item} =~ s/\:$//;
 7473: 	$items.= $item.'='.$allitems{$item}.'&';
 7474:     }
 7475:     $items=~s/\&$//;
 7476:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7477: }
 7478: 
 7479: # ------------------------------------------------------ critical put interface
 7480: 
 7481: sub cput {
 7482:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7483:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7484:    if (!$uname) { $uname=$env{'user.name'}; }
 7485:    my $uhome=&homeserver($uname,$udomain);
 7486:    my $items='';
 7487:    foreach my $item (keys(%$storehash)) {
 7488:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7489:    }
 7490:    $items=~s/\&$//;
 7491:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7492: }
 7493: 
 7494: # -------------------------------------------------------------- eget interface
 7495: 
 7496: sub eget {
 7497:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7498:    my $items='';
 7499:    foreach my $item (@$storearr) {
 7500:        $items.=&escape($item).'&';
 7501:    }
 7502:    $items=~s/\&$//;
 7503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7504:    if (!$uname) { $uname=$env{'user.name'}; }
 7505:    my $uhome=&homeserver($uname,$udomain);
 7506:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7507:    my @pairs=split(/\&/,$rep);
 7508:    my %returnhash=();
 7509:    my $i=0;
 7510:    foreach my $item (@$storearr) {
 7511:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7512:       $i++;
 7513:    }
 7514:    return %returnhash;
 7515: }
 7516: 
 7517: # ------------------------------------------------------------ tmpput interface
 7518: sub tmpput {
 7519:     my ($storehash,$server,$context)=@_;
 7520:     my $items='';
 7521:     foreach my $item (keys(%$storehash)) {
 7522: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7523:     }
 7524:     $items=~s/\&$//;
 7525:     if (defined($context)) {
 7526:         $items .= ':'.&escape($context);
 7527:     }
 7528:     return &reply("tmpput:$items",$server);
 7529: }
 7530: 
 7531: # ------------------------------------------------------------ tmpget interface
 7532: sub tmpget {
 7533:     my ($token,$server)=@_;
 7534:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7535:     my $rep=&reply("tmpget:$token",$server);
 7536:     my %returnhash;
 7537:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7538:         return %returnhash;
 7539:     }
 7540:     foreach my $item (split(/\&/,$rep)) {
 7541: 	my ($key,$value)=split(/=/,$item);
 7542: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7543:     }
 7544:     return %returnhash;
 7545: }
 7546: 
 7547: # ------------------------------------------------------------ tmpdel interface
 7548: sub tmpdel {
 7549:     my ($token,$server)=@_;
 7550:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7551:     return &reply("tmpdel:$token",$server);
 7552: }
 7553: 
 7554: # ------------------------------------------------------------ get_timebased_id 
 7555: 
 7556: sub get_timebased_id {
 7557:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7558:         $maxtries) = @_;
 7559:     my ($newid,$error,$dellock);
 7560:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7561:         return ('','ok','invalid call to get suffix');
 7562:     }
 7563: 
 7564: # set defaults for any optional args for which values were not supplied
 7565:     if ($who eq '') {
 7566:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7567:     }
 7568:     if (!$locktries) {
 7569:         $locktries = 3;
 7570:     }
 7571:     if (!$maxtries) {
 7572:         $maxtries = 10;
 7573:     }
 7574:     
 7575:     if (($cdom eq '') || ($cnum eq '')) {
 7576:         if ($env{'request.course.id'}) {
 7577:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7578:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7579:         }
 7580:         if (($cdom eq '') || ($cnum eq '')) {
 7581:             return ('','ok','call to get suffix not in course context');
 7582:         }
 7583:     }
 7584: 
 7585: # construct locking item
 7586:     my $lockhash = {
 7587:                       $prefix."\0".'locked_'.$keyid => $who,
 7588:                    };
 7589:     my $tries = 0;
 7590: 
 7591: # attempt to get lock on nohist_$namespace file
 7592:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7593:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7594:         $tries ++;
 7595:         sleep 1;
 7596:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7597:     }
 7598: 
 7599: # attempt to get unique identifier, based on current timestamp
 7600:     if ($gotlock eq 'ok') {
 7601:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7602:         my $id = time;
 7603:         $newid = $id;
 7604:         if ($idtype eq 'addcode') {
 7605:             $newid .= &sixnum_code();
 7606:         }
 7607:         my $idtries = 0;
 7608:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7609:             if ($idtype eq 'concat') {
 7610:                 $newid = $id.$idtries;
 7611:             } elsif ($idtype eq 'addcode') {
 7612:                 $newid = $newid.&sixnum_code();
 7613:             } else {
 7614:                 $newid ++;
 7615:             }
 7616:             $idtries ++;
 7617:         }
 7618:         if (!exists($inuse{$prefix."\0".$newid})) {
 7619:             my %new_item =  (
 7620:                               $prefix."\0".$newid => $who,
 7621:                             );
 7622:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7623:                                                  $cdom,$cnum);
 7624:             if ($putresult ne 'ok') {
 7625:                 undef($newid);
 7626:                 $error = 'error saving new item: '.$putresult;
 7627:             }
 7628:         } else {
 7629:              undef($newid);
 7630:              $error = ('error: no unique suffix available for the new item ');
 7631:         }
 7632: #  remove lock
 7633:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7634:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7635:     } else {
 7636:         $error = "error: could not obtain lockfile\n";
 7637:         $dellock = 'ok';
 7638:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7639:             $dellock = 'nolock';
 7640:         }
 7641:     }
 7642:     return ($newid,$dellock,$error);
 7643: }
 7644: 
 7645: sub sixnum_code {
 7646:     my $code;
 7647:     for (0..6) {
 7648:         $code .= int( rand(9) );
 7649:     }
 7650:     return $code;
 7651: }
 7652: 
 7653: # -------------------------------------------------- portfolio access checking
 7654: 
 7655: sub portfolio_access {
 7656:     my ($requrl,$clientip) = @_;
 7657:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7658:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7659:     if ($result) {
 7660:         my %setters;
 7661:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7662:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7663:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7664:             if (($startblock && $endblock) || ($by_ip)) {
 7665:                 return 'B';
 7666:             }
 7667:         } else {
 7668:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7669:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7670:             if (($startblock && $endblock) || ($by_ip)) {
 7671:                 return 'B';
 7672:             }
 7673:         }
 7674:     }
 7675:     if ($result eq 'ok') {
 7676:        return 'F';
 7677:     } elsif ($result =~ /^[^:]+:guest_/) {
 7678:        return 'A';
 7679:     }
 7680:     return '';
 7681: }
 7682: 
 7683: sub get_portfolio_access {
 7684:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7685: 
 7686:     if (!ref($access_hash)) {
 7687: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7688: 	my %access_controls = &get_access_controls($current_perms,$group,
 7689: 						   $file_name);
 7690: 	$access_hash = $access_controls{$file_name};
 7691:     }
 7692: 
 7693:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7694:     my $now = time;
 7695:     if (ref($access_hash) eq 'HASH') {
 7696:         foreach my $key (keys(%{$access_hash})) {
 7697:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7698:             if ($start > $now) {
 7699:                 next;
 7700:             }
 7701:             if ($end && $end<$now) {
 7702:                 next;
 7703:             }
 7704:             if ($scope eq 'public') {
 7705:                 $public = $key;
 7706:                 last;
 7707:             } elsif ($scope eq 'guest') {
 7708:                 $guest = $key;
 7709:             } elsif ($scope eq 'domains') {
 7710:                 push(@domains,$key);
 7711:             } elsif ($scope eq 'users') {
 7712:                 push(@users,$key);
 7713:             } elsif ($scope eq 'course') {
 7714:                 push(@courses,$key);
 7715:             } elsif ($scope eq 'group') {
 7716:                 push(@groups,$key);
 7717:             } elsif ($scope eq 'ip') {
 7718:                 push(@ips,$key);
 7719:             }
 7720:         }
 7721:         if ($public) {
 7722:             return 'ok';
 7723:         } elsif (@ips > 0) {
 7724:             my $allowed;
 7725:             foreach my $ipkey (@ips) {
 7726:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7727:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7728:                         $allowed = 1;
 7729:                         last; 
 7730:                     }
 7731:                 }
 7732:             }
 7733:             if ($allowed) {
 7734:                 return 'ok';
 7735:             }
 7736:         }
 7737:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7738:             if ($guest) {
 7739:                 return $guest;
 7740:             }
 7741:         } else {
 7742:             if (@domains > 0) {
 7743:                 foreach my $domkey (@domains) {
 7744:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7745:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7746:                             return 'ok';
 7747:                         }
 7748:                     }
 7749:                 }
 7750:             }
 7751:             if (@users > 0) {
 7752:                 foreach my $userkey (@users) {
 7753:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7754:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7755:                             if (ref($item) eq 'HASH') {
 7756:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7757:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7758:                                     return 'ok';
 7759:                                 }
 7760:                             }
 7761:                         }
 7762:                     } 
 7763:                 }
 7764:             }
 7765:             my %roleshash;
 7766:             my @courses_and_groups = @courses;
 7767:             push(@courses_and_groups,@groups); 
 7768:             if (@courses_and_groups > 0) {
 7769:                 my (%allgroups,%allroles); 
 7770:                 my ($start,$end,$role,$sec,$group);
 7771:                 foreach my $envkey (%env) {
 7772:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7773:                         my $cid = $2.'_'.$3; 
 7774:                         if ($1 eq 'gr') {
 7775:                             $group = $4;
 7776:                             $allgroups{$cid}{$group} = $env{$envkey};
 7777:                         } else {
 7778:                             if ($4 eq '') {
 7779:                                 $sec = 'none';
 7780:                             } else {
 7781:                                 $sec = $4;
 7782:                             }
 7783:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7784:                         }
 7785:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7786:                         my $cid = $2.'_'.$3;
 7787:                         if ($4 eq '') {
 7788:                             $sec = 'none';
 7789:                         } else {
 7790:                             $sec = $4;
 7791:                         }
 7792:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7793:                     }
 7794:                 }
 7795:                 if (keys(%allroles) == 0) {
 7796:                     return;
 7797:                 }
 7798:                 foreach my $key (@courses_and_groups) {
 7799:                     my %content = %{$$access_hash{$key}};
 7800:                     my $cnum = $content{'number'};
 7801:                     my $cdom = $content{'domain'};
 7802:                     my $cid = $cdom.'_'.$cnum;
 7803:                     if (!exists($allroles{$cid})) {
 7804:                         next;
 7805:                     }    
 7806:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7807:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7808:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7809:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7810:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7811:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7812:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7813:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7814:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7815:                                         if (grep/^all$/,@sections) {
 7816:                                             return 'ok';
 7817:                                         } else {
 7818:                                             if (grep/^$sec$/,@sections) {
 7819:                                                 return 'ok';
 7820:                                             }
 7821:                                         }
 7822:                                     }
 7823:                                 }
 7824:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7825:                                     if (grep/^none$/,@groups) {
 7826:                                         return 'ok';
 7827:                                     }
 7828:                                 } else {
 7829:                                     if (grep/^all$/,@groups) {
 7830:                                         return 'ok';
 7831:                                     } 
 7832:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7833:                                         if (grep/^$group$/,@groups) {
 7834:                                             return 'ok';
 7835:                                         }
 7836:                                     }
 7837:                                 } 
 7838:                             }
 7839:                         }
 7840:                     }
 7841:                 }
 7842:             }
 7843:             if ($guest) {
 7844:                 return $guest;
 7845:             }
 7846:         }
 7847:     }
 7848:     return;
 7849: }
 7850: 
 7851: sub course_group_datechecker {
 7852:     my ($dates,$now,$status) = @_;
 7853:     my ($start,$end) = split(/\./,$dates);
 7854:     if (!$start && !$end) {
 7855:         return 'ok';
 7856:     }
 7857:     if (grep/^active$/,@{$status}) {
 7858:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7859:             return 'ok';
 7860:         }
 7861:     }
 7862:     if (grep/^previous$/,@{$status}) {
 7863:         if ($end > $now ) {
 7864:             return 'ok';
 7865:         }
 7866:     }
 7867:     if (grep/^future$/,@{$status}) {
 7868:         if ($start > $now) {
 7869:             return 'ok';
 7870:         }
 7871:     }
 7872:     return; 
 7873: }
 7874: 
 7875: sub parse_portfolio_url {
 7876:     my ($url) = @_;
 7877: 
 7878:     my ($type,$udom,$unum,$group,$file_name);
 7879:     
 7880:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7881: 	$type = 1;
 7882:         $udom = $1;
 7883:         $unum = $2;
 7884:         $file_name = $3;
 7885:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7886: 	$type = 2;
 7887:         $udom = $1;
 7888:         $unum = $2;
 7889:         $group = $3;
 7890:         $file_name = $3.'/'.$4;
 7891:     }
 7892:     if (wantarray) {
 7893: 	return ($type,$udom,$unum,$file_name,$group);
 7894:     }
 7895:     return $type;
 7896: }
 7897: 
 7898: sub is_portfolio_url {
 7899:     my ($url) = @_;
 7900:     return scalar(&parse_portfolio_url($url));
 7901: }
 7902: 
 7903: sub is_portfolio_file {
 7904:     my ($file) = @_;
 7905:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7906:         return 1;
 7907:     }
 7908:     return;
 7909: }
 7910: 
 7911: sub usertools_access {
 7912:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7913:     my ($access,%tools);
 7914:     if ($context eq '') {
 7915:         $context = 'tools';
 7916:     }
 7917:     if ($context eq 'requestcourses') {
 7918:         %tools = (
 7919:                       official   => 1,
 7920:                       unofficial => 1,
 7921:                       community  => 1,
 7922:                       textbook   => 1,
 7923:                       placement  => 1,
 7924:                       lti        => 1,
 7925:                  );
 7926:     } elsif ($context eq 'requestauthor') {
 7927:         %tools = (
 7928:                       requestauthor => 1,
 7929:                  );
 7930:     } else {
 7931:         %tools = (
 7932:                       aboutme   => 1,
 7933:                       blog      => 1,
 7934:                       webdav    => 1,
 7935:                       portfolio => 1,
 7936:                  );
 7937:     }
 7938:     return if (!defined($tools{$tool}));
 7939: 
 7940:     if (($udom eq '') || ($uname eq '')) {
 7941:         $udom = $env{'user.domain'};
 7942:         $uname = $env{'user.name'};
 7943:     }
 7944: 
 7945:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7946:         if ($action ne 'reload') {
 7947:             if ($context eq 'requestcourses') {
 7948:                 return $env{'environment.canrequest.'.$tool};
 7949:             } elsif ($context eq 'requestauthor') {
 7950:                 return $env{'environment.canrequest.author'};
 7951:             } else {
 7952:                 return $env{'environment.availabletools.'.$tool};
 7953:             }
 7954:         }
 7955:     }
 7956: 
 7957:     my ($toolstatus,$inststatus,$envkey);
 7958:     if ($context eq 'requestauthor') {
 7959:         $envkey = $context; 
 7960:     } else {
 7961:         $envkey = $context.'.'.$tool;
 7962:     }
 7963: 
 7964:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7965:          ($action ne 'reload')) {
 7966:         $toolstatus = $env{'environment.'.$envkey};
 7967:         $inststatus = $env{'environment.inststatus'};
 7968:     } else {
 7969:         if (ref($userenvref) eq 'HASH') {
 7970:             $toolstatus = $userenvref->{$envkey};
 7971:             $inststatus = $userenvref->{'inststatus'};
 7972:         } else {
 7973:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7974:             $toolstatus = $userenv{$envkey};
 7975:             $inststatus = $userenv{'inststatus'};
 7976:         }
 7977:     }
 7978: 
 7979:     if ($toolstatus ne '') {
 7980:         if ($toolstatus) {
 7981:             $access = 1;
 7982:         } else {
 7983:             $access = 0;
 7984:         }
 7985:         return $access;
 7986:     }
 7987: 
 7988:     my ($is_adv,%domdef);
 7989:     if (ref($is_advref) eq 'HASH') {
 7990:         $is_adv = $is_advref->{'is_adv'};
 7991:     } else {
 7992:         $is_adv = &is_advanced_user($udom,$uname);
 7993:     }
 7994:     if (ref($domdefref) eq 'HASH') {
 7995:         %domdef = %{$domdefref};
 7996:     } else {
 7997:         %domdef = &get_domain_defaults($udom);
 7998:     }
 7999:     if (ref($domdef{$tool}) eq 'HASH') {
 8000:         if ($is_adv) {
 8001:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8002:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8003:                     $access = 1;
 8004:                 } else {
 8005:                     $access = 0;
 8006:                 }
 8007:                 return $access;
 8008:             }
 8009:         }
 8010:         if ($inststatus ne '') {
 8011:             my ($hasaccess,$hasnoaccess);
 8012:             foreach my $affiliation (split(/:/,$inststatus)) {
 8013:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8014:                     if ($domdef{$tool}{$affiliation}) {
 8015:                         $hasaccess = 1;
 8016:                     } else {
 8017:                         $hasnoaccess = 1;
 8018:                     }
 8019:                 }
 8020:             }
 8021:             if ($hasaccess || $hasnoaccess) {
 8022:                 if ($hasaccess) {
 8023:                     $access = 1;
 8024:                 } elsif ($hasnoaccess) {
 8025:                     $access = 0; 
 8026:                 }
 8027:                 return $access;
 8028:             }
 8029:         } else {
 8030:             if ($domdef{$tool}{'default'} ne '') {
 8031:                 if ($domdef{$tool}{'default'}) {
 8032:                     $access = 1;
 8033:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8034:                     $access = 0;
 8035:                 }
 8036:                 return $access;
 8037:             }
 8038:         }
 8039:     } else {
 8040:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8041:             $access = 1;
 8042:         } else {
 8043:             $access = 0;
 8044:         }
 8045:         return $access;
 8046:     }
 8047: }
 8048: 
 8049: sub is_course_owner {
 8050:     my ($cdom,$cnum,$udom,$uname) = @_;
 8051:     if (($udom eq '') || ($uname eq '')) {
 8052:         $udom = $env{'user.domain'};
 8053:         $uname = $env{'user.name'};
 8054:     }
 8055:     unless (($udom eq '') || ($uname eq '')) {
 8056:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8057:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8058:                 return 1;
 8059:             } else {
 8060:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 8061:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8062:                     return 1;
 8063:                 }
 8064:             }
 8065:         }
 8066:     }
 8067:     return;
 8068: }
 8069: 
 8070: sub is_advanced_user {
 8071:     my ($udom,$uname) = @_;
 8072:     if ($udom ne '' && $uname ne '') {
 8073:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8074:             if (wantarray) {
 8075:                 return ($env{'user.adv'},$env{'user.author'});
 8076:             } else {
 8077:                 return $env{'user.adv'};
 8078:             }
 8079:         }
 8080:     }
 8081:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8082:     my %allroles;
 8083:     my ($is_adv,$is_author);
 8084:     foreach my $role (keys(%roleshash)) {
 8085:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8086:         my $area = '/'.$tdomain.'/'.$trest;
 8087:         if ($sec ne '') {
 8088:             $area .= '/'.$sec;
 8089:         }
 8090:         if (($area ne '') && ($trole ne '')) {
 8091:             my $spec=$trole.'.'.$area;
 8092:             if ($trole =~ /^cr\//) {
 8093:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8094:             } elsif ($trole ne 'gr') {
 8095:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8096:             }
 8097:             if ($trole eq 'au') {
 8098:                 $is_author = 1;
 8099:             }
 8100:         }
 8101:     }
 8102:     foreach my $role (keys(%allroles)) {
 8103:         last if ($is_adv);
 8104:         foreach my $item (split(/:/,$allroles{$role})) {
 8105:             if ($item ne '') {
 8106:                 my ($privilege,$restrictions)=split(/&/,$item);
 8107:                 if ($privilege eq 'adv') {
 8108:                     $is_adv = 1;
 8109:                     last;
 8110:                 }
 8111:             }
 8112:         }
 8113:     }
 8114:     if (wantarray) {
 8115:         return ($is_adv,$is_author);
 8116:     }
 8117:     return $is_adv;
 8118: }
 8119: 
 8120: sub check_can_request {
 8121:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8122:     my $canreq = 0;
 8123:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8124:         $uname = $env{'user.name'};
 8125:         $udom = $env{'user.domain'};
 8126:     }
 8127:     my ($types,$typename) = &Apache::loncommon::course_types();
 8128:     my @options = ('approval','validate','autolimit');
 8129:     my $optregex = join('|',@options);
 8130:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8131:         my %willtrust;
 8132:         foreach my $type (@{$types}) {
 8133:             if (&usertools_access($uname,$udom,$type,undef,
 8134:                                   'requestcourses')) {
 8135:                 $canreq ++;
 8136:                 if (ref($request_domains) eq 'HASH') {
 8137:                     push(@{$request_domains->{$type}},$udom);
 8138:                 }
 8139:                 if ($dom eq $udom) {
 8140:                     $can_request->{$type} = 1;
 8141:                 }
 8142:             }
 8143:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8144:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8145:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8146:                 if (@curr > 0) {
 8147:                     foreach my $item (@curr) {
 8148:                         if (ref($request_domains) eq 'HASH') {
 8149:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8150:                             if ($otherdom ne '') {
 8151:                                 unless (exists($willtrust{$otherdom})) {
 8152:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8153:                                 }
 8154:                                 if ($willtrust{$otherdom}) {
 8155:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8156:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8157:                                             push(@{$request_domains->{$type}},$otherdom);
 8158:                                         }
 8159:                                     } else {
 8160:                                         push(@{$request_domains->{$type}},$otherdom);
 8161:                                     }
 8162:                                 }
 8163:                             }
 8164:                         }
 8165:                     }
 8166:                     unless ($dom eq $env{'user.domain'}) {
 8167:                         $canreq ++;
 8168:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8169:                             $can_request->{$type} = 1;
 8170:                         }
 8171:                     }
 8172:                 }
 8173:             }
 8174:         }
 8175:     }
 8176:     return $canreq;
 8177: }
 8178: 
 8179: # ---------------------------------------------- Custom access rule evaluation
 8180: 
 8181: sub customaccess {
 8182:     my ($priv,$uri)=@_;
 8183:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8184:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8185:     $udom = &LONCAPA::clean_domain($udom);
 8186:     $ucrs = &LONCAPA::clean_username($ucrs);
 8187:     my $access=0;
 8188:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8189: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8190: 	if ($type eq 'user') {
 8191: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8192: 		my ($tdom,$tuname)=split(m{/},$scope);
 8193: 		if ($tdom) {
 8194: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8195: 		}
 8196: 		if ($tuname) {
 8197: 		    if ($tuname ne $env{'user.name'}) { next; }
 8198: 		}
 8199: 		$access=($effect eq 'allow');
 8200: 		last;
 8201: 	    }
 8202: 	} else {
 8203: 	    if ($role) {
 8204: 		if ($role ne $urole) { next; }
 8205: 	    }
 8206: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8207: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8208: 		if ($tdom) {
 8209: 		    if ($tdom ne $udom) { next; }
 8210: 		}
 8211: 		if ($tcrs) {
 8212: 		    if ($tcrs ne $ucrs) { next; }
 8213: 		}
 8214: 		if ($tsec) {
 8215: 		    if ($tsec ne $usec) { next; }
 8216: 		}
 8217: 		$access=($effect eq 'allow');
 8218: 		last;
 8219: 	    }
 8220: 	    if ($realm eq '' && $role eq '') {
 8221: 		$access=($effect eq 'allow');
 8222: 	    }
 8223: 	}
 8224:     }
 8225:     return $access;
 8226: }
 8227: 
 8228: # ------------------------------------------------- Check for a user privilege
 8229: 
 8230: sub allowed {
 8231:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8232:     my $ver_orguri=$uri;
 8233:     $uri=&deversion($uri);
 8234:     my $orguri=$uri;
 8235:     $uri=&declutter($uri);
 8236: 
 8237:     if ($priv eq 'evb') {
 8238: # Evade communication block restrictions for specified role in a course or domain
 8239:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8240:             return $1;
 8241:         } else {
 8242:             return;
 8243:         }
 8244:     }
 8245: 
 8246:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8247: # Free bre access to adm and meta resources
 8248:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8249: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8250: 	&& ($priv eq 'bre')) {
 8251: 	return 'F';
 8252:     }
 8253: 
 8254: # Free bre access to user's own portfolio contents
 8255:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8256:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8257: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8258:         my %setters;
 8259:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8260:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8261:         if (($startblock && $endblock) || ($by_ip)) {
 8262:             return 'B';
 8263:         } else {
 8264:             return 'F';
 8265:         }
 8266:     }
 8267: 
 8268: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8269:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8270:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8271:         if (exists($env{'request.course.id'})) {
 8272:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8273:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8274:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8275:                 my $courseprivid=$env{'request.course.id'};
 8276:                 $courseprivid=~s/\_/\//;
 8277:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8278:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8279:                     return $1; 
 8280:                 } else {
 8281:                     if ($env{'request.course.sec'}) {
 8282:                         $courseprivid.='/'.$env{'request.course.sec'};
 8283:                     }
 8284:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8285:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8286:                         return $2;
 8287:                     }
 8288:                 }
 8289:             }
 8290:         }
 8291:     }
 8292: 
 8293: # Free bre to public access
 8294: 
 8295:     if ($priv eq 'bre') {
 8296:         my $copyright;
 8297:         unless ($uri =~ /ext\.tool/) {
 8298:             $copyright=&metadata($uri,'copyright');
 8299:         }
 8300: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8301:            return 'F'; 
 8302:         }
 8303:         if ($copyright eq 'priv') {
 8304:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8305: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8306: 		return '';
 8307:             }
 8308:         }
 8309:         if ($copyright eq 'domain') {
 8310:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8311: 	    unless (($env{'user.domain'} eq $1) ||
 8312:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8313: 		return '';
 8314:             }
 8315:         }
 8316:         if ($env{'request.role'}=~ /li\.\//) {
 8317:             # Library role, so allow browsing of resources in this domain.
 8318:             return 'F';
 8319:         }
 8320:         if ($copyright eq 'custom') {
 8321: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8322:         }
 8323:     }
 8324:     # Domain coordinator is trying to create a course
 8325:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8326:         # uri is the requested domain in this case.
 8327:         # comparison to 'request.role.domain' shows if the user has selected
 8328:         # a role of dc for the domain in question.
 8329:         return 'F' if ($uri eq $env{'request.role.domain'});
 8330:     }
 8331: 
 8332:     my $thisallowed='';
 8333:     my $statecond=0;
 8334:     my $courseprivid='';
 8335: 
 8336:     my $ownaccess;
 8337:     # Community Coordinator or Assistant Co-author browsing resource space.
 8338:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8339:         if ($uri eq '') {
 8340:             $ownaccess = 1;
 8341:         } else {
 8342:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8343:                 my $udom = $env{'user.domain'};
 8344:                 my $uname = $env{'user.name'};
 8345:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8346:                     $ownaccess = 1;
 8347:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8348:                     unless ($uri =~ m{\.\./}) {
 8349:                         $ownaccess = 1;
 8350:                     }
 8351:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8352:                     my $now = time;
 8353:                     if ($uri =~ m{^([^/]+)/?$}) {
 8354:                         my $adom = $1;
 8355:                         foreach my $key (keys(%env)) {
 8356:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8357:                                 my ($start,$end) = split(/\./,$env{$key});
 8358:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8359:                                     $ownaccess = 1;
 8360:                                     last;
 8361:                                 }
 8362:                             }
 8363:                         }
 8364:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8365:                         my $adom = $1;
 8366:                         my $aname = $2;
 8367:                         foreach my $role ('ca','aa') { 
 8368:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8369:                                 my ($start,$end) =
 8370:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8371:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8372:                                     $ownaccess = 1;
 8373:                                     last;
 8374:                                 }
 8375:                             }
 8376:                         }
 8377:                     }
 8378:                 }
 8379:             }
 8380:         }
 8381:     }
 8382: 
 8383: # Course
 8384: 
 8385:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8386:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8387:             $thisallowed.=$1;
 8388:         }
 8389:     }
 8390: 
 8391: # Domain
 8392: 
 8393:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8394:        =~/\Q$priv\E\&([^\:]*)/) {
 8395:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8396:             $thisallowed.=$1;
 8397:         }
 8398:     }
 8399: 
 8400: # User who is not author or co-author might still be able to edit
 8401: # resource of an author in the domain (e.g., if Domain Coordinator).
 8402:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8403:         (&allowed('mdc',$env{'request.course.id'}))) {
 8404:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8405:             $thisallowed.=$1;
 8406:         }
 8407:     }
 8408: 
 8409: # Course: uri itself is a course
 8410:     my $courseuri=$uri;
 8411:     $courseuri=~s/\_(\d)/\/$1/;
 8412:     $courseuri=~s/^([^\/])/\/$1/;
 8413: 
 8414:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8415:        =~/\Q$priv\E\&([^\:]*)/) {
 8416:         if ($priv eq 'mip') {
 8417:             my $rem = $1;
 8418:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8419:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8420:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8421:                 if ($cdom ne '') {
 8422:                     my %passwdconf = &get_passwdconf($cdom);
 8423:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8424:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8425:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8426:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8427:                                 unless (@inststatuses) {
 8428:                                     @inststatuses = ('default');
 8429:                                 }
 8430:                                 foreach my $status (@inststatuses) {
 8431:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8432:                                         $thisallowed.=$rem;
 8433:                                     }
 8434:                                 }
 8435:                             }
 8436:                         }
 8437:                     }
 8438:                 }
 8439:             }
 8440:         } else {
 8441:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8442:                 $thisallowed.=$1;
 8443:             }
 8444:         }
 8445:     }
 8446: 
 8447: # URI is an uploaded document for this course, default permissions don't matter
 8448: # not allowing 'edit' access (editupload) to uploaded course docs
 8449:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8450: 	$thisallowed='';
 8451:         my ($match)=&is_on_map($uri);
 8452:         if ($match) {
 8453:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8454:                   =~/\Q$priv\E\&([^\:]*)/) {
 8455:                 my $value = $1;
 8456:                 my $deeplinkblock;
 8457:                 unless ($nodeeplinkcheck) {
 8458:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8459:                 }
 8460:                 if ($deeplinkblock) {
 8461:                     $thisallowed='D';
 8462:                 } elsif ($noblockcheck) {
 8463:                     $thisallowed.=$value;
 8464:                 } else {
 8465:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8466:                     if (@blockers > 0) {
 8467:                         $thisallowed = 'B';
 8468:                     } else {
 8469:                         $thisallowed.=$value;
 8470:                     }
 8471:                 }
 8472:             }
 8473:         } else {
 8474:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8475:             if ($refuri) {
 8476:                 if ($refuri =~ m|^/adm/|) {
 8477:                     $thisallowed='F';
 8478:                 } else {
 8479:                     $refuri=&declutter($refuri);
 8480:                     my ($match) = &is_on_map($refuri);
 8481:                     if ($match) {
 8482:                         my $deeplinkblock;
 8483:                         unless ($nodeeplinkcheck) {
 8484:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8485:                         }
 8486:                         if ($deeplinkblock) {
 8487:                             $thisallowed='D';
 8488:                         } elsif ($noblockcheck) {
 8489:                             $thisallowed='F';
 8490:                         } else {
 8491:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8492:                             if (@blockers > 0) {
 8493:                                 $thisallowed = 'B';
 8494:                             } else {
 8495:                                 $thisallowed='F';
 8496:                             }
 8497:                         }
 8498:                     }
 8499:                 }
 8500:             }
 8501:         }
 8502:     }
 8503: 
 8504:     if ($priv eq 'bre'
 8505: 	&& $thisallowed ne 'F' 
 8506: 	&& $thisallowed ne '2'
 8507: 	&& &is_portfolio_url($uri)) {
 8508: 	$thisallowed = &portfolio_access($uri,$clientip);
 8509:     }
 8510: 
 8511: # Full access at system, domain or course-wide level? Exit.
 8512:     if ($thisallowed=~/F/) {
 8513: 	return 'F';
 8514:     }
 8515: 
 8516: # If this is generating or modifying users, exit with special codes
 8517: 
 8518:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8519: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8520: 	    my ($audom,$auname)=split('/',$uri);
 8521: # no author name given, so this just checks on the general right to make a co-author in this domain
 8522: 	    unless ($auname) { return $thisallowed; }
 8523: # an author name is given, so we are about to actually make a co-author for a certain account
 8524: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8525: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8526: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8527: 	}
 8528: 	return $thisallowed;
 8529:     }
 8530: #
 8531: # Gathered so far: system, domain and course wide privileges
 8532: #
 8533: # Course: See if uri or referer is an individual resource that is part of 
 8534: # the course
 8535: 
 8536:     if ($env{'request.course.id'}) {
 8537: 
 8538: # If this is modifying password (internal auth) domains must match for user and user's role.
 8539: 
 8540:         if ($priv eq 'mip') {
 8541:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8542:                 return $thisallowed;
 8543:             } else {
 8544:                 return '';
 8545:             }
 8546:         }
 8547: 
 8548:        $courseprivid=$env{'request.course.id'};
 8549:        if ($env{'request.course.sec'}) {
 8550:           $courseprivid.='/'.$env{'request.course.sec'};
 8551:        }
 8552:        $courseprivid=~s/\_/\//;
 8553:        my $checkreferer=1;
 8554:        my ($match,$cond)=&is_on_map($uri);
 8555:        if ($match) {
 8556:            $statecond=$cond;
 8557:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8558:                =~/\Q$priv\E\&([^\:]*)/) {
 8559:                my $value = $1;
 8560:                if ($priv eq 'bre') {
 8561:                    my $deeplinkblock;
 8562:                    unless ($nodeeplinkcheck) {
 8563:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8564:                    }
 8565:                    if ($deeplinkblock) {
 8566:                        $thisallowed = 'D';
 8567:                    } elsif ($noblockcheck) {
 8568:                        $thisallowed.=$value;
 8569:                    } else {
 8570:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8571:                        if (@blockers > 0) {
 8572:                            $thisallowed = 'B';
 8573:                        } else {
 8574:                            $thisallowed.=$value;
 8575:                        }
 8576:                    }
 8577:                } else {
 8578:                    $thisallowed.=$value;
 8579:                }
 8580:                $checkreferer=0;
 8581:            }
 8582:        }
 8583: 
 8584:        if ($checkreferer) {
 8585: 	  my $refuri=$env{'httpref.'.$orguri};
 8586:             unless ($refuri) {
 8587:                 foreach my $key (keys(%env)) {
 8588: 		    if ($key=~/^httpref\..*\*/) {
 8589: 			my $pattern=$key;
 8590:                         $pattern=~s/^httpref\.\/res\///;
 8591:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8592:                         $pattern=~s/\//\\\//g;
 8593:                         if ($orguri=~/$pattern/) {
 8594: 			    $refuri=$env{$key};
 8595:                         }
 8596:                     }
 8597:                 }
 8598:             }
 8599: 
 8600:          if ($refuri) { 
 8601: 	  $refuri=&declutter($refuri);
 8602:           my ($match,$cond)=&is_on_map($refuri);
 8603:             if ($match) {
 8604:               my $refstatecond=$cond;
 8605:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8606:                   =~/\Q$priv\E\&([^\:]*)/) {
 8607:                   my $value = $1;
 8608:                   if ($priv eq 'bre') {
 8609:                       my $deeplinkblock;
 8610:                       unless ($nodeeplinkcheck) {
 8611:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8612:                       }
 8613:                       if ($deeplinkblock) {
 8614:                           $thisallowed = 'D';
 8615:                       } elsif ($noblockcheck) {
 8616:                           $thisallowed.=$value;
 8617:                       } else {
 8618:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8619:                           if (@blockers > 0) {
 8620:                               $thisallowed = 'B';
 8621:                           } else {
 8622:                               $thisallowed.=$value;
 8623:                           }
 8624:                       }
 8625:                   } else {
 8626:                       $thisallowed.=$value;
 8627:                   }
 8628:                   $uri=$refuri;
 8629:                   $statecond=$refstatecond;
 8630:               }
 8631:           }
 8632:         }
 8633:        }
 8634:    }
 8635: 
 8636: #
 8637: # Gathered now: all privileges that could apply, and condition number
 8638: # 
 8639: #
 8640: # Full or no access?
 8641: #
 8642: 
 8643:     if ($thisallowed=~/F/) {
 8644: 	return 'F';
 8645:     }
 8646: 
 8647:     unless ($thisallowed) {
 8648:         return '';
 8649:     }
 8650: 
 8651: # Restrictions exist, deal with them
 8652: #
 8653: #   C:according to course preferences
 8654: #   R:according to resource settings
 8655: #   L:unless locked
 8656: #   X:according to user session state
 8657: #
 8658: 
 8659: # Possibly locked functionality, check all courses
 8660: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8661: # Locks might take effect only after 10 minutes cache expiration for other
 8662: # courses, and 2 minutes for current course, in which user has st or ta role
 8663: # which is neither expired nor a future role (unless current course).
 8664: 
 8665:     my ($needlockcheck,$now,$crsonly);
 8666:     if ($thisallowed=~/L/) {
 8667:         $now = time;
 8668:         if ($priv eq 'bre') {
 8669:             if ($uri ne '') {
 8670:                 if ($orguri =~ m{^/+res/}) {
 8671:                     if ($uri =~ m{^lib/templates/}) {
 8672:                         if ($env{'request.course.id'}) {
 8673:                             $crsonly = 1;
 8674:                             $needlockcheck = 1;
 8675:                         }
 8676:                     } else {
 8677:                         $needlockcheck = 1;
 8678:                     }
 8679:                 } elsif ($env{'request.course.id'}) {
 8680:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8681:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8682:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8683:                         $crsonly = 1;
 8684:                     }
 8685:                     $needlockcheck = 1;
 8686:                 }
 8687:             }
 8688:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8689:             $needlockcheck = 1;
 8690:         }
 8691:     }
 8692:     if ($needlockcheck) {
 8693:         foreach my $envkey (keys(%env)) {
 8694:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8695:                my $courseid=$2;
 8696:                my $roleid=$1.'.'.$2;
 8697:                $courseid=~s/^\///;
 8698:                unless ($env{'request.role'} eq $roleid) {
 8699:                    my ($start,$end) = split(/\./,$env{$envkey});
 8700:                    next unless (($now >= $start) && (!$end || $end > $now));
 8701:                }
 8702:                my $expiretime=600;
 8703:                if ($env{'request.role'} eq $roleid) {
 8704: 		  $expiretime=120;
 8705:                }
 8706: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8707:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8708:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8709: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8710:                }
 8711:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8712:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8713: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8714:                        &log($env{'user.domain'},$env{'user.name'},
 8715:                             $env{'user.home'},
 8716:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8717:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8718:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8719: 		       return '';
 8720:                    }
 8721:                }
 8722:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8723:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8724: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8725:                        &log($env{'user.domain'},$env{'user.name'},
 8726:                             $env{'user.home'},
 8727:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8728:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8729:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8730: 		       return '';
 8731:                    }
 8732:                }
 8733: 	   }
 8734:        }
 8735:     }
 8736: 
 8737: #
 8738: # Rest of the restrictions depend on selected course
 8739: #
 8740: 
 8741:     unless ($env{'request.course.id'}) {
 8742: 	if ($thisallowed eq 'A') {
 8743: 	    return 'A';
 8744:         } elsif ($thisallowed eq 'B') {
 8745:             return 'B';
 8746: 	} else {
 8747: 	    return '1';
 8748: 	}
 8749:     }
 8750: 
 8751: #
 8752: # Now user is definitely in a course
 8753: #
 8754: 
 8755: 
 8756: # Course preferences
 8757: 
 8758:    if ($thisallowed=~/C/) {
 8759:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8760:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8761:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8762: 	   =~/\Q$rolecode\E/) {
 8763: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8764: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8765: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8766: 			$env{'request.course.id'});
 8767: 	   }
 8768:            return '';
 8769:        }
 8770: 
 8771:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8772: 	   =~/\Q$unamedom\E/) {
 8773: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8774: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8775: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8776: 			$env{'request.course.id'});
 8777: 	   }
 8778:            return '';
 8779:        }
 8780:    }
 8781: 
 8782: # Resource preferences
 8783: 
 8784:    if ($thisallowed=~/R/) {
 8785:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8786:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8787: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8788: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8789: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8790: 	   }
 8791: 	   return '';
 8792:        }
 8793:    }
 8794: 
 8795: # Restricted for deeplinked session?
 8796: 
 8797:     if ($env{'request.deeplink.login'}) {
 8798:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8799:             if (!$symb) { $symb=&symbread($uri,1); }
 8800:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8801:                 return '';
 8802:             }
 8803:         }
 8804:     }
 8805: 
 8806: # Restricted by state or randomout?
 8807: 
 8808:    if ($thisallowed=~/X/) {
 8809:       if ($env{'acc.randomout'}) {
 8810: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8811:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8812:             return ''; 
 8813:          }
 8814:       }
 8815:       if (&condval($statecond)) {
 8816: 	 return '2';
 8817:       } else {
 8818:          return '';
 8819:       }
 8820:    }
 8821: 
 8822:     if ($thisallowed eq 'A') {
 8823: 	return 'A';
 8824:     } elsif ($thisallowed eq 'B') {
 8825:         return 'B';
 8826:     } elsif ($thisallowed eq 'D') {
 8827:         return 'D';
 8828:     }
 8829:    return 'F';
 8830: }
 8831: 
 8832: # ------------------------------------------- Check construction space access
 8833: 
 8834: sub constructaccess {
 8835:     my ($url,$setpriv)=@_;
 8836: 
 8837: # We do not allow editing of previous versions of files
 8838:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8839: 
 8840: # Get username and domain from URL
 8841:     my ($ownername,$ownerdomain,$ownerhome);
 8842: 
 8843:     ($ownerdomain,$ownername) =
 8844:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8845: 
 8846: # The URL does not really point to any authorspace, forget it
 8847:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8848: 
 8849: # Now we need to see if the user has access to the authorspace of
 8850: # $ownername at $ownerdomain
 8851: 
 8852:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8853: # Real author for this?
 8854:        $ownerhome = $env{'user.home'};
 8855:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8856:           return ($ownername,$ownerdomain,$ownerhome);
 8857:        }
 8858:     } else {
 8859: # Co-author for this?
 8860:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8861:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8862:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8863:             return ($ownername,$ownerdomain,$ownerhome);
 8864:         }
 8865:         if ($env{'request.course.id'}) {
 8866:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8867:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8868:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8869:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8870:                     return ($ownername,$ownerdomain,$ownerhome);
 8871:                 }
 8872:             }
 8873:         }
 8874:     }
 8875: 
 8876: # We don't have any access right now. If we are not possibly going to do anything about this,
 8877: # we might as well leave
 8878:    unless ($setpriv) { return ''; }
 8879: 
 8880: # Backdoor access?
 8881:     my $allowed=&allowed('eco',$ownerdomain);
 8882: # Nope
 8883:     unless ($allowed) { return ''; }
 8884: # Looks like we may have access, but could be locked by the owner of the construction space
 8885:     if ($allowed eq 'U') {
 8886:         my %blocked=&get('environment',['domcoord.author'],
 8887:                          $ownerdomain,$ownername);
 8888: # Is blocked by owner
 8889:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8890:     }
 8891:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8892: # Grant temporary access
 8893:         my $then=$env{'user.login.time'};
 8894:         my $update=$env{'user.update.time'};
 8895:         if (!$update) { $update = $then; }
 8896:         my $refresh=$env{'user.refresh.time'};
 8897:         if (!$refresh) { $refresh = $update; }
 8898:         my $now = time;
 8899:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8900:                            $now,'ca','constructaccess');
 8901:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8902:         return($ownername,$ownerdomain,$ownerhome);
 8903:     }
 8904: # No business here
 8905:     return '';
 8906: }
 8907: 
 8908: # ----------------------------------------------------------- Content Blocking
 8909: 
 8910: {
 8911: # Caches for faster Course Contents display where content blocking
 8912: # is in operation (i.e., interval param set) for timed quiz.
 8913: #
 8914: # User for whom data are being temporarily cached.
 8915: my $cacheduser='';
 8916: # Course for which data are being temporarily cached.
 8917: my $cachedcid='';
 8918: # Cached blockers for this user (a hash of blocking items). 
 8919: my %cachedblockers=();
 8920: # When the data were last cached.
 8921: my $cachedlast='';
 8922: 
 8923: sub load_all_blockers {
 8924:     my ($uname,$udom)=@_;
 8925:     if (($uname ne '') && ($udom ne '')) { 
 8926:         if (($cacheduser eq $uname.':'.$udom) &&
 8927:             ($cachedcid eq $env{'request.course.id'}) &&
 8928:             (abs($cachedlast-time)<5)) {
 8929:             return;
 8930:         }
 8931:     }
 8932:     $cachedlast=time;
 8933:     $cacheduser=$uname.':'.$udom;
 8934:     $cachedcid=$env{'request.course.id'};
 8935:     %cachedblockers = &get_commblock_resources();
 8936:     return;
 8937: }
 8938: 
 8939: sub get_comm_blocks {
 8940:     my ($cdom,$cnum) = @_;
 8941:     if ($cdom eq '' || $cnum eq '') {
 8942:         return unless ($env{'request.course.id'});
 8943:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8944:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8945:     }
 8946:     my %commblocks;
 8947:     my $hashid=$cdom.'_'.$cnum;
 8948:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8949:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8950:         %commblocks = %{$blocksref};
 8951:     } else {
 8952:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8953:         my $cachetime = 600;
 8954:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8955:     }
 8956:     return %commblocks;
 8957: }
 8958: 
 8959: sub get_commblock_resources {
 8960:     my ($blocks) = @_;
 8961:     my %blockers = ();
 8962:     return %blockers unless ($env{'request.course.id'});
 8963:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8964:     if ($env{'request.course.sec'}) {
 8965:         $courseurl .= '/'.$env{'request.course.sec'};
 8966:     }
 8967:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8968:     my %commblocks;
 8969:     if (ref($blocks) eq 'HASH') {
 8970:         %commblocks = %{$blocks};
 8971:     } else {
 8972:         %commblocks = &get_comm_blocks();
 8973:     }
 8974:     return %blockers unless (keys(%commblocks) > 0); 
 8975:     my $navmap = Apache::lonnavmaps::navmap->new();
 8976:     return %blockers unless (ref($navmap));
 8977:     my $now = time;
 8978:     foreach my $block (keys(%commblocks)) {
 8979:         if ($block =~ /^(\d+)____(\d+)$/) {
 8980:             my ($start,$end) = ($1,$2);
 8981:             if ($start <= $now && $end >= $now) {
 8982:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8983:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8984:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8985:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8986:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8987:                             }
 8988:                         }
 8989:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8990:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8991:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8992:                             }
 8993:                         }
 8994:                     }
 8995:                 }
 8996:             }
 8997:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8998:             my $item = $1;
 8999:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9000:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9001:                     my (@interval,$mapname);
 9002:                     my $type = 'map';
 9003:                     if ($item eq 'course') {
 9004:                         $type = 'course';
 9005:                         @interval=&EXT("resource.0.interval");
 9006:                     } else {
 9007:                         if ($item =~ /___\d+___/) {
 9008:                             $type = 'resource';
 9009:                             @interval=&EXT("resource.0.interval",$item);
 9010:                         } else {
 9011:                             $mapname = &deversion($item);
 9012:                             if (ref($navmap)) {
 9013:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9014:                                 @interval = ($timelimit,'map');
 9015:                             }
 9016:                         }
 9017:                     }
 9018:                     if ($interval[0] =~ /^(\d+)/) {
 9019:                         my $timelimit = $1; 
 9020:                         my $first_access;
 9021:                         if ($type eq 'resource') {
 9022:                             $first_access=&get_first_access($interval[1],$item);
 9023:                         } elsif ($type eq 'map') {
 9024:                             $first_access=&get_first_access($interval[1],undef,$item);
 9025:                         } else {
 9026:                             $first_access=&get_first_access($interval[1]);
 9027:                         }
 9028:                         if ($first_access) {
 9029:                             my $timesup = $first_access+$timelimit;
 9030:                             if ($timesup > $now) {
 9031:                                 my $activeblock;
 9032:                                 if ($type eq 'resource') {
 9033:                                     if (ref($navmap)) {
 9034:                                         my $res = $navmap->getBySymb($item);
 9035:                                         if ($res->answerable()) {
 9036:                                             $activeblock = 1;
 9037:                                         }
 9038:                                     }
 9039:                                 } elsif ($type eq 'map') {
 9040:                                     my $mapsymb = &symbread($mapname,1);
 9041:                                     if (($mapsymb) && (ref($navmap))) {
 9042:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9043:                                         if (ref($mapres)) {
 9044:                                             my $first = $mapres->map_start();
 9045:                                             my $finish = $mapres->map_finish();
 9046:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9047:                                             if (ref($it)) {
 9048:                                                 my $res;
 9049:                                                 while ($res = $it->next(undef,1)) {
 9050:                                                     next unless (ref($res));
 9051:                                                     my $symb = $res->symb();
 9052:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9053:                                                     @interval=&EXT("resource.0.interval",$symb);
 9054:                                                     if ($interval[1] eq 'map') {
 9055:                                                         if ($res->answerable()) {
 9056:                                                             $activeblock = 1;
 9057:                                                             last;
 9058:                                                         }
 9059:                                                     }
 9060:                                                 }
 9061:                                             }
 9062:                                         }
 9063:                                     }
 9064:                                 }
 9065:                                 if ($activeblock) {
 9066:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9067:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9068:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9069:                                          }
 9070:                                     }
 9071:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9072:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9073:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9074:                                         }
 9075:                                     }
 9076:                                 }
 9077:                             }
 9078:                         }
 9079:                     }
 9080:                 }
 9081:             }
 9082:         }
 9083:     }
 9084:     return %blockers;
 9085: }
 9086: 
 9087: sub has_comm_blocking {
 9088:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9089:     my @blockers;
 9090:     return unless ($env{'request.course.id'});
 9091:     return unless ($priv eq 'bre');
 9092:     return if ($env{'request.state'} eq 'construct');
 9093:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9094:     if ($env{'request.course.sec'}) {
 9095:         $courseurl .= '/'.$env{'request.course.sec'};
 9096:     }
 9097:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9098:     my %blockinfo;
 9099:     if (ref($blocks) eq 'HASH') {
 9100:         %blockinfo = &get_commblock_resources($blocks);
 9101:     } else {
 9102:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9103:         %blockinfo = %cachedblockers;
 9104:     }
 9105:     return unless (keys(%blockinfo) > 0);
 9106:     my (%possibles,@symbs);
 9107:     if (!$symb) {
 9108:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9109:     }
 9110:     if ($symb) {
 9111:         @symbs = ($symb);
 9112:     } elsif (keys(%possibles)) { 
 9113:         @symbs = keys(%possibles);
 9114:     }
 9115:     my $noblock;
 9116:     foreach my $symb (@symbs) {
 9117:         last if ($noblock);
 9118:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9119:         foreach my $block (keys(%blockinfo)) {
 9120:             if ($block =~ /^firstaccess____(.+)$/) {
 9121:                 my $item = $1;
 9122:                 unless ($blocked) {
 9123:                     if (($item eq $map) || ($item eq $symb)) {
 9124:                         $noblock = 1;
 9125:                         last;
 9126:                     }
 9127:                 }
 9128:             }
 9129:             if (ref($blockinfo{$block}) eq 'HASH') {
 9130:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9131:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9132:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9133:                             push(@blockers,$block);
 9134:                         }
 9135:                     }
 9136:                 }
 9137:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9138:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9139:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9140:                             push(@blockers,$block);
 9141:                         }
 9142:                     }
 9143:                 }
 9144:             }
 9145:         }
 9146:     }
 9147:     unless ($noblock) { 
 9148:         return @blockers;
 9149:     }
 9150:     return;
 9151: }
 9152: }
 9153: 
 9154: sub deeplink_check {
 9155:     my ($priv,$symb,$uri) = @_;
 9156:     return unless ($env{'request.course.id'});
 9157:     return unless ($priv eq 'bre');
 9158:     return if ($env{'request.state'} eq 'construct');
 9159:     return if ($env{'request.role.adv'});
 9160:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9161:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9162:     my (%possibles,@symbs);
 9163:     if (!$symb) {
 9164:         $symb = &symbread($uri,1,1,1,\%possibles);
 9165:     }
 9166:     if ($symb) {
 9167:         @symbs = ($symb);
 9168:     } elsif (keys(%possibles)) {
 9169:         @symbs = keys(%possibles);
 9170:     }
 9171: 
 9172:     my ($deeplink_symb,$allow);
 9173:     if ($env{'request.deeplink.login'}) {
 9174:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9175:     }
 9176:     foreach my $symb (@symbs) {
 9177:         last if ($allow);
 9178:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9179:         if ($deeplink eq '') {
 9180:             $allow = 1;
 9181:         } else {
 9182:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9183:             if ($state ne 'only') {
 9184:                 $allow = 1;
 9185:             } else {
 9186:                 my $check_deeplink_entry;
 9187:                 if ($protect ne 'none') {
 9188:                     my ($acctype,$item) = split(/:/,$protect);
 9189:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9190:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9191:                             $check_deeplink_entry = 1
 9192:                         }
 9193:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9194:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9195:                             $check_deeplink_entry = 1;
 9196:                         }
 9197:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9198:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9199:                             $check_deeplink_entry = 1;
 9200:                         }
 9201:                     }
 9202:                 }
 9203:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9204:                     if ($scope eq 'res') {
 9205:                         if ($symb eq $deeplink_symb) {
 9206:                             $allow = 1;
 9207:                         }
 9208:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9209:                         my ($map_from_symb,$map_from_login);
 9210:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9211:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9212:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9213:                         } else {
 9214:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9215:                         }
 9216:                         if (($map_from_symb) && ($map_from_login)) {
 9217:                             if ($map_from_symb eq $map_from_login) {
 9218:                                 $allow = 1;
 9219:                             } elsif ($scope eq 'rec') {
 9220:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9221:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9222:                                     $allow = 1;
 9223:                                 }
 9224:                             }
 9225:                         }
 9226:                     }
 9227:                 }
 9228:             }
 9229:         }
 9230:     }
 9231:     return if ($allow);
 9232:     return 1;
 9233: }
 9234: 
 9235: # -------------------------------- Deversion and split uri into path an filename   
 9236: 
 9237: #
 9238: #   Removes the version from a URI and
 9239: #   splits it in to its filename and path to the filename.
 9240: #   Seems like File::Basename could have done this more clearly.
 9241: #   Parameters:
 9242: #      $uri   - input URI
 9243: #   Returns:
 9244: #     Two element list consisting of 
 9245: #     $pathname  - the URI up to and excluding the trailing /
 9246: #     $filename  - The part of the URI following the last /
 9247: #  NOTE:
 9248: #    Another realization of this is simply:
 9249: #    use File::Basename;
 9250: #    ...
 9251: #    $uri = shift;
 9252: #    $filename = basename($uri);
 9253: #    $path     = dirname($uri);
 9254: #    return ($filename, $path);
 9255: #
 9256: #     The implementation below is probably faster however.
 9257: #
 9258: sub split_uri_for_cond {
 9259:     my $uri=&deversion(&declutter(shift));
 9260:     my @uriparts=split(/\//,$uri);
 9261:     my $filename=pop(@uriparts);
 9262:     my $pathname=join('/',@uriparts);
 9263:     return ($pathname,$filename);
 9264: }
 9265: # --------------------------------------------------- Is a resource on the map?
 9266: 
 9267: sub is_on_map {
 9268:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9269:     #Trying to find the conditional for the file
 9270:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9271: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9272:     if ($match) {
 9273: 	return (1,$1);
 9274:     } else {
 9275: 	return (0,0);
 9276:     }
 9277: }
 9278: 
 9279: # --------------------------------------------------------- Get symb from alias
 9280: 
 9281: sub get_symb_from_alias {
 9282:     my $symb=shift;
 9283:     my ($map,$resid,$url)=&decode_symb($symb);
 9284: # Already is a symb
 9285:     if ($url) { return $symb; }
 9286: # Must be an alias
 9287:     my $aliassymb='';
 9288:     my %bighash;
 9289:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9290:                             &GDBM_READER(),0640)) {
 9291:         my $rid=$bighash{'mapalias_'.$symb};
 9292: 	if ($rid) {
 9293: 	    my ($mapid,$resid)=split(/\./,$rid);
 9294: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9295: 				    $resid,$bighash{'src_'.$rid});
 9296: 	}
 9297:         untie %bighash;
 9298:     }
 9299:     return $aliassymb;
 9300: }
 9301: 
 9302: # ----------------------------------------------------------------- Define Role
 9303: 
 9304: sub definerole {
 9305:   if (allowed('mcr','/')) {
 9306:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9307:     foreach my $role (split(':',$sysrole)) {
 9308: 	my ($crole,$cqual)=split(/\&/,$role);
 9309:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9310:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9311: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9312:                return "refused:s:$crole&$cqual"; 
 9313:             }
 9314:         }
 9315:     }
 9316:     foreach my $role (split(':',$domrole)) {
 9317: 	my ($crole,$cqual)=split(/\&/,$role);
 9318:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9319:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9320: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9321:                return "refused:d:$crole&$cqual"; 
 9322:             }
 9323:         }
 9324:     }
 9325:     foreach my $role (split(':',$courole)) {
 9326: 	my ($crole,$cqual)=split(/\&/,$role);
 9327:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9328:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9329: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9330:                return "refused:c:$crole&$cqual"; 
 9331:             }
 9332:         }
 9333:     }
 9334:     my $uhome;
 9335:     if (($uname ne '') && ($udom ne '')) {
 9336:         $uhome = &homeserver($uname,$udom);
 9337:         return $uhome if ($uhome eq 'no_host');
 9338:     } else {
 9339:         $uname = $env{'user.name'};
 9340:         $udom = $env{'user.domain'};
 9341:         $uhome = $env{'user.home'};
 9342:     }
 9343:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9344:                 "$udom:$uname:rolesdef_$rolename=".
 9345:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9346:     return reply($command,$uhome);
 9347:   } else {
 9348:     return 'refused';
 9349:   }
 9350: }
 9351: 
 9352: # ---------------- Make a metadata query against the network of library servers
 9353: 
 9354: sub metadata_query {
 9355:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9356:     my %rhash;
 9357:     my %libserv = &all_library();
 9358:     my @server_list = (defined($server_array) ? @$server_array
 9359:                                               : keys(%libserv) );
 9360:     for my $server (@server_list) {
 9361:         my $domains = ''; 
 9362:         if (ref($domains_hash) eq 'HASH') {
 9363:             $domains = $domains_hash->{$server}; 
 9364:         }
 9365: 	unless ($custom or $customshow) {
 9366: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9367: 	    $rhash{$server}=$reply;
 9368: 	}
 9369: 	else {
 9370: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9371: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9372: 			     $server);
 9373: 	    $rhash{$server}=$reply;
 9374: 	}
 9375:     }
 9376:     return \%rhash;
 9377: }
 9378: 
 9379: # ----------------------------------------- Send log queries and wait for reply
 9380: 
 9381: sub log_query {
 9382:     my ($uname,$udom,$query,%filters)=@_;
 9383:     my $uhome=&homeserver($uname,$udom);
 9384:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9385:     my $uhost=&hostname($uhome);
 9386:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9387:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9388:                        $uhome);
 9389:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9390:     return get_query_reply($queryid);
 9391: }
 9392: 
 9393: # -------------------------- Update MySQL table for portfolio file
 9394: 
 9395: sub update_portfolio_table {
 9396:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9397:     if ($group ne '') {
 9398:         $file_name =~s /^\Q$group\E//;
 9399:     }
 9400:     my $homeserver = &homeserver($uname,$udom);
 9401:     my $queryid=
 9402:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9403:                ':'.&escape($file_name).':'.$action,$homeserver);
 9404:     my $reply = &get_query_reply($queryid);
 9405:     return $reply;
 9406: }
 9407: 
 9408: # -------------------------- Update MySQL allusers table
 9409: 
 9410: sub update_allusers_table {
 9411:     my ($uname,$udom,$names) = @_;
 9412:     my $homeserver = &homeserver($uname,$udom);
 9413:     my $queryid=
 9414:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9415:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9416:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9417:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9418:                'generation='.&escape($names->{'generation'}).'%%'.
 9419:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9420:                'id='.&escape($names->{'id'}),$homeserver);
 9421:     return;
 9422: }
 9423: 
 9424: # ------- Request retrieval of institutional classlists for course(s)
 9425: 
 9426: sub fetch_enrollment_query {
 9427:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9428:     my ($homeserver,$sleep,$loopmax);
 9429:     my $maxtries = 1;
 9430:     if ($context eq 'automated') {
 9431:         $homeserver = $perlvar{'lonHostID'};
 9432:         $sleep = 2;
 9433:         $loopmax = 100;
 9434:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9435:     } else {
 9436:         $homeserver = &homeserver($cnum,$dom);
 9437:     }
 9438:     my $host=&hostname($homeserver);
 9439:     my $cmd = '';
 9440:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9441:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9442:     }
 9443:     $cmd =~ s/%%$//;
 9444:     $cmd = &escape($cmd);
 9445:     my $query = 'fetchenrollment';
 9446:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9447:     unless ($queryid=~/^\Q$host\E\_/) { 
 9448:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9449:         return 'error: '.$queryid;
 9450:     }
 9451:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9452:     my $tries = 1;
 9453:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9454:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9455:         $tries ++;
 9456:     }
 9457:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9458:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9459:     } else {
 9460:         my @responses = split(/:/,$reply);
 9461:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9462:             foreach my $line (@responses) {
 9463:                 my ($key,$value) = split(/=/,$line,2);
 9464:                 $$replyref{$key} = $value;
 9465:             }
 9466:         } else {
 9467:             my $pathname = LONCAPA::tempdir();
 9468:             foreach my $line (@responses) {
 9469:                 my ($key,$value) = split(/=/,$line);
 9470:                 $$replyref{$key} = $value;
 9471:                 if ($value > 0) {
 9472:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9473:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9474:                         my $destname = $pathname.'/'.$filename;
 9475:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9476:                         if ($xml_classlist =~ /^error/) {
 9477:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9478:                         } else {
 9479:                             if ( open(FILE,">",$destname) ) {
 9480:                                 print FILE &unescape($xml_classlist);
 9481:                                 close(FILE);
 9482:                             } else {
 9483:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9484:                             }
 9485:                         }
 9486:                     }
 9487:                 }
 9488:             }
 9489:         }
 9490:         return 'ok';
 9491:     }
 9492:     return 'error';
 9493: }
 9494: 
 9495: sub get_query_reply {
 9496:     my ($queryid,$sleep,$loopmax) = @_;
 9497:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9498:         $sleep = 0.2;
 9499:     }
 9500:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9501:         $loopmax = 100;
 9502:     }
 9503:     my $replyfile=LONCAPA::tempdir().$queryid;
 9504:     my $reply='';
 9505:     for (1..$loopmax) {
 9506: 	sleep($sleep);
 9507:         if (-e $replyfile.'.end') {
 9508: 	    if (open(my $fh,"<",$replyfile)) {
 9509: 		$reply = join('',<$fh>);
 9510: 		close($fh);
 9511: 	   } else { return 'error: reply_file_error'; }
 9512:            return &unescape($reply);
 9513: 	}
 9514:     }
 9515:     return 'timeout:'.$queryid;
 9516: }
 9517: 
 9518: sub courselog_query {
 9519: #
 9520: # possible filters:
 9521: # url: url or symb
 9522: # username
 9523: # domain
 9524: # action: view, submit, grade
 9525: # start: timestamp
 9526: # end: timestamp
 9527: #
 9528:     my (%filters)=@_;
 9529:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9530:     if ($filters{'url'}) {
 9531: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9532:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9533:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9534:     }
 9535:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9536:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9537:     return &log_query($cname,$cdom,'courselog',%filters);
 9538: }
 9539: 
 9540: sub userlog_query {
 9541: #
 9542: # possible filters:
 9543: # action: log check role
 9544: # start: timestamp
 9545: # end: timestamp
 9546: #
 9547:     my ($uname,$udom,%filters)=@_;
 9548:     return &log_query($uname,$udom,'userlog',%filters);
 9549: }
 9550: 
 9551: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9552: 
 9553: sub auto_run {
 9554:     my ($cnum,$cdom) = @_;
 9555:     my $response = 0;
 9556:     my $settings;
 9557:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9558:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9559:         $settings = $domconfig{'autoenroll'};
 9560:         if ($settings->{'run'} eq '1') {
 9561:             $response = 1;
 9562:         }
 9563:     } else {
 9564:         my $homeserver;
 9565:         if (&is_course($cdom,$cnum)) {
 9566:             $homeserver = &homeserver($cnum,$cdom);
 9567:         } else {
 9568:             $homeserver = &domain($cdom,'primary');
 9569:         }
 9570:         if ($homeserver ne 'no_host') {
 9571:             $response = &reply('autorun:'.$cdom,$homeserver);
 9572:         }
 9573:     }
 9574:     return $response;
 9575: }
 9576: 
 9577: sub auto_get_sections {
 9578:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9579:     my $homeserver;
 9580:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9581:         $homeserver = &homeserver($cnum,$cdom);
 9582:     }
 9583:     if (!defined($homeserver)) { 
 9584:         if ($cdom =~ /^$match_domain$/) {
 9585:             $homeserver = &domain($cdom,'primary');
 9586:         }
 9587:     }
 9588:     my @secs;
 9589:     if (defined($homeserver)) {
 9590:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9591:         unless ($response eq 'refused') {
 9592:             @secs = split(/:/,$response);
 9593:         }
 9594:     }
 9595:     return @secs;
 9596: }
 9597: 
 9598: sub auto_new_course {
 9599:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9600:     my $homeserver = &homeserver($cnum,$cdom);
 9601:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9602:     return $response;
 9603: }
 9604: 
 9605: sub auto_validate_courseID {
 9606:     my ($cnum,$cdom,$inst_course_id) = @_;
 9607:     my $homeserver = &homeserver($cnum,$cdom);
 9608:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9609:     return $response;
 9610: }
 9611: 
 9612: sub auto_validate_instcode {
 9613:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9614:     my ($homeserver,$response);
 9615:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9616:         $homeserver = &homeserver($cnum,$cdom);
 9617:     }
 9618:     if (!defined($homeserver)) {
 9619:         if ($cdom =~ /^$match_domain$/) {
 9620:             $homeserver = &domain($cdom,'primary');
 9621:         }
 9622:     }
 9623:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9624:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9625:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9626:     return ($outcome,$description,$defaultcredits);
 9627: }
 9628: 
 9629: sub auto_validate_inst_crosslist {
 9630:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9631:     my ($homeserver,$response);
 9632:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9633:         $homeserver = &homeserver($cnum,$cdom);
 9634:     }
 9635:     if (!defined($homeserver)) {
 9636:         if ($cdom =~ /^$match_domain$/) {
 9637:             $homeserver = &domain($cdom,'primary');
 9638:         }
 9639:     }
 9640:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9641:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9642:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9643:                          &escape($coowner),$homeserver);
 9644:     }
 9645:     return $response;
 9646: }
 9647: 
 9648: sub auto_create_password {
 9649:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9650:     my ($homeserver,$response);
 9651:     my $create_passwd = 0;
 9652:     my $authchk = '';
 9653:     if ($udom =~ /^$match_domain$/) {
 9654:         $homeserver = &domain($udom,'primary');
 9655:     }
 9656:     if ($homeserver eq '') {
 9657:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9658:             $homeserver = &homeserver($cnum,$cdom);
 9659:         }
 9660:     }
 9661:     if ($homeserver eq '') {
 9662:         $authchk = 'nodomain';
 9663:     } else {
 9664:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9665:         if ($response eq 'refused') {
 9666:             $authchk = 'refused';
 9667:         } else {
 9668:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9669:         }
 9670:     }
 9671:     return ($authparam,$create_passwd,$authchk);
 9672: }
 9673: 
 9674: sub auto_photo_permission {
 9675:     my ($cnum,$cdom,$students) = @_;
 9676:     my $homeserver = &homeserver($cnum,$cdom);
 9677:     my ($outcome,$perm_reqd,$conditions) = 
 9678: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9679:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9680: 	return (undef,undef);
 9681:     }
 9682:     return ($outcome,$perm_reqd,$conditions);
 9683: }
 9684: 
 9685: sub auto_checkphotos {
 9686:     my ($uname,$udom,$pid) = @_;
 9687:     my $homeserver = &homeserver($uname,$udom);
 9688:     my ($result,$resulttype);
 9689:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9690: 				   &escape($uname).':'.&escape($pid),
 9691: 				   $homeserver));
 9692:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9693: 	return (undef,undef);
 9694:     }
 9695:     if ($outcome) {
 9696:         ($result,$resulttype) = split(/:/,$outcome);
 9697:     } 
 9698:     return ($result,$resulttype);
 9699: }
 9700: 
 9701: sub auto_photochoice {
 9702:     my ($cnum,$cdom) = @_;
 9703:     my $homeserver = &homeserver($cnum,$cdom);
 9704:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9705: 						       &escape($cdom),
 9706: 						       $homeserver)));
 9707:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9708: 	return (undef,undef);
 9709:     }
 9710:     return ($update,$comment);
 9711: }
 9712: 
 9713: sub auto_photoupdate {
 9714:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9715:     my $homeserver = &homeserver($cnum,$dom);
 9716:     my $host=&hostname($homeserver);
 9717:     my $cmd = '';
 9718:     my $maxtries = 1;
 9719:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9720:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9721:     }
 9722:     $cmd =~ s/%%$//;
 9723:     $cmd = &escape($cmd);
 9724:     my $query = 'institutionalphotos';
 9725:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9726:     unless ($queryid=~/^\Q$host\E\_/) {
 9727:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9728:         return 'error: '.$queryid;
 9729:     }
 9730:     my $reply = &get_query_reply($queryid);
 9731:     my $tries = 1;
 9732:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9733:         $reply = &get_query_reply($queryid);
 9734:         $tries ++;
 9735:     }
 9736:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9737:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9738:     } else {
 9739:         my @responses = split(/:/,$reply);
 9740:         my $outcome = shift(@responses); 
 9741:         foreach my $item (@responses) {
 9742:             my ($key,$value) = split(/=/,$item);
 9743:             $$photo{$key} = $value;
 9744:         }
 9745:         return $outcome;
 9746:     }
 9747:     return 'error';
 9748: }
 9749: 
 9750: sub auto_instcode_format {
 9751:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9752: 	$cat_order) = @_;
 9753:     my $courses = '';
 9754:     my @homeservers;
 9755:     if ($caller eq 'global') {
 9756: 	my %servers = &get_servers($codedom,'library');
 9757: 	foreach my $tryserver (keys(%servers)) {
 9758: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9759: 		push(@homeservers,$tryserver);
 9760: 	    }
 9761:         }
 9762:     } elsif ($caller eq 'requests') {
 9763:         if ($codedom =~ /^$match_domain$/) {
 9764:             my $chome = &domain($codedom,'primary');
 9765:             unless ($chome eq 'no_host') {
 9766:                 push(@homeservers,$chome);
 9767:             }
 9768:         }
 9769:     } else {
 9770:         push(@homeservers,&homeserver($caller,$codedom));
 9771:     }
 9772:     foreach my $code (keys(%{$instcodes})) {
 9773:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9774:     }
 9775:     chop($courses);
 9776:     my $ok_response = 0;
 9777:     my $response;
 9778:     while (@homeservers > 0 && $ok_response == 0) {
 9779:         my $server = shift(@homeservers); 
 9780:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9781:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9782:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9783: 		split(/:/,$response);
 9784:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9785:             push(@{$codetitles},&str2array($codetitles_str));
 9786:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9787:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9788:             $ok_response = 1;
 9789:         }
 9790:     }
 9791:     if ($ok_response) {
 9792:         return 'ok';
 9793:     } else {
 9794:         return $response;
 9795:     }
 9796: }
 9797: 
 9798: sub auto_instcode_defaults {
 9799:     my ($domain,$returnhash,$code_order) = @_;
 9800:     my @homeservers;
 9801: 
 9802:     my %servers = &get_servers($domain,'library');
 9803:     foreach my $tryserver (keys(%servers)) {
 9804: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9805: 	    push(@homeservers,$tryserver);
 9806: 	}
 9807:     }
 9808: 
 9809:     my $response;
 9810:     foreach my $server (@homeservers) {
 9811:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9812:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9813: 	
 9814: 	foreach my $pair (split(/\&/,$response)) {
 9815: 	    my ($name,$value)=split(/\=/,$pair);
 9816: 	    if ($name eq 'code_order') {
 9817: 		@{$code_order} = split(/\&/,&unescape($value));
 9818: 	    } else {
 9819: 		$returnhash->{&unescape($name)}=&unescape($value);
 9820: 	    }
 9821: 	}
 9822: 	return 'ok';
 9823:     }
 9824: 
 9825:     return $response;
 9826: }
 9827: 
 9828: sub auto_possible_instcodes {
 9829:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9830:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9831:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9832:         return;
 9833:     }
 9834:     my (@homeservers,$uhome);
 9835:     if (defined(&domain($domain,'primary'))) {
 9836:         $uhome=&domain($domain,'primary');
 9837:         push(@homeservers,&domain($domain,'primary'));
 9838:     } else {
 9839:         my %servers = &get_servers($domain,'library');
 9840:         foreach my $tryserver (keys(%servers)) {
 9841:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9842:                 push(@homeservers,$tryserver);
 9843:             }
 9844:         }
 9845:     }
 9846:     my $response;
 9847:     foreach my $server (@homeservers) {
 9848:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9849:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9850:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9851:             split(':',$response);
 9852:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9853:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9854:         foreach my $item (split('&',$cat_title)) {   
 9855:             my ($name,$value)=split('=',$item);
 9856:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9857:         }
 9858:         foreach my $item (split('&',$cat_order)) {
 9859:             my ($name,$value)=split('=',$item);
 9860:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9861:         }
 9862:         return 'ok';
 9863:     }
 9864:     return $response;
 9865: }
 9866: 
 9867: sub auto_courserequest_checks {
 9868:     my ($dom) = @_;
 9869:     my ($homeserver,%validations);
 9870:     if ($dom =~ /^$match_domain$/) {
 9871:         $homeserver = &domain($dom,'primary');
 9872:     }
 9873:     unless ($homeserver eq 'no_host') {
 9874:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9875:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9876:             my @items = split(/&/,$response);
 9877:             foreach my $item (@items) {
 9878:                 my ($key,$value) = split('=',$item);
 9879:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9880:             }
 9881:         }
 9882:     }
 9883:     return %validations; 
 9884: }
 9885: 
 9886: sub auto_courserequest_validation {
 9887:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9888:     my ($homeserver,$response);
 9889:     if ($dom =~ /^$match_domain$/) {
 9890:         $homeserver = &domain($dom,'primary');
 9891:     }
 9892:     unless ($homeserver eq 'no_host') {
 9893:         my $customdata;
 9894:         if (ref($custominfo) eq 'HASH') {
 9895:             $customdata = &freeze_escape($custominfo);
 9896:         }
 9897:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9898:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9899:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9900:                                     $customdata,$homeserver));
 9901:     }
 9902:     return $response;
 9903: }
 9904: 
 9905: sub auto_validate_class_sec {
 9906:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9907:     my $homeserver = &homeserver($cnum,$cdom);
 9908:     my $ownerlist;
 9909:     if (ref($owners) eq 'ARRAY') {
 9910:         $ownerlist = join(',',@{$owners});
 9911:     } else {
 9912:         $ownerlist = $owners;
 9913:     }
 9914:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9915:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9916:     return $response;
 9917: }
 9918: 
 9919: sub auto_instsec_reformat {
 9920:     my ($cdom,$action,$instsecref) = @_;
 9921:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9922:     my @homeservers;
 9923:     if (defined(&domain($cdom,'primary'))) {
 9924:         push(@homeservers,&domain($cdom,'primary'));
 9925:     } else {
 9926:         my %servers = &get_servers($cdom,'library');
 9927:         foreach my $tryserver (keys(%servers)) {
 9928:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9929:                 push(@homeservers,$tryserver);
 9930:             }
 9931:         }
 9932:     }
 9933:     my $response;
 9934:     my %reformatted = %{$instsecref};
 9935:     foreach my $server (@homeservers) {
 9936:         if (ref($instsecref) eq 'HASH') {
 9937:             my $info = &freeze_escape($instsecref);
 9938:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9939:                                 $action.':'.$info,$server);
 9940:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9941:             my @items = split(/&/,$response);
 9942:             foreach my $item (@items) {
 9943:                 my ($key,$value) = split(/=/,$item);
 9944:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9945:             }
 9946:         }
 9947:     }
 9948:     return %reformatted;
 9949: }
 9950: 
 9951: sub auto_validate_instclasses {
 9952:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9953:     my ($homeserver,%validations);
 9954:     $homeserver = &homeserver($cnum,$cdom);
 9955:     unless ($homeserver eq 'no_host') {
 9956:         my $ownerlist;
 9957:         if (ref($owners) eq 'ARRAY') {
 9958:             $ownerlist = join(',',@{$owners});
 9959:         } else {
 9960:             $ownerlist = $owners;
 9961:         }
 9962:         if (ref($classesref) eq 'HASH') {
 9963:             my $classes = &freeze_escape($classesref);
 9964:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9965:                                 ':'.$cdom.':'.$classes,$homeserver);
 9966:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9967:                 my @items = split(/&/,$response);
 9968:                 foreach my $item (@items) {
 9969:                     my ($key,$value) = split('=',$item);
 9970:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9971:                 }
 9972:             }
 9973:         }
 9974:     }
 9975:     return %validations;
 9976: }
 9977: 
 9978: sub auto_crsreq_update {
 9979:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9980:         $code,$accessstart,$accessend,$inbound) = @_;
 9981:     my ($homeserver,%crsreqresponse);
 9982:     if ($cdom =~ /^$match_domain$/) {
 9983:         $homeserver = &domain($cdom,'primary');
 9984:     }
 9985:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9986:         my $info;
 9987:         if (ref($inbound) eq 'HASH') {
 9988:             $info = &freeze_escape($inbound);
 9989:         }
 9990:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9991:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9992:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9993:                             &escape($title).':'.&escape($code).':'.
 9994:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9995:                             $homeserver);
 9996:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9997:             my @items = split(/&/,$response);
 9998:             foreach my $item (@items) {
 9999:                 my ($key,$value) = split('=',$item);
10000:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10001:             }
10002:         }
10003:     }
10004:     return \%crsreqresponse;
10005: }
10006: 
10007: sub auto_export_grades {
10008:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10009:     my ($homeserver,%exportresponse);
10010:     if ($cdom =~ /^$match_domain$/) {
10011:         $homeserver = &domain($cdom,'primary');
10012:     }
10013:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10014:         my $info;
10015:         if (ref($inforef) eq 'HASH') {
10016:             $info = &freeze_escape($inforef);
10017:         }
10018:         if (ref($gradesref) eq 'HASH') {
10019:             my $grades = &freeze_escape($gradesref);
10020:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10021:                                 $info.':'.$grades,$homeserver);
10022:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10023:                 my @items = split(/&/,$response);
10024:                 foreach my $item (@items) {
10025:                     my ($key,$value) = split('=',$item);
10026:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10027:                 }
10028:             }
10029:         }
10030:     }
10031:     return \%exportresponse;
10032: }
10033: 
10034: sub check_instcode_cloning {
10035:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10036:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10037:         return;
10038:     }
10039:     my $canclone;
10040:     if (@{$code_order} > 0) {
10041:         my $instcoderegexp ='^';
10042:         my @clonecodes = split(/\&/,$cloner);
10043:         foreach my $item (@{$code_order}) {
10044:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10045:                 foreach my $pair (@clonecodes) {
10046:                     my ($key,$val) = split(/\=/,$pair,2);
10047:                     $val = &unescape($val);
10048:                     if ($key eq $item) {
10049:                         $instcoderegexp .= '('.$val.')';
10050:                         last;
10051:                     }
10052:                 }
10053:             } else {
10054:                 $instcoderegexp .= $codedefaults->{$item};
10055:             }
10056:         }
10057:         $instcoderegexp .= '$';
10058:         my (@from,@to);
10059:         eval {
10060:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10061:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10062:         };
10063:         if ((@from > 0) && (@to > 0)) {
10064:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10065:             if (!@diffs) {
10066:                 $canclone = 1;
10067:             }
10068:         }
10069:     }
10070:     return $canclone;
10071: }
10072: 
10073: sub default_instcode_cloning {
10074:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10075:     my (%codedefaults,@code_order,$canclone);
10076:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10077:         %codedefaults = %{$codedefaultsref};
10078:         @code_order = @{$codeorderref};
10079:     } elsif ($clonedom) {
10080:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10081:     }
10082:     if (($domdefclone) && (@code_order)) {
10083:         my @clonecodes = split(/\+/,$domdefclone);
10084:         my $instcoderegexp ='^';
10085:         foreach my $item (@code_order) {
10086:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10087:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10088:             } else {
10089:                 $instcoderegexp .= $codedefaults{$item};
10090:             }
10091:         }
10092:         $instcoderegexp .= '$';
10093:         my (@from,@to);
10094:         eval {
10095:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10096:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10097:         };
10098:         if ((@from > 0) && (@to > 0)) {
10099:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10100:             if (!@diffs) {
10101:                 $canclone = 1;
10102:             }
10103:         }
10104:     }
10105:     return $canclone;
10106: }
10107: 
10108: # ------------------------------------------------------- Course Group routines
10109: 
10110: sub get_coursegroups {
10111:     my ($cdom,$cnum,$group,$namespace) = @_;
10112:     return(&dump($namespace,$cdom,$cnum,$group));
10113: }
10114: 
10115: sub modify_coursegroup {
10116:     my ($cdom,$cnum,$groupsettings) = @_;
10117:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10118: }
10119: 
10120: sub toggle_coursegroup_status {
10121:     my ($cdom,$cnum,$group,$action) = @_;
10122:     my ($from_namespace,$to_namespace);
10123:     if ($action eq 'delete') {
10124:         $from_namespace = 'coursegroups';
10125:         $to_namespace = 'deleted_groups';
10126:     } else {
10127:         $from_namespace = 'deleted_groups';
10128:         $to_namespace = 'coursegroups';
10129:     }
10130:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10131:     if (my $tmp = &error(%curr_group)) {
10132:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10133:         return ('read error',$tmp);
10134:     } else {
10135:         my %savedsettings = %curr_group; 
10136:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10137:         my $deloutcome;
10138:         if ($result eq 'ok') {
10139:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10140:         } else {
10141:             return ('write error',$result);
10142:         }
10143:         if ($deloutcome eq 'ok') {
10144:             return 'ok';
10145:         } else {
10146:             return ('delete error',$deloutcome);
10147:         }
10148:     }
10149: }
10150: 
10151: sub modify_group_roles {
10152:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10153:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10154:     my $role = 'gr/'.&escape($userprivs);
10155:     my ($uname,$udom) = split(/:/,$user);
10156:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10157:     if ($result eq 'ok') {
10158:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10159:     }
10160:     return $result;
10161: }
10162: 
10163: sub modify_coursegroup_membership {
10164:     my ($cdom,$cnum,$membership) = @_;
10165:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10166:     return $result;
10167: }
10168: 
10169: sub get_active_groups {
10170:     my ($udom,$uname,$cdom,$cnum) = @_;
10171:     my $now = time;
10172:     my %groups = ();
10173:     foreach my $key (keys(%env)) {
10174:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10175:             my ($start,$end) = split(/\./,$env{$key});
10176:             if (($end!=0) && ($end<$now)) { next; }
10177:             if (($start!=0) && ($start>$now)) { next; }
10178:             if ($1 eq $cdom && $2 eq $cnum) {
10179:                 $groups{$3} = $env{$key} ;
10180:             }
10181:         }
10182:     }
10183:     return %groups;
10184: }
10185: 
10186: sub get_group_membership {
10187:     my ($cdom,$cnum,$group) = @_;
10188:     return(&dump('groupmembership',$cdom,$cnum,$group));
10189: }
10190: 
10191: sub get_users_groups {
10192:     my ($udom,$uname,$courseid) = @_;
10193:     my @usersgroups;
10194:     my $cachetime=1800;
10195: 
10196:     my $hashid="$udom:$uname:$courseid";
10197:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10198:     if (defined($cached)) {
10199:         @usersgroups = split(/:/,$grouplist);
10200:     } else {  
10201:         $grouplist = '';
10202:         my $courseurl = &courseid_to_courseurl($courseid);
10203:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10204:         my $access_end = $env{'course.'.$courseid.
10205:                               '.default_enrollment_end_date'};
10206:         my $now = time;
10207:         foreach my $key (keys(%roleshash)) {
10208:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10209:                 my $group = $1;
10210:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10211:                     my $start = $2;
10212:                     my $end = $1;
10213:                     if ($start == -1) { next; } # deleted from group
10214:                     if (($start!=0) && ($start>$now)) { next; }
10215:                     if (($end!=0) && ($end<$now)) {
10216:                         if ($access_end && $access_end < $now) {
10217:                             if ($access_end - $end < 86400) {
10218:                                 push(@usersgroups,$group);
10219:                             }
10220:                         }
10221:                         next;
10222:                     }
10223:                     push(@usersgroups,$group);
10224:                 }
10225:             }
10226:         }
10227:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10228:         $grouplist = join(':',@usersgroups);
10229:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10230:     }
10231:     return @usersgroups;
10232: }
10233: 
10234: sub devalidate_getgroups_cache {
10235:     my ($udom,$uname,$cdom,$cnum)=@_;
10236:     my $courseid = $cdom.'_'.$cnum;
10237: 
10238:     my $hashid="$udom:$uname:$courseid";
10239:     &devalidate_cache_new('getgroups',$hashid);
10240: }
10241: 
10242: # ------------------------------------------------------------------ Plain Text
10243: 
10244: sub plaintext {
10245:     my ($short,$type,$cid,$forcedefault) = @_;
10246:     if ($short =~ m{^cr/}) {
10247: 	return (split('/',$short))[-1];
10248:     }
10249:     if (!defined($cid)) {
10250:         $cid = $env{'request.course.id'};
10251:     }
10252:     my %rolenames = (
10253:                       Course    => 'std',
10254:                       Community => 'alt1',
10255:                       Placement => 'std',
10256:                     );
10257:     if ($cid ne '') {
10258:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10259:             unless ($forcedefault) {
10260:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10261:                 &Apache::lonlocal::mt_escape(\$roletext);
10262:                 return &Apache::lonlocal::mt($roletext);
10263:             }
10264:         }
10265:     }
10266:     if ((defined($type)) && (defined($rolenames{$type})) &&
10267:         (defined($rolenames{$type})) && 
10268:         (defined($prp{$short}{$rolenames{$type}}))) {
10269:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10270:     } elsif ($cid ne '') {
10271:         my $crstype = $env{'course.'.$cid.'.type'};
10272:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10273:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10274:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10275:         }
10276:     }
10277:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10278: }
10279: 
10280: # ----------------------------------------------------------------- Assign Role
10281: 
10282: sub assignrole {
10283:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10284:         $context)=@_;
10285:     my $mrole;
10286:     if ($role =~ /^cr\//) {
10287:         my $cwosec=$url;
10288:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10289: 	unless (&allowed('ccr',$cwosec)) {
10290:            my $refused = 1;
10291:            if ($context eq 'requestcourses') {
10292:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10293:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10294:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10295:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10296:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10297:                            if ($crsenv{'internal.courseowner'} eq
10298:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10299:                                $refused = '';
10300:                            }
10301:                        }
10302:                    }
10303:                }
10304:            }
10305:            if ($refused) {
10306:                &logthis('Refused custom assignrole: '.
10307:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10308:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10309:                return 'refused';
10310:            }
10311:         }
10312:         $mrole='cr';
10313:     } elsif ($role =~ /^gr\//) {
10314:         my $cwogrp=$url;
10315:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10316:         unless (&allowed('mdg',$cwogrp)) {
10317:             &logthis('Refused group assignrole: '.
10318:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10319:                     $env{'user.name'}.' at '.$env{'user.domain'});
10320:             return 'refused';
10321:         }
10322:         $mrole='gr';
10323:     } else {
10324:         my $cwosec=$url;
10325:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10326:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10327:             my $refused;
10328:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10329:                 if (!(&allowed('c'.$role,$url))) {
10330:                     $refused = 1;
10331:                 }
10332:             } else {
10333:                 $refused = 1;
10334:             }
10335:             if ($refused) {
10336:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10337:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10338:                     my %crsenv;
10339:                     if ($role eq 'cc' || $role eq 'co') {
10340:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10341:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10342:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10343:                                 if ($crsenv{'internal.courseowner'} eq 
10344:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10345:                                     $refused = '';
10346:                                 }
10347:                             }
10348:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10349:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10350:                                 if ($crsenv{'internal.courseowner'} eq 
10351:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10352:                                     $refused = '';
10353:                                 }
10354:                             }
10355:                         }
10356:                     }
10357:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10358:                     if ($role eq 'st') {
10359:                         $refused = '';
10360:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10361:                         $refused = '';
10362:                     }
10363:                 } elsif ($context eq 'requestcourses') {
10364:                     my @possroles = ('st','ta','ep','in','cc','co');
10365:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10366:                         my $wrongcc;
10367:                         if ($cnum =~ /^$match_community$/) {
10368:                             $wrongcc = 1 if ($role eq 'cc');
10369:                         } else {
10370:                             $wrongcc = 1 if ($role eq 'co');
10371:                         }
10372:                         unless ($wrongcc) {
10373:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10374:                             if ($crsenv{'internal.courseowner'} eq 
10375:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10376:                                 $refused = '';
10377:                             }
10378:                         }
10379:                     }
10380:                 } elsif ($context eq 'requestauthor') {
10381:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10382:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10383:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10384:                             $refused = '';
10385:                         } else {
10386:                             my %domdefaults = &get_domain_defaults($udom);
10387:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10388:                                 my $checkbystatus;
10389:                                 if ($env{'user.adv'}) { 
10390:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10391:                                     if ($disposition eq 'automatic') {
10392:                                         $refused = '';
10393:                                     } elsif ($disposition eq '') {
10394:                                         $checkbystatus = 1;
10395:                                     } 
10396:                                 } else {
10397:                                     $checkbystatus = 1;
10398:                                 }
10399:                                 if ($checkbystatus) {
10400:                                     if ($env{'environment.inststatus'}) {
10401:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10402:                                         foreach my $type (@inststatuses) {
10403:                                             if (($type ne '') &&
10404:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10405:                                                 $refused = '';
10406:                                             }
10407:                                         }
10408:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10409:                                         $refused = '';
10410:                                     }
10411:                                 }
10412:                             }
10413:                         }
10414:                     }
10415:                 }
10416:                 if ($refused) {
10417:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10418:                              ' '.$role.' '.$end.' '.$start.' by '.
10419: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10420:                     return 'refused';
10421:                 }
10422:             }
10423:         } elsif ($role eq 'au') {
10424:             if ($url ne '/'.$udom.'/') {
10425:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10426:                          ' to assign author role for '.$uname.':'.$udom.
10427:                          ' in domain: '.$url.' refused (wrong domain).');
10428:                 return 'refused';
10429:             }
10430:         }
10431:         $mrole=$role;
10432:     }
10433:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10434:                 "$udom:$uname:$url".'_'."$mrole=$role";
10435:     if ($end) { $command.='_'.$end; }
10436:     if ($start) {
10437: 	if ($end) { 
10438:            $command.='_'.$start; 
10439:         } else {
10440:            $command.='_0_'.$start;
10441:         }
10442:     }
10443:     my $origstart = $start;
10444:     my $origend = $end;
10445:     my $delflag;
10446: # actually delete
10447:     if ($deleteflag) {
10448: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10449: # modify command to delete the role
10450:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10451:                 "$udom:$uname:$url".'_'."$mrole";
10452: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10453: # set start and finish to negative values for userrolelog
10454:            $start=-1;
10455:            $end=-1;
10456:            $delflag = 1;
10457:         }
10458:     }
10459: # send command
10460:     my $answer=&reply($command,&homeserver($uname,$udom));
10461: # log new user role if status is ok
10462:     if ($answer eq 'ok') {
10463: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10464:         if (($role eq 'cc') || ($role eq 'in') ||
10465:             ($role eq 'ep') || ($role eq 'ad') ||
10466:             ($role eq 'ta') || ($role eq 'st') ||
10467:             ($role=~/^cr/) || ($role eq 'gr') ||
10468:             ($role eq 'co')) {
10469: # for course roles, perform group memberships changes triggered by role change.
10470:             unless ($role =~ /^gr/) {
10471:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10472:                                                  $origstart,$selfenroll,$context);
10473:             }
10474:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10475:                            $selfenroll,$context);
10476:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10477:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10478:                  ($role eq 'da')) {
10479:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10480:                            $context);
10481:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10482:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10483:                              $context); 
10484:         }
10485:         if ($role eq 'cc') {
10486:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10487:         }
10488:     }
10489:     return $answer;
10490: }
10491: 
10492: sub autoupdate_coowners {
10493:     my ($url,$end,$start,$uname,$udom) = @_;
10494:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10495:     if (($cdom ne '') && ($cnum ne '')) {
10496:         my $now = time;
10497:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10498:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10499:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10500:             my $instcode = $coursehash{'internal.coursecode'};
10501:             my $xlists = $coursehash{'internal.crosslistings'};
10502:             if ($instcode ne '') {
10503:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10504:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10505:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10506:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10507:                         unless ($result eq 'valid') {
10508:                             if ($xlists ne '') {
10509:                                 foreach my $xlist (split(',',$xlists)) {
10510:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10511:                                     $result =
10512:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10513:                                                                       $inst_crosslist,$uname.':'.$udom);
10514:                                     last if ($result eq 'valid');
10515:                                 }
10516:                             }
10517:                         }
10518:                         if ($result eq 'valid') {
10519:                             if ($coursehash{'internal.co-owners'}) {
10520:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10521:                                     push(@newcoowners,$coowner);
10522:                                 }
10523:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10524:                                     push(@newcoowners,$uname.':'.$udom);
10525:                                 }
10526:                                 @newcoowners = sort(@newcoowners);
10527:                             } else {
10528:                                 push(@newcoowners,$uname.':'.$udom);
10529:                             }
10530:                         } elsif ($coursehash{'internal.co-owners'}) {
10531:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10532:                                 unless ($coowner eq $uname.':'.$udom) {
10533:                                     push(@newcoowners,$coowner);
10534:                                 }
10535:                             }
10536:                             unless (@newcoowners > 0) {
10537:                                 $delcoowners = 1;
10538:                                 $coowners = '';
10539:                             }
10540:                         }
10541:                         if (@newcoowners || $delcoowners) {
10542:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10543:                                             $delcoowners,@newcoowners);
10544:                         }
10545:                     }
10546:                 }
10547:             }
10548:         }
10549:     }
10550: }
10551: 
10552: sub store_coowners {
10553:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10554:     my $cid = $cdom.'_'.$cnum;
10555:     my ($coowners,$delresult,$putresult);
10556:     if (@newcoowners) {
10557:         $coowners = join(',',@newcoowners);
10558:         my %coownershash = (
10559:                             'internal.co-owners' => $coowners,
10560:                            );
10561:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10562:         if ($putresult eq 'ok') {
10563:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10564:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10565:             }
10566:         }
10567:     }
10568:     if ($delcoowners) {
10569:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10570:         if ($delresult eq 'ok') {
10571:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10572:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10573:             }
10574:         }
10575:     }
10576:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10577:         my %crsinfo =
10578:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10579:         if (ref($crsinfo{$cid}) eq 'HASH') {
10580:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10581:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10582:         }
10583:     }
10584: }
10585: 
10586: # -------------------------------------------------- Modify user authentication
10587: # Overrides without validation
10588: 
10589: sub modifyuserauth {
10590:     my ($udom,$uname,$umode,$upass)=@_;
10591:     my $uhome=&homeserver($uname,$udom);
10592:     my $allowed;
10593:     if (&allowed('mau',$udom)) {
10594:         $allowed = 1;
10595:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10596:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10597:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10598:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10599:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10600:         if (($cdom ne '') && ($cnum ne '')) {
10601:             my $is_owner = &is_course_owner($cdom,$cnum);
10602:             if ($is_owner) {
10603:                 $allowed = 1;
10604:             }
10605:         }
10606:     }
10607:     unless ($allowed) { return 'refused'; }
10608:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10609:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10610:              ' in domain '.$env{'request.role.domain'});  
10611:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10612: 		     &escape($upass),$uhome);
10613:     my $ip = &get_requestor_ip();
10614:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10615:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10616:          '(Remote '.$ip.'): '.$reply);
10617:     &log($udom,,$uname,$uhome,
10618:         'Authentication changed by '.$env{'user.domain'}.', '.
10619:                                      $env{'user.name'}.', '.$umode.
10620:          '(Remote '.$ip.'): '.$reply);
10621:     unless ($reply eq 'ok') {
10622:         &logthis('Authentication mode error: '.$reply);
10623: 	return 'error: '.$reply;
10624:     }   
10625:     return 'ok';
10626: }
10627: 
10628: # --------------------------------------------------------------- Modify a user
10629: 
10630: sub modifyuser {
10631:     my ($udom,    $uname, $uid,
10632:         $umode,   $upass, $first,
10633:         $middle,  $last,  $gene,
10634:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10635:     $udom= &LONCAPA::clean_domain($udom);
10636:     $uname=&LONCAPA::clean_username($uname);
10637:     my $showcandelete = 'none';
10638:     if (ref($candelete) eq 'ARRAY') {
10639:         if (@{$candelete} > 0) {
10640:             $showcandelete = join(', ',@{$candelete});
10641:         }
10642:     }
10643:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10644:              $umode.', '.$first.', '.$middle.', '.
10645: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10646:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10647:                                      ' desiredhome not specified'). 
10648:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10649:              ' in domain '.$env{'request.role.domain'});
10650:     my $uhome=&homeserver($uname,$udom,'true');
10651:     my $newuser;
10652:     if ($uhome eq 'no_host') {
10653:         $newuser = 1;
10654:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10655:                 ($umode eq 'lti')) {
10656:             return 'error: more information needed to create new user';
10657:         }
10658:     }
10659: # ----------------------------------------------------------------- Create User
10660:     if (($uhome eq 'no_host') && 
10661: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10662:         my $unhome='';
10663:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10664:             $unhome = $desiredhome;
10665: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10666: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10667:         } else { # load balancing routine for determining $unhome
10668:             my $loadm=10000000;
10669: 	    my %servers = &get_servers($udom,'library');
10670: 	    foreach my $tryserver (keys(%servers)) {
10671: 		my $answer=reply('load',$tryserver);
10672: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10673: 		    $loadm=$answer;
10674: 		    $unhome=$tryserver;
10675: 		}
10676: 	    }
10677:         }
10678:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10679: 	    return 'error: unable to find a home server for '.$uname.
10680:                    ' in domain '.$udom;
10681:         }
10682:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10683:                          &escape($upass),$unhome);
10684: 	unless ($reply eq 'ok') {
10685:             return 'error: '.$reply;
10686:         }   
10687:         $uhome=&homeserver($uname,$udom,'true');
10688:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10689: 	    return 'error: unable verify users home machine.';
10690:         }
10691:     }   # End of creation of new user
10692: # ---------------------------------------------------------------------- Add ID
10693:     if ($uid) {
10694:        $uid=~tr/A-Z/a-z/;
10695:        my %uidhash=&idrget($udom,$uname);
10696:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10697:          && (!$forceid)) {
10698: 	  unless ($uid eq $uidhash{$uname}) {
10699: 	      return 'error: user id "'.$uid.'" does not match '.
10700:                   'current user id "'.$uidhash{$uname}.'".';
10701:           }
10702:        } else {
10703: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10704:        }
10705:     }
10706: # -------------------------------------------------------------- Add names, etc
10707:     my @tmp=&get('environment',
10708: 		   ['firstname','middlename','lastname','generation','id',
10709:                     'permanentemail','inststatus'],
10710: 		   $udom,$uname);
10711:     my (%names,%oldnames);
10712:     if ($tmp[0] =~ m/^error:.*/) { 
10713:         %names=(); 
10714:     } else {
10715:         %names = @tmp;
10716:         %oldnames = %names;
10717:     }
10718: #
10719: # If name, email and/or uid are blank (e.g., because an uploaded file
10720: # of users did not contain them), do not overwrite existing values
10721: # unless field is in $candelete array ref.  
10722: #
10723: 
10724:     my @fields = ('firstname','middlename','lastname','generation',
10725:                   'permanentemail','id');
10726:     my %newvalues;
10727:     if (ref($candelete) eq 'ARRAY') {
10728:         foreach my $field (@fields) {
10729:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10730:                 if ($field eq 'firstname') {
10731:                     $names{$field} = $first;
10732:                 } elsif ($field eq 'middlename') {
10733:                     $names{$field} = $middle;
10734:                 } elsif ($field eq 'lastname') {
10735:                     $names{$field} = $last;
10736:                 } elsif ($field eq 'generation') { 
10737:                     $names{$field} = $gene;
10738:                 } elsif ($field eq 'permanentemail') {
10739:                     $names{$field} = $email;
10740:                 } elsif ($field eq 'id') {
10741:                     $names{$field}  = $uid;
10742:                 }
10743:             }
10744:         }
10745:     }
10746:     if ($first)  { $names{'firstname'}  = $first; }
10747:     if (defined($middle)) { $names{'middlename'} = $middle; }
10748:     if ($last)   { $names{'lastname'}   = $last; }
10749:     if (defined($gene))   { $names{'generation'} = $gene; }
10750:     if ($email) {
10751:        $email=~s/[^\w\@\.\-\,]//gs;
10752:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10753:     }
10754:     if ($uid) { $names{'id'}  = $uid; }
10755:     if (defined($inststatus)) {
10756:         $names{'inststatus'} = '';
10757:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10758:         if (ref($usertypes) eq 'HASH') {
10759:             my @okstatuses; 
10760:             foreach my $item (split(/:/,$inststatus)) {
10761:                 if (defined($usertypes->{$item})) {
10762:                     push(@okstatuses,$item);  
10763:                 }
10764:             }
10765:             if (@okstatuses) {
10766:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10767:             }
10768:         }
10769:     }
10770:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10771:                  $umode.', '.$first.', '.$middle.', '.
10772:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10773:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10774:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10775:     } else {
10776:         $logmsg .= ' during self creation';
10777:     }
10778:     my $changed;
10779:     if ($newuser) {
10780:         $changed = 1;
10781:     } else {
10782:         foreach my $field (@fields) {
10783:             if ($names{$field} ne $oldnames{$field}) {
10784:                 $changed = 1;
10785:                 last;
10786:             }
10787:         }
10788:     }
10789:     unless ($changed) {
10790:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10791:         &logthis($logmsg);
10792:         return 'ok';
10793:     }
10794:     my $reply = &put('environment', \%names, $udom,$uname);
10795:     if ($reply ne 'ok') { 
10796:         return 'error: '.$reply;
10797:     }
10798:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10799:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10800:     }
10801:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10802:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10803:     $logmsg = 'Success modifying user '.$logmsg;
10804:     &logthis($logmsg);
10805:     return 'ok';
10806: }
10807: 
10808: # -------------------------------------------------------------- Modify student
10809: 
10810: sub modifystudent {
10811:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10812:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10813:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10814:     if (!$cid) {
10815: 	unless ($cid=$env{'request.course.id'}) {
10816: 	    return 'not_in_class';
10817: 	}
10818:     }
10819: # --------------------------------------------------------------- Make the user
10820:     my $reply=&modifyuser
10821: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10822:          $desiredhome,$email,$inststatus);
10823:     unless ($reply eq 'ok') { return $reply; }
10824:     # This will cause &modify_student_enrollment to get the uid from the
10825:     # student's environment
10826:     $uid = undef if (!$forceid);
10827:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10828:                                         $gene,$usec,$end,$start,$type,$locktype,
10829:                                         $cid,$selfenroll,$context,$credits,$instsec);
10830:     return $reply;
10831: }
10832: 
10833: sub modify_student_enrollment {
10834:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10835:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10836:     my ($cdom,$cnum,$chome);
10837:     if (!$cid) {
10838: 	unless ($cid=$env{'request.course.id'}) {
10839: 	    return 'not_in_class';
10840: 	}
10841: 	$cdom=$env{'course.'.$cid.'.domain'};
10842: 	$cnum=$env{'course.'.$cid.'.num'};
10843:     } else {
10844: 	($cdom,$cnum)=split(/_/,$cid);
10845:     }
10846:     $chome=$env{'course.'.$cid.'.home'};
10847:     if (!$chome) {
10848: 	$chome=&homeserver($cnum,$cdom);
10849:     }
10850:     if (!$chome) { return 'unknown_course'; }
10851:     # Make sure the user exists
10852:     my $uhome=&homeserver($uname,$udom);
10853:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10854: 	return 'error: no such user';
10855:     }
10856:     # Get student data if we were not given enough information
10857:     if (!defined($first)  || $first  eq '' || 
10858:         !defined($last)   || $last   eq '' || 
10859:         !defined($uid)    || $uid    eq '' || 
10860:         !defined($middle) || $middle eq '' || 
10861:         !defined($gene)   || $gene   eq '') {
10862:         # They did not supply us with enough data to enroll the student, so
10863:         # we need to pick up more information.
10864:         my %tmp = &get('environment',
10865:                        ['firstname','middlename','lastname', 'generation','id']
10866:                        ,$udom,$uname);
10867: 
10868:         #foreach my $key (keys(%tmp)) {
10869:         #    &logthis("key $key = ".$tmp{$key});
10870:         #}
10871:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10872:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10873:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10874:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10875:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10876:     }
10877:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10878:     my $user = "$uname:$udom";
10879:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10880:     my $reply=cput('classlist',
10881: 		   {$user => 
10882: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10883: 		   $cdom,$cnum);
10884:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10885:         &devalidate_getsection_cache($udom,$uname,$cid);
10886:     } else { 
10887: 	return 'error: '.$reply;
10888:     }
10889:     # Add student role to user
10890:     my $uurl='/'.$cid;
10891:     $uurl=~s/\_/\//g;
10892:     if ($usec) {
10893: 	$uurl.='/'.$usec;
10894:     }
10895:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10896:                              $selfenroll,$context);
10897:     if ($result ne 'ok') {
10898:         if ($old_entry{$user} ne '') {
10899:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10900:         } else {
10901:             $reply = &del('classlist',[$user],$cdom,$cnum);
10902:         }
10903:     }
10904:     return $result; 
10905: }
10906: 
10907: sub format_name {
10908:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10909:     my $name;
10910:     if ($first ne 'lastname') {
10911: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10912:     } else {
10913: 	if ($lastname=~/\S/) {
10914: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10915: 	    $name=~s/\s+,/,/;
10916: 	} else {
10917: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10918: 	}
10919:     }
10920:     $name=~s/^\s+//;
10921:     $name=~s/\s+$//;
10922:     $name=~s/\s+/ /g;
10923:     return $name;
10924: }
10925: 
10926: # ------------------------------------------------- Write to course preferences
10927: 
10928: sub writecoursepref {
10929:     my ($courseid,%prefs)=@_;
10930:     $courseid=~s/^\///;
10931:     $courseid=~s/\_/\//g;
10932:     my ($cdomain,$cnum)=split(/\//,$courseid);
10933:     my $chome=homeserver($cnum,$cdomain);
10934:     if (($chome eq '') || ($chome eq 'no_host')) { 
10935: 	return 'error: no such course';
10936:     }
10937:     my $cstring='';
10938:     foreach my $pref (keys(%prefs)) {
10939: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10940:     }
10941:     $cstring=~s/\&$//;
10942:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10943: }
10944: 
10945: # ---------------------------------------------------------- Make/modify course
10946: 
10947: sub createcourse {
10948:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10949:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10950:     $url=&declutter($url);
10951:     my $cid='';
10952:     if ($context eq 'requestcourses') {
10953:         my $can_create = 0;
10954:         my ($ownername,$ownerdom) = split(':',$course_owner);
10955:         if ($udom eq $ownerdom) {
10956:             my $reload;
10957:             if (($callercontext eq 'auto') &&
10958:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10959:                 $reload = 'reload';
10960:             }
10961:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10962:                                   $context)) {
10963:                 $can_create = 1;
10964:             }
10965:         } else {
10966:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10967:                                            $category);
10968:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10969:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10970:                 if (@curr > 0) {
10971:                     my @options = qw(approval validate autolimit);
10972:                     my $optregex = join('|',@options);
10973:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10974:                         $can_create = 1;
10975:                     }
10976:                 }
10977:             }
10978:         }
10979:         if ($can_create) {
10980:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10981:                 unless (&allowed('ccc',$udom)) {
10982:                     return 'refused'; 
10983:                 }
10984:             }
10985:         } else {
10986:             return 'refused';
10987:         }
10988:     } elsif (!&allowed('ccc',$udom)) {
10989:         return 'refused';
10990:     }
10991: # --------------------------------------------------------------- Get Unique ID
10992:     my $uname;
10993:     if ($cnum =~ /^$match_courseid$/) {
10994:         my $chome=&homeserver($cnum,$udom,'true');
10995:         if (($chome eq '') || ($chome eq 'no_host')) {
10996:             $uname = $cnum;
10997:         } else {
10998:             $uname = &generate_coursenum($udom,$crstype);
10999:         }
11000:     } else {
11001:         $uname = &generate_coursenum($udom,$crstype);
11002:     }
11003:     return $uname if ($uname =~ /^error/);
11004: # -------------------------------------------------- Check supplied server name
11005:     if (!defined($course_server)) {
11006:         if (defined(&domain($udom,'primary'))) {
11007:             $course_server = &domain($udom,'primary');
11008:         } else {
11009:             $course_server = $env{'user.home'}; 
11010:         }
11011:     }
11012:     my %host_servers =
11013:         &Apache::lonnet::get_servers($udom,'library');
11014:     unless ($host_servers{$course_server}) {
11015:         return 'error: invalid home server for course: '.$course_server;
11016:     }
11017: # ------------------------------------------------------------- Make the course
11018:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11019:                       $course_server);
11020:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11021:     my $uhome=&homeserver($uname,$udom,'true');
11022:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11023: 	return 'error: no such course';
11024:     }
11025: # ----------------------------------------------------------------- Course made
11026: # log existence
11027:     my $now = time;
11028:     my $newcourse = {
11029:                     $udom.'_'.$uname => {
11030:                                      description => $description,
11031:                                      inst_code   => $inst_code,
11032:                                      owner       => $course_owner,
11033:                                      type        => $crstype,
11034:                                      creator     => $env{'user.name'}.':'.
11035:                                                     $env{'user.domain'},
11036:                                      created     => $now,
11037:                                      context     => $context,
11038:                                                 },
11039:                     };
11040:     &courseidput($udom,$newcourse,$uhome,'notime');
11041: # set toplevel url
11042:     my $topurl=$url;
11043:     unless ($nonstandard) {
11044: # ------------------------------------------ For standard courses, make top url
11045:         my $mapurl=&clutter($url);
11046:         if ($mapurl eq '/res/') { $mapurl=''; }
11047:         $env{'form.initmap'}=(<<ENDINITMAP);
11048: <map>
11049: <resource id="1" type="start"></resource>
11050: <resource id="2" src="$mapurl"></resource>
11051: <resource id="3" type="finish"></resource>
11052: <link index="1" from="1" to="2"></link>
11053: <link index="2" from="2" to="3"></link>
11054: </map>
11055: ENDINITMAP
11056:         $topurl=&declutter(
11057:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11058:                           );
11059:     }
11060: # ----------------------------------------------------------- Write preferences
11061:     &writecoursepref($udom.'_'.$uname,
11062:                      ('description'              => $description,
11063:                       'url'                      => $topurl,
11064:                       'internal.creator'         => $env{'user.name'}.':'.
11065:                                                     $env{'user.domain'},
11066:                       'internal.created'         => $now,
11067:                       'internal.creationcontext' => $context)
11068:                     );
11069:     return '/'.$udom.'/'.$uname;
11070: }
11071: 
11072: # ------------------------------------------------------------------- Create ID
11073: sub generate_coursenum {
11074:     my ($udom,$crstype) = @_;
11075:     my $domdesc = &domain($udom);
11076:     return 'error: invalid domain' if ($domdesc eq '');
11077:     my $first;
11078:     if ($crstype eq 'Community') {
11079:         $first = '0';
11080:     } else {
11081:         $first = int(1+rand(9)); 
11082:     } 
11083:     my $uname=$first.
11084:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11085:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11086:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11087: # ----------------------------------------------- Make sure that does not exist
11088:     my $uhome=&homeserver($uname,$udom,'true');
11089:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11090:         if ($crstype eq 'Community') {
11091:             $first = '0';
11092:         } else {
11093:             $first = int(1+rand(9));
11094:         }
11095:         $uname=$first.
11096:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11097:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11098:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11099:         $uhome=&homeserver($uname,$udom,'true');
11100:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11101:             return 'error: unable to generate unique course-ID';
11102:         }
11103:     }
11104:     return $uname;
11105: }
11106: 
11107: sub is_course {
11108:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11109:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11110: 
11111:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11112:     my $uhome=&homeserver($cnum,$cdom);
11113:     my $iscourse;
11114:     if (grep { $_ eq $uhome } current_machine_ids()) {
11115:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11116:     } else {
11117:         my $hashid = $cdom.':'.$cnum;
11118:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11119:         unless (defined($cached)) {
11120:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11121:                                         $cnum,undef,undef,'.');
11122:             $iscourse = 0;
11123:             if (exists($courses{$cdom.'_'.$cnum})) {
11124:                 $iscourse = 1;
11125:             }
11126:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11127:         }
11128:     }
11129:     return unless ($iscourse);
11130:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11131: }
11132: 
11133: sub store_userdata {
11134:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11135:     my $result;
11136:     if ($datakey ne '') {
11137:         if (ref($storehash) eq 'HASH') {
11138:             if ($udom eq '' || $uname eq '') {
11139:                 $udom = $env{'user.domain'};
11140:                 $uname = $env{'user.name'};
11141:             }
11142:             my $uhome=&homeserver($uname,$udom);
11143:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11144:                 $result = 'error: no_host';
11145:             } else {
11146:                 $storehash->{'ip'} = &get_requestor_ip();
11147:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11148: 
11149:                 my $namevalue='';
11150:                 foreach my $key (keys(%{$storehash})) {
11151:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11152:                 }
11153:                 $namevalue=~s/\&$//;
11154:                 unless ($namespace eq 'courserequests') {
11155:                     $datakey = &escape($datakey);
11156:                 }
11157:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11158:                                   $namevalue,$uhome);
11159:             }
11160:         } else {
11161:             $result = 'error: data to store was not a hash reference'; 
11162:         }
11163:     } else {
11164:         $result= 'error: invalid requestkey'; 
11165:     }
11166:     return $result;
11167: }
11168: 
11169: # ---------------------------------------------------------- Assign Custom Role
11170: 
11171: sub assigncustomrole {
11172:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11173:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11174:                        $end,$start,$deleteflag,$selfenroll,$context);
11175: }
11176: 
11177: # ----------------------------------------------------------------- Revoke Role
11178: 
11179: sub revokerole {
11180:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11181:     my $now=time;
11182:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11183: }
11184: 
11185: # ---------------------------------------------------------- Revoke Custom Role
11186: 
11187: sub revokecustomrole {
11188:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11189:     my $now=time;
11190:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11191:            $deleteflag,$selfenroll,$context);
11192: }
11193: 
11194: # ------------------------------------------------------------ Disk usage
11195: sub diskusage {
11196:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11197:     $directorypath =~ s/\/$//;
11198:     my $listing=&reply('du2:'.&escape($directorypath).':'
11199:                        .&escape($getpropath).':'.&escape($uname).':'
11200:                        .&escape($udom),homeserver($uname,$udom));
11201:     if ($listing eq 'unknown_cmd') {
11202:         if ($getpropath) {
11203:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11204:         }
11205:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11206:     }
11207:     return $listing;
11208: }
11209: 
11210: sub is_locked {
11211:     my ($file_name, $domain, $user, $which) = @_;
11212:     my @check;
11213:     my $is_locked;
11214:     push (@check,$file_name);
11215:     my %locked = &get('file_permissions',\@check,
11216: 		      $env{'user.domain'},$env{'user.name'});
11217:     my ($tmp)=keys(%locked);
11218:     if ($tmp=~/^error:/) { undef(%locked); }
11219:     
11220:     if (ref($locked{$file_name}) eq 'ARRAY') {
11221:         $is_locked = 'false';
11222:         foreach my $entry (@{$locked{$file_name}}) {
11223:            if (ref($entry) eq 'ARRAY') {
11224:                $is_locked = 'true';
11225:                if (ref($which) eq 'ARRAY') {
11226:                    push(@{$which},$entry);
11227:                } else {
11228:                    last;
11229:                }
11230:            }
11231:        }
11232:     } else {
11233:         $is_locked = 'false';
11234:     }
11235:     return $is_locked;
11236: }
11237: 
11238: sub declutter_portfile {
11239:     my ($file) = @_;
11240:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11241:     return $file;
11242: }
11243: 
11244: # ------------------------------------------------------------- Mark as Read Only
11245: 
11246: sub mark_as_readonly {
11247:     my ($domain,$user,$files,$what) = @_;
11248:     my %current_permissions = &dump('file_permissions',$domain,$user);
11249:     my ($tmp)=keys(%current_permissions);
11250:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11251:     foreach my $file (@{$files}) {
11252: 	$file = &declutter_portfile($file);
11253:         push(@{$current_permissions{$file}},$what);
11254:     }
11255:     &put('file_permissions',\%current_permissions,$domain,$user);
11256:     return;
11257: }
11258: 
11259: # ------------------------------------------------------------Save Selected Files
11260: 
11261: sub save_selected_files {
11262:     my ($user, $path, @files) = @_;
11263:     my $filename = $user."savedfiles";
11264:     my @other_files = &files_not_in_path($user, $path);
11265:     open (OUT,'>',LONCAPA::tempdir().$filename);
11266:     foreach my $file (@files) {
11267:         print (OUT $env{'form.currentpath'}.$file."\n");
11268:     }
11269:     foreach my $file (@other_files) {
11270:         print (OUT $file."\n");
11271:     }
11272:     close (OUT);
11273:     return 'ok';
11274: }
11275: 
11276: sub clear_selected_files {
11277:     my ($user) = @_;
11278:     my $filename = $user."savedfiles";
11279:     open (OUT,'>',LONCAPA::tempdir().$filename);
11280:     print (OUT undef);
11281:     close (OUT);
11282:     return ("ok");    
11283: }
11284: 
11285: sub files_in_path {
11286:     my ($user, $path) = @_;
11287:     my $filename = $user."savedfiles";
11288:     my %return_files;
11289:     open (IN,'<',LONCAPA::tempdir().$filename);
11290:     while (my $line_in = <IN>) {
11291:         chomp ($line_in);
11292:         my @paths_and_file = split (m!/!, $line_in);
11293:         my $file_part = pop (@paths_and_file);
11294:         my $path_part = join ('/', @paths_and_file);
11295:         $path_part.='/';
11296:         my $path_and_file = $path_part.$file_part;
11297:         if ($path_part eq $path) {
11298:             $return_files{$file_part}= 'selected';
11299:         }
11300:     }
11301:     close (IN);
11302:     return (\%return_files);
11303: }
11304: 
11305: # called in portfolio select mode, to show files selected NOT in current directory
11306: sub files_not_in_path {
11307:     my ($user, $path) = @_;
11308:     my $filename = $user."savedfiles";
11309:     my @return_files;
11310:     my $path_part;
11311:     open(IN, '<',LONCAPA::tempdir().$filename);
11312:     while (my $line = <IN>) {
11313:         #ok, I know it's clunky, but I want it to work
11314:         my @paths_and_file = split(m|/|, $line);
11315:         my $file_part = pop(@paths_and_file);
11316:         chomp($file_part);
11317:         my $path_part = join('/', @paths_and_file);
11318:         $path_part .= '/';
11319:         my $path_and_file = $path_part.$file_part;
11320:         if ($path_part ne $path) {
11321:             push(@return_files, ($path_and_file));
11322:         }
11323:     }
11324:     close(OUT);
11325:     return (@return_files);
11326: }
11327: 
11328: #------------------------------Submitted/Handedback Portfolio Files Versioning
11329:  
11330: sub portfiles_versioning {
11331:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11332:     my $portfolio_root = '/userfiles/portfolio';
11333:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11334:     foreach my $file (@{$portfiles}) {
11335:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11336:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11337:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11338:         my $getpropath = 1;
11339:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11340:                                              $stu_name,$getpropath);
11341:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11342:         my $new_answer = 
11343:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11344:         if ($new_answer ne 'problem getting file') {
11345:             push(@{$versioned_portfiles}, $directory.$new_answer);
11346:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11347:                               [$symb,$env{'request.course.id'},'graded']);
11348:         }
11349:     }
11350: }
11351: 
11352: sub get_next_version {
11353:     my ($answer_name, $answer_ext, $dir_list) = @_;
11354:     my $version;
11355:     if (ref($dir_list) eq 'ARRAY') {
11356:         foreach my $row (@{$dir_list}) {
11357:             my ($file) = split(/\&/,$row,2);
11358:             my ($file_name,$file_version,$file_ext) =
11359:                 &file_name_version_ext($file);
11360:             if (($file_name eq $answer_name) &&
11361:                 ($file_ext eq $answer_ext)) {
11362:                      # gets here if filename and extension match,
11363:                      # regardless of version
11364:                 if ($file_version ne '') {
11365:                     # a versioned file is found  so save it for later
11366:                     if ($file_version > $version) {
11367:                         $version = $file_version;
11368:                     }
11369:                 }
11370:             }
11371:         }
11372:     }
11373:     $version ++;
11374:     return($version);
11375: }
11376: 
11377: sub version_selected_portfile {
11378:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11379:     my ($answer_name,$answer_ver,$answer_ext) =
11380:         &file_name_version_ext($file_name);
11381:     my $new_answer;
11382:     $env{'form.copy'} =
11383:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11384:     if($env{'form.copy'} eq '-1') {
11385:         $new_answer = 'problem getting file';
11386:     } else {
11387:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11388:         my $copy_result = 
11389:             &finishuserfileupload($stu_name,$domain,'copy',
11390:                                   '/portfolio'.$directory.$new_answer);
11391:     }
11392:     undef($env{'form.copy'});
11393:     return ($new_answer);
11394: }
11395: 
11396: sub file_name_version_ext {
11397:     my ($file)=@_;
11398:     my @file_parts = split(/\./, $file);
11399:     my ($name,$version,$ext);
11400:     if (@file_parts > 1) {
11401:         $ext=pop(@file_parts);
11402:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11403:             $version=pop(@file_parts);
11404:         }
11405:         $name=join('.',@file_parts);
11406:     } else {
11407:         $name=join('.',@file_parts);
11408:     }
11409:     return($name,$version,$ext);
11410: }
11411: 
11412: #----------------------------------------------Get portfolio file permissions
11413: 
11414: sub get_portfile_permissions {
11415:     my ($domain,$user) = @_;
11416:     my %current_permissions = &dump('file_permissions',$domain,$user);
11417:     my ($tmp)=keys(%current_permissions);
11418:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11419:     return \%current_permissions;
11420: }
11421: 
11422: #---------------------------------------------Get portfolio file access controls
11423: 
11424: sub get_access_controls {
11425:     my ($current_permissions,$group,$file) = @_;
11426:     my %access;
11427:     my $real_file = $file;
11428:     $file =~ s/\.meta$//;
11429:     if (defined($file)) {
11430:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11431:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11432:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11433:             }
11434:         }
11435:     } else {
11436:         foreach my $key (keys(%{$current_permissions})) {
11437:             if ($key =~ /\0accesscontrol$/) {
11438:                 if (defined($group)) {
11439:                     if ($key !~ m-^\Q$group\E/-) {
11440:                         next;
11441:                     }
11442:                 }
11443:                 my ($fullpath) = split(/\0/,$key);
11444:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11445:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11446:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11447:                     }
11448:                 }
11449:             }
11450:         }
11451:     }
11452:     return %access;
11453: }
11454: 
11455: sub modify_access_controls {
11456:     my ($file_name,$changes,$domain,$user)=@_;
11457:     my ($outcome,$deloutcome);
11458:     my %store_permissions;
11459:     my %new_values;
11460:     my %new_control;
11461:     my %translation;
11462:     my @deletions = ();
11463:     my $now = time;
11464:     if (exists($$changes{'activate'})) {
11465:         if (ref($$changes{'activate'}) eq 'HASH') {
11466:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11467:             my $numnew = scalar(@newitems);
11468:             for (my $i=0; $i<$numnew; $i++) {
11469:                 my $newkey = $newitems[$i];
11470:                 my $newid = &Apache::loncommon::get_cgi_id();
11471:                 if ($newkey =~ /^\d+:/) { 
11472:                     $newkey =~ s/^(\d+)/$newid/;
11473:                     $translation{$1} = $newid;
11474:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11475:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11476:                     $translation{$1} = $newid;
11477:                 }
11478:                 $new_values{$file_name."\0".$newkey} = 
11479:                                           $$changes{'activate'}{$newitems[$i]};
11480:                 $new_control{$newkey} = $now;
11481:             }
11482:         }
11483:     }
11484:     my %todelete;
11485:     my %changed_items;
11486:     foreach my $action ('delete','update') {
11487:         if (exists($$changes{$action})) {
11488:             if (ref($$changes{$action}) eq 'HASH') {
11489:                 foreach my $key (keys(%{$$changes{$action}})) {
11490:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11491:                     if ($action eq 'delete') { 
11492:                         $todelete{$itemnum} = 1;
11493:                     } else {
11494:                         $changed_items{$itemnum} = $key;
11495:                     }
11496:                 }
11497:             }
11498:         }
11499:     }
11500:     # get lock on access controls for file.
11501:     my $lockhash = {
11502:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11503:                                                        ':'.$env{'user.domain'},
11504:                    }; 
11505:     my $tries = 0;
11506:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11507:    
11508:     while (($gotlock ne 'ok') && $tries < 10) {
11509:         $tries ++;
11510:         sleep(0.1);
11511:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11512:     }
11513:     if ($gotlock eq 'ok') {
11514:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11515:         my ($tmp)=keys(%curr_permissions);
11516:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11517:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11518:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11519:             if (ref($curr_controls) eq 'HASH') {
11520:                 foreach my $control_item (keys(%{$curr_controls})) {
11521:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11522:                     if (defined($todelete{$itemnum})) {
11523:                         push(@deletions,$file_name."\0".$control_item);
11524:                     } else {
11525:                         if (defined($changed_items{$itemnum})) {
11526:                             $new_control{$changed_items{$itemnum}} = $now;
11527:                             push(@deletions,$file_name."\0".$control_item);
11528:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11529:                         } else {
11530:                             $new_control{$control_item} = $$curr_controls{$control_item};
11531:                         }
11532:                     }
11533:                 }
11534:             }
11535:         }
11536:         my ($group);
11537:         if (&is_course($domain,$user)) {
11538:             ($group,my $file) = split(/\//,$file_name,2);
11539:         }
11540:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11541:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11542:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11543:         #  remove lock
11544:         my @del_lock = ($file_name."\0".'locked_access_records');
11545:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11546:         my $sqlresult =
11547:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11548:                                     $group);
11549:     } else {
11550:         $outcome = "error: could not obtain lockfile\n";  
11551:     }
11552:     return ($outcome,$deloutcome,\%new_values,\%translation);
11553: }
11554: 
11555: sub make_public_indefinitely {
11556:     my (@requrl) = @_;
11557:     return &automated_portfile_access('public',\@requrl);
11558: }
11559: 
11560: sub automated_portfile_access {
11561:     my ($accesstype,$addsref,$delsref,$info) = @_;
11562:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11563:         return 'invalid';
11564:     }
11565:     my %urls;
11566:     if (ref($addsref) eq 'ARRAY') {
11567:         foreach my $requrl (@{$addsref}) {
11568:             if (&is_portfolio_url($requrl)) {
11569:                 unless (exists($urls{$requrl})) {
11570:                     $urls{$requrl} = 'add';
11571:                 }
11572:             }
11573:         }
11574:     }
11575:     if (ref($delsref) eq 'ARRAY') {
11576:         foreach my $requrl (@{$delsref}) { 
11577:             if (&is_portfolio_url($requrl)) {
11578:                 unless (exists($urls{$requrl})) {
11579:                     $urls{$requrl} = 'delete'; 
11580:                 }
11581:             }
11582:         }
11583:     }
11584:     unless (keys(%urls)) {
11585:         return 'invalid';
11586:     }
11587:     my $ip;
11588:     if ($accesstype eq 'ip') {
11589:         if (ref($info) eq 'HASH') {
11590:             if ($info->{'ip'} ne '') {
11591:                 $ip = $info->{'ip'};
11592:             }
11593:         }
11594:         if ($ip eq '') {
11595:             return 'invalid';
11596:         }
11597:     }
11598:     my $errors;
11599:     my $now = time;
11600:     my %current_perms;
11601:     foreach my $requrl (sort(keys(%urls))) {
11602:         my $action;
11603:         if ($urls{$requrl} eq 'add') {
11604:             $action = 'activate';
11605:         } else {
11606:             $action = 'none';
11607:         }
11608:         my $aclnum = 0;
11609:         my (undef,$udom,$unum,$file_name,$group) =
11610:             &parse_portfolio_url($requrl);
11611:         unless (exists($current_perms{$unum.':'.$udom})) {
11612:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11613:         }
11614:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11615:                                                    $group,$file_name);
11616:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11617:             my ($num,$scope,$end,$start) = 
11618:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11619:             if ($scope eq $accesstype) {
11620:                 if (($start <= $now) && ($end == 0)) {
11621:                     if ($accesstype eq 'ip') {
11622:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11623:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11624:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11625:                                     if ($urls{$requrl} eq 'add') {
11626:                                         $action = 'none';
11627:                                         last;
11628:                                     } else {
11629:                                         $action = 'delete';
11630:                                         $aclnum = $num;
11631:                                         last;
11632:                                     }
11633:                                 }
11634:                             }
11635:                         }
11636:                     } elsif ($accesstype eq 'public') {
11637:                         if ($urls{$requrl} eq 'add') {
11638:                             $action = 'none';
11639:                             last;
11640:                         } else {
11641:                             $action = 'delete';
11642:                             $aclnum = $num;
11643:                             last;
11644:                         }
11645:                     }
11646:                 } elsif ($accesstype eq 'public') {
11647:                     $action = 'update';
11648:                     $aclnum = $num;
11649:                     last;
11650:                 }
11651:             }
11652:         }
11653:         if ($action eq 'none') {
11654:             next;
11655:         } else {
11656:             my %changes;
11657:             my $newend = 0;
11658:             my $newstart = $now;
11659:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11660:             $changes{$action}{$newkey} = {
11661:                 type => $accesstype,
11662:                 time => {
11663:                     start => $newstart,
11664:                     end   => $newend,
11665:                 },
11666:             };
11667:             if ($accesstype eq 'ip') {
11668:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11669:             }
11670:             my ($outcome,$deloutcome,$new_values,$translation) =
11671:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11672:             unless ($outcome eq 'ok') {
11673:                 $errors .= $outcome.' ';
11674:             }
11675:         }
11676:     }
11677:     if ($errors) {
11678:         $errors =~ s/\s$//;
11679:         return $errors;
11680:     } else {
11681:         return 'ok';
11682:     }
11683: }
11684: 
11685: #------------------------------------------------------Get Marked as Read Only
11686: 
11687: sub get_marked_as_readonly {
11688:     my ($domain,$user,$what,$group) = @_;
11689:     my $current_permissions = &get_portfile_permissions($domain,$user);
11690:     my @readonly_files;
11691:     my $cmp1=$what;
11692:     if (ref($what)) { $cmp1=join('',@{$what}) };
11693:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11694:         if (defined($group)) {
11695:             if ($file_name !~ m-^\Q$group\E/-) {
11696:                 next;
11697:             }
11698:         }
11699:         if (ref($value) eq "ARRAY"){
11700:             foreach my $stored_what (@{$value}) {
11701:                 my $cmp2=$stored_what;
11702:                 if (ref($stored_what) eq 'ARRAY') {
11703:                     $cmp2=join('',@{$stored_what});
11704:                 }
11705:                 if ($cmp1 eq $cmp2) {
11706:                     push(@readonly_files, $file_name);
11707:                     last;
11708:                 } elsif (!defined($what)) {
11709:                     push(@readonly_files, $file_name);
11710:                     last;
11711:                 }
11712:             }
11713:         }
11714:     }
11715:     return @readonly_files;
11716: }
11717: #-----------------------------------------------------------Get Marked as Read Only Hash
11718: 
11719: sub get_marked_as_readonly_hash {
11720:     my ($current_permissions,$group,$what) = @_;
11721:     my %readonly_files;
11722:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11723:         if (defined($group)) {
11724:             if ($file_name !~ m-^\Q$group\E/-) {
11725:                 next;
11726:             }
11727:         }
11728:         if (ref($value) eq "ARRAY"){
11729:             foreach my $stored_what (@{$value}) {
11730:                 if (ref($stored_what) eq 'ARRAY') {
11731:                     foreach my $lock_descriptor(@{$stored_what}) {
11732:                         if ($lock_descriptor eq 'graded') {
11733:                             $readonly_files{$file_name} = 'graded';
11734:                         } elsif ($lock_descriptor eq 'handback') {
11735:                             $readonly_files{$file_name} = 'handback';
11736:                         } else {
11737:                             if (!exists($readonly_files{$file_name})) {
11738:                                 $readonly_files{$file_name} = 'locked';
11739:                             }
11740:                         }
11741:                     }
11742:                 } 
11743:             }
11744:         } 
11745:     }
11746:     return %readonly_files;
11747: }
11748: # ------------------------------------------------------------ Unmark as Read Only
11749: 
11750: sub unmark_as_readonly {
11751:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11752:     # for portfolio submissions, $what contains [$symb,$crsid] 
11753:     my ($domain,$user,$what,$file_name,$group) = @_;
11754:     $file_name = &declutter_portfile($file_name);
11755:     my $symb_crs = $what;
11756:     if (ref($what)) { $symb_crs=join('',@$what); }
11757:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11758:     my ($tmp)=keys(%current_permissions);
11759:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11760:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11761:     foreach my $file (@readonly_files) {
11762: 	my $clean_file = &declutter_portfile($file);
11763: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11764: 	my $current_locks = $current_permissions{$file};
11765:         my @new_locks;
11766:         my @del_keys;
11767:         if (ref($current_locks) eq "ARRAY"){
11768:             foreach my $locker (@{$current_locks}) {
11769:                 my $compare=$locker;
11770:                 if (ref($locker) eq 'ARRAY') {
11771:                     $compare=join('',@{$locker});
11772:                     if ($compare ne $symb_crs) {
11773:                         push(@new_locks, $locker);
11774:                     }
11775:                 }
11776:             }
11777:             if (scalar(@new_locks) > 0) {
11778:                 $current_permissions{$file} = \@new_locks;
11779:             } else {
11780:                 push(@del_keys, $file);
11781:                 &del('file_permissions',\@del_keys, $domain, $user);
11782:                 delete($current_permissions{$file});
11783:             }
11784:         }
11785:     }
11786:     &put('file_permissions',\%current_permissions,$domain,$user);
11787:     return;
11788: }
11789: 
11790: # ------------------------------------------------------------ Directory lister
11791: 
11792: sub dirlist {
11793:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11794:     $uri=~s/^\///;
11795:     $uri=~s/\/$//;
11796:     my ($udom, $uname);
11797:     if ($getuserdir) {
11798:         $udom = $userdomain;
11799:         $uname = $username;
11800:     } else {
11801:         (undef,$udom,$uname)=split(/\//,$uri);
11802:         if(defined($userdomain)) {
11803:             $udom = $userdomain;
11804:         }
11805:         if(defined($username)) {
11806:             $uname = $username;
11807:         }
11808:     }
11809:     my ($dirRoot,$listing,@listing_results);
11810: 
11811:     $dirRoot = $perlvar{'lonDocRoot'};
11812:     if (defined($getpropath)) {
11813:         $dirRoot = &propath($udom,$uname);
11814:         $dirRoot =~ s/\/$//;
11815:     } elsif (defined($getuserdir)) {
11816:         my $subdir=$uname.'__';
11817:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11818:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11819:                    ."/$udom/$subdir/$uname";
11820:     } elsif (defined($alternateRoot)) {
11821:         $dirRoot = $alternateRoot;
11822:     }
11823: 
11824:     if($udom) {
11825:         if($uname) {
11826:             my $uhome = &homeserver($uname,$udom);
11827:             if ($uhome eq 'no_host') {
11828:                 return ([],'no_host');
11829:             }
11830:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11831:                               .$getuserdir.':'.&escape($dirRoot)
11832:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11833:             if ($listing eq 'unknown_cmd') {
11834:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11835:             } else {
11836:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11837:             }
11838:             if ($listing eq 'unknown_cmd') {
11839:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11840:                 @listing_results = split(/:/,$listing);
11841:             } else {
11842:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11843:             }
11844:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11845:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11846:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11847:                 return ([],$listing);
11848:             } else {
11849:                 return (\@listing_results);
11850:             }
11851:         } elsif(!$alternateRoot) {
11852:             my (%allusers,%listerror);
11853: 	    my %servers = &get_servers($udom,'library');
11854:  	    foreach my $tryserver (keys(%servers)) {
11855:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11856:                                   &escape($udom),$tryserver);
11857:                 if ($listing eq 'unknown_cmd') {
11858: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11859: 				      $udom, $tryserver);
11860:                 } else {
11861:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11862:                 }
11863: 		if ($listing eq 'unknown_cmd') {
11864: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11865: 				      $udom, $tryserver);
11866: 		    @listing_results = split(/:/,$listing);
11867: 		} else {
11868: 		    @listing_results =
11869: 			map { &unescape($_); } split(/:/,$listing);
11870: 		}
11871:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11872:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11873:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11874:                     $listerror{$tryserver} = $listing;
11875:                 } else {
11876: 		    foreach my $line (@listing_results) {
11877: 			my ($entry) = split(/&/,$line,2);
11878: 			$allusers{$entry} = 1;
11879: 		    }
11880: 		}
11881:             }
11882:             my @alluserslist=();
11883:             foreach my $user (sort(keys(%allusers))) {
11884:                 push(@alluserslist,$user.'&user');
11885:             }
11886: 
11887:             if (!%listerror) {
11888:                 # no errors
11889:                 return (\@alluserslist);
11890:             } elsif (scalar(keys(%servers)) == 1) {
11891:                 # one library server, one error 
11892:                 my ($key) = keys(%listerror);
11893:                 return (\@alluserslist, $listerror{$key});
11894:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11895:                 # con_lost indicates that we might miss data from at least one
11896:                 # library server
11897:                 return (\@alluserslist, 'con_lost');
11898:             } else {
11899:                 # multiple library servers and no con_lost -> data should be
11900:                 # complete. 
11901:                 return (\@alluserslist);
11902:             }
11903: 
11904:         } else {
11905:             return ([],'missing username');
11906:         }
11907:     } elsif(!defined($getpropath)) {
11908:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11909:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11910:         return (\@all_domains);
11911:     } else {
11912:         return ([],'missing domain');
11913:     }
11914: }
11915: 
11916: # --------------------------------------------- GetFileTimestamp
11917: # This function utilizes dirlist and returns the date stamp for
11918: # when it was last modified.  It will also return an error of -1
11919: # if an error occurs
11920: 
11921: sub GetFileTimestamp {
11922:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11923:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11924:     $studentName   = &LONCAPA::clean_username($studentName);
11925:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11926:                                     undef,$getuserdir);
11927:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11928:         return -1;
11929:     }
11930:     if (ref($fileref) eq 'ARRAY') {
11931:         my @stats = split('&',$fileref->[0]);
11932:         # @stats contains first the filename, then the stat output
11933:         return $stats[10]; # so this is 10 instead of 9.
11934:     } else {
11935:         return -1;
11936:     }
11937: }
11938: 
11939: sub stat_file {
11940:     my ($uri) = @_;
11941:     $uri = &clutter_with_no_wrapper($uri);
11942: 
11943:     my ($udom,$uname,$file);
11944:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11945: 	($udom,$uname,$file) =
11946: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11947: 	$file = 'userfiles/'.$file;
11948:     }
11949:     if ($uri =~ m-^/res/-) {
11950: 	($udom,$uname) = 
11951: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11952: 	$file = $uri;
11953:     }
11954: 
11955:     if (!$udom || !$uname || !$file) {
11956: 	# unable to handle the uri
11957: 	return ();
11958:     }
11959:     my $getpropath;
11960:     if ($file =~ /^userfiles\//) {
11961:         $getpropath = 1;
11962:     }
11963:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11964:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11965:         return ();
11966:     } else {
11967:         if (ref($listref) eq 'ARRAY') {
11968:             my @stats = split('&',$listref->[0]);
11969: 	    shift(@stats); #filename is first
11970: 	    return @stats;
11971:         }
11972:     }
11973:     return ();
11974: }
11975: 
11976: # --------------------------------------------------------- recursedirs
11977: # Recursive function to traverse either a specific user's Authoring Space
11978: # or corresponding Published Resource Space, and populate the hash ref:
11979: # $dirhashref with URLs of all directories, and if $filehashref hash
11980: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11981: # or .rights files in resource space, and .meta, .save, .log, and .bak
11982: # files in Authoring Space.
11983: #
11984: # Inputs:
11985: #
11986: # $is_home - true if current server is home server for user's space
11987: # $context - either: priv, or res respectively for Authoring or Resource Space.
11988: # $docroot - Document root (i.e., /home/httpd/html
11989: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11990: # $relpath - Current path (relative to top level).
11991: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11992: # $filehashref - reference to hash to populate with URLs of files (Optional)
11993: #
11994: # Returns: nothing
11995: #
11996: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11997: #
11998: # Currently used by interface/londocs.pm to create linked select boxes for
11999: # directory and filename to import a Course "Author" resource into a course, and
12000: # also to create linked select boxes for Authoring Space and Directory to choose
12001: # save location for creation of a new "standard" problem from the Course Editor.
12002: #
12003: 
12004: sub recursedirs {
12005:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12006:     return unless (ref($dirhashref) eq 'HASH');
12007:     my $currpath = $docroot.$toppath;
12008:     if ($relpath) {
12009:         $currpath .= "/$relpath";
12010:     }
12011:     my $savefile;
12012:     if (ref($filehashref)) {
12013:         $savefile = 1;
12014:     }
12015:     if ($is_home) {
12016:         if (opendir(my $dirh,$currpath)) {
12017:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12018:                 next if ($item eq '');
12019:                 if (-d "$currpath/$item") {
12020:                     my $newpath;
12021:                     if ($relpath) {
12022:                         $newpath = "$relpath/$item";
12023:                     } else {
12024:                         $newpath = $item;
12025:                     }
12026:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12027:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12028:                 } elsif ($savefile) {
12029:                     if ($context eq 'priv') {
12030:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12031:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12032:                         }
12033:                     } else {
12034:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12035:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12036:                         }
12037:                     }
12038:                 }
12039:             }
12040:             closedir($dirh);
12041:         }
12042:     } else {
12043:         my ($dirlistref,$listerror) =
12044:             &dirlist($toppath.$relpath);
12045:         my @dir_lines;
12046:         my $dirptr=16384;
12047:         if (ref($dirlistref) eq 'ARRAY') {
12048:             foreach my $dir_line (sort
12049:                               {
12050:                                   my ($afile)=split('&',$a,2);
12051:                                   my ($bfile)=split('&',$b,2);
12052:                                   return (lc($afile) cmp lc($bfile));
12053:                               } (@{$dirlistref})) {
12054:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12055:                     split(/\&/,$dir_line,16);
12056:                 $item =~ s/\s+$//;
12057:                 next if (($item =~ /^\.\.?$/) || ($obs));
12058:                 if ($dirptr&$testdir) {
12059:                     my $newpath;
12060:                     if ($relpath) {
12061:                         $newpath = "$relpath/$item";
12062:                     } else {
12063:                         $relpath = '/';
12064:                         $newpath = $item;
12065:                     }
12066:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12067:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12068:                 } elsif ($savefile) {
12069:                     if ($context eq 'priv') {
12070:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12071:                             $filehashref->{$relpath}{$item} = 1;
12072:                         }
12073:                     } else {
12074:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12075:                             $filehashref->{$relpath}{$item} = 1;
12076:                         }
12077:                     }
12078:                 }
12079:             }
12080:         }
12081:     }
12082:     return;
12083: }
12084: 
12085: # -------------------------------------------------------- Value of a Condition
12086: 
12087: # gets the value of a specific preevaluated condition
12088: #    stored in the string  $env{user.state.<cid>}
12089: # or looks up a condition reference in the bighash and if if hasn't
12090: # already been evaluated recurses into docondval to get the value of
12091: # the condition, then memoizing it to 
12092: #   $env{user.state.<cid>.<condition>}
12093: sub directcondval {
12094:     my $number=shift;
12095:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12096: 	&Apache::lonuserstate::evalstate();
12097:     }
12098:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12099: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12100:     } elsif ($number =~ /^_/) {
12101: 	my $sub_condition;
12102: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12103: 		&GDBM_READER(),0640)) {
12104: 	    $sub_condition=$bighash{'conditions'.$number};
12105: 	    untie(%bighash);
12106: 	}
12107: 	my $value = &docondval($sub_condition);
12108: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12109: 	return $value;
12110:     }
12111:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12112:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12113:     } else {
12114:        return 2;
12115:     }
12116: }
12117: 
12118: # get the collection of conditions for this resource
12119: sub condval {
12120:     my $condidx=shift;
12121:     my $allpathcond='';
12122:     foreach my $cond (split(/\|/,$condidx)) {
12123: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12124: 	    $allpathcond.=
12125: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12126: 	}
12127:     }
12128:     $allpathcond=~s/\|$//;
12129:     return &docondval($allpathcond);
12130: }
12131: 
12132: #evaluates an expression of conditions
12133: sub docondval {
12134:     my ($allpathcond) = @_;
12135:     my $result=0;
12136:     if ($env{'request.course.id'}
12137: 	&& defined($allpathcond)) {
12138: 	my $operand='|';
12139: 	my @stack;
12140: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12141: 	    if ($chunk eq '(') {
12142: 		push @stack,($operand,$result);
12143: 	    } elsif ($chunk eq ')') {
12144: 		my $before=pop @stack;
12145: 		if (pop @stack eq '&') {
12146: 		    $result=$result>$before?$before:$result;
12147: 		} else {
12148: 		    $result=$result>$before?$result:$before;
12149: 		}
12150: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12151: 		$operand=$chunk;
12152: 	    } else {
12153: 		my $new=directcondval($chunk);
12154: 		if ($operand eq '&') {
12155: 		    $result=$result>$new?$new:$result;
12156: 		} else {
12157: 		    $result=$result>$new?$result:$new;
12158: 		}
12159: 	    }
12160: 	}
12161:     }
12162:     return $result;
12163: }
12164: 
12165: # ---------------------------------------------------- Devalidate courseresdata
12166: 
12167: sub devalidatecourseresdata {
12168:     my ($coursenum,$coursedomain)=@_;
12169:     my $hashid=$coursenum.':'.$coursedomain;
12170:     &devalidate_cache_new('courseres',$hashid);
12171: }
12172: 
12173: 
12174: # --------------------------------------------------- Course Resourcedata Query
12175: #
12176: #  Parameters:
12177: #      $coursenum    - Number of the course.
12178: #      $coursedomain - Domain at which the course was created.
12179: #  Returns:
12180: #     A hash of the course parameters along (I think) with timestamps
12181: #     and version info.
12182: 
12183: sub get_courseresdata {
12184:     my ($coursenum,$coursedomain)=@_;
12185:     my $coursehom=&homeserver($coursenum,$coursedomain);
12186:     my $hashid=$coursenum.':'.$coursedomain;
12187:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12188:     my %dumpreply;
12189:     unless (defined($cached)) {
12190: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12191: 	$result=\%dumpreply;
12192: 	my ($tmp) = keys(%dumpreply);
12193: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12194: 	    &do_cache_new('courseres',$hashid,$result,600);
12195: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12196: 	    return $tmp;
12197: 	} elsif ($tmp =~ /^(error)/) {
12198: 	    $result=undef;
12199: 	    &do_cache_new('courseres',$hashid,$result,600);
12200: 	}
12201:     }
12202:     return $result;
12203: }
12204: 
12205: sub devalidateuserresdata {
12206:     my ($uname,$udom)=@_;
12207:     my $hashid="$udom:$uname";
12208:     &devalidate_cache_new('userres',$hashid);
12209: }
12210: 
12211: sub get_userresdata {
12212:     my ($uname,$udom)=@_;
12213:     #most student don\'t have any data set, check if there is some data
12214:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12215: 
12216:     my $hashid="$udom:$uname";
12217:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12218:     if (!defined($cached)) {
12219: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12220: 	$result=\%resourcedata;
12221: 	&do_cache_new('userres',$hashid,$result,600);
12222:     }
12223:     my ($tmp)=keys(%$result);
12224:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12225: 	return $result;
12226:     }
12227:     #error 2 occurs when the .db doesn't exist
12228:     if ($tmp!~/error: 2 /) {
12229:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12230: 	    &logthis("<font color=\"blue\">WARNING:".
12231: 		     " Trying to get resource data for ".
12232: 		     $uname." at ".$udom.": ".
12233: 		     $tmp."</font>");
12234:         }
12235:     } elsif ($tmp=~/error: 2 /) {
12236: 	#&EXT_cache_set($udom,$uname);
12237: 	&do_cache_new('userres',$hashid,undef,600);
12238: 	undef($tmp); # not really an error so don't send it back
12239:     }
12240:     return $tmp;
12241: }
12242: #----------------------------------------------- resdata - return resource data
12243: #  Purpose:
12244: #    Return resource data for either users or for a course.
12245: #  Parameters:
12246: #     $name      - Course/user name.
12247: #     $domain    - Name of the domain the user/course is registered on.
12248: #     $type      - Type of thing $name is (must be 'course' or 'user')
12249: #     $mapp      - decluttered URL of enclosing map  
12250: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12251: #     $recurseup - Ref to array of map URLs, starting with map containing
12252: #                  $mapp up through hierarchy of nested maps to top level map.  
12253: #     $courseid  - CourseID (first part of param identifier).
12254: #     $modifier  - Middle part of param identifier.
12255: #     $what      - Last part of param identifier.
12256: #     @which     - Array of names of resources desired.
12257: #  Returns:
12258: #     The value of the first reasource in @which that is found in the
12259: #     resource hash.
12260: #  Exceptional Conditions:
12261: #     If the $type passed in is not valid (not the string 'course' or 
12262: #     'user', an undefined  reference is returned.
12263: #     If none of the resources are found, an undef is returned
12264: sub resdata {
12265:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12266:         $modifier,$what,@which)=@_;
12267:     my $result;
12268:     if ($type eq 'course') {
12269: 	$result=&get_courseresdata($name,$domain);
12270:     } elsif ($type eq 'user') {
12271: 	$result=&get_userresdata($name,$domain);
12272:     }
12273:     if (!ref($result)) { return $result; }    
12274:     foreach my $item (@which) {
12275:         if ($item->[1] eq 'course') {
12276:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12277:                 unless ($$recursed) {
12278:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12279:                     $$recursed = 1;
12280:                 }
12281:                 foreach my $item (@${recurseup}) {
12282:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12283:                     last if (defined($result->{$norecursechk}));
12284:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12285:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12286:                 }
12287:             }
12288:         }
12289:         if (defined($result->{$item->[0]})) {
12290: 	    return [$result->{$item->[0]},$item->[1]];
12291: 	}
12292:     }
12293:     return undef;
12294: }
12295: 
12296: sub get_domain_lti {
12297:     my ($cdom,$context) = @_;
12298:     my ($name,$cachename,%lti);
12299:     if ($context eq 'consumer') {
12300:         $name = 'ltitools';
12301:     } elsif ($context eq 'provider') {
12302:         $name = 'lti';
12303:     } elsif ($context eq 'linkprot') {
12304:         $name = 'ltisec';
12305:     } else {
12306:         return %lti;
12307:     }
12308: 
12309:     if ($context eq 'linkprot') {
12310:         $cachename = $context;
12311:     } else {
12312:         $cachename = $name;
12313:     }
12314:     
12315:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12316:     if (defined($cached)) {
12317:         if (ref($result) eq 'HASH') {
12318:             %lti = %{$result};
12319:         }
12320:     } else {
12321:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12322:         if (ref($domconfig{$name}) eq 'HASH') {
12323:             if ($context eq 'linkprot') {
12324:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12325:                     %lti = %{$domconfig{$name}{'linkprot'}};
12326:                 }
12327:             } else {
12328:                 %lti = %{$domconfig{$name}};
12329:             }
12330:             if (($context eq 'consumer') && (keys(%lti))) {
12331:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12332:                 if (ref($encdomconfig{$name}) eq 'HASH') {
12333:                     foreach my $id (keys(%lti)) {
12334:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12335:                             foreach my $item ('key','secret') {
12336:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12337:                             }
12338:                         }
12339:                     }
12340:                 }
12341:             }
12342:         }
12343:         my $cachetime = 24*60*60;
12344:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12345:     }
12346:     return %lti;
12347: }
12348: 
12349: sub get_course_lti {
12350:     my ($cnum,$cdom) = @_;
12351:     my $hashid=$cdom.'_'.$cnum;
12352:     my %courselti;
12353:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12354:     if (defined($cached)) {
12355:         if (ref($result) eq 'HASH') {
12356:             %courselti = %{$result};
12357:         }
12358:     } else {
12359:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12360:         my $cachetime = 24*60*60;
12361:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12362:     }
12363:     return %courselti;
12364: }
12365: 
12366: sub courselti_itemid {
12367:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12368:     my ($chome,$itemid);
12369:     $chome = &homeserver($cnum,$cdom);
12370:     return if ($chome eq 'no_host');
12371:     if (ref($params) eq 'HASH') {
12372:         my $items = &freeze_escape($params);
12373:         my $rep;
12374:         if (grep { $_ eq $chome } current_machine_ids()) {
12375:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12376:         } else {
12377:             my $escurl = &escape($url);
12378:             my $escmethod = &escape($method);
12379:             my $items = &freeze_escape($params);
12380:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12381:         }
12382:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12383:                 ($rep eq 'unknown_cmd')) {
12384:             $itemid = $rep;
12385:         }
12386:     }
12387:     return $itemid;
12388: }
12389: 
12390: sub domainlti_itemid {
12391:     my ($cdom,$url,$method,$params,$context) = @_;
12392:     my ($primary_id,$itemid);
12393:     $primary_id = &domain($cdom,'primary');
12394:     return if ($primary_id eq '');
12395:     if (ref($params) eq 'HASH') {
12396:         my $items = &freeze_escape($params);
12397:         my $rep;
12398:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12399:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12400:         } else {
12401:             my $cnum = '';
12402:             my $escurl = &escape($url);
12403:             my $escmethod = &escape($method);
12404:             my $items = &freeze_escape($params);
12405:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12406:         }
12407:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12408:                 ($rep eq 'unknown_cmd')) {
12409:             $itemid = $rep;
12410:         }
12411:     }
12412:     return $itemid;
12413: }
12414: 
12415: sub get_numsuppfiles {
12416:     my ($cnum,$cdom,$ignorecache)=@_;
12417:     my $hashid=$cnum.':'.$cdom;
12418:     my ($suppcount,$cached);
12419:     unless ($ignorecache) {
12420:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12421:     }
12422:     unless (defined($cached)) {
12423:         my $chome=&homeserver($cnum,$cdom);
12424:         unless ($chome eq 'no_host') {
12425:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12426:             my $suppmap = 'supplemental.sequence';
12427:             ($suppcount,$supptools,$errors) =
12428:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12429:                                                          $supptools,$errors);
12430:         }
12431:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12432:     }
12433:     return $suppcount;
12434: }
12435: 
12436: #
12437: # EXT resource caching routines
12438: #
12439: 
12440: {
12441: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12442: #
12443: # The course for which we cache
12444: my $cachedmapkey='';
12445: # The cached recursive maps for this course
12446: my %cachedmaps=();
12447: # When this was last done
12448: my $cachedmaptime='';
12449: 
12450: sub clear_EXT_cache_status {
12451:     &delenv('cache.EXT.');
12452: }
12453: 
12454: sub EXT_cache_status {
12455:     my ($target_domain,$target_user) = @_;
12456:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12457:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12458:         # We know already the user has no data
12459:         return 1;
12460:     } else {
12461:         return 0;
12462:     }
12463: }
12464: 
12465: sub EXT_cache_set {
12466:     my ($target_domain,$target_user) = @_;
12467:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12468:     #&appenv({$cachename => time});
12469: }
12470: 
12471: # --------------------------------------------------------- Value of a Variable
12472: sub EXT {
12473: 
12474:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12475:     unless ($varname) { return ''; }
12476:     #get real user name/domain, courseid and symb
12477:     my $courseid;
12478:     my $publicuser;
12479:     if ($symbparm) {
12480: 	$symbparm=&get_symb_from_alias($symbparm);
12481:     }
12482:     if (!($uname && $udom)) {
12483:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12484:       if (!$symbparm) {	$symbparm=$cursymb; }
12485:     } else {
12486: 	$courseid=$env{'request.course.id'};
12487:     }
12488:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12489:     my $rest;
12490:     if (defined($therest[0])) {
12491:        $rest=join('.',@therest);
12492:     } else {
12493:        $rest='';
12494:     }
12495: 
12496:     my $qualifierrest=$qualifier;
12497:     if ($rest) { $qualifierrest.='.'.$rest; }
12498:     my $spacequalifierrest=$space;
12499:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12500:     if ($realm eq 'user') {
12501: # --------------------------------------------------------------- user.resource
12502: 	if ($space eq 'resource') {
12503: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12504: 		  || defined($Apache::lonhomework::parsing_a_task))
12505: 		 &&
12506: 		 ($symbparm eq &symbread()) ) {
12507: 		# if we are in the middle of processing the resource the
12508: 		# get the value we are planning on committing
12509:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12510:                     return $Apache::lonhomework::results{$qualifierrest};
12511:                 } else {
12512:                     return $Apache::lonhomework::history{$qualifierrest};
12513:                 }
12514: 	    } else {
12515: 		my %restored;
12516: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12517: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12518: 		} else {
12519: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12520: 		}
12521: 		return $restored{$qualifierrest};
12522: 	    }
12523: # ----------------------------------------------------------------- user.access
12524:         } elsif ($space eq 'access') {
12525: 	    # FIXME - not supporting calls for a specific user
12526:             return &allowed($qualifier,$rest);
12527: # ------------------------------------------ user.preferences, user.environment
12528:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12529: 	    if (($uname eq $env{'user.name'}) &&
12530: 		($udom eq $env{'user.domain'})) {
12531: 		return $env{join('.',('environment',$qualifierrest))};
12532: 	    } else {
12533: 		my %returnhash;
12534: 		if (!$publicuser) {
12535: 		    %returnhash=&userenvironment($udom,$uname,
12536: 						 $qualifierrest);
12537: 		}
12538: 		return $returnhash{$qualifierrest};
12539: 	    }
12540: # ----------------------------------------------------------------- user.course
12541:         } elsif ($space eq 'course') {
12542: 	    # FIXME - not supporting calls for a specific user
12543:             return $env{join('.',('request.course',$qualifier))};
12544: # ------------------------------------------------------------------- user.role
12545:         } elsif ($space eq 'role') {
12546: 	    # FIXME - not supporting calls for a specific user
12547:             my ($role,$where)=split(/\./,$env{'request.role'});
12548:             if ($qualifier eq 'value') {
12549: 		return $role;
12550:             } elsif ($qualifier eq 'extent') {
12551:                 return $where;
12552:             }
12553: # ----------------------------------------------------------------- user.domain
12554:         } elsif ($space eq 'domain') {
12555:             return $udom;
12556: # ------------------------------------------------------------------- user.name
12557:         } elsif ($space eq 'name') {
12558:             return $uname;
12559: # ---------------------------------------------------- Any other user namespace
12560:         } else {
12561: 	    my %reply;
12562: 	    if (!$publicuser) {
12563: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12564: 	    }
12565: 	    return $reply{$qualifierrest};
12566:         }
12567:     } elsif ($realm eq 'query') {
12568: # ---------------------------------------------- pull stuff out of query string
12569:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12570: 						[$spacequalifierrest]);
12571: 	return $env{'form.'.$spacequalifierrest}; 
12572:    } elsif ($realm eq 'request') {
12573: # ------------------------------------------------------------- request.browser
12574:         if ($space eq 'browser') {
12575:             return $env{'browser.'.$qualifier};
12576: # ------------------------------------------------------------ request.filename
12577:         } else {
12578:             return $env{'request.'.$spacequalifierrest};
12579:         }
12580:     } elsif ($realm eq 'course') {
12581: # ---------------------------------------------------------- course.description
12582:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12583:     } elsif ($realm eq 'resource') {
12584: 
12585: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12586: 	    if (!$symbparm) { $symbparm=&symbread(); }
12587: 	}
12588: 
12589:         if ($qualifier eq '') {
12590: 	    if ($space eq 'title') {
12591: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12592: 	        return &gettitle($symbparm);
12593: 	    }
12594: 	
12595: 	    if ($space eq 'map') {
12596: 	        my ($map) = &decode_symb($symbparm);
12597: 	        return &symbread($map);
12598: 	    }
12599:             if ($space eq 'maptitle') {
12600:                 my ($map) = &decode_symb($symbparm);
12601:                 return &gettitle($map);
12602:             }
12603: 	    if ($space eq 'filename') {
12604: 	        if ($symbparm) {
12605: 		    return &clutter((&decode_symb($symbparm))[2]);
12606: 	        }
12607: 	        return &hreflocation('',$env{'request.filename'});
12608: 	    }
12609: 
12610:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12611:                 if ($space eq 'visibleparts') {
12612:                     my $navmap = Apache::lonnavmaps::navmap->new();
12613:                     my $item;
12614:                     if (ref($navmap)) {
12615:                         my $res = $navmap->getBySymb($symbparm);
12616:                         my $parts = $res->parts();
12617:                         if (ref($parts) eq 'ARRAY') {
12618:                             $item = join(',',@{$parts});
12619:                         }
12620:                         undef($navmap);
12621:                     }
12622:                     return $item;
12623:                 }
12624:             }
12625:         }
12626: 
12627: 	my ($section, $group, @groups, @recurseup, $recursed);
12628:         if (ref($recurseupref) eq 'ARRAY') {
12629:             @recurseup = @{$recurseupref};
12630:             $recursed = 1;
12631:         }
12632: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12633:         if (($courseid eq '') && ($cid)) {
12634:             $courseid = $cid;
12635:         }
12636: 	if (($symbparm && $courseid) && 
12637: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12638: 
12639: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12640: 
12641: # ----------------------------------------------------- Cascading lookup scheme
12642: 	    my $symbp=$symbparm;
12643: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12644: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12645:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12646: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12647: 	    if (($env{'user.name'} eq $uname) &&
12648: 		($env{'user.domain'} eq $udom)) {
12649: 		$section=$env{'request.course.sec'};
12650:                 @groups = split(/:/,$env{'request.course.groups'});  
12651:                 @groups=&sort_course_groups($courseid,@groups); 
12652: 	    } else {
12653: 		if (! defined($usection)) {
12654: 		    $section=&getsection($udom,$uname,$courseid);
12655: 		} else {
12656: 		    $section = $usection;
12657: 		}
12658:                 @groups = &get_users_groups($udom,$uname,$courseid);
12659: 	    }
12660: 
12661: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12662: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12663:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12664: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12665: 
12666: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12667: 	    my $courselevelr=$courseid.'.'.$symbparm;
12668:             $courseleveli=$courseid.'.'.$recurseparm;
12669: 	    $courselevelm=$courseid.'.'.$mapparm;
12670: 
12671: # ----------------------------------------------------------- first, check user
12672: 
12673: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12674:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12675: 				       ([$courselevelr,'resource'],
12676: 					[$courselevelm,'map'     ],
12677:                                         [$courseleveli,'map'     ],
12678: 					[$courselevel, 'course'  ]));
12679: 	    if (defined($userreply)) { return &get_reply($userreply); }
12680: 
12681: # ------------------------------------------------ second, check some of course
12682:             my $coursereply;
12683:             if (@groups > 0) {
12684:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12685:                                        $recurseparm,$mapparm,$spacequalifierrest,
12686:                                        $mapp,\$recursed,\@recurseup);
12687:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12688:             }
12689: 
12690: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12691: 				  $env{'course.'.$courseid.'.domain'},
12692: 				  'course',$mapp,\$recursed,\@recurseup,
12693:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12694: 				  ([$seclevelr,   'resource'],
12695: 				   [$seclevelm,   'map'     ],
12696:                                    [$secleveli,   'map'     ],
12697: 				   [$seclevel,    'course'  ],
12698: 				   [$courselevelr,'resource']));
12699: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12700: 
12701: # ------------------------------------------------------ third, check map parms
12702: 	    my %parmhash=();
12703: 	    my $thisparm='';
12704: 	    if (tie(%parmhash,'GDBM_File',
12705: 		    $env{'request.course.fn'}.'_parms.db',
12706: 		    &GDBM_READER(),0640)) {
12707: 		$thisparm=$parmhash{$symbparm};
12708: 		untie(%parmhash);
12709: 	    }
12710: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12711: 	}
12712: # ------------------------------------------ fourth, look in resource metadata
12713:  
12714:         my $what = $spacequalifierrest;
12715: 	$what=~s/\./\_/;
12716: 	my $filename;
12717: 	if (!$symbparm) { $symbparm=&symbread(); }
12718: 	if ($symbparm) {
12719: 	    $filename=(&decode_symb($symbparm))[2];
12720: 	} else {
12721: 	    $filename=$env{'request.filename'};
12722: 	}
12723:         my $toolsymb;
12724:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12725:             $toolsymb = $symbparm;
12726:         }
12727: 	my $metadata=&metadata($filename,$what,$toolsymb);
12728: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12729: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12730: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12731: 
12732: # ----------------------------------------------- fifth, look in rest of course
12733: 	if ($symbparm && defined($courseid) && 
12734: 	    $courseid eq $env{'request.course.id'}) {
12735: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12736: 				     $env{'course.'.$courseid.'.domain'},
12737: 				     'course',$mapp,\$recursed,\@recurseup,
12738:                                      $courseid,'.',$spacequalifierrest,
12739: 				     ([$courselevelm,'map'   ],
12740:                                       [$courseleveli,'map'   ],
12741: 				      [$courselevel, 'course']));
12742: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12743: 	}
12744: # ------------------------------------------------------------------ Cascade up
12745: 	unless ($space eq '0') {
12746: 	    my @parts=split(/_/,$space);
12747: 	    my $id=pop(@parts);
12748: 	    my $part=join('_',@parts);
12749: 	    if ($part eq '') { $part='0'; }
12750: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12751: 				 $symbparm,$udom,$uname,$section,1);
12752: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12753: 	}
12754: 	if ($recurse) { return undef; }
12755: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12756: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12757: # ---------------------------------------------------- Any other user namespace
12758:     } elsif ($realm eq 'environment') {
12759: # ----------------------------------------------------------------- environment
12760: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12761: 	    return $env{'environment.'.$spacequalifierrest};
12762: 	} else {
12763: 	    if ($uname eq 'anonymous' && $udom eq '') {
12764: 		return '';
12765: 	    }
12766: 	    my %returnhash=&userenvironment($udom,$uname,
12767: 					    $spacequalifierrest);
12768: 	    return $returnhash{$spacequalifierrest};
12769: 	}
12770:     } elsif ($realm eq 'system') {
12771: # ----------------------------------------------------------------- system.time
12772: 	if ($space eq 'time') {
12773: 	    return time;
12774:         }
12775:     } elsif ($realm eq 'server') {
12776: # ----------------------------------------------------------------- system.time
12777: 	if ($space eq 'name') {
12778: 	    return $ENV{'SERVER_NAME'};
12779:         }
12780:     } elsif ($realm eq 'client') {
12781:         if ($space eq 'remote_addr') {
12782:             return &get_requestor_ip();
12783:         }
12784:     }
12785:     return '';
12786: }
12787: 
12788: sub get_reply {
12789:     my ($reply_value) = @_;
12790:     if (ref($reply_value) eq 'ARRAY') {
12791:         if (wantarray) {
12792: 	    return @$reply_value;
12793:         }
12794:         return $reply_value->[0];
12795:     } else {
12796:         return $reply_value;
12797:     }
12798: }
12799: 
12800: sub check_group_parms {
12801:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12802:         $recursed,$recurseupref) = @_;
12803:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12804:                   [$what,'course']);
12805:     my $coursereply;
12806:     foreach my $group (@{$groups}) {
12807:         my @groupitems = ();
12808:         foreach my $level (@levels) {
12809:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12810:              push(@groupitems,[$item,$level->[1]]);
12811:         }
12812:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12813:                                    $env{'course.'.$courseid.'.domain'},
12814:                                    'course',$mapp,$recursed,$recurseupref,
12815:                                    $courseid,'.['.$group.'].',$what,
12816:                                    @groupitems);
12817:         last if (defined($coursereply));
12818:     }
12819:     return $coursereply;
12820: }
12821: 
12822: sub get_map_hierarchy {
12823:     my ($mapname,$courseid) = @_;
12824:     my @recurseup = ();
12825:     if ($mapname) {
12826:         if (($cachedmapkey eq $courseid) &&
12827:             (abs($cachedmaptime-time)<5)) {
12828:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12829:                 return @{$cachedmaps{$mapname}};
12830:             }
12831:         }
12832:         my $navmap = Apache::lonnavmaps::navmap->new();
12833:         if (ref($navmap)) {
12834:             @recurseup = $navmap->recurseup_maps($mapname);
12835:             undef($navmap);
12836:             $cachedmaps{$mapname} = \@recurseup;
12837:             $cachedmaptime=time;
12838:             $cachedmapkey=$courseid;
12839:         }
12840:     }
12841:     return @recurseup;
12842: }
12843: 
12844: }
12845: 
12846: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12847:     my ($courseid,@groups) = @_;
12848:     @groups = sort(@groups);
12849:     return @groups;
12850: }
12851: 
12852: sub packages_tab_default {
12853:     my ($uri,$varname,$toolsymb)=@_;
12854:     my (undef,$part,$name)=split(/\./,$varname);
12855: 
12856:     my (@extension,@specifics,$do_default);
12857:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12858: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12859: 	if ($pack_type eq 'default') {
12860: 	    $do_default=1;
12861: 	} elsif ($pack_type eq 'extension') {
12862: 	    push(@extension,[$package,$pack_type,$pack_part]);
12863: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12864: 	    # only look at packages defaults for packages that this id is
12865: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12866: 	}
12867:     }
12868:     # first look for a package that matches the requested part id
12869:     foreach my $package (@specifics) {
12870: 	my (undef,$pack_type,$pack_part)=@{$package};
12871: 	next if ($pack_part ne $part);
12872: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12873: 	    return $packagetab{"$pack_type&$name&default"};
12874: 	}
12875:     }
12876:     # look for any possible matching non extension_ package
12877:     foreach my $package (@specifics) {
12878: 	my (undef,$pack_type,$pack_part)=@{$package};
12879: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12880: 	    return $packagetab{"$pack_type&$name&default"};
12881: 	}
12882: 	if ($pack_type eq 'part') { $pack_part='0'; }
12883: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12884: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12885: 	}
12886:     }
12887:     # look for any posible extension_ match
12888:     foreach my $package (@extension) {
12889: 	my ($package,$pack_type)=@{$package};
12890: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12891: 	    return $packagetab{"$pack_type&$name&default"};
12892: 	}
12893: 	if (defined($packagetab{$package."&$name&default"})) {
12894: 	    return $packagetab{$package."&$name&default"};
12895: 	}
12896:     }
12897:     # look for a global default setting
12898:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12899: 	return $packagetab{"default&$name&default"};
12900:     }
12901:     return undef;
12902: }
12903: 
12904: sub add_prefix_and_part {
12905:     my ($prefix,$part)=@_;
12906:     my $keyroot;
12907:     if (defined($prefix) && $prefix !~ /^__/) {
12908: 	# prefix that has a part already
12909: 	$keyroot=$prefix;
12910:     } elsif (defined($prefix)) {
12911: 	# prefix that is missing a part
12912: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12913:     } else {
12914: 	# no prefix at all
12915: 	if (defined($part)) { $keyroot='_'.$part; }
12916:     }
12917:     return $keyroot;
12918: }
12919: 
12920: # ---------------------------------------------------------------- Get metadata
12921: 
12922: my %metaentry;
12923: my %importedpartids;
12924: my %importedrespids;
12925: sub metadata {
12926:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12927:     $uri=&declutter($uri);
12928:     # if it is a non metadata possible uri return quickly
12929:     if (($uri eq '') || 
12930: 	(($uri =~ m|^/*adm/|) && 
12931: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12932:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12933: 	return undef;
12934:     }
12935:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12936: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12937: 	return undef;
12938:     }
12939:     my $filename=$uri;
12940:     $uri=~s/\.meta$//;
12941: #
12942: # Is the metadata already cached?
12943: # Look at timestamp of caching
12944: # Everything is cached by the main uri, libraries are never directly cached
12945: #
12946:     if (!defined($liburi)) {
12947: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12948: 	if (defined($cached)) { return $result->{':'.$what}; }
12949:     }
12950: 
12951: #
12952: # If the uri is for an external tool the file from
12953: # which metadata should be retrieved depends on whether
12954: # the tool had been configured to be gradable (set in the Course
12955: # Editor or Resource Editor).
12956: #
12957: # If a valid symb has been included as the third arg in the call
12958: # to &metadata() that can be used to retrieve the value of
12959: # parameter_0_gradable set for the resource, and included in the
12960: # uploaded map containing the tool. The value is retrieved via
12961: # &EXT(), if a valid symb is available.  Otherwise the value of
12962: # gradable in the exttool_$marker.db file for the tool instance
12963: # is retrieved via &get().
12964: #
12965: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12966: # hiddenresource and encrypturl (during course initialization)
12967: # the map-level parameter for resource.0.gradable included in the 
12968: # uploaded map containing the tool will not yet have been stored
12969: # in the user_course_parms.db file for the user's session, so in 
12970: # this case fall back to retrieving gradable status from the
12971: # exttool_$marker.db file.
12972: #
12973: # In order to avoid an infinite loop, &metadata() will return
12974: # before a call to &EXT(), if the uri is for an external tool
12975: # and the $what for which metadata is being requested is
12976: # parameter_0_gradable or 0_gradable.
12977: #
12978: 
12979:     if ($uri =~ /ext\.tool$/) {
12980:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12981:             return;
12982:         } else {
12983:             my ($checked,$use_passback);
12984:             if ($toolsymb ne '') {
12985:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12986:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12987:                     $checked = 1;
12988:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12989:                         $use_passback = 1;
12990:                     }
12991:                 }
12992:             }
12993:             unless ($checked) {
12994:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12995:                 $marker=~s/\D//g;
12996:                 if ($marker) {
12997:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12998:                     $use_passback = $toolsettings{'gradable'};
12999:                 }
13000:             }
13001:             if ($use_passback) {
13002:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13003:             } else {
13004:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13005:             }
13006:         }
13007:     }
13008: 
13009:     {
13010: # Imported parts would go here
13011:         my @origfiletagids=();
13012:         my $importedparts=0;
13013: 
13014: # Imported responseids would go here
13015:         my $importedresponses=0;
13016: #
13017: # Is this a recursive call for a library?
13018: #
13019: #	if (! exists($metacache{$uri})) {
13020: #	    $metacache{$uri}={};
13021: #	}
13022: 	my $cachetime = 60*60;
13023:         if ($liburi) {
13024: 	    $liburi=&declutter($liburi);
13025:             $filename=$liburi;
13026:         } else {
13027: 	    &devalidate_cache_new('meta',$uri);
13028: 	    undef(%metaentry);
13029: 	}
13030:         my %metathesekeys=();
13031:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13032: 	my $metastring;
13033: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13034: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13035: 	    $metastring = 
13036: 		&Apache::lonnet::ssi_body($which,
13037: 					  ('grade_target' => 'meta'));
13038: 	    $cachetime = 1; # only want this cached in the child not long term
13039: 	} elsif (($uri !~ m -^(editupload)/-) && 
13040:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13041: 	    my $file=&filelocation('',&clutter($filename));
13042: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13043: 	    $metastring=&getfile($file);
13044: 	}
13045:         my $parser=HTML::LCParser->new(\$metastring);
13046:         my $token;
13047:         undef %metathesekeys;
13048:         while ($token=$parser->get_token) {
13049: 	    if ($token->[0] eq 'S') {
13050: 		if (defined($token->[2]->{'package'})) {
13051: #
13052: # This is a package - get package info
13053: #
13054: 		    my $package=$token->[2]->{'package'};
13055: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13056: 		    if (defined($token->[2]->{'id'})) { 
13057: 			$keyroot.='_'.$token->[2]->{'id'}; 
13058: 		    }
13059: 		    if ($metaentry{':packages'}) {
13060: 			$metaentry{':packages'}.=','.$package.$keyroot;
13061: 		    } else {
13062: 			$metaentry{':packages'}=$package.$keyroot;
13063: 		    }
13064: 		    foreach my $pack_entry (keys(%packagetab)) {
13065: 			my $part=$keyroot;
13066: 			$part=~s/^\_//;
13067: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13068: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13069: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13070: 			    # ignore package.tab specified default values
13071:                             # here &package_tab_default() will fetch those
13072: 			    if ($subp eq 'default') { next; }
13073: 			    my $value=$packagetab{$pack_entry};
13074: 			    my $unikey;
13075: 			    if ($pack =~ /_0$/) {
13076: 				$unikey='parameter_0_'.$name;
13077: 				$part=0;
13078: 			    } else {
13079: 				$unikey='parameter'.$keyroot.'_'.$name;
13080: 			    }
13081: 			    if ($subp eq 'display') {
13082: 				$value.=' [Part: '.$part.']';
13083: 			    }
13084: 			    $metaentry{':'.$unikey.'.part'}=$part;
13085: 			    $metathesekeys{$unikey}=1;
13086: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13087: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13088: 			    }
13089: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13090: 				$metaentry{':'.$unikey}=
13091: 				    $metaentry{':'.$unikey.'.default'};
13092: 			    }
13093: 			}
13094: 		    }
13095: 		} else {
13096: #
13097: # This is not a package - some other kind of start tag
13098: #
13099: 		    my $entry=$token->[1];
13100: 		    my $unikey='';
13101: 
13102: 		    if ($entry eq 'import') {
13103: #
13104: # Importing a library here
13105: #
13106:                         my $location=$parser->get_text('/import');
13107:                         my $dir=$filename;
13108:                         $dir=~s|[^/]*$||;
13109:                         $location=&filelocation($dir,$location);
13110: 
13111:                         my $importid=$token->[2]->{'id'};
13112:                         my $importmode=$token->[2]->{'importmode'};
13113: #
13114: # Check metadata for imported file to
13115: # see if it contained response items
13116: #
13117:                         my ($origfile,@libfilekeys);
13118:                         my %currmetaentry = %metaentry;
13119:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13120:                                                            $depthcount+1));
13121:                         if (grep(/^responseorder$/,@libfilekeys)) {
13122:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13123:                                                              undef,$depthcount+1);
13124:                             if ($libresponseorder ne '') {
13125:                                 if ($#origfiletagids<0) {
13126:                                     undef(%importedrespids);
13127:                                     undef(%importedpartids);
13128:                                 }
13129:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13130:                                 if (@respids) {
13131:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13132:                                 }
13133:                                 if ($importedrespids{$importid} ne '') {
13134:                                     $importedresponses = 1;
13135: # We need to get the original file and the imported file to get the response order correct
13136: # Load and inspect original file
13137:                                     if ($#origfiletagids<0) {
13138:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13139:                                         $origfile=&getfile($origfilelocation);
13140:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13141:                                     }
13142:                                 }
13143:                             }
13144:                         }
13145: # Do not overwrite contents of %metaentry hash for resource itself with 
13146: # hash populated for imported library file
13147:                         %metaentry = %currmetaentry;
13148:                         undef(%currmetaentry);
13149:                         if ($importmode eq 'part') {
13150: # Import as part(s)
13151:                            $importedparts=1;
13152: # We need to get the original file and the imported file to get the part order correct
13153: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13154: # Load and inspect original file if we didn't do that already
13155:                            if ($#origfiletagids<0) {
13156:                                undef(%importedrespids);
13157:                                undef(%importedpartids);
13158:                                if ($origfile eq '') {
13159:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13160:                                    $origfile=&getfile($origfilelocation);
13161:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13162:                                }
13163:                            }
13164:                            my @impfilepartids;
13165: # If <partorder> tag is included in metadata for the imported file
13166: # get the parts in the imported file from that.
13167:                            if (grep(/^partorder$/,@libfilekeys)) {
13168:                                %currmetaentry = %metaentry;
13169:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13170:                                                             $depthcount+1);
13171:                                %metaentry = %currmetaentry;
13172:                                undef(%currmetaentry);
13173:                                if ($libpartorder ne '') {
13174:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13175:                                }
13176:                            } else {
13177: # If no <partorder> tag available, load and inspect imported file
13178:                                my $impfile=&getfile($location);
13179:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13180:                            }
13181:                            if ($#impfilepartids>=0) {
13182: # This problem had parts
13183:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13184:                            } else {
13185: # Importing by turning a single problem into a problem part
13186: # It gets the import-tags ID as part-ID
13187:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13188:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13189:                            }
13190:                         } else {
13191: # Import as problem or as normal import
13192:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13193:                             unless ($importmode eq 'problem') {
13194: # Normal import
13195:                                 if (defined($token->[2]->{'id'})) {
13196:                                     $unikey.='_'.$token->[2]->{'id'};
13197:                                 }
13198:                             }
13199: # Check metadata for imported file to
13200: # see if it contained parts
13201:                             if (grep(/^partorder$/,@libfilekeys)) {
13202:                                 %currmetaentry = %metaentry;
13203:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13204:                                                              $depthcount+1);
13205:                                 %metaentry = %currmetaentry;
13206:                                 undef(%currmetaentry);
13207:                                 if ($libpartorder ne '') {
13208:                                     $importedparts = 1;
13209:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13210:                                 }
13211:                             }
13212:                         }
13213: 			if ($depthcount<20) {
13214: 			    my $metadata = 
13215: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13216: 					  $depthcount+1);
13217: 			    foreach my $meta (split(',',$metadata)) {
13218: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13219: 				$metathesekeys{$meta}=1;
13220: 			    }
13221:                         }
13222: 		    } else {
13223: #
13224: # Not importing, some other kind of non-package, non-library start tag
13225: # 
13226:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13227:                         if (defined($token->[2]->{'id'})) {
13228:                             $unikey.='_'.$token->[2]->{'id'};
13229:                         }
13230: 			if (defined($token->[2]->{'name'})) { 
13231: 			    $unikey.='_'.$token->[2]->{'name'}; 
13232: 			}
13233: 			$metathesekeys{$unikey}=1;
13234: 			foreach my $param (@{$token->[3]}) {
13235: 			    $metaentry{':'.$unikey.'.'.$param} =
13236: 				$token->[2]->{$param};
13237: 			}
13238: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13239: 			my $default=$metaentry{':'.$unikey.'.default'};
13240: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13241: 		 # only ws inside the tag, and not in default, so use default
13242: 		 # as value
13243: 			    $metaentry{':'.$unikey}=$default;
13244: 			} elsif ( $internaltext =~ /\S/ ) {
13245: 		  # something interesting inside the tag
13246: 			    $metaentry{':'.$unikey}=$internaltext;
13247: 			} else {
13248: 		  # no interesting values, don't set a default
13249: 			}
13250: # end of not-a-package not-a-library import
13251: 		    }
13252: # end of not-a-package start tag
13253: 		}
13254: # the next is the end of "start tag"
13255: 	    }
13256: 	}
13257: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13258: 	$extension = lc($extension);
13259: 	if ($extension eq 'htm') { $extension='html'; }
13260: 
13261: 	foreach my $key (keys(%packagetab)) {
13262: 	    #no specific packages #how's our extension
13263: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13264: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13265: 					 \%metathesekeys);
13266: 	}
13267: 
13268: 	if (!exists($metaentry{':packages'})
13269: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13270: 	    foreach my $key (keys(%packagetab)) {
13271: 		#no specific packages well let's get default then
13272: 		if ($key!~/^default&/) { next; }
13273: 		&metadata_create_package_def($uri,$key,'default',
13274: 					     \%metathesekeys);
13275: 	    }
13276: 	}
13277: # are there custom rights to evaluate
13278: 	if ($metaentry{':copyright'} eq 'custom') {
13279: 
13280:     #
13281:     # Importing a rights file here
13282:     #
13283: 	    unless ($depthcount) {
13284: 		my $location=$metaentry{':customdistributionfile'};
13285: 		my $dir=$filename;
13286: 		$dir=~s|[^/]*$||;
13287: 		$location=&filelocation($dir,$location);
13288: 		my $rights_metadata =
13289: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13290: 			      $depthcount+1);
13291: 		foreach my $rights (split(',',$rights_metadata)) {
13292: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13293: 		    $metathesekeys{$rights}=1;
13294: 		}
13295: 	    }
13296: 	}
13297: 	# uniqifiy package listing
13298: 	my %seen;
13299: 	my @uniq_packages =
13300: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13301: 	$metaentry{':packages'} = join(',',@uniq_packages);
13302: 
13303:         if (($importedresponses) || ($importedparts)) {
13304:             if ($importedparts) {
13305: # We had imported parts and need to rebuild partorder
13306:                 $metaentry{':partorder'}='';
13307:                 $metathesekeys{'partorder'}=1;
13308:             }
13309:             if ($importedresponses) {
13310: # We had imported responses and need to rebuil responseorder
13311:                 $metaentry{':responseorder'}='';
13312:                 $metathesekeys{'responseorder'}=1;
13313:             }
13314:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13315:                 my $origid = $origfiletagids[$index+1];
13316:                 if ($origfiletagids[$index] eq 'part') {
13317: # Original part, part of the problem
13318:                     if ($importedparts) {
13319:                         $metaentry{':partorder'}.=','.$origid;
13320:                     }
13321:                 } elsif ($origfiletagids[$index] eq 'import') {
13322:                     if ($importedparts) {
13323: # We have imported parts at this position
13324:                         if ($importedpartids{$origid} ne '') {
13325:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13326:                         }
13327:                     }
13328:                     if ($importedresponses) {
13329: # We have imported responses at this position
13330:                         if ($importedrespids{$origid} ne '') {
13331:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13332:                         }
13333:                     }
13334:                 } else {
13335: # Original response item, part of the problem
13336:                     if ($importedresponses) {
13337:                         $metaentry{':responseorder'}.=','.$origid;
13338:                     }
13339:                 }
13340:             }
13341:             if ($importedparts) {
13342:                 $metaentry{':partorder'}=~s/^\,//;
13343:             }
13344:             if ($importedresponses) {
13345:                 $metaentry{':responseorder'}=~s/^\,//;
13346:             }
13347:         }
13348: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13349: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13350: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13351:         unless ($liburi) {
13352: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13353:         }
13354: # this is the end of "was not already recently cached
13355:     }
13356:     return $metaentry{':'.$what};
13357: }
13358: 
13359: sub metadata_create_package_def {
13360:     my ($uri,$key,$package,$metathesekeys)=@_;
13361:     my ($pack,$name,$subp)=split(/\&/,$key);
13362:     if ($subp eq 'default') { next; }
13363:     
13364:     if (defined($metaentry{':packages'})) {
13365: 	$metaentry{':packages'}.=','.$package;
13366:     } else {
13367: 	$metaentry{':packages'}=$package;
13368:     }
13369:     my $value=$packagetab{$key};
13370:     my $unikey;
13371:     $unikey='parameter_0_'.$name;
13372:     $metaentry{':'.$unikey.'.part'}=0;
13373:     $$metathesekeys{$unikey}=1;
13374:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13375: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13376:     }
13377:     if (defined($metaentry{':'.$unikey.'.default'})) {
13378: 	$metaentry{':'.$unikey}=
13379: 	    $metaentry{':'.$unikey.'.default'};
13380:     }
13381: }
13382: 
13383: sub metadata_generate_part0 {
13384:     my ($metadata,$metacache,$uri) = @_;
13385:     my %allnames;
13386:     foreach my $metakey (keys(%$metadata)) {
13387: 	if ($metakey=~/^parameter\_(.*)/) {
13388: 	  my $part=$$metacache{':'.$metakey.'.part'};
13389: 	  my $name=$$metacache{':'.$metakey.'.name'};
13390: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13391: 	    $allnames{$name}=$part;
13392: 	  }
13393: 	}
13394:     }
13395:     foreach my $name (keys(%allnames)) {
13396:       $$metadata{"parameter_0_$name"}=1;
13397:       my $key=":parameter_0_$name";
13398:       $$metacache{"$key.part"}='0';
13399:       $$metacache{"$key.name"}=$name;
13400:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13401: 					   $allnames{$name}.'_'.$name.
13402: 					   '.type'};
13403:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13404: 			     '.display'};
13405:       my $expr='[Part: '.$allnames{$name}.']';
13406:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13407:       $$metacache{"$key.display"}=$olddis;
13408:     }
13409: }
13410: 
13411: # ------------------------------------------------------ Devalidate title cache
13412: 
13413: sub devalidate_title_cache {
13414:     my ($url)=@_;
13415:     if (!$env{'request.course.id'}) { return; }
13416:     my $symb=&symbread($url);
13417:     if (!$symb) { return; }
13418:     my $key=$env{'request.course.id'}."\0".$symb;
13419:     &devalidate_cache_new('title',$key);
13420: }
13421: 
13422: # ------------------------------------------------- Get the title of a course
13423: 
13424: sub current_course_title {
13425:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13426: }
13427: # ------------------------------------------------- Get the title of a resource
13428: 
13429: sub gettitle {
13430:     my $urlsymb=shift;
13431:     my $symb=&symbread($urlsymb);
13432:     if ($symb) {
13433: 	my $key=$env{'request.course.id'}."\0".$symb;
13434: 	my ($result,$cached)=&is_cached_new('title',$key);
13435: 	if (defined($cached)) { 
13436: 	    return $result;
13437: 	}
13438: 	my ($map,$resid,$url)=&decode_symb($symb);
13439: 	my $title='';
13440: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13441: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13442: 	} else {
13443: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13444: 		    &GDBM_READER(),0640)) {
13445: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13446: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13447: 		untie(%bighash);
13448: 	    }
13449: 	}
13450: 	$title=~s/\&colon\;/\:/gs;
13451: 	if ($title) {
13452: # Remember both $symb and $title for dynamic metadata
13453:             $accesshash{$symb.'___crstitle'}=$title;
13454:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13455: # Cache this title and then return it
13456: 	    return &do_cache_new('title',$key,$title,600);
13457: 	}
13458: 	$urlsymb=$url;
13459:     }
13460:     my $title=&metadata($urlsymb,'title');
13461:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13462:     return $title;
13463: }
13464: 
13465: sub get_slot {
13466:     my ($which,$cnum,$cdom)=@_;
13467:     if (!$cnum || !$cdom) {
13468: 	(undef,my $courseid)=&whichuser();
13469: 	$cdom=$env{'course.'.$courseid.'.domain'};
13470: 	$cnum=$env{'course.'.$courseid.'.num'};
13471:     }
13472:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13473:     my %slotinfo;
13474:     if (exists($remembered{$key})) {
13475: 	$slotinfo{$which} = $remembered{$key};
13476:     } else {
13477: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13478: 	&Apache::lonhomework::showhash(%slotinfo);
13479: 	my ($tmp)=keys(%slotinfo);
13480: 	if ($tmp=~/^error:/) { return (); }
13481: 	$remembered{$key} = $slotinfo{$which};
13482:     }
13483:     if (ref($slotinfo{$which}) eq 'HASH') {
13484: 	return %{$slotinfo{$which}};
13485:     }
13486:     return $slotinfo{$which};
13487: }
13488: 
13489: sub get_reservable_slots {
13490:     my ($cnum,$cdom,$uname,$udom) = @_;
13491:     my $now = time;
13492:     my $reservable_info;
13493:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13494:     if (exists($remembered{$key})) {
13495:         $reservable_info = $remembered{$key};
13496:     } else {
13497:         my %resv;
13498:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13499:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13500:         $reservable_info = \%resv;
13501:         $remembered{$key} = $reservable_info;
13502:     }
13503:     return $reservable_info;
13504: }
13505: 
13506: sub get_course_slots {
13507:     my ($cnum,$cdom) = @_;
13508:     my $hashid=$cnum.':'.$cdom;
13509:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13510:     if (defined($cached)) {
13511:         if (ref($result) eq 'HASH') {
13512:             return %{$result};
13513:         }
13514:     } else {
13515:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13516:         my ($tmp) = keys(%slots);
13517:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13518:             &do_cache_new('allslots',$hashid,\%slots,600);
13519:             return %slots;
13520:         }
13521:     }
13522:     return;
13523: }
13524: 
13525: sub devalidate_slots_cache {
13526:     my ($cnum,$cdom)=@_;
13527:     my $hashid=$cnum.':'.$cdom;
13528:     &devalidate_cache_new('allslots',$hashid);
13529: }
13530: 
13531: sub get_coursechange {
13532:     my ($cdom,$cnum) = @_;
13533:     if ($cdom eq '' || $cnum eq '') {
13534:         return unless ($env{'request.course.id'});
13535:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13536:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13537:     }
13538:     my $hashid=$cdom.'_'.$cnum;
13539:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13540:     if ((defined($cached)) && ($change ne '')) {
13541:         return $change;
13542:     } else {
13543:         my %crshash;
13544:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13545:         if ($crshash{'internal.contentchange'} eq '') {
13546:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13547:             if ($change eq '') {
13548:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13549:                 $change = $crshash{'internal.created'};
13550:             }
13551:         } else {
13552:             $change = $crshash{'internal.contentchange'};
13553:         }
13554:         my $cachetime = 600;
13555:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13556:     }
13557:     return $change;
13558: }
13559: 
13560: sub devalidate_coursechange_cache {
13561:     my ($cnum,$cdom)=@_;
13562:     my $hashid=$cnum.':'.$cdom;
13563:     &devalidate_cache_new('crschange',$hashid);
13564: }
13565: 
13566: # ------------------------------------------------- Update symbolic store links
13567: 
13568: sub symblist {
13569:     my ($mapname,%newhash)=@_;
13570:     $mapname=&deversion(&declutter($mapname));
13571:     my %hash;
13572:     if (($env{'request.course.fn'}) && (%newhash)) {
13573:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13574:                       &GDBM_WRCREAT(),0640)) {
13575: 	    foreach my $url (keys(%newhash)) {
13576: 		next if ($url eq 'last_known'
13577: 			 && $env{'form.no_update_last_known'});
13578: 		$hash{declutter($url)}=&encode_symb($mapname,
13579: 						    $newhash{$url}->[1],
13580: 						    $newhash{$url}->[0]);
13581:             }
13582:             if (untie(%hash)) {
13583: 		return 'ok';
13584:             }
13585:         }
13586:     }
13587:     return 'error';
13588: }
13589: 
13590: # --------------------------------------------------------------- Verify a symb
13591: 
13592: sub symbverify {
13593:     my ($symb,$thisurl,$encstate)=@_;
13594:     my $thisfn=$thisurl;
13595:     $thisfn=&declutter($thisfn);
13596: # direct jump to resource in page or to a sequence - will construct own symbs
13597:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13598: # check URL part
13599:     my ($map,$resid,$url)=&decode_symb($symb);
13600: 
13601:     unless ($url eq $thisfn) { return 0; }
13602: 
13603:     $symb=&symbclean($symb);
13604:     $thisurl=&deversion($thisurl);
13605:     $thisfn=&deversion($thisfn);
13606: 
13607:     my %bighash;
13608:     my $okay=0;
13609: 
13610:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13611:                             &GDBM_READER(),0640)) {
13612:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13613:             $thisurl =~ s/\?.+$//;
13614:             if ($map =~ m{^uploaded/.+\.page$}) {
13615:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13616:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13617:             }
13618:         }
13619:         my $ids;
13620:         if ($map =~ m{^uploaded/.+\.page$}) {
13621:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13622:         } else {
13623:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13624:         }
13625:         unless ($ids) {
13626:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13627:             $ids=$bighash{$idkey};
13628:         }
13629:         if ($ids) {
13630: # ------------------------------------------------------------------- Has ID(s)
13631:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13632:                 $symb =~ s/\?.+$//;
13633:             }
13634: 	    foreach my $id (split(/\,/,$ids)) {
13635: 	       my ($mapid,$resid)=split(/\./,$id);
13636:                if (
13637:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13638:    eq $symb) {
13639:                    if (ref($encstate)) {
13640:                        $$encstate = $bighash{'encrypted_'.$id};
13641:                    }
13642: 		   if (($env{'request.role.adv'}) ||
13643: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13644:                        ($thisurl eq '/adm/navmaps')) {
13645: 		       $okay=1;
13646:                        last;
13647: 		   }
13648: 	       }
13649: 	   }
13650:         }
13651: 	untie(%bighash);
13652:     }
13653:     return $okay;
13654: }
13655: 
13656: # --------------------------------------------------------------- Clean-up symb
13657: 
13658: sub symbclean {
13659:     my $symb=shift;
13660:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13661: # remove version from map
13662:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13663: 
13664: # remove version from URL
13665:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13666: 
13667: # remove wrapper
13668: 
13669:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13670:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13671:     return $symb;
13672: }
13673: 
13674: # ---------------------------------------------- Split symb to find map and url
13675: 
13676: sub encode_symb {
13677:     my ($map,$resid,$url)=@_;
13678:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13679: }
13680: 
13681: sub decode_symb {
13682:     my $symb=shift;
13683:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13684:     my ($map,$resid,$url)=split(/___/,$symb);
13685:     return (&fixversion($map),$resid,&fixversion($url));
13686: }
13687: 
13688: sub fixversion {
13689:     my $fn=shift;
13690:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13691:     my %bighash;
13692:     my $uri=&clutter($fn);
13693:     my $key=$env{'request.course.id'}.'_'.$uri;
13694: # is this cached?
13695:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13696:     if (defined($cached)) { return $result; }
13697: # unfortunately not cached, or expired
13698:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13699: 	    &GDBM_READER(),0640)) {
13700:  	if ($bighash{'version_'.$uri}) {
13701:  	    my $version=$bighash{'version_'.$uri};
13702:  	    unless (($version eq 'mostrecent') || 
13703: 		    ($version==&getversion($uri))) {
13704:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13705:  	    }
13706:  	}
13707:  	untie %bighash;
13708:     }
13709:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13710: }
13711: 
13712: sub deversion {
13713:     my $url=shift;
13714:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13715:     return $url;
13716: }
13717: 
13718: # ------------------------------------------------------ Return symb list entry
13719: 
13720: sub symbread {
13721:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13722:         $ignoresymbdb,$noenccheck)=@_;
13723:     my $cache_str='request.symbread.cached.'.$thisfn;
13724:     if (defined($env{$cache_str})) {
13725:         unless (ref($possibles) eq 'HASH') {
13726:             if ($ignorecachednull) {
13727:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13728:             } else {
13729:                 return $env{$cache_str};
13730:             }
13731:         }
13732:     }
13733: # no filename provided? try from environment
13734:     unless ($thisfn) {
13735:         if ($env{'request.symb'}) {
13736:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13737: 	}
13738: 	$thisfn=$env{'request.filename'};
13739:     }
13740:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13741: # is that filename actually a symb? Verify, clean, and return
13742:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13743: 	if (&symbverify($thisfn,$1)) {
13744: 	    return $env{$cache_str}=&symbclean($thisfn);
13745: 	}
13746:     }
13747:     $thisfn=declutter($thisfn);
13748:     my %hash;
13749:     my %bighash;
13750:     my $syval='';
13751:     if (($env{'request.course.fn'}) && ($thisfn)) {
13752:         my $targetfn = $thisfn;
13753: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13754: 	    $targetfn=$1;
13755: 	}
13756:         unless ($ignoresymbdb) {
13757:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13758:                           &GDBM_READER(),0640)) {
13759: 	        $syval=$hash{$targetfn};
13760:                 untie(%hash);
13761:             }
13762:             if ($syval && $checkforblock) {
13763:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13764:                 if (@blockers) {
13765:                     $syval='';
13766:                 }
13767:             }
13768:         }
13769: # ---------------------------------------------------------- There was an entry
13770:         if ($syval) {
13771: 	    #unless ($syval=~/\_\d+$/) {
13772: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13773: 		    #&appenv({'request.ambiguous' => $thisfn});
13774: 		    #return $env{$cache_str}='';
13775: 		#}    
13776: 		#$syval.=$1;
13777: 	    #}
13778:         } else {
13779: # ------------------------------------------------------- Was not in symb table
13780:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13781:                             &GDBM_READER(),0640)) {
13782: # ---------------------------------------------- Get ID(s) for current resource
13783:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13784:               unless ($ids) { 
13785:                  $ids=$bighash{'ids_/'.$thisfn};
13786:               }
13787:               unless ($ids) {
13788: # alias?
13789: 		  $ids=$bighash{'mapalias_'.$thisfn};
13790:               }
13791:               if ($ids) {
13792: # ------------------------------------------------------------------- Has ID(s)
13793:                  my @possibilities=split(/\,/,$ids);
13794:                  if ($#possibilities==0) {
13795: # ----------------------------------------------- There is only one possibility
13796: 		     my ($mapid,$resid)=split(/\./,$ids);
13797: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13798: 						    $resid,$thisfn);
13799:                      if (ref($possibles) eq 'HASH') {
13800:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13801:                              $possibles->{$syval} = 1;
13802:                          }
13803:                      }
13804:                      if ($checkforblock) {
13805:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13806:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13807:                              if (@blockers) {
13808:                                  $syval = '';
13809:                                  untie(%bighash);
13810:                                  return $env{$cache_str}='';
13811:                              }
13812:                          }
13813:                      }
13814:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13815: # ------------------------------------------ There is more than one possibility
13816:                      my $realpossible=0;
13817:                      foreach my $id (@possibilities) {
13818: 			 my $file=$bighash{'src_'.$id};
13819:                          my $canaccess;
13820:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13821:                              $canaccess = 1;
13822:                          } else { 
13823:                              $canaccess = &allowed('bre',$file);
13824:                          }
13825:                          if ($canaccess) {
13826:          		     my ($mapid,$resid)=split(/\./,$id);
13827:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13828:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13829: 						             $resid,$thisfn);
13830:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13831:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13832:                                  if ($checkforblock) {
13833:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13834:                                      if (@blockers > 0) {
13835:                                          $syval = '';
13836:                                      } else {
13837:                                          $syval = $poss_syval;
13838:                                          $realpossible++;
13839:                                      }
13840:                                  } else {
13841:                                      $syval = $poss_syval;
13842:                                      $realpossible++;
13843:                                  }
13844:                                  if ($syval) {
13845:                                      if (ref($possibles) eq 'HASH') {
13846:                                          $possibles->{$syval} = 1;
13847:                                      }
13848:                                  }
13849:                              }
13850: 			 }
13851:                      }
13852: 		     if ($realpossible!=1) { $syval=''; }
13853:                  } else {
13854:                      $syval='';
13855:                  }
13856: 	      }
13857:               untie(%bighash);
13858:            }
13859:         }
13860:         if ($syval) {
13861: 	    return $env{$cache_str}=$syval;
13862:         }
13863:     }
13864:     &appenv({'request.ambiguous' => $thisfn});
13865:     return $env{$cache_str}='';
13866: }
13867: 
13868: # ---------------------------------------------------------- Return random seed
13869: 
13870: sub numval {
13871:     my $txt=shift;
13872:     $txt=~tr/A-J/0-9/;
13873:     $txt=~tr/a-j/0-9/;
13874:     $txt=~tr/K-T/0-9/;
13875:     $txt=~tr/k-t/0-9/;
13876:     $txt=~tr/U-Z/0-5/;
13877:     $txt=~tr/u-z/0-5/;
13878:     $txt=~s/\D//g;
13879:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13880:     return int($txt);
13881: }
13882: 
13883: sub numval2 {
13884:     my $txt=shift;
13885:     $txt=~tr/A-J/0-9/;
13886:     $txt=~tr/a-j/0-9/;
13887:     $txt=~tr/K-T/0-9/;
13888:     $txt=~tr/k-t/0-9/;
13889:     $txt=~tr/U-Z/0-5/;
13890:     $txt=~tr/u-z/0-5/;
13891:     $txt=~s/\D//g;
13892:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13893:     my $total;
13894:     foreach my $val (@txts) { $total+=$val; }
13895:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13896:     return int($total);
13897: }
13898: 
13899: sub numval3 {
13900:     use integer;
13901:     my $txt=shift;
13902:     $txt=~tr/A-J/0-9/;
13903:     $txt=~tr/a-j/0-9/;
13904:     $txt=~tr/K-T/0-9/;
13905:     $txt=~tr/k-t/0-9/;
13906:     $txt=~tr/U-Z/0-5/;
13907:     $txt=~tr/u-z/0-5/;
13908:     $txt=~s/\D//g;
13909:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13910:     my $total;
13911:     foreach my $val (@txts) { $total+=$val; }
13912:     if ($_64bit) { $total=(($total<<32)>>32); }
13913:     return $total;
13914: }
13915: 
13916: sub digest {
13917:     my ($data)=@_;
13918:     my $digest=&Digest::MD5::md5($data);
13919:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13920:     my ($e,$f);
13921:     {
13922:         use integer;
13923:         $e=($a+$b);
13924:         $f=($c+$d);
13925:         if ($_64bit) {
13926:             $e=(($e<<32)>>32);
13927:             $f=(($f<<32)>>32);
13928:         }
13929:     }
13930:     if (wantarray) {
13931: 	return ($e,$f);
13932:     } else {
13933: 	my $g;
13934: 	{
13935: 	    use integer;
13936: 	    $g=($e+$f);
13937: 	    if ($_64bit) {
13938: 		$g=(($g<<32)>>32);
13939: 	    }
13940: 	}
13941: 	return $g;
13942:     }
13943: }
13944: 
13945: sub latest_rnd_algorithm_id {
13946:     return '64bit5';
13947: }
13948: 
13949: sub get_rand_alg {
13950:     my ($courseid)=@_;
13951:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13952:     if ($courseid) {
13953: 	return $env{"course.$courseid.rndseed"};
13954:     }
13955:     return &latest_rnd_algorithm_id();
13956: }
13957: 
13958: sub validCODE {
13959:     my ($CODE)=@_;
13960:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13961:     return 0;
13962: }
13963: 
13964: sub getCODE {
13965:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13966:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13967: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13968: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13969: 	return $Apache::lonhomework::history{'resource.CODE'};
13970:     }
13971:     return undef;
13972: }
13973: #
13974: #  Determines the random seed for a specific context:
13975: #
13976: # parameters:
13977: #   symb      - in course context the symb for the seed.
13978: #   course_id - The course id of the form domain_coursenum.
13979: #   domain    - Domain for the user.
13980: #   course    - Course for the user.
13981: #   cenv      - environment of the course.
13982: #
13983: # NOTE:
13984: #   All parameters are picked out of the environment if missing
13985: #   or not defined.
13986: #   If a symb cannot be determined the current time is used instead.
13987: #
13988: #  For a given well defined symb, courside, domain, username,
13989: #  and course environment, the seed is reproducible.
13990: #
13991: sub rndseed {
13992:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13993:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13994:     if (!defined($symb)) {
13995: 	unless ($symb=$wsymb) { return time; }
13996:     }
13997:     if (!defined $courseid) { 
13998: 	$courseid=$wcourseid; 
13999:     }
14000:     if (!defined $domain) { $domain=$wdomain; }
14001:     if (!defined $username) { $username=$wusername }
14002: 
14003:     my $which;
14004:     if (defined($cenv->{'rndseed'})) {
14005: 	$which = $cenv->{'rndseed'};
14006:     } else {
14007: 	$which =&get_rand_alg($courseid);
14008:     }
14009:     if (defined(&getCODE())) {
14010: 
14011: 	if ($which eq '64bit5') {
14012: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14013: 	} elsif ($which eq '64bit4') {
14014: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14015: 	} else {
14016: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14017: 	}
14018:     } elsif ($which eq '64bit5') {
14019: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14020:     } elsif ($which eq '64bit4') {
14021: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14022:     } elsif ($which eq '64bit3') {
14023: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14024:     } elsif ($which eq '64bit2') {
14025: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14026:     } elsif ($which eq '64bit') {
14027: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14028:     }
14029:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14030: }
14031: 
14032: sub rndseed_32bit {
14033:     my ($symb,$courseid,$domain,$username)=@_;
14034:     {
14035: 	use integer;
14036: 	my $symbchck=unpack("%32C*",$symb) << 27;
14037: 	my $symbseed=numval($symb) << 22;
14038: 	my $namechck=unpack("%32C*",$username) << 17;
14039: 	my $nameseed=numval($username) << 12;
14040: 	my $domainseed=unpack("%32C*",$domain) << 7;
14041: 	my $courseseed=unpack("%32C*",$courseid);
14042: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14044: 	#&logthis("rndseed :$num:$symb");
14045: 	if ($_64bit) { $num=(($num<<32)>>32); }
14046: 	return $num;
14047:     }
14048: }
14049: 
14050: sub rndseed_64bit {
14051:     my ($symb,$courseid,$domain,$username)=@_;
14052:     {
14053: 	use integer;
14054: 	my $symbchck=unpack("%32S*",$symb) << 21;
14055: 	my $symbseed=numval($symb) << 10;
14056: 	my $namechck=unpack("%32S*",$username);
14057: 	
14058: 	my $nameseed=numval($username) << 21;
14059: 	my $domainseed=unpack("%32S*",$domain) << 10;
14060: 	my $courseseed=unpack("%32S*",$courseid);
14061: 	
14062: 	my $num1=$symbchck+$symbseed+$namechck;
14063: 	my $num2=$nameseed+$domainseed+$courseseed;
14064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14065: 	#&logthis("rndseed :$num:$symb");
14066: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14067: 	return "$num1,$num2";
14068:     }
14069: }
14070: 
14071: sub rndseed_64bit2 {
14072:     my ($symb,$courseid,$domain,$username)=@_;
14073:     {
14074: 	use integer;
14075: 	# strings need to be an even # of cahracters long, it it is odd the
14076:         # last characters gets thrown away
14077: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14078: 	my $symbseed=numval($symb) << 10;
14079: 	my $namechck=unpack("%32S*",$username.' ');
14080: 	
14081: 	my $nameseed=numval($username) << 21;
14082: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14083: 	my $courseseed=unpack("%32S*",$courseid.' ');
14084: 	
14085: 	my $num1=$symbchck+$symbseed+$namechck;
14086: 	my $num2=$nameseed+$domainseed+$courseseed;
14087: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14088: 	#&logthis("rndseed :$num:$symb");
14089: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14090: 	return "$num1,$num2";
14091:     }
14092: }
14093: 
14094: sub rndseed_64bit3 {
14095:     my ($symb,$courseid,$domain,$username)=@_;
14096:     {
14097: 	use integer;
14098: 	# strings need to be an even # of cahracters long, it it is odd the
14099:         # last characters gets thrown away
14100: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14101: 	my $symbseed=numval2($symb) << 10;
14102: 	my $namechck=unpack("%32S*",$username.' ');
14103: 	
14104: 	my $nameseed=numval2($username) << 21;
14105: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14106: 	my $courseseed=unpack("%32S*",$courseid.' ');
14107: 	
14108: 	my $num1=$symbchck+$symbseed+$namechck;
14109: 	my $num2=$nameseed+$domainseed+$courseseed;
14110: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14111: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14112: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14113: 	
14114: 	return "$num1:$num2";
14115:     }
14116: }
14117: 
14118: sub rndseed_64bit4 {
14119:     my ($symb,$courseid,$domain,$username)=@_;
14120:     {
14121: 	use integer;
14122: 	# strings need to be an even # of cahracters long, it it is odd the
14123:         # last characters gets thrown away
14124: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14125: 	my $symbseed=numval3($symb) << 10;
14126: 	my $namechck=unpack("%32S*",$username.' ');
14127: 	
14128: 	my $nameseed=numval3($username) << 21;
14129: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14130: 	my $courseseed=unpack("%32S*",$courseid.' ');
14131: 	
14132: 	my $num1=$symbchck+$symbseed+$namechck;
14133: 	my $num2=$nameseed+$domainseed+$courseseed;
14134: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14135: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14136: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14137: 	
14138: 	return "$num1:$num2";
14139:     }
14140: }
14141: 
14142: sub rndseed_64bit5 {
14143:     my ($symb,$courseid,$domain,$username)=@_;
14144:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14145:     return "$num1:$num2";
14146: }
14147: 
14148: sub rndseed_CODE_64bit {
14149:     my ($symb,$courseid,$domain,$username)=@_;
14150:     {
14151: 	use integer;
14152: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14153: 	my $symbseed=numval2($symb);
14154: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14155: 	my $CODEseed=numval(&getCODE());
14156: 	my $courseseed=unpack("%32S*",$courseid.' ');
14157: 	my $num1=$symbseed+$CODEchck;
14158: 	my $num2=$CODEseed+$courseseed+$symbchck;
14159: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14160: 	#&logthis("rndseed :$num1:$num2:$symb");
14161: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14162: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14163: 	return "$num1:$num2";
14164:     }
14165: }
14166: 
14167: sub rndseed_CODE_64bit4 {
14168:     my ($symb,$courseid,$domain,$username)=@_;
14169:     {
14170: 	use integer;
14171: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14172: 	my $symbseed=numval3($symb);
14173: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14174: 	my $CODEseed=numval3(&getCODE());
14175: 	my $courseseed=unpack("%32S*",$courseid.' ');
14176: 	my $num1=$symbseed+$CODEchck;
14177: 	my $num2=$CODEseed+$courseseed+$symbchck;
14178: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14179: 	#&logthis("rndseed :$num1:$num2:$symb");
14180: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14181: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14182: 	return "$num1:$num2";
14183:     }
14184: }
14185: 
14186: sub rndseed_CODE_64bit5 {
14187:     my ($symb,$courseid,$domain,$username)=@_;
14188:     my $code = &getCODE();
14189:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14190:     return "$num1:$num2";
14191: }
14192: 
14193: sub setup_random_from_rndseed {
14194:     my ($rndseed)=@_;
14195:     if ($rndseed =~/([,:])/) {
14196:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14197:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14198:             &Math::Random::random_set_seed_from_phrase($rndseed);
14199:         } else {
14200:             &Math::Random::random_set_seed($num1,$num2);
14201:         }
14202:     } else {
14203: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14204:     }
14205: }
14206: 
14207: sub latest_receipt_algorithm_id {
14208:     return 'receipt3';
14209: }
14210: 
14211: sub recunique {
14212:     my $fucourseid=shift;
14213:     my $unique;
14214:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14215: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14216: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14217:     } else {
14218: 	$unique=$perlvar{'lonReceipt'};
14219:     }
14220:     return unpack("%32C*",$unique);
14221: }
14222: 
14223: sub recprefix {
14224:     my $fucourseid=shift;
14225:     my $prefix;
14226:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14227: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14228: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14229:     } else {
14230: 	$prefix=$perlvar{'lonHostID'};
14231:     }
14232:     return unpack("%32C*",$prefix);
14233: }
14234: 
14235: sub ireceipt {
14236:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14237: 
14238:     my $return =&recprefix($fucourseid).'-';
14239: 
14240:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14241: 	$env{'request.state'} eq 'construct') {
14242: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14243: 	return $return;
14244:     }
14245: 
14246:     my $cuname=unpack("%32C*",$funame);
14247:     my $cudom=unpack("%32C*",$fudom);
14248:     my $cucourseid=unpack("%32C*",$fucourseid);
14249:     my $cusymb=unpack("%32C*",$fusymb);
14250:     my $cunique=&recunique($fucourseid);
14251:     my $cpart=unpack("%32S*",$part);
14252:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14253: 
14254: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14255: 			       
14256: 	$return.= ($cunique%$cuname+
14257: 		   $cunique%$cudom+
14258: 		   $cusymb%$cuname+
14259: 		   $cusymb%$cudom+
14260: 		   $cucourseid%$cuname+
14261: 		   $cucourseid%$cudom+
14262: 		   $cpart%$cuname+
14263: 		   $cpart%$cudom);
14264:     } else {
14265: 	$return.= ($cunique%$cuname+
14266: 		   $cunique%$cudom+
14267: 		   $cusymb%$cuname+
14268: 		   $cusymb%$cudom+
14269: 		   $cucourseid%$cuname+
14270: 		   $cucourseid%$cudom);
14271:     }
14272:     return $return;
14273: }
14274: 
14275: sub receipt {
14276:     my ($part)=@_;
14277:     my ($symb,$courseid,$domain,$name) = &whichuser();
14278:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14279: }
14280: 
14281: sub whichuser {
14282:     my ($passedsymb)=@_;
14283:     my ($symb,$courseid,$domain,$name,$publicuser);
14284:     if (defined($env{'form.grade_symb'})) {
14285: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14286: 	my $allowed=&allowed('vgr',$tmp_courseid);
14287: 	if (!$allowed &&
14288: 	    exists($env{'request.course.sec'}) &&
14289: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14290: 	    $allowed=&allowed('vgr',$tmp_courseid.
14291: 			      '/'.$env{'request.course.sec'});
14292: 	}
14293: 	if ($allowed) {
14294: 	    ($symb)=&get_env_multiple('form.grade_symb');
14295: 	    $courseid=$tmp_courseid;
14296: 	    ($domain)=&get_env_multiple('form.grade_domain');
14297: 	    ($name)=&get_env_multiple('form.grade_username');
14298: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14299: 	}
14300:     }
14301:     if (!$passedsymb) {
14302: 	$symb=&symbread();
14303:     } else {
14304: 	$symb=$passedsymb;
14305:     }
14306:     $courseid=$env{'request.course.id'};
14307:     $domain=$env{'user.domain'};
14308:     $name=$env{'user.name'};
14309:     if ($name eq 'public' && $domain eq 'public') {
14310: 	if (!defined($env{'form.username'})) {
14311: 	    $env{'form.username'}.=time.rand(10000000);
14312: 	}
14313: 	$name.=$env{'form.username'};
14314:     }
14315:     return ($symb,$courseid,$domain,$name,$publicuser);
14316: 
14317: }
14318: 
14319: # ------------------------------------------------------------ Serves up a file
14320: # returns either the contents of the file or 
14321: # -1 if the file doesn't exist
14322: #
14323: # if the target is a file that was uploaded via DOCS, 
14324: # a check will be made to see if a current copy exists on the local server,
14325: # if it does this will be served, otherwise a copy will be retrieved from
14326: # the home server for the course and stored in /home/httpd/html/userfiles on
14327: # the local server.   
14328: 
14329: sub getfile {
14330:     my ($file) = @_;
14331:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14332:     &repcopy($file);
14333:     return &readfile($file);
14334: }
14335: 
14336: sub repcopy_userfile {
14337:     my ($file)=@_;
14338:     my $londocroot = $perlvar{'lonDocRoot'};
14339:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14340:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14341:     my ($cdom,$cnum,$filename) = 
14342: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14343:     my $uri="/uploaded/$cdom/$cnum/$filename";
14344:     if (-e "$file") {
14345: # we already have a local copy, check it out
14346: 	my @fileinfo = stat($file);
14347: 	my $rtncode;
14348: 	my $info;
14349: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14350: 	if ($lwpresp ne 'ok') {
14351: # there is no such file anymore, even though we had a local copy
14352: 	    if ($rtncode eq '404') {
14353: 		unlink($file);
14354: 	    }
14355: 	    return -1;
14356: 	}
14357: 	if ($info < $fileinfo[9]) {
14358: # nice, the file we have is up-to-date, just say okay
14359: 	    return 'ok';
14360: 	} else {
14361: # the file is outdated, get rid of it
14362: 	    unlink($file);
14363: 	}
14364:     }
14365: # one way or the other, at this point, we don't have the file
14366: # construct the correct path for the file
14367:     my @parts = ($cdom,$cnum); 
14368:     if ($filename =~ m|^(.+)/[^/]+$|) {
14369: 	push @parts, split(/\//,$1);
14370:     }
14371:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14372:     foreach my $part (@parts) {
14373: 	$path .= '/'.$part;
14374: 	if (!-e $path) {
14375: 	    mkdir($path,0770);
14376: 	}
14377:     }
14378: # now the path exists for sure
14379: # get a user agent
14380:     my $transferfile=$file.'.in.transfer';
14381: # FIXME: this should flock
14382:     if (-e $transferfile) { return 'ok'; }
14383:     my $request;
14384:     $uri=~s/^\///;
14385:     my $homeserver = &homeserver($cnum,$cdom);
14386:     my $hostname = &hostname($homeserver);
14387:     my $protocol = $protocol{$homeserver};
14388:     $protocol = 'http' if ($protocol ne 'https');
14389:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14390:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14391: # did it work?
14392:     if ($response->is_error()) {
14393: 	unlink($transferfile);
14394: 	&logthis("Userfile repcopy failed for $uri");
14395: 	return -1;
14396:     }
14397: # worked, rename the transfer file
14398:     rename($transferfile,$file);
14399:     return 'ok';
14400: }
14401: 
14402: sub tokenwrapper {
14403:     my $uri=shift;
14404:     $uri=~s|^https?\://([^/]+)||;
14405:     $uri=~s|^/||;
14406:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14407:     my $token=$1;
14408:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14409:     if ($udom && $uname && $file) {
14410: 	$file=~s|(\?\.*)*$||;
14411:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14412:         my $homeserver = &homeserver($uname,$udom);
14413:         my $hostname = &hostname($homeserver);
14414:         my $protocol = $protocol{$homeserver};
14415:         $protocol = 'http' if ($protocol ne 'https');
14416:         return $protocol.'://'.$hostname.'/'.$uri.
14417:                (($uri=~/\?/)?'&':'?').'token='.$token.
14418:                                '&tokenissued='.$perlvar{'lonHostID'};
14419:     } else {
14420:         return '/adm/notfound.html';
14421:     }
14422: }
14423: 
14424: # call with reqtype HEAD: get last modification time
14425: # call with reqtype GET: get the file contents
14426: # Do not call this with reqtype GET for large files! It loads everything into memory
14427: #
14428: sub getuploaded {
14429:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14430:     $uri=~s/^\///;
14431:     my $homeserver = &homeserver($cnum,$cdom);
14432:     my $hostname = &hostname($homeserver);
14433:     my $protocol = $protocol{$homeserver};
14434:     $protocol = 'http' if ($protocol ne 'https');
14435:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14436:     my $request=new HTTP::Request($reqtype,$uri);
14437:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14438:     $$rtncode = $response->code;
14439:     if (! $response->is_success()) {
14440: 	return 'failed';
14441:     }      
14442:     if ($reqtype eq 'HEAD') {
14443: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14444:     } elsif ($reqtype eq 'GET') {
14445: 	$$info = $response->content;
14446:     }
14447:     return 'ok';
14448: }
14449: 
14450: sub readfile {
14451:     my $file = shift;
14452:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14453:     my $fh;
14454:     open($fh,"<",$file);
14455:     my $a='';
14456:     while (my $line = <$fh>) { $a .= $line; }
14457:     return $a;
14458: }
14459: 
14460: sub filelocation {
14461:     my ($dir,$file) = @_;
14462:     my $location;
14463:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14464: 
14465:     if ($file =~ m-^/adm/-) {
14466: 	$file=~s-^/adm/wrapper/-/-;
14467: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14468:     }
14469: 
14470:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14471:         $location = $file;
14472:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14473:         my ($udom,$uname,$filename)=
14474:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14475:         my $home=&homeserver($uname,$udom);
14476:         my $is_me=0;
14477:         my @ids=&current_machine_ids();
14478:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14479:         if ($is_me) {
14480:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14481:         } else {
14482:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14483:   	      $udom.'/'.$uname.'/'.$filename;
14484:         }
14485:     } elsif ($file =~ m-^/adm/-) {
14486: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14487:     } else {
14488:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14489:         $file=~s:^/(res|priv)/:/:;
14490:         my $space=$1;
14491:         if ( !( $file =~ m:^/:) ) {
14492:             $location = $dir. '/'.$file;
14493:         } else {
14494:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14495:         }
14496:     }
14497:     $location=~s://+:/:g; # remove duplicate /
14498:     while ($location=~m{/\.\./}) {
14499: 	if ($location =~ m{/[^/]+/\.\./}) {
14500: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14501: 	} else {
14502: 	    $location=~ s{/\.\./}{/}g;
14503: 	}
14504:     } #remove dir/..
14505:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14506:     return $location;
14507: }
14508: 
14509: sub hreflocation {
14510:     my ($dir,$file)=@_;
14511:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14512: 	$file=filelocation($dir,$file);
14513:     } elsif ($file=~m-^/adm/-) {
14514: 	$file=~s-^/adm/wrapper/-/-;
14515: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14516:     }
14517:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14518: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14519:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14520: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14521: 	        {/uploaded/$1/$2/}x;
14522:     }
14523:     if ($file=~ m{^/userfiles/}) {
14524: 	$file =~ s{^/userfiles/}{/uploaded/};
14525:     }
14526:     return $file;
14527: }
14528: 
14529: 
14530: 
14531: 
14532: 
14533: sub current_machine_domains {
14534:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14535: }
14536: 
14537: sub machine_domains {
14538:     my ($hostname) = @_;
14539:     my @domains;
14540:     my %hostname = &all_hostnames();
14541:     while( my($id, $name) = each(%hostname)) {
14542: #	&logthis("-$id-$name-$hostname-");
14543: 	if ($hostname eq $name) {
14544: 	    push(@domains,&host_domain($id));
14545: 	}
14546:     }
14547:     return @domains;
14548: }
14549: 
14550: sub current_machine_ids {
14551:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14552: }
14553: 
14554: sub machine_ids {
14555:     my ($hostname) = @_;
14556:     $hostname ||= &hostname($perlvar{'lonHostID'});
14557:     my @ids;
14558:     my %name_to_host = &all_names();
14559:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14560: 	return @{ $name_to_host{$hostname} };
14561:     }
14562:     return;
14563: }
14564: 
14565: sub additional_machine_domains {
14566:     my @domains;
14567:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14568:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14569:             while (my $line = <$fh>) {
14570:                 chomp($line);           
14571:                 $line =~ s/\s//g;
14572:                 push(@domains,$line);
14573:             }
14574:             close($fh);
14575:         }
14576:     }
14577:     return @domains;
14578: }
14579: 
14580: sub default_login_domain {
14581:     my $domain = $perlvar{'lonDefDomain'};
14582:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14583:     foreach my $posdom (&current_machine_domains(),
14584:                         &additional_machine_domains()) {
14585:         if (lc($posdom) eq lc($testdomain)) {
14586:             $domain=$posdom;
14587:             last;
14588:         }
14589:     }
14590:     return $domain;
14591: }
14592: 
14593: sub shared_institution {
14594:     my ($dom,$lonhost) = @_;
14595:     if ($lonhost eq '') {
14596:         $lonhost = $perlvar{'lonHostID'};
14597:     }
14598:     my $same_intdom;
14599:     my $hostintdom = &internet_dom($lonhost);
14600:     if ($hostintdom ne '') {
14601:         my %iphost = &get_iphost();
14602:         my $primary_id = &domain($dom,'primary');
14603:         my $primary_ip = &get_host_ip($primary_id);
14604:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14605:             foreach my $id (@{$iphost{$primary_ip}}) {
14606:                 my $intdom = &internet_dom($id);
14607:                 if ($intdom eq $hostintdom) {
14608:                     $same_intdom = 1;
14609:                     last;
14610:                 }
14611:             }
14612:         }
14613:     }
14614:     return $same_intdom;
14615: }
14616: 
14617: sub uses_sts {
14618:     my ($ignore_cache) = @_;
14619:     my $lonhost = $perlvar{'lonHostID'};
14620:     my $hostname = &hostname($lonhost);
14621:     my $sts_on;
14622:     if ($protocol{$lonhost} eq 'https') {
14623:         my $cachetime = 12*3600;
14624:         if (!$ignore_cache) {
14625:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14626:             if (defined($cached)) {
14627:                 return $sts_on;
14628:             }
14629:         }
14630:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14631:         my $request=new HTTP::Request('HEAD',$url);
14632:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14633:         if ($response->is_success) {
14634:             my $has_sts = $response->header('Strict-Transport-Security');
14635:             if ($has_sts eq '') {
14636:                 $sts_on = 0;
14637:             } else {
14638:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14639:                     my $maxage = $1;
14640:                     if ($maxage) {
14641:                         $sts_on = 1;
14642:                     } else {
14643:                         $sts_on = 0;
14644:                     }
14645:                 } else {
14646:                     $sts_on = 0;
14647:                 }
14648:             }
14649:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14650:         }
14651:     }
14652:     return;
14653: }
14654: 
14655: sub waf_allssl {
14656:     my ($host_name) = @_;
14657:     my $alias = &get_proxy_alias();
14658:     if ($host_name eq '') {
14659:         $host_name = $ENV{'SERVER_NAME'};
14660:     }
14661:     if (($host_name ne '') && ($alias eq $host_name)) {
14662:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14663:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14664:         if ($defdomdefaults{'waf_sslopt'}) {
14665:             return $defdomdefaults{'waf_sslopt'};
14666:         }
14667:     }
14668:     return;
14669: }
14670: 
14671: sub get_requestor_ip {
14672:     my ($r,$nolookup,$noproxy) = @_;
14673:     my $from_ip;
14674:     if (ref($r)) {
14675:         if ($r->can('useragent_ip')) {
14676:             if ($noproxy && $r->can('client_ip')) {
14677:                 $from_ip = $r->client_ip();
14678:             } else {
14679:                 $from_ip = $r->useragent_ip();
14680:             }
14681:         } elsif ($r->connection->can('remote_ip')) {
14682:             $from_ip = $r->connection->remote_ip();
14683:         } else {
14684:             $from_ip = $r->get_remote_host($nolookup);
14685:         }
14686:     } else {
14687:         $from_ip = $ENV{'REMOTE_ADDR'};
14688:     }
14689:     return $from_ip if ($noproxy); 
14690:     # Who controls proxy settings for server
14691:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14692:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14693:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14694:         if ($proxyinfo->{'vpnint'}) {
14695:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14696:                 return $from_ip;
14697:             }
14698:         }
14699:         if ($proxyinfo->{'trusted'}) {
14700:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14701:                 my $ipheader = $proxyinfo->{'ipheader'};
14702:                 my ($ip,$xfor);
14703:                 if (ref($r)) {
14704:                     if ($ipheader) {
14705:                         $ip = $r->headers_in->{$ipheader};
14706:                     }
14707:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14708:                 } else {
14709:                     if ($ipheader) {
14710:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14711:                     }
14712:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14713:                 }
14714:                 if (($ip eq '') && ($xfor ne '')) {
14715:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14716:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14717:                             $ip = $poss_ip;
14718:                             last;
14719:                         }
14720:                     }
14721:                 }
14722:                 if ($ip ne '') {
14723:                     return $ip;
14724:                 }
14725:             }
14726:         }
14727:     }
14728:     return $from_ip;
14729: }
14730: 
14731: sub get_proxy_settings {
14732:     my ($dom_in_use) = @_;
14733:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14734:     my $proxyinfo = {
14735:                        ipheader => $domdefaults{'waf_ipheader'},
14736:                        trusted  => $domdefaults{'waf_trusted'},
14737:                        vpnint   => $domdefaults{'waf_vpnint'},
14738:                        vpnext   => $domdefaults{'waf_vpnext'},
14739:                        sslopt   => $domdefaults{'waf_sslopt'},
14740:                     };
14741:     return $proxyinfo;
14742: }
14743: 
14744: sub ip_match {
14745:     my ($ip,$pattern_str) = @_;
14746:     $ip=Net::CIDR::cidrvalidate($ip);
14747:     if ($ip) {
14748:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14749:     }
14750:     return;
14751: }
14752: 
14753: sub get_proxy_alias {
14754:     my ($lonid) = @_;
14755:     if ($lonid eq '') {
14756:         $lonid = $perlvar{'lonHostID'};
14757:     }
14758:     if (!defined(&hostname($lonid))) {
14759:         return;
14760:     }
14761:     if ($lonid ne '') {
14762:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14763:         if ($cached) {
14764:             return $alias;
14765:         }
14766:         my $dom = &Apache::lonnet::host_domain($lonid);
14767:         if ($dom ne '') {
14768:             my $cachetime = 60*60*24;
14769:             my %domconfig =
14770:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14771:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14772:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14773:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14774:                 }
14775:             }
14776:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14777:         }
14778:     }
14779:     return;
14780: }
14781: 
14782: sub use_proxy_alias {
14783:     my ($r,$lonid) = @_;
14784:     my $alias = &get_proxy_alias($lonid);
14785:     if ($alias) {
14786:         my $dom = &host_domain($lonid);
14787:         if ($dom ne '') {
14788:             my $proxyinfo = &get_proxy_settings($dom);
14789:             my ($vpnint,$remote_ip);
14790:             if (ref($proxyinfo) eq 'HASH') {
14791:                 $vpnint = $proxyinfo->{'vpnint'};
14792:                 if ($vpnint) {
14793:                     $remote_ip = &get_requestor_ip($r,1,1);
14794:                 }
14795:             }
14796:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14797:                 return $alias;
14798:             }
14799:         }
14800:     }
14801:     return;
14802: }
14803: 
14804: sub alias_sso {
14805:     my ($lonid) = @_;
14806:     if ($lonid eq '') {
14807:         $lonid = $perlvar{'lonHostID'};
14808:     }
14809:     if (!defined(&hostname($lonid))) {
14810:         return;
14811:     }
14812:     if ($lonid ne '') {
14813:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14814:         if ($cached) {
14815:             return $use_alias;
14816:         }
14817:         my $dom = &Apache::lonnet::host_domain($lonid);
14818:         if ($dom ne '') {
14819:             my $cachetime = 60*60*24;
14820:             my %domconfig =
14821:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14822:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14823:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14824:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14825:                 }
14826:             }
14827:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14828:         }
14829:     }
14830:     return;
14831: }
14832: 
14833: sub get_saml_landing {
14834:     my ($lonid) = @_;
14835:     if ($lonid eq '') {
14836:         my $defdom = &default_login_domain();
14837:         my @hosts = &current_machine_ids();
14838:         if (@hosts > 1) {
14839:             foreach my $hostid (@hosts) {
14840:                 if (&host_domain($hostid) eq $defdom) {
14841:                     $lonid = $hostid;
14842:                     last;
14843:                 }
14844:             }
14845:         } else {
14846:             $lonid = $perlvar{'lonHostID'};
14847:         }
14848:         if ($lonid) {
14849:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14850:                 return;
14851:             }
14852:         } else {
14853:             return;
14854:         }
14855:     } elsif (!defined(&hostname($lonid))) {
14856:         return;
14857:     }
14858:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14859:     if ($cached) {
14860:         return $landing;
14861:     }
14862:     my $dom = &Apache::lonnet::host_domain($lonid);
14863:     if ($dom ne '') {
14864:         my $cachetime = 60*60*24;
14865:         my %domconfig =
14866:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14867:         if (ref($domconfig{'login'}) eq 'HASH') {
14868:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14869:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14870:                     $landing = 1;
14871:                 }
14872:             }
14873:         }
14874:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14875:     }
14876:     return;
14877: }
14878: 
14879: # ------------------------------------------------------------- Declutters URLs
14880: 
14881: sub declutter {
14882:     my $thisfn=shift;
14883:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14884:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14885:         $thisfn=~s{^/home/httpd/html}{};
14886:     }
14887:     $thisfn=~s/^\///;
14888:     $thisfn=~s|^adm/wrapper/||;
14889:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14890:     $thisfn=~s/^res\///;
14891:     $thisfn=~s/^priv\///;
14892:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14893:         $thisfn=~s/\?.+$//;
14894:     }
14895:     return $thisfn;
14896: }
14897: 
14898: # ------------------------------------------------------------- Clutter up URLs
14899: 
14900: sub clutter {
14901:     my $thisfn='/'.&declutter(shift);
14902:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14903: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14904:        $thisfn='/res'.$thisfn; 
14905:     }
14906:     if ($thisfn !~m|^/adm|) {
14907: 	if ($thisfn =~ m|^/ext/|) {
14908: 	    $thisfn='/adm/wrapper'.$thisfn;
14909: 	} else {
14910: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14911: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14912: 	    if ($embstyle eq 'ssi'
14913: 		|| ($embstyle eq 'hdn')
14914: 		|| ($embstyle eq 'rat')
14915: 		|| ($embstyle eq 'prv')
14916: 		|| ($embstyle eq 'ign')) {
14917: 		#do nothing with these
14918: 	    } elsif (($embstyle eq 'img') 
14919: 		|| ($embstyle eq 'emb')
14920: 		|| ($embstyle eq 'wrp')) {
14921: 		$thisfn='/adm/wrapper'.$thisfn;
14922: 	    } elsif ($embstyle eq 'unk'
14923: 		     && $thisfn!~/\.(sequence|page)$/) {
14924: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14925: 	    } else {
14926: #		&logthis("Got a blank emb style");
14927: 	    }
14928: 	}
14929:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14930:         $thisfn='/adm/wrapper'.$thisfn;
14931:     }
14932:     return $thisfn;
14933: }
14934: 
14935: sub clutter_with_no_wrapper {
14936:     my $uri = &clutter(shift);
14937:     if ($uri =~ m-^/adm/-) {
14938: 	$uri =~ s-^/adm/wrapper/-/-;
14939: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14940:     }
14941:     return $uri;
14942: }
14943: 
14944: sub freeze_escape {
14945:     my ($value)=@_;
14946:     if (ref($value)) {
14947: 	$value=&nfreeze($value);
14948: 	return '__FROZEN__'.&escape($value);
14949:     }
14950:     return &escape($value);
14951: }
14952: 
14953: 
14954: sub thaw_unescape {
14955:     my ($value)=@_;
14956:     if ($value =~ /^__FROZEN__/) {
14957: 	substr($value,0,10,undef);
14958: 	$value=&unescape($value);
14959: 	return &thaw($value);
14960:     }
14961:     return &unescape($value);
14962: }
14963: 
14964: sub correct_line_ends {
14965:     my ($result)=@_;
14966:     $$result =~s/\r\n/\n/mg;
14967:     $$result =~s/\r/\n/mg;
14968: }
14969: # ================================================================ Main Program
14970: 
14971: sub goodbye {
14972:    &logthis("Starting Shut down");
14973: #not converted to using infrastruture and probably shouldn't be
14974:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14975: #converted
14976: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14977:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14978: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14979: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14980: #1.1 only
14981: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14982: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14983: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14984: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14985:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14986:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14987:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14988:    &flushcourselogs();
14989:    &logthis("Shutting down");
14990: }
14991: 
14992: sub get_dns {
14993:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14994:     if (!$ignore_cache) {
14995: 	my ($content,$cached)=
14996: 	    &Apache::lonnet::is_cached_new('dns',$url);
14997: 	if ($cached) {
14998: 	    &$func($content,$hashref);
14999: 	    return;
15000: 	}
15001:     }
15002: 
15003:     my %alldns;
15004:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15005:         foreach my $dns (<$config>) {
15006: 	    next if ($dns !~ /^\^(\S*)/x);
15007:             my $line = $1;
15008:             my ($host,$protocol) = split(/:/,$line);
15009:             if ($protocol ne 'https') {
15010:                 $protocol = 'http';
15011:             }
15012: 	    $alldns{$host} = $protocol;
15013:         }
15014:         close($config);
15015:     }
15016:     while (%alldns) {
15017: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15018:         my ($contents,@content);
15019:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15020:             my $command = (split('/',$url))[3];
15021:             my ($dir,$file) = &parse_getdns_url($command,$url);
15022:             delete($alldns{$dns});
15023:             next if (($dir eq '') || ($file eq ''));
15024:             if (open(my $config,'<',"$dir/$file")) {
15025:                 @content = <$config>;
15026:                 close($config);
15027:             }
15028:             if ($url eq '/adm/dns/loncapaCRL') {
15029:                 $contents = join('',@content);
15030:             }
15031:         } else {
15032: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15033:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15034:             delete($alldns{$dns});
15035: 	    next if ($response->is_error());
15036:             if ($url eq '/adm/dns/loncapaCRL') {
15037:                 $contents = $response->content;
15038:             } else {
15039:                 @content = split("\n",$response->content);
15040:             }
15041:         }
15042:         if ($url eq '/adm/dns/loncapaCRL') {
15043:             return &$func($contents);
15044:         } else {
15045: 	    unless ($nocache) {
15046: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15047: 	    }
15048: 	    &$func(\@content,$hashref);
15049:             return;
15050:         }
15051:     }
15052:     my $which = (split('/',$url,4))[3];
15053:     if ($which eq 'loncapaCRL') {
15054:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15055:         if (-e $diskfile) {
15056:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15057:         } else {
15058:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15059:         }
15060:     } else {
15061:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15062:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15063:             my @content = <$config>;
15064:             close($config);
15065:             &$func(\@content,$hashref);
15066:         }
15067:     }
15068:     return;
15069: }
15070: 
15071: # ------------------------------------------------------Get DNS checksums file
15072: sub parse_dns_checksums_tab {
15073:     my ($lines,$hashref) = @_;
15074:     my $lonhost = $perlvar{'lonHostID'};
15075:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
15076:     my $loncaparev = &get_server_loncaparev($machine_dom);
15077:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15078:     my $webconfdir = '/etc/httpd/conf';
15079:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15080:         $webconfdir = '/etc/apache2';
15081:     } elsif ($distro =~ /^sles(\d+)$/) {
15082:         if ($1 >= 10) {
15083:             $webconfdir = '/etc/apache2';
15084:         }
15085:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15086:         if ($1 >= 10.0) {
15087:             $webconfdir = '/etc/apache2';
15088:         }
15089:     }
15090:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15091:     my (%chksum,%revnum);
15092:     if (ref($lines) eq 'ARRAY') {
15093:         chomp(@{$lines});
15094:         my $version = shift(@{$lines});
15095:         if ($version eq $release) {  
15096:             foreach my $line (@{$lines}) {
15097:                 my ($file,$version,$shasum) = split(/,/,$line);
15098:                 if ($file =~ m{^/etc/httpd/conf}) {
15099:                     if ($webconfdir eq '/etc/apache2') {
15100:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15101:                     }
15102:                 }
15103:                 $chksum{$file} = $shasum;
15104:                 $revnum{$file} = $version;
15105:             }
15106:             if (ref($hashref) eq 'HASH') {
15107:                 %{$hashref} = (
15108:                                 sums     => \%chksum,
15109:                                 versions => \%revnum,
15110:                               );
15111:             }
15112:         }
15113:     }
15114:     return;
15115: }
15116: 
15117: sub fetch_dns_checksums {
15118:     my %checksums;
15119:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
15120:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15121:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15122:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15123:              \%checksums);
15124:     return \%checksums;
15125: }
15126: 
15127: sub fetch_crl_pemfile {
15128:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15129: }
15130: 
15131: sub save_crl_pem {
15132:     my ($content) = @_;
15133:     my ($msg,$hadchanges);
15134:     if ($content ne '') {
15135:         my $now = time;
15136:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15137:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15138:         if (open(my $fh,'>',"$tmpcrl")) {
15139:             print $fh $content;
15140:             close($fh);
15141:             if (-e $lonca) {
15142:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15143:                     my $check = <PIPE>;
15144:                     close(PIPE);
15145:                     chomp($check);
15146:                     if ($check eq 'verify OK') {
15147:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15148:                         my $backup;
15149:                         if (-e $dest) {
15150:                             if (&File::Copy::move($dest,"$dest.bak")) {
15151:                                 $backup = 'ok';
15152:                             }
15153:                         }
15154:                         if (&File::Copy::move($tmpcrl,$dest)) {
15155:                             $msg = 'ok';
15156:                             if ($backup) {
15157:                                 my (%oldnums,%newnums);
15158:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15159:                                     while (<PIPE>) {
15160:                                         $oldnums{(split(/:/))[1]} = 1;
15161:                                     }
15162:                                     close(PIPE);
15163:                                 }
15164:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15165:                                     while(<PIPE>) {
15166:                                         $newnums{(split(/:/))[1]} = 1;
15167:                                     }
15168:                                     close(PIPE);
15169:                                 }
15170:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15171:                                     unless (exists($oldnums{$key})) {
15172:                                         $hadchanges = 1;
15173:                                         last;
15174:                                     }
15175:                                 }
15176:                                 unless ($hadchanges) {
15177:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15178:                                         unless (exists($newnums{$key})) {
15179:                                             $hadchanges = 1;
15180:                                             last;
15181:                                         }
15182:                                     }
15183:                                 }
15184:                             }
15185:                         }
15186:                     } else {
15187:                         unlink($tmpcrl);
15188:                     }
15189:                 } else {
15190:                     unlink($tmpcrl);
15191:                 }
15192:             } else {
15193:                 unlink($tmpcrl);
15194:             }
15195:         }
15196:     }
15197:     return ($msg,$hadchanges);
15198: }
15199: 
15200: sub parse_getdns_url {
15201:     my ($command,$url) = @_;
15202:     my $dir = $perlvar{'lonTabDir'};
15203:     my $file;
15204:     if ($command eq 'hosts') {
15205:         $file = 'dns_hosts.tab';
15206:     } elsif ($command eq 'domain') {
15207:         $file = 'dns_domain.tab';
15208:     } elsif ($command eq 'checksums') {
15209:         my $version = (split('/',$url))[4];
15210:         $file = "dns_checksums/$version.tab",
15211:     } elsif ($command eq 'loncapaCRL') {
15212:         $dir = $perlvar{'lonCertificateDirectory'};
15213:         $file = $perlvar{'lonnetCertRevocationList'};
15214:     }
15215:     return ($dir,$file);
15216: }
15217: 
15218: # ------------------------------------------------------------ Read domain file
15219: {
15220:     my $loaded;
15221:     my %domain;
15222: 
15223:     sub parse_domain_tab {
15224: 	my ($lines) = @_;
15225: 	foreach my $line (@$lines) {
15226: 	    next if ($line =~ /^(\#|\s*$ )/x);
15227: 
15228: 	    chomp($line);
15229: 	    my ($name,@elements) = split(/:/,$line,9);
15230: 	    my %this_domain;
15231: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15232: 			       'lang_def', 'city', 'longi', 'lati',
15233: 			       'primary') {
15234: 		$this_domain{$field} = shift(@elements);
15235: 	    }
15236: 	    $domain{$name} = \%this_domain;
15237: 	}
15238:     }
15239: 
15240:     sub reset_domain_info {
15241: 	undef($loaded);
15242: 	undef(%domain);
15243:     }
15244: 
15245:     sub load_domain_tab {
15246: 	my ($ignore_cache,$nocache) = @_;
15247: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15248: 	my $fh;
15249: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15250: 	    my @lines = <$fh>;
15251: 	    &parse_domain_tab(\@lines);
15252: 	}
15253: 	close($fh);
15254: 	$loaded = 1;
15255:     }
15256: 
15257:     sub domain {
15258: 	&load_domain_tab() if (!$loaded);
15259: 
15260: 	my ($name,$what) = @_;
15261: 	return if ( !exists($domain{$name}) );
15262: 
15263: 	if (!$what) {
15264: 	    return $domain{$name}{'description'};
15265: 	}
15266: 	return $domain{$name}{$what};
15267:     }
15268: 
15269:     sub domain_info {
15270:         &load_domain_tab() if (!$loaded);
15271:         return %domain;
15272:     }
15273: 
15274: }
15275: 
15276: 
15277: # ------------------------------------------------------------- Read hosts file
15278: {
15279:     my %hostname;
15280:     my %hostdom;
15281:     my %libserv;
15282:     my $loaded;
15283:     my %name_to_host;
15284:     my %internetdom;
15285:     my %LC_dns_serv;
15286: 
15287:     sub parse_hosts_tab {
15288: 	my ($file) = @_;
15289: 	foreach my $configline (@$file) {
15290: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15291:             chomp($configline);
15292: 	    if ($configline =~ /^\^/) {
15293:                 if ($configline =~ /^\^([\w.\-]+)/) {
15294:                     $LC_dns_serv{$1} = 1;
15295:                 }
15296:                 next;
15297:             }
15298: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15299: 	    $name=~s/\s//g;
15300: 	    if ($id && $domain && $role && $name) {
15301:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15302:                     my $curr = $hostname{$id};
15303:                     my $skip;
15304:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15305:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15306:                             $skip = 1;
15307:                         } else {
15308:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15309:                         }
15310:                     }
15311:                     unless ($skip) {
15312:                         push(@{$name_to_host{$name}},$id);
15313:                     }
15314:                 } else {
15315:                     push(@{$name_to_host{$name}},$id);
15316:                 }
15317: 		$hostname{$id}=$name;
15318: 		$hostdom{$id}=$domain;
15319: 		if ($role eq 'library') { $libserv{$id}=$name; }
15320:                 if (defined($protocol)) {
15321:                     if ($protocol eq 'https') {
15322:                         $protocol{$id} = $protocol;
15323:                     } else {
15324:                         $protocol{$id} = 'http'; 
15325:                     }
15326:                 } else {
15327:                     $protocol{$id} = 'http';
15328:                 }
15329:                 if (defined($intdom)) {
15330:                     $internetdom{$id} = $intdom;
15331:                 }
15332: 	    }
15333: 	}
15334:     }
15335:     
15336:     sub reset_hosts_info {
15337: 	&purge_remembered();
15338: 	&reset_domain_info();
15339: 	&reset_hosts_ip_info();
15340:         undef(%internetdom);
15341: 	undef(%name_to_host);
15342: 	undef(%hostname);
15343: 	undef(%hostdom);
15344: 	undef(%libserv);
15345: 	undef($loaded);
15346:     }
15347: 
15348:     sub load_hosts_tab {
15349: 	my ($ignore_cache,$nocache) = @_;
15350: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15351: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15352: 	my @config = <$config>;
15353: 	&parse_hosts_tab(\@config);
15354: 	close($config);
15355: 	$loaded=1;
15356:     }
15357: 
15358:     sub hostname {
15359: 	&load_hosts_tab() if (!$loaded);
15360: 
15361: 	my ($lonid) = @_;
15362: 	return $hostname{$lonid};
15363:     }
15364: 
15365:     sub all_hostnames {
15366: 	&load_hosts_tab() if (!$loaded);
15367: 
15368: 	return %hostname;
15369:     }
15370: 
15371:     sub all_names {
15372:         my ($ignore_cache,$nocache) = @_;
15373: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15374: 
15375: 	return %name_to_host;
15376:     }
15377: 
15378:     sub all_host_domain {
15379:         &load_hosts_tab() if (!$loaded);
15380:         return %hostdom;
15381:     }
15382: 
15383:     sub all_host_intdom {
15384:         &load_hosts_tab() if (!$loaded);
15385:         return %internetdom;
15386:     }
15387: 
15388:     sub is_library {
15389: 	&load_hosts_tab() if (!$loaded);
15390: 
15391: 	return exists($libserv{$_[0]});
15392:     }
15393: 
15394:     sub all_library {
15395: 	&load_hosts_tab() if (!$loaded);
15396: 
15397: 	return %libserv;
15398:     }
15399: 
15400:     sub unique_library {
15401: 	#2x reverse removes all hostnames that appear more than once
15402:         my %unique = reverse &all_library();
15403:         return reverse %unique;
15404:     }
15405: 
15406:     sub get_servers {
15407: 	&load_hosts_tab() if (!$loaded);
15408: 
15409: 	my ($domain,$type) = @_;
15410: 	my %possible_hosts = ($type eq 'library') ? %libserv
15411: 	                                          : %hostname;
15412: 	my %result;
15413: 	if (ref($domain) eq 'ARRAY') {
15414: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15415: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15416: 		    $result{$host} = $hostname;
15417: 		}
15418: 	    }
15419: 	} else {
15420: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15421: 		if ($hostdom{$host} eq $domain) {
15422: 		    $result{$host} = $hostname;
15423: 		}
15424: 	    }
15425: 	}
15426: 	return %result;
15427:     }
15428: 
15429:     sub get_unique_servers {
15430:         my %unique = reverse &get_servers(@_);
15431: 	return reverse %unique;
15432:     }
15433: 
15434:     sub host_domain {
15435: 	&load_hosts_tab() if (!$loaded);
15436: 
15437: 	my ($lonid) = @_;
15438: 	return $hostdom{$lonid};
15439:     }
15440: 
15441:     sub all_domains {
15442: 	&load_hosts_tab() if (!$loaded);
15443: 
15444: 	my %seen;
15445: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15446: 	return @uniq;
15447:     }
15448: 
15449:     sub internet_dom {
15450:         &load_hosts_tab() if (!$loaded);
15451: 
15452:         my ($lonid) = @_;
15453:         return $internetdom{$lonid};
15454:     }
15455: 
15456:     sub is_LC_dns {
15457:         &load_hosts_tab() if (!$loaded);
15458: 
15459:         my ($hostname) = @_;
15460:         return exists($LC_dns_serv{$hostname});
15461:     }
15462: 
15463: }
15464: 
15465: { 
15466:     my %iphost;
15467:     my %name_to_ip;
15468:     my %lonid_to_ip;
15469: 
15470:     sub get_hosts_from_ip {
15471: 	my ($ip) = @_;
15472: 	my %iphosts = &get_iphost();
15473: 	if (ref($iphosts{$ip})) {
15474: 	    return @{$iphosts{$ip}};
15475: 	}
15476: 	return;
15477:     }
15478:     
15479:     sub reset_hosts_ip_info {
15480: 	undef(%iphost);
15481: 	undef(%name_to_ip);
15482: 	undef(%lonid_to_ip);
15483:     }
15484: 
15485:     sub get_host_ip {
15486: 	my ($lonid) = @_;
15487: 	if (exists($lonid_to_ip{$lonid})) {
15488: 	    return $lonid_to_ip{$lonid};
15489: 	}
15490: 	my $name=&hostname($lonid);
15491:    	my $ip = gethostbyname($name);
15492: 	return if (!$ip || length($ip) ne 4);
15493: 	$ip=inet_ntoa($ip);
15494: 	$name_to_ip{$name}   = $ip;
15495: 	$lonid_to_ip{$lonid} = $ip;
15496: 	return $ip;
15497:     }
15498:     
15499:     sub get_iphost {
15500: 	my ($ignore_cache,$nocache) = @_;
15501: 
15502: 	if (!$ignore_cache) {
15503: 	    if (%iphost) {
15504: 		return %iphost;
15505: 	    }
15506: 	    my ($ip_info,$cached)=
15507: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15508: 	    if ($cached) {
15509: 		%iphost      = %{$ip_info->[0]};
15510: 		%name_to_ip  = %{$ip_info->[1]};
15511: 		%lonid_to_ip = %{$ip_info->[2]};
15512: 		return %iphost;
15513: 	    }
15514: 	}
15515: 
15516: 	# get yesterday's info for fallback
15517: 	my %old_name_to_ip;
15518: 	my ($ip_info,$cached)=
15519: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15520: 	if ($cached) {
15521: 	    %old_name_to_ip = %{$ip_info->[1]};
15522: 	}
15523: 
15524: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15525: 	foreach my $name (keys(%name_to_host)) {
15526: 	    my $ip;
15527: 	    if (!exists($name_to_ip{$name})) {
15528: 		$ip = gethostbyname($name);
15529: 		if (!$ip || length($ip) ne 4) {
15530: 		    if (defined($old_name_to_ip{$name})) {
15531: 			$ip = $old_name_to_ip{$name};
15532: 			&logthis("Can't find $name defaulting to old $ip");
15533: 		    } else {
15534: 			&logthis("Name $name no IP found");
15535: 			next;
15536: 		    }
15537: 		} else {
15538: 		    $ip=inet_ntoa($ip);
15539: 		}
15540: 		$name_to_ip{$name} = $ip;
15541: 	    } else {
15542: 		$ip = $name_to_ip{$name};
15543: 	    }
15544: 	    foreach my $id (@{ $name_to_host{$name} }) {
15545: 		$lonid_to_ip{$id} = $ip;
15546: 	    }
15547: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15548: 	}
15549:         unless ($nocache) {
15550: 	    &do_cache_new('iphost','iphost',
15551: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15552: 		          48*60*60);
15553:         }
15554: 
15555: 	return %iphost;
15556:     }
15557: 
15558:     #
15559:     #  Given a DNS returns the loncapa host name for that DNS 
15560:     # 
15561:     sub host_from_dns {
15562:         my ($dns) = @_;
15563:         my @hosts;
15564:         my $ip;
15565: 
15566:         if (exists($name_to_ip{$dns})) {
15567:             $ip = $name_to_ip{$dns};
15568:         }
15569:         if (!$ip) {
15570:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15571:             if (length($ip) == 4) { 
15572: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15573:             }
15574:         }
15575:         if ($ip) {
15576: 	    @hosts = get_hosts_from_ip($ip);
15577: 	    return $hosts[0];
15578:         }
15579:         return undef;
15580:     }
15581: 
15582:     sub get_internet_names {
15583:         my ($lonid) = @_;
15584:         return if ($lonid eq '');
15585:         my ($idnref,$cached)=
15586:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15587:         if ($cached) {
15588:             return $idnref;
15589:         }
15590:         my $ip = &get_host_ip($lonid);
15591:         my @hosts = &get_hosts_from_ip($ip);
15592:         my %iphost = &get_iphost();
15593:         my (@idns,%seen);
15594:         foreach my $id (@hosts) {
15595:             my $dom = &host_domain($id);
15596:             my $prim_id = &domain($dom,'primary');
15597:             my $prim_ip = &get_host_ip($prim_id);
15598:             next if ($seen{$prim_ip});
15599:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15600:                 foreach my $id (@{$iphost{$prim_ip}}) {
15601:                     my $intdom = &internet_dom($id);
15602:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15603:                         push(@idns,$intdom);
15604:                     }
15605:                 }
15606:             }
15607:             $seen{$prim_ip} = 1;
15608:         }
15609:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15610:     }
15611: 
15612: }
15613: 
15614: sub all_loncaparevs {
15615:     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);
15616: }
15617: 
15618: # ---------------------------------------------------------- Read loncaparev table
15619: {
15620:     sub load_loncaparevs { 
15621:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15622:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15623:                 while (my $configline=<$config>) {
15624:                     chomp($configline);
15625:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15626:                     $loncaparevs{$hostid}=$loncaparev;
15627:                 }
15628:                 close($config);
15629:             }
15630:         }
15631:     }
15632: }
15633: 
15634: # ---------------------------------------------------------- Read serverhostID table
15635: {
15636:     sub load_serverhomeIDs {
15637:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15638:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15639:                 while (my $configline=<$config>) {
15640:                     chomp($configline);
15641:                     my ($name,$id)=split(/:/,$configline);
15642:                     $serverhomeIDs{$name}=$id;
15643:                 }
15644:                 close($config);
15645:             }
15646:         }
15647:     }
15648: }
15649: 
15650: 
15651: BEGIN {
15652: 
15653: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15654:     unless ($readit) {
15655: {
15656:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15657:     %perlvar = (%perlvar,%{$configvars});
15658: }
15659: 
15660: 
15661: # ------------------------------------------------------ Read spare server file
15662: {
15663:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15664: 
15665:     while (my $configline=<$config>) {
15666:        chomp($configline);
15667:        if ($configline) {
15668: 	   my ($host,$type) = split(':',$configline,2);
15669: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15670: 	   push(@{ $spareid{$type} }, $host);
15671:        }
15672:     }
15673:     close($config);
15674: }
15675: # ------------------------------------------------------------ Read permissions
15676: {
15677:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15678: 
15679:     while (my $configline=<$config>) {
15680: 	chomp($configline);
15681: 	if ($configline) {
15682: 	    my ($role,$perm)=split(/ /,$configline);
15683: 	    if ($perm ne '') { $pr{$role}=$perm; }
15684: 	}
15685:     }
15686:     close($config);
15687: }
15688: 
15689: # -------------------------------------------- Read plain texts for permissions
15690: {
15691:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15692: 
15693:     while (my $configline=<$config>) {
15694: 	chomp($configline);
15695: 	if ($configline) {
15696: 	    my ($short,@plain)=split(/:/,$configline);
15697:             %{$prp{$short}} = ();
15698: 	    if (@plain > 0) {
15699:                 $prp{$short}{'std'} = $plain[0];
15700:                 for (my $i=1; $i<@plain; $i++) {
15701:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15702:                 }
15703:             }
15704: 	}
15705:     }
15706:     close($config);
15707: }
15708: 
15709: # ---------------------------------------------------------- Read package table
15710: {
15711:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15712: 
15713:     while (my $configline=<$config>) {
15714: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15715: 	chomp($configline);
15716: 	my ($short,$plain)=split(/:/,$configline);
15717: 	my ($pack,$name)=split(/\&/,$short);
15718: 	if ($plain ne '') {
15719: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15720: 	    $packagetab{$short}=$plain; 
15721: 	}
15722:     }
15723:     close($config);
15724: }
15725: 
15726: # ---------------------------------------------------------- Read loncaparev table
15727: 
15728: &load_loncaparevs();
15729: 
15730: # ---------------------------------------------------------- Read serverhostID table
15731: 
15732: &load_serverhomeIDs();
15733: 
15734: # ---------------------------------------------------------- Read releaseslist XML
15735: {
15736:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15737:     if (-e $file) {
15738:         my $parser = HTML::LCParser->new($file);
15739:         while (my $token = $parser->get_token()) {
15740:             if ($token->[0] eq 'S') {
15741:                 my $item = $token->[1];
15742:                 my $name = $token->[2]{'name'};
15743:                 my $value = $token->[2]{'value'};
15744:                 my $valuematch = $token->[2]{'valuematch'};
15745:                 my $namematch = $token->[2]{'namematch'};
15746:                 if ($item eq 'parameter') {
15747:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15748:                         my $release = $parser->get_text();
15749:                         $release =~ s/(^\s*|\s*$ )//gx;
15750:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15751:                     }
15752:                 } elsif ($item ne '' && $name ne '') {
15753:                     my $release = $parser->get_text();
15754:                     $release =~ s/(^\s*|\s*$ )//gx;
15755:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15756:                 }
15757:             }
15758:         }
15759:     }
15760: }
15761: 
15762: # ---------------------------------------------------------- Read managers table
15763: {
15764:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15765:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15766:             while (my $configline=<$config>) {
15767:                 chomp($configline);
15768:                 next if ($configline =~ /^\#/);
15769:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15770:                     $managerstab{$configline} = 1;
15771:                 }
15772:             }
15773:             close($config);
15774:         }
15775:     }
15776: }
15777: 
15778: # ------------- set up temporary directory
15779: {
15780:     $tmpdir = LONCAPA::tempdir();
15781: 
15782: }
15783: 
15784: # ------------- set default texengine (domain default overrides this)
15785: {
15786:     $deftex = LONCAPA::texengine();
15787: }
15788: 
15789: # ------------- set default minimum length for passwords for internal auth users
15790: {
15791:     $passwdmin = LONCAPA::passwd_min();
15792: }
15793: 
15794: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15795: 				'compress_threshold'=> 20_000,
15796:  			        });
15797: 
15798: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15799: $dumpcount=0;
15800: $locknum=0;
15801: 
15802: &logtouch();
15803: &logthis('<font color="yellow">INFO: Read configuration</font>');
15804: $readit=1;
15805:     {
15806: 	use integer;
15807: 	my $test=(2**32)+1;
15808: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15809: 	&logthis(" Detected 64bit platform ($_64bit)");
15810:     }
15811: }
15812: }
15813: 
15814: 1;
15815: __END__
15816: 
15817: =pod
15818: 
15819: =head1 NAME
15820: 
15821: Apache::lonnet - Subroutines to ask questions about things in the network.
15822: 
15823: =head1 SYNOPSIS
15824: 
15825: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15826: 
15827:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15828: 
15829: Common parameters:
15830: 
15831: =over 4
15832: 
15833: =item *
15834: 
15835: $uname : an internal username (if $cname expecting a course Id specifically)
15836: 
15837: =item *
15838: 
15839: $udom : a domain (if $cdom expecting a course's domain specifically)
15840: 
15841: =item *
15842: 
15843: $symb : a resource instance identifier
15844: 
15845: =item *
15846: 
15847: $namespace : the name of a .db file that contains the data needed or
15848: being set.
15849: 
15850: =back
15851: 
15852: =head1 OVERVIEW
15853: 
15854: lonnet provides subroutines which interact with the
15855: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15856: about classes, users, and resources.
15857: 
15858: For many of these objects you can also use this to store data about
15859: them or modify them in various ways.
15860: 
15861: =head2 Symbs
15862: 
15863: To identify a specific instance of a resource, LON-CAPA uses symbols
15864: or "symbs"X<symb>. These identifiers are built from the URL of the
15865: map, the resource number of the resource in the map, and the URL of
15866: the resource itself. The latter is somewhat redundant, but might help
15867: if maps change.
15868: 
15869: An example is
15870: 
15871:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15872: 
15873: The respective map entry is
15874: 
15875:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15876:   title="Problem 2">
15877:  </resource>
15878: 
15879: Symbs are used by the random number generator, as well as to store and
15880: restore data specific to a certain instance of for example a problem.
15881: 
15882: =head2 Storing And Retrieving Data
15883: 
15884: X<store()>X<cstore()>X<restore()>Three of the most important functions
15885: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15886: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15887: is is the non-critical message twin of cstore. These functions are for
15888: handlers to store a perl hash to a user's permanent data space in an
15889: easy manner, and to retrieve it again on another call. It is expected
15890: that a handler would use this once at the beginning to retrieve data,
15891: and then again once at the end to send only the new data back.
15892: 
15893: The data is stored in the user's data directory on the user's
15894: homeserver under the ID of the course.
15895: 
15896: The hash that is returned by restore will have all of the previous
15897: value for all of the elements of the hash.
15898: 
15899: Example:
15900: 
15901:  #creating a hash
15902:  my %hash;
15903:  $hash{'foo'}='bar';
15904: 
15905:  #storing it
15906:  &Apache::lonnet::cstore(\%hash);
15907: 
15908:  #changing a value
15909:  $hash{'foo'}='notbar';
15910: 
15911:  #adding a new value
15912:  $hash{'bar'}='foo';
15913:  &Apache::lonnet::cstore(\%hash);
15914: 
15915:  #retrieving the hash
15916:  my %history=&Apache::lonnet::restore();
15917: 
15918:  #print the hash
15919:  foreach my $key (sort(keys(%history))) {
15920:    print("\%history{$key} = $history{$key}");
15921:  }
15922: 
15923: Will print out:
15924: 
15925:  %history{1:foo} = bar
15926:  %history{1:keys} = foo:timestamp
15927:  %history{1:timestamp} = 990455579
15928:  %history{2:bar} = foo
15929:  %history{2:foo} = notbar
15930:  %history{2:keys} = foo:bar:timestamp
15931:  %history{2:timestamp} = 990455580
15932:  %history{bar} = foo
15933:  %history{foo} = notbar
15934:  %history{timestamp} = 990455580
15935:  %history{version} = 2
15936: 
15937: Note that the special hash entries C<keys>, C<version> and
15938: C<timestamp> were added to the hash. C<version> will be equal to the
15939: total number of versions of the data that have been stored. The
15940: C<timestamp> attribute will be the UNIX time the hash was
15941: stored. C<keys> is available in every historical section to list which
15942: keys were added or changed at a specific historical revision of a
15943: hash.
15944: 
15945: B<Warning>: do not store the hash that restore returns directly. This
15946: will cause a mess since it will restore the historical keys as if the
15947: were new keys. I.E. 1:foo will become 1:1:foo etc.
15948: 
15949: Calling convention:
15950: 
15951:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15952:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15953: 
15954: For more detailed information, see lonnet specific documentation.
15955: 
15956: =head1 RETURN MESSAGES
15957: 
15958: =over 4
15959: 
15960: =item * B<con_lost>: unable to contact remote host
15961: 
15962: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15963: when the connection is brought back up
15964: 
15965: =item * B<con_failed>: unable to contact remote host and unable to save message
15966: for later delivery
15967: 
15968: =item * B<error:>: an error a occurred, a description of the error follows the :
15969: 
15970: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15971: that was requested
15972: 
15973: =back
15974: 
15975: =head1 PUBLIC SUBROUTINES
15976: 
15977: =head2 Session Environment Functions
15978: 
15979: =over 4
15980: 
15981: =item * 
15982: X<appenv()>
15983: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15984: the user envirnoment file, and will be restored for each access this
15985: user makes during this session, also modifies the %env for the current
15986: process. Optional rolesarrayref - if defined contains a reference to an array
15987: of roles which are exempt from the restriction on modifying user.role entries 
15988: in the user's environment.db and in %env.    
15989: 
15990: =item *
15991: X<delenv()>
15992: B<delenv($delthis,$regexp)>: removes all items from the session
15993: environment file that begin with $delthis. If the 
15994: optional second arg - $regexp - is true, $delthis is treated as a 
15995: regular expression, otherwise \Q$delthis\E is used. 
15996: The values are also deleted from the current processes %env.
15997: 
15998: =item * get_env_multiple($name) 
15999: 
16000: gets $name from the %env hash, it seemlessly handles the cases where multiple
16001: values may be defined and end up as an array ref.
16002: 
16003: returns an array of values
16004: 
16005: =back
16006: 
16007: =head2 User Information
16008: 
16009: =over 4
16010: 
16011: =item *
16012: X<queryauthenticate()>
16013: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16014: authentication scheme
16015: 
16016: =item *
16017: X<authenticate()>
16018: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16019: authenticate user from domain's lib servers (first use the current
16020: one). C<$upass> should be the users password.
16021: $checkdefauth is optional (value is 1 if a check should be made to
16022:    authenticate user using default authentication method, and allow
16023:    account creation if username does not have account in the domain).
16024: $clientcancheckhost is optional (value is 1 if checking whether the
16025:    server can host will occur on the client side in lonauth.pm).   
16026: 
16027: =item *
16028: X<homeserver()>
16029: B<homeserver($uname,$udom)>: find the server which has
16030: the user's directory and files (there must be only one), this caches
16031: the answer, and also caches if there is a borken connection.
16032: 
16033: =item *
16034: X<idget()>
16035: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16036: a list of student/employee IDs or clicker IDs
16037: (student/employee IDs are a unique resource in a domain, there must be 
16038: only 1 ID per username, and only 1 username per ID in a specific domain).
16039: clickerIDs are not necessarily unique, as students might share clickers.
16040: (returns hash: id=>name,id=>name)
16041: 
16042: =item *
16043: X<idrget()>
16044: B<idrget($udom,@unames)>: find the IDs behind a list of
16045: usernames (returns hash: name=>id,name=>id)
16046: 
16047: =item *
16048: X<idput()>
16049: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16050: names and associated student/employee IDs or clicker IDs.
16051: 
16052: =item *
16053: X<iddel()>
16054: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16055: student/employee ID or clicker ID username look-ups from domain.
16056: The homeserver ($uhome) and namespace ($namespace) are optional.
16057: If no $uhome is provided, it will be determined usig &homeserver()
16058: for each user.  If no $namespace is provided, the default is ids.
16059: 
16060: =item *
16061: X<updateclickers()>
16062: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16063: clicker ID-to-username look-ups in clickers.db on library server.
16064: Permitted actions are add or del (i.e., add or delete). The 
16065: clickers.db contains clickerID as keys (escaped), and each corresponding
16066: value is an escaped comma-separated list of usernames (for whom the
16067: library server is the homeserver), who registered that particular ID.
16068: If $critical is true, the update will be sent via &critical, otherwise
16069: &reply() will be used.
16070: 
16071: =item *
16072: X<rolesinit()>
16073: B<rolesinit($udom,$username)>: get user privileges.
16074: returns user role, first access and timer interval hashes
16075: 
16076: =item *
16077: X<privileged()>
16078: B<privileged($username,$domain)>: returns a true if user has a
16079: privileged and active role (i.e. su or dc), false otherwise.
16080: 
16081: =item *
16082: X<getsection()>
16083: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16084: course $cname, return section name/number or '' for "not in course"
16085: and '-1' for "no section"
16086: 
16087: =item *
16088: X<userenvironment()>
16089: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16090: passed in @what from the requested user's environment, returns a hash
16091: 
16092: =item * 
16093: X<userlog_query()>
16094: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16095: activity.log file. %filters defines filters applied when parsing the
16096: log file. These can be start or end timestamps, or the type of action
16097: - log to look for Login or Logout events, check for Checkin or
16098: Checkout, role for role selection. The response is in the form
16099: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16100: escaped strings of the action recorded in the activity.log file.
16101: 
16102: =back
16103: 
16104: =head2 User Roles
16105: 
16106: =over 4
16107: 
16108: =item *
16109: 
16110: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16111: returns codes for allowed actions.
16112: 
16113: The first argument is required, all others are optional.
16114: 
16115: $priv is the privilege being checked.
16116: $uri contains additional information about what is being checked for access (e.g.,
16117: URL, course ID etc.). 
16118: $symb is the unique resource instance identifier in a course; if needed,
16119: but not provided, it will be retrieved via a call to &symbread(). 
16120: $role is the role for which a priv is being checked (only used if priv is evb). 
16121: $clientip is the user's IP address (only used when checking for access to portfolio 
16122: files).
16123: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16124: prevents recursive calls to &allowed.
16125: 
16126:  F: full access
16127:  U,I,K: authentication modes (cxx only)
16128:  '': forbidden
16129:  1: user needs to choose course
16130:  2: browse allowed
16131:  A: passphrase authentication needed
16132:  B: access temporarily blocked because of a blocking event in a course.
16133:  D: access blocked because access is required via session initiated via deep-link 
16134: 
16135: =item *
16136: 
16137: constructaccess($url,$setpriv) : check for access to construction space URL
16138: 
16139: See if the owner domain and name in the URL match those in the
16140: expected environment.  If so, return three element list
16141: ($ownername,$ownerdomain,$ownerhome).
16142: 
16143: Otherwise return the null string.
16144: 
16145: If second argument 'setpriv' is true, it assigns the privileges,
16146: and returns the same three element list, unless the owner has
16147: blocked "ad hoc" Domain Coordinator access to the Author Space,
16148: in which case the null string is returned.
16149: 
16150: =item *
16151: 
16152: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16153: define a custom role rolename set privileges in format of lonTabs/roles.tab
16154: for system, domain, and course level. $uname and $udom are optional (current
16155: user's username and domain will be used when either of $uname or $udom are absent.
16156: 
16157: =item *
16158: 
16159: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16160: (rolesplain.tab); plain text explanation of a user role term.
16161: $type is Course (default) or Community.
16162: If $forcedefault evaluates to true, text returned will be default 
16163: text for $type. Otherwise, if this is a course, the text returned 
16164: will be a custom name for the role (if defined in the course's 
16165: environment).  If no custom name is defined the default is returned.
16166:    
16167: =item *
16168: 
16169: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16170: All arguments are optional. Returns a hash of a roles, either for
16171: co-author/assistant author roles for a user's Construction Space
16172: (default), or if $context is 'userroles', roles for the user himself,
16173: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16174: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16175: For each key, value is set to colon-separated start and end times for
16176: the role.  If no username and domain are specified, will default to
16177: current user/domain. Types, roles, and roledoms are references to arrays
16178: of role statuses (active, future or previous), roles 
16179: (e.g., cc,in, st etc.) and domains of the roles which can be used
16180: to restrict the list of roles reported. If no array ref is 
16181: provided for types, will default to return only active roles.
16182: 
16183: =item *
16184: 
16185: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16186: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16187: 
16188: Additional optional arguments are: $type (if role checking is to be restricted 
16189: to certain user status types -- previous (expired roles), active (currently
16190: available roles) or future (roles available in the future), and
16191: $hideprivileged -- if true will not report course roles for users who
16192: have active Domain Coordinator role in course's domain or in additional
16193: domains (specified in 'Domains to check for privileged users' in course
16194: environment -- set via:  Course Settings -> Classlists and staff listing).
16195: 
16196: =item *
16197: 
16198: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16199: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16200: $possdomains and $possroles are optional array refs -- to domains to check and
16201: roles to check.  If $possdomains is not specified, a dump will be done of the
16202: users' roles.db to check for a dc or su role in any domain. This can be
16203: time consuming if &privileged is called repeatedly (e.g., when displaying a
16204: classlist), so in such cases, supplying a $possdomains array is preferred, as
16205: this then allows &privileged_by_domain() to be used, which caches the identity
16206: of privileged users, eliminating the need for repeated calls to &dump().
16207: 
16208: =item *
16209: 
16210: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16211: where the outer hash keys are domains specified in the $possdomains array ref,
16212: next inner hash keys are privileged roles specified in the $roles array ref,
16213: and the innermost hash contains key = value pairs for username:domain = end:start
16214: for active or future "privileged" users with that role in that domain. To avoid
16215: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16216: innerhash are cached using priv_$role and $dom as the identifiers.
16217: 
16218: =back
16219: 
16220: =head2 User Modification
16221: 
16222: =over 4
16223: 
16224: =item *
16225: 
16226: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16227: user for the level given by URL.  Optional start and end dates (leave empty
16228: string or zero for "no date")
16229: 
16230: =item *
16231: 
16232: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16233: change a users, password, possible return values are: ok,
16234: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16235: refused
16236: 
16237: =item *
16238: 
16239: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16240: 
16241: =item *
16242: 
16243: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16244:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16245: 
16246: will update user information (firstname,middlename,lastname,generation,
16247: permanentemail), and if forceid is true, student/employee ID also.
16248: A user's institutional affiliation(s) can also be updated.
16249: User information fields will not be overwritten with empty entries 
16250: unless the field is included in the $candelete array reference.
16251: This array is included when a single user is modified via "Manage Users",
16252: or when Autoupdate.pl is run by cron in a domain.
16253: 
16254: =item *
16255: 
16256: modifystudent
16257: 
16258: modify a student's enrollment and identification information.
16259: The course id is resolved based on the current user's environment.  
16260: This means the invoking user must be a course coordinator or otherwise
16261: associated with a course.
16262: 
16263: This call is essentially a wrapper for lonnet::modifyuser and
16264: lonnet::modify_student_enrollment
16265: 
16266: Inputs: 
16267: 
16268: =over 4
16269: 
16270: =item B<$udom> Student's loncapa domain
16271: 
16272: =item B<$uname> Student's loncapa login name
16273: 
16274: =item B<$uid> Student/Employee ID
16275: 
16276: =item B<$umode> Student's authentication mode
16277: 
16278: =item B<$upass> Student's password
16279: 
16280: =item B<$first> Student's first name
16281: 
16282: =item B<$middle> Student's middle name
16283: 
16284: =item B<$last> Student's last name
16285: 
16286: =item B<$gene> Student's generation
16287: 
16288: =item B<$usec> Student's section in course
16289: 
16290: =item B<$end> Unix time of the roles expiration
16291: 
16292: =item B<$start> Unix time of the roles start date
16293: 
16294: =item B<$forceid> If defined, allow $uid to be changed
16295: 
16296: =item B<$desiredhome> server to use as home server for student
16297: 
16298: =item B<$email> Student's permanent e-mail address
16299: 
16300: =item B<$type> Type of enrollment (auto or manual)
16301: 
16302: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16303: 
16304: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16305: 
16306: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16307: 
16308: =item B<$context> role change context (shown in User Management Logs display in a course)
16309: 
16310: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16311: 
16312: =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.
16313: 
16314: =back
16315: 
16316: =item *
16317: 
16318: modify_student_enrollment
16319: 
16320: Change a student's enrollment status in a class.  The environment variable
16321: 'role.request.course' must be defined for this function to proceed.
16322: 
16323: Inputs:
16324: 
16325: =over 4
16326: 
16327: =item $udom, student's domain
16328: 
16329: =item $uname, student's name
16330: 
16331: =item $uid, student's user id
16332: 
16333: =item $first, student's first name
16334: 
16335: =item $middle
16336: 
16337: =item $last
16338: 
16339: =item $gene
16340: 
16341: =item $usec
16342: 
16343: =item $end
16344: 
16345: =item $start
16346: 
16347: =item $type
16348: 
16349: =item $locktype
16350: 
16351: =item $cid
16352: 
16353: =item $selfenroll
16354: 
16355: =item $context
16356: 
16357: =item $credits, number of credits student will earn from this class
16358: 
16359: =item $instsec, institutional course section code for student
16360: 
16361: =back
16362: 
16363: 
16364: =item *
16365: 
16366: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16367: custom role; give a custom role to a user for the level given by URL.  Specify
16368: name and domain of role author, and role name
16369: 
16370: =item *
16371: 
16372: revokerole($udom,$uname,$url,$role) : revoke a role for url
16373: 
16374: =item *
16375: 
16376: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16377: 
16378: =back
16379: 
16380: =head2 Course Infomation
16381: 
16382: =over 4
16383: 
16384: =item *
16385: 
16386: coursedescription($courseid,$options) : returns a hash of information about the
16387: specified course id, including all environment settings for the
16388: course, the description of the course will be in the hash under the
16389: key 'description'
16390: 
16391: $options is an optional parameter that if supplied is a hash reference that controls
16392: what how this function works.  It has the following key/values:
16393: 
16394: =over 4
16395: 
16396: =item freshen_cache
16397: 
16398: If defined, and the environment cache for the course is valid, it is 
16399: returned in the returned hash.
16400: 
16401: =item one_time
16402: 
16403: If defined, the last cache time is set to _now_
16404: 
16405: =item user
16406: 
16407: If defined, the supplied username is used instead of the current user.
16408: 
16409: 
16410: =back
16411: 
16412: =item *
16413: 
16414: resdata($name,$domain,$type,@which) : request for current parameter
16415: setting for a specific $type, where $type is either 'course' or 'user',
16416: @what should be a list of parameters to ask about. This routine caches
16417: answers for 10 minutes.
16418: 
16419: =item *
16420: 
16421: get_courseresdata($courseid, $domain) : dump the entire course resource
16422: data base, returning a hash that is keyed by the resource name and has
16423: values that are the resource value.  I believe that the timestamps and
16424: versions are also returned.
16425: 
16426: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16427: supplemental content area. This routine caches the number of files for 
16428: 10 minutes.
16429: 
16430: =back
16431: 
16432: =head2 Course Modification
16433: 
16434: =over 4
16435: 
16436: =item *
16437: 
16438: writecoursepref($courseid,%prefs) : write preferences (environment
16439: database) for a course
16440: 
16441: =item *
16442: 
16443: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16444: 
16445: =item *
16446: 
16447: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16448: 
16449: =item *
16450: 
16451: is_course($courseid), is_course($cdom, $cnum)
16452: 
16453: Accepts either a combined $courseid (in the form of domain_courseid) or the
16454: two component version $cdom, $cnum. It checks if the specified course exists.
16455: 
16456: Returns:
16457:     undef if the course doesn't exist, otherwise
16458:     in scalar context the combined courseid.
16459:     in list context the two components of the course identifier, domain and 
16460:     courseid.    
16461: 
16462: =back
16463: 
16464: =head2 Bubblesheet Configuration
16465: 
16466: =over 4
16467: 
16468: =item *
16469: 
16470: get_scantron_config($which)
16471: 
16472: $which - the name of the configuration to parse from the file.
16473: 
16474: Parses and returns the bubblesheet configuration line selected as a
16475: hash of configuration file fields.
16476: 
16477: 
16478: Returns:
16479:     If the named configuration is not in the file, an empty
16480:     hash is returned.
16481: 
16482:     a hash with the fields
16483:       name         - internal name for the this configuration setup
16484:       description  - text to display to operator that describes this config
16485:       CODElocation - if 0 or the string 'none'
16486:                           - no CODE exists for this config
16487:                      if -1 || the string 'letter'
16488:                           - a CODE exists for this config and is
16489:                             a string of letters
16490:                      Unsupported value (but planned for future support)
16491:                           if a positive integer
16492:                                - The CODE exists as the first n items from
16493:                                  the question section of the form
16494:                           if the string 'number'
16495:                                - The CODE exists for this config and is
16496:                                  a string of numbers
16497:       CODEstart   - (only matter if a CODE exists) column in the line where
16498:                      the CODE starts
16499:       CODElength  - length of the CODE
16500:       IDstart     - column where the student/employee ID starts
16501:       IDlength    - length of the student/employee ID info
16502:       Qstart      - column where the information from the bubbled
16503:                     'questions' start
16504:       Qlength     - number of columns comprising a single bubble line from
16505:                     the sheet. (usually either 1 or 10)
16506:       Qon         - either a single character representing the character used
16507:                     to signal a bubble was chosen in the positional setup, or
16508:                     the string 'letter' if the letter of the chosen bubble is
16509:                     in the final, or 'number' if a number representing the
16510:                     chosen bubble is in the file (1->A 0->J)
16511:       Qoff        - the character used to represent that a bubble was
16512:                     left blank
16513:       PaperID     - if the scanning process generates a unique number for each
16514:                     sheet scanned the column that this ID number starts in
16515:       PaperIDlength - number of columns that comprise the unique ID number
16516:                       for the sheet of paper
16517:       FirstName   - column that the first name starts in
16518:       FirstNameLength - number of columns that the first name spans
16519:       LastName    - column that the last name starts in
16520:       LastNameLength - number of columns that the last name spans
16521:       BubblesPerRow - number of bubbles available in each row used to
16522:                       bubble an answer. (If not specified, 10 assumed).
16523: 
16524: 
16525: =item *
16526: 
16527: get_scantronformat_file($cdom)
16528: 
16529: $cdom - the course's domain (optional); if not supplied, uses
16530: domain for current $env{'request.course.id'}.
16531: 
16532: Returns an array containing lines from the scantron format file for
16533: the domain of the course.
16534: 
16535: If a url for a custom.tab file is listed in domain's configuration.db,
16536: lines are from this file.
16537: 
16538: Otherwise, if a default.tab has been published in RES space by the
16539: domainconfig user, lines are from this file.
16540: 
16541: Otherwise, fall back to getting lines from the legacy file on the
16542: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16543: 
16544: =back
16545: 
16546: =head2 Resource Subroutines
16547: 
16548: =over 4
16549: 
16550: =item *
16551: 
16552: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16553: 
16554: =item *
16555: 
16556: repcopy($filename) : subscribes to the requested file, and attempts to
16557: replicate from the owning library server, Might return
16558: 'unavailable', 'not_found', 'forbidden', 'ok', or
16559: 'bad_request', also attempts to grab the metadata for the
16560: resource. Expects the local filesystem pathname
16561: (/home/httpd/html/res/....)
16562: 
16563: =back
16564: 
16565: =head2 Resource Information
16566: 
16567: =over 4
16568: 
16569: =item *
16570: 
16571: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16572: and returns the value of a variety of different possible values,
16573: $varname should be a request string, and the other parameters can be
16574: used to specify who and what one is asking about. Ordinarily, $cid 
16575: does not need to be specified, as it is retrived from 
16576: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16577: within lonuserstate::loadmap() when initializing a course, before
16578: $env{'request.course.id'} has been set, so it needs to be provided
16579: in that one case.
16580: 
16581: Possible values for $varname are environment.lastname (or other item
16582: from the envirnment hash), user.name (or someother aspect about the
16583: user), resource.0.maxtries (or some other part and parameter of a
16584: resource)
16585: 
16586: =item *
16587: 
16588: directcondval($number) : get current value of a condition; reads from a state
16589: string
16590: 
16591: =item *
16592: 
16593: condval($condidx) : value of condition index based on state
16594: 
16595: =item *
16596: 
16597: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16598: resource's metadata, $what should be either a specific key, or either
16599: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16600: packages that this resource currently uses, the last 3 arguments are 
16601: only used internally for recursive metadata.
16602: 
16603: the toolsymb is only used where the uri is for an external tool (for which
16604: the uri as well as the symb are guaranteed to be unique).
16605: 
16606: this function automatically caches all requests except any made recursively
16607: to retrieve a list of metadata keys for an imported library file ($liburi is 
16608: defined).
16609: 
16610: =item *
16611: 
16612: metadata_query($query,$custom,$customshow) : make a metadata query against the
16613: network of library servers; returns file handle of where SQL and regex results
16614: will be stored for query
16615: 
16616: =item *
16617: 
16618: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16619: return symbolic list entry (all arguments optional). 
16620: 
16621: Args: filename is the filename (including path) for the file for which a symb 
16622: is required; donotrecurse, if true will prevent calls to allowed() being made 
16623: to check access status if more than one resource was found in the bighash 
16624: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16625: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16626: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16627: cause possible symbs to be checked to determine if they are subject to content
16628: blocking, if so they will not be included as possible symbs; possibles is a
16629: ref to a hash, which, as a side effect, will be populated with all possible 
16630: symbs (content blocking not tested).
16631:  
16632: returns the data handle
16633: 
16634: =item *
16635: 
16636: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16637: and is a possible symb for the URL in $thisfn, and if is an encrypted
16638: resource that the user accessed using /enc/ returns a 1 on success, 0
16639: on failure, user must be in a course, as it assumes the existence of
16640: the course initial hash, and uses $env('request.course.id'}.  The third
16641: arg is an optional reference to a scalar.  If this arg is passed in the 
16642: call to symbverify, it will be set to 1 if the symb has been set to be 
16643: encrypted; otherwise it will be null.  
16644: 
16645: =item *
16646: 
16647: symbclean($symb) : removes versions numbers from a symb, returns the
16648: cleaned symb
16649: 
16650: =item *
16651: 
16652: is_on_map($uri) : checks if the $uri is somewhere on the current
16653: course map, user must be in a course for it to work.
16654: 
16655: =item *
16656: 
16657: numval($salt) : return random seed value (addend for rndseed)
16658: 
16659: =item *
16660: 
16661: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16662: a random seed, all arguments are optional, if they aren't sent it uses the
16663: environment to derive them. Note: if symb isn't sent and it can't get one
16664: from &symbread it will use the current time as its return value
16665: 
16666: =item *
16667: 
16668: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16669: unfakeable, receipt
16670: 
16671: =item *
16672: 
16673: receipt() : API to ireceipt working off of env values; given out to users
16674: 
16675: =item *
16676: 
16677: countacc($url) : count the number of accesses to a given URL
16678: 
16679: =item *
16680: 
16681: 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
16682: 
16683: =item *
16684: 
16685: 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)
16686: 
16687: =item *
16688: 
16689: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16690: 
16691: =item *
16692: 
16693: devalidate($symb) : devalidate temporary spreadsheet calculations,
16694: forcing spreadsheet to reevaluate the resource scores next time.
16695: 
16696: =item * 
16697: 
16698: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16699: when viewing in course context.
16700: 
16701:  input: six args -- filename (decluttered), course number, course domain,
16702:                     url, symb (if registered) and group (if this is a 
16703:                     group item -- e.g., bulletin board, group page etc.).
16704: 
16705:  output: array of five scalars --
16706:          $cfile -- url for file editing if editable on current server
16707:          $home -- homeserver of resource (i.e., for author if published,
16708:                                           or course if uploaded.).
16709:          $switchserver --  1 if server switch will be needed.
16710:          $forceedit -- 1 if icon/link should be to go to edit mode 
16711:          $forceview -- 1 if icon/link should be to go to view mode
16712: 
16713: =item *
16714: 
16715: is_course_upload($file,$cnum,$cdom)
16716: 
16717: Used in course context to determine if current file was uploaded to 
16718: the course (i.e., would be found in /userfiles/docs on the course's 
16719: homeserver.
16720: 
16721:   input: 3 args -- filename (decluttered), course number and course domain.
16722:   output: boolean -- 1 if file was uploaded.
16723: 
16724: =back
16725: 
16726: =head2 Storing/Retreiving Data
16727: 
16728: =over 4
16729: 
16730: =item *
16731: 
16732: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16733: permanently for this url; hashref needs to be given and should be a \%hashname;
16734: the remaining args aren't required and if they aren't passed or are '' they will
16735: be derived from the env (with the exception of $laststore, which is an 
16736: optional arg used when a user's submission is stored in grading).
16737: $laststore is $version=$timestamp, where $version is the most recent version
16738: number retrieved for the corresponding $symb in the $namespace db file, and
16739: $timestamp is the timestamp for that transaction (UNIX time).
16740: $laststore is currently only passed when cstore() is called by 
16741: structuretags::finalize_storage().
16742: 
16743: =item *
16744: 
16745: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16746: but uses critical subroutine
16747: 
16748: =item *
16749: 
16750: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16751: all args are optional
16752: 
16753: =item *
16754: 
16755: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16756: dumps the complete (or key matching regexp) namespace into a hash
16757: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16758: normally &store()ed into
16759: 
16760: $range should be either an integer '100' (give me the first 100
16761:                                            matching records)
16762:               or be  two integers sperated by a - with no spaces
16763:                  '30-50' (give me the 30th through the 50th matching
16764:                           records)
16765: 
16766: 
16767: =item *
16768: 
16769: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16770: replaces a &store() version of data with a replacement set of data
16771: for a particular resource in a namespace passed in the $storehash hash 
16772: reference. If $tolog is true, the transaction is logged in the courselog
16773: with an action=PUTSTORE.
16774: 
16775: =item *
16776: 
16777: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16778: works very similar to store/cstore, but all data is stored in a
16779: temporary location and can be reset using tmpreset, $storehash should
16780: be a hash reference, returns nothing on success
16781: 
16782: =item *
16783: 
16784: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16785: similar to restore, but all data is stored in a temporary location and
16786: can be reset using tmpreset. Returns a hash of values on success,
16787: error string otherwise.
16788: 
16789: =item *
16790: 
16791: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16792: deltes all keys for $symb form the temporary storage hash.
16793: 
16794: =item *
16795: 
16796: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16797: reference filled in from namesp ($udom and $uname are optional)
16798: 
16799: =item *
16800: 
16801: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16802: namesp ($udom and $uname are optional)
16803: 
16804: =item *
16805: 
16806: dump($namespace,$udom,$uname,$regexp,$range) : 
16807: dumps the complete (or key matching regexp) namespace into a hash
16808: ($udom, $uname, $regexp, $range are optional)
16809: 
16810: $range should be either an integer '100' (give me the first 100
16811:                                            matching records)
16812:               or be  two integers sperated by a - with no spaces
16813:                  '30-50' (give me the 30th through the 50th matching
16814:                           records)
16815: =item *
16816: 
16817: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16818: $store can be a scalar, an array reference, or if the amount to be 
16819: incremented is > 1, a hash reference.
16820: 
16821: ($udom and $uname are optional)
16822: 
16823: =item *
16824: 
16825: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16826: ($udom and $uname are optional)
16827: 
16828: =item *
16829: 
16830: cput($namespace,$storehash,$udom,$uname) : critical put
16831: ($udom and $uname are optional)
16832: 
16833: =item *
16834: 
16835: newput($namespace,$storehash,$udom,$uname) :
16836: 
16837: Attempts to store the items in the $storehash, but only if they don't
16838: currently exist, if this succeeds you can be certain that you have 
16839: successfully created a new key value pair in the $namespace db.
16840: 
16841: 
16842: Args:
16843:  $namespace: name of database to store values to
16844:  $storehash: hashref to store to the db
16845:  $udom: (optional) domain of user containing the db
16846:  $uname: (optional) name of user caontaining the db
16847: 
16848: Returns:
16849:  'ok' -> succeeded in storing all keys of $storehash
16850:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16851:                         least <key> already existed in the db (other
16852:                         requested keys may also already exist)
16853:  'error: <msg>' -> unable to tie the DB or other error occurred
16854:  'con_lost' -> unable to contact request server
16855:  'refused' -> action was not allowed by remote machine
16856: 
16857: 
16858: =item *
16859: 
16860: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16861: reference filled in from namesp (encrypts the return communication)
16862: ($udom and $uname are optional)
16863: 
16864: =item *
16865: 
16866: log($udom,$name,$home,$message) : write to permanent log for user; use
16867: critical subroutine
16868: 
16869: =item *
16870: 
16871: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16872: array reference filled in from namespace found in domain level on either
16873: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16874: 
16875: =item *
16876: 
16877: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16878: domain level either on specified domain server ($uhome) or primary domain 
16879: server ($udom and $uhome are optional)
16880: 
16881: =item * 
16882: 
16883: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16884: for: authentication, language, quotas, timezone, date locale, and portal URL in
16885: the target domain.
16886: 
16887: May also include additional key => value pairs for the following groups:
16888: 
16889: =over
16890: 
16891: =item
16892: disk quotas (MB allocated by default to portfolios and authoring spaces).
16893: 
16894: =over
16895: 
16896: =item defaultquota, authorquota
16897: 
16898: =back
16899: 
16900: =item
16901: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16902: portfolio for users).
16903: 
16904: =over
16905: 
16906: =item
16907: aboutme, blog, webdav, portfolio
16908: 
16909: =back
16910: 
16911: =item
16912: requestcourses: ability to request courses, and how requests are processed.
16913: 
16914: =over
16915: 
16916: =item
16917: official, unofficial, community, textbook, placement
16918: 
16919: =back
16920: 
16921: =item
16922: inststatus: types of institutional affiliation, and order in which they are displayed.
16923: 
16924: =over
16925: 
16926: =item
16927: inststatustypes, inststatusorder, inststatusguest
16928: 
16929: =back
16930: 
16931: =item
16932: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16933: for course's uploaded content.
16934: 
16935: =over
16936: 
16937: =item
16938: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16939: communityquota, textbookquota, placementquota
16940: 
16941: =back
16942: 
16943: =item
16944: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16945: on your servers.
16946: 
16947: =over
16948: 
16949: =item 
16950: remotesessions, hostedsessions
16951: 
16952: =back
16953: 
16954: =back
16955: 
16956: In cases where a domain coordinator has never used the "Set Domain Configuration"
16957: utility to create a configuration.db file on a domain's primary library server 
16958: only the following domain defaults: auth_def, auth_arg_def, lang_def
16959: -- corresponding values are authentication type (internal, krb4, krb5,
16960: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16961: will be available. Values are retrieved from cache (if current), unless the
16962: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16963: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16964: 
16965: Typical usage:
16966: 
16967: %domdefaults = &get_domain_defaults($target_domain);
16968: 
16969: =back
16970: 
16971: =head2 Network Status Functions
16972: 
16973: =over 4
16974: 
16975: =item *
16976: 
16977: dirlist() : return directory list based on URI (first arg).
16978: 
16979: Inputs: 1 required, 5 optional.
16980: 
16981: =over
16982: 
16983: =item 
16984: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16985: 
16986: =item
16987: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16988: 
16989: =item
16990: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16991: 
16992: =item
16993: $getpropath - boolean: 1 if prepend path using &propath(). 
16994: 
16995: =item
16996: $getuserdir - boolean: 1 if prepend path for "userfiles".
16997: 
16998: =item 
16999: $alternateRoot - path to prepend in place of path from $uri.
17000: 
17001: =back
17002: 
17003: Returns: Array of up to two items.
17004: 
17005: =over
17006: 
17007: a reference to an array of files/subdirectories
17008: 
17009: =over
17010: 
17011: Each element in the array of files/subdirectories is a & separated list of
17012: item name and the result of running stat on the item.  If dirlist was requested
17013: for a file instead of a directory, the item name will be ''. For a directory 
17014: listing, if the item is a metadata file, the element will end &N&M 
17015: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17016: default copyright set (1).  
17017: 
17018: =back
17019: 
17020: a scalar containing error condition (if encountered).
17021: 
17022: =over
17023: 
17024: =item 
17025: no_host (no homeserver identified for $username:$domain).
17026: 
17027: =item 
17028: no_such_host (server contacted for listing not identified as valid host).
17029: 
17030: =item 
17031: con_lost (connection to remote server failed).
17032: 
17033: =item 
17034: refused (invalid $username:$domain received on lond side).
17035: 
17036: =item 
17037: no_such_dir (directory at specified path on lond side does not exist). 
17038: 
17039: =item 
17040: empty (directory at specified path on lond side is empty).
17041: 
17042: =over
17043: 
17044: This is currently not encountered because the &ls3, &ls2, 
17045: &ls (_handler) routines on the lond side do not filter out
17046: . and .. from a directory listing. 
17047: 
17048: =back
17049: 
17050: =back
17051: 
17052: =back
17053: 
17054: =item *
17055: 
17056: spareserver() : find server with least workload from spare.tab
17057: 
17058: 
17059: =item *
17060: 
17061: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17062: if there is no corresponding loncapa host.
17063: 
17064: =back
17065: 
17066: 
17067: =head2 Apache Request
17068: 
17069: =over 4
17070: 
17071: =item *
17072: 
17073: ssi($url,%hash) : server side include, does a complete request cycle on url to
17074: localhost, posts hash
17075: 
17076: =back
17077: 
17078: =head2 Data to String to Data
17079: 
17080: =over 4
17081: 
17082: =item *
17083: 
17084: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17085: and '&' separators, supports elements that are arrayrefs and hashrefs
17086: 
17087: =item *
17088: 
17089: hashref2str($hashref) : convert a hashref into a string complete with
17090: escaping and '=' and '&' separators, supports elements that are
17091: arrayrefs and hashrefs
17092: 
17093: =item *
17094: 
17095: arrayref2str($arrayref) : convert an arrayref into a string complete
17096: with escaping and '&' separators, supports elements that are arrayrefs
17097: and hashrefs
17098: 
17099: =item *
17100: 
17101: str2hash($string) : convert string to hash using unescaping and
17102: splitting on '=' and '&', supports elements that are arrayrefs and
17103: hashrefs
17104: 
17105: =item *
17106: 
17107: str2array($string) : convert string to hash using unescaping and
17108: splitting on '&', supports elements that are arrayrefs and hashrefs
17109: 
17110: =back
17111: 
17112: =head2 Logging Routines
17113: 
17114: 
17115: These routines allow one to make log messages in the lonnet.log and
17116: lonnet.perm logfiles.
17117: 
17118: =over 4
17119: 
17120: =item *
17121: 
17122: logtouch() : make sure the logfile, lonnet.log, exists
17123: 
17124: =item *
17125: 
17126: logthis() : append message to the normal lonnet.log file, it gets
17127: preiodically rolled over and deleted.
17128: 
17129: =item *
17130: 
17131: logperm() : append a permanent message to lonnet.perm.log, this log
17132: file never gets deleted by any automated portion of the system, only
17133: messages of critical importance should go in here.
17134: 
17135: 
17136: =back
17137: 
17138: =head2 General File Helper Routines
17139: 
17140: =over 4
17141: 
17142: =item *
17143: 
17144: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17145: (a) files in /uploaded
17146:   (i) If a local copy of the file exists - 
17147:       compares modification date of local copy with last-modified date for 
17148:       definitive version stored on home server for course. If local copy is 
17149:       stale, requests a new version from the home server and stores it. 
17150:       If the original has been removed from the home server, then local copy 
17151:       is unlinked.
17152:   (ii) If local copy does not exist -
17153:       requests the file from the home server and stores it. 
17154:   
17155:   If $caller is 'uploadrep':  
17156:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17157:     for request for files originally uploaded via DOCS. 
17158:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17159:   
17160:   Otherwise:
17161:      This indicates a call from the content generation phase of the request.
17162:      -  returns the entire contents of the file or -1.
17163:      
17164: (b) files in /res
17165:    - returns the entire contents of a file or -1; 
17166:    it properly subscribes to and replicates the file if neccessary.
17167: 
17168: 
17169: =item *
17170: 
17171: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17172:                   reference
17173: 
17174: returns either a stat() list of data about the file or an empty list
17175: if the file doesn't exist or couldn't find out about it (connection
17176: problems or user unknown)
17177: 
17178: =item *
17179: 
17180: filelocation($dir,$file) : returns file system location of a file
17181: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17182: directory that relative $file lookups are to looked in ($dir of /a/dir
17183: and a file of ../bob will become /a/bob)
17184: 
17185: =item *
17186: 
17187: hreflocation($dir,$file) : returns file system location or a URL; same as
17188: filelocation except for hrefs
17189: 
17190: =item *
17191: 
17192: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17193: also removes beginning /home/httpd/html unless /priv/ follows it.
17194: 
17195: =back
17196: 
17197: =head2 Usererfile file routines (/uploaded*)
17198: 
17199: =over 4
17200: 
17201: =item *
17202: 
17203: userfileupload(): main rotine for putting a file in a user or course's
17204:                   filespace, arguments are,
17205: 
17206:  formname - required - this is the name of the element in $env where the
17207:            filename, and the contents of the file to create/modifed exist
17208:            the filename is in $env{'form.'.$formname.'.filename'} and the
17209:            contents of the file is located in $env{'form.'.$formname}
17210:  context - if coursedoc, store the file in the course of the active role
17211:              of the current user; 
17212:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17213:            if 'canceloverwrite': delete file in tmp/overwrites directory
17214:  subdir - required - subdirectory to put the file in under ../userfiles/
17215:          if undefined, it will be placed in "unknown"
17216: 
17217:  (This routine calls clean_filename() to remove any dangerous
17218:  characters from the filename, and then calls finuserfileupload() to
17219:  complete the transaction)
17220: 
17221:  returns either the url of the uploaded file (/uploaded/....) if successful
17222:  and /adm/notfound.html if unsuccessful
17223: 
17224: =item *
17225: 
17226: clean_filename(): routine for cleaing a filename up for storage in
17227:                  userfile space, argument is:
17228: 
17229:  filename - proposed filename
17230: 
17231: returns: the new clean filename
17232: 
17233: =item *
17234: 
17235: finishuserfileupload(): routine that creates and sends the file to
17236: userspace, probably shouldn't be called directly
17237: 
17238:   docuname: username or courseid of destination for the file
17239:   docudom: domain of user/course of destination for the file
17240:   formname: same as for userfileupload()
17241:   fname: filename (including subdirectories) for the file
17242:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17243:           if hashref, and context is scantron, will convert csv format to standard format
17244:   allfiles: reference to hash used to store objects found by parser
17245:   codebase: reference to hash used for codebases of java objects found by parser
17246:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17247:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17248:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17249:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17250:   context: if 'overwrite', will move the uploaded file from its temporary location to
17251:             userfiles to facilitate overwriting a previously uploaded file with same name.
17252:   mimetype: reference to scalar to accommodate mime type determined
17253:             from File::MMagic if $parser = parse.
17254: 
17255:  returns either the url of the uploaded file (/uploaded/....) if successful
17256:  and /adm/notfound.html if unsuccessful (or an error message if context 
17257:  was 'overwrite').
17258:  
17259: 
17260: =item *
17261: 
17262: renameuserfile(): renames an existing userfile to a new name
17263: 
17264:   Args:
17265:    docuname: username or courseid of destination for the file
17266:    docudom: domain of user/course of destination for the file
17267:    old: current file name (including any subdirs under userfiles)
17268:    new: desired file name (including any subdirs under userfiles)
17269: 
17270: =item *
17271: 
17272: mkdiruserfile(): creates a directory is a userfiles dir
17273: 
17274:   Args:
17275:    docuname: username or courseid of destination for the file
17276:    docudom: domain of user/course of destination for the file
17277:    dir: dir to create (including any subdirs under userfiles)
17278: 
17279: =item *
17280: 
17281: removeuserfile(): removes a file that exists in userfiles
17282: 
17283:   Args:
17284:    docuname: username or courseid of destination for the file
17285:    docudom: domain of user/course of destination for the file
17286:    fname: filname to delete (including any subdirs under userfiles)
17287: 
17288: =item *
17289: 
17290: removeuploadedurl(): convience function for removeuserfile()
17291: 
17292:   Args:
17293:    url:  a full /uploaded/... url to delete
17294: 
17295: =item * 
17296: 
17297: get_portfile_permissions():
17298:   Args:
17299:     domain: domain of user or course contain the portfolio files
17300:     user: name of user or num of course contain the portfolio files
17301:   Returns:
17302:     hashref of a dump of the proper file_permissions.db
17303:    
17304: 
17305: =item * 
17306: 
17307: get_access_controls():
17308: 
17309: Args:
17310:   current_permissions: the hash ref returned from get_portfile_permissions()
17311:   group: (optional) the group you want the files associated with
17312:   file: (optional) the file you want access info on
17313: 
17314: Returns:
17315:     a hash (keys are file names) of hashes containing
17316:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17317:         values are XML containing access control settings (see below) 
17318: 
17319: Internal notes:
17320: 
17321:  access controls are stored in file_permissions.db as key=value pairs.
17322:     key -> path to file/file_name\0uniqueID:scope_end_start
17323:         where scope -> public,guest,course,group,domains or users.
17324:               end -> UNIX time for end of access (0 -> no end date)
17325:               start -> UNIX time for start of access
17326: 
17327:     value -> XML description of access control
17328:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17329:             <start></start>
17330:             <end></end>
17331: 
17332:             <password></password>  for scope type = guest
17333: 
17334:             <domain></domain>     for scope type = course or group
17335:             <number></number>
17336:             <roles id="">
17337:              <role></role>
17338:              <access></access>
17339:              <section></section>
17340:              <group></group>
17341:             </roles>
17342: 
17343:             <dom></dom>         for scope type = domains
17344: 
17345:             <users>             for scope type = users
17346:              <user>
17347:               <uname></uname>
17348:               <udom></udom>
17349:              </user>
17350:             </users>
17351:            </scope> 
17352:               
17353:  Access data is also aggregated for each file in an additional key=value pair:
17354:  key -> path to file/file_name\0accesscontrol 
17355:  value -> reference to hash
17356:           hash contains key = value pairs
17357:           where key = uniqueID:scope_end_start
17358:                 value = UNIX time record was last updated
17359: 
17360:           Used to improve speed of look-ups of access controls for each file.  
17361:  
17362:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17363: 
17364: =item *
17365: 
17366: modify_access_controls():
17367: 
17368: Modifies access controls for a portfolio file
17369: Args
17370: 1. file name
17371: 2. reference to hash of required changes,
17372: 3. domain
17373: 4. username
17374:   where domain,username are the domain of the portfolio owner 
17375:   (either a user or a course) 
17376: 
17377: Returns:
17378: 1. result of additions or updates ('ok' or 'error', with error message). 
17379: 2. result of deletions ('ok' or 'error', with error message).
17380: 3. reference to hash of any new or updated access controls.
17381: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17382:    key = integer (inbound ID)
17383:    value = uniqueID
17384: 
17385: =item *
17386: 
17387: get_timebased_id():
17388: 
17389: Attempts to get a unique timestamp-based suffix for use with items added to a 
17390: course via the Course Editor (e.g., folders, composite pages, 
17391: group bulletin boards).
17392: 
17393: Args: (first three required; six others optional)
17394: 
17395: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17396:    docssequence, or name of group
17397: 
17398: 2. keyid (alphanumeric): name of temporary locking key in hash,
17399:    e.g., num, boardids
17400: 
17401: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17402:    file will be named nohist_namespace.db
17403: 
17404: 4. cdom: domain of course; default is current course domain from %env
17405: 
17406: 5. cnum: course number; default is current course number from %env
17407: 
17408: 6. idtype: set to concat if an additional digit is to be appended to the 
17409:    unix timestamp to form the suffix, if the plain timestamp is already
17410:    in use.  Default is to not do this, but simply increment the unix 
17411:    timestamp by 1 until a unique key is obtained.
17412: 
17413: 7. who: holder of locking key; defaults to user:domain for user.
17414: 
17415: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17416:    retrying); default is 3.
17417: 
17418: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17419: 
17420: Returns:
17421: 
17422: 1. suffix obtained (numeric)
17423: 
17424: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17425: 
17426: 3. error: contains (localized) error message if an error occurred.
17427: 
17428: 
17429: =back
17430: 
17431: =head2 HTTP Helper Routines
17432: 
17433: =over 4
17434: 
17435: =item *
17436: 
17437: escape() : unpack non-word characters into CGI-compatible hex codes
17438: 
17439: =item *
17440: 
17441: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17442: 
17443: =back
17444: 
17445: =head1 PRIVATE SUBROUTINES
17446: 
17447: =head2 Underlying communication routines (Shouldn't call)
17448: 
17449: =over 4
17450: 
17451: =item *
17452: 
17453: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17454: 
17455: =item *
17456: 
17457: reply() : uses subreply to send a message to remote machine, logs all failures
17458: 
17459: =item *
17460: 
17461: critical() : passes a critical message to another server; if cannot
17462: get through then place message in connection buffer directory and
17463: returns con_delayed, if incapable of saving message, returns
17464: con_failed
17465: 
17466: =item *
17467: 
17468: reconlonc() : tries to reconnect lonc client processes.
17469: 
17470: =back
17471: 
17472: =head2 Resource Access Logging
17473: 
17474: =over 4
17475: 
17476: =item *
17477: 
17478: flushcourselogs() : flush (save) buffer logs and access logs
17479: 
17480: =item *
17481: 
17482: courselog($what) : save message for course in hash
17483: 
17484: =item *
17485: 
17486: courseacclog($what) : save message for course using &courselog().  Perform
17487: special processing for specific resource types (problems, exams, quizzes, etc).
17488: 
17489: =item *
17490: 
17491: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17492: as a PerlChildExitHandler
17493: 
17494: =back
17495: 
17496: =head2 Other
17497: 
17498: =over 4
17499: 
17500: =item *
17501: 
17502: symblist($mapname,%newhash) : update symbolic storage links
17503: 
17504: =back
17505: 
17506: =cut
17507: 

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