File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1505: download - view: text, annotated - select for diffs
Mon Mar 27 18:41:07 2023 UTC (15 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- "In course" authoring.
  Improved handling of case where no suitable resources authored in course
  exist when (a) using "Import from Course Resources" in Course Editor, and
  (b) using Choose File >  "Use a course file" to select published file as src
  in img tag in colorful editor.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1505 2023/03/27 18:41:07 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 = &domain($udom,'primary');
  989:         $uint_dom = &internet_dom($uprimary_id);
  990:         my %udomdefaults = &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 = &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:                 &get_dom('configuration',['loadbalancing'],$udom);
 1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1217:                                            $cachetime);
 1218:             }
 1219:         }
 1220:     }
 1221:     foreach my $lonhost (keys(%servers)) {
 1222:         if ($skiploadbal) {
 1223:             if (ref($balancers) eq 'HASH') {
 1224:                 next if (exists($balancers->{$lonhost}));
 1225:             }
 1226:         }
 1227:         my $loginvia;
 1228:         if ($checkloginvia) {
 1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1230:             if ($loginvia) {
 1231:                 my ($server,$path) = split(/:/,$loginvia);
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $server) {
 1235:                     $portal_path = $path;
 1236:                     $isredirect = 1;
 1237:                 }
 1238:             } else {
 1239:                 ($login_host, $lowest_load) =
 1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1241:                 if ($login_host eq $lonhost) {
 1242:                     $portal_path = '';
 1243:                     $isredirect = ''; 
 1244:                 }
 1245:             }
 1246:         } else {
 1247:             ($login_host, $lowest_load) =
 1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1249:         }
 1250:     }
 1251:     if ($login_host ne '') {
 1252:         $hostname = &hostname($login_host);
 1253:     }
 1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1255: }
 1256: 
 1257: sub get_course_sessions {
 1258:     my ($cnum,$cdom,$lastactivity) = @_;
 1259:     my %servers = &internet_dom_servers($cdom);
 1260:     my %returnhash;
 1261:     foreach my $server (sort(keys(%servers))) {
 1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1263:         my @pairs=split(/\&/,$rep);
 1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1265:             foreach my $item (@pairs) {
 1266:                 my ($key,$value)=split(/=/,$item,2);
 1267:                 $key = &unescape($key);
 1268:                 next if ($key =~ /^error: 2 /);
 1269:                 if (exists($returnhash{$key})) {
 1270:                     next if ($value < $returnhash{$key});
 1271:                 }
 1272:                 $returnhash{$key}=$value;
 1273:             }
 1274:         }
 1275:     }
 1276:     return %returnhash;
 1277: }
 1278: 
 1279: # --------------------------------------------- Try to change a user's password
 1280: 
 1281: sub changepass {
 1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1283:     $currentpass = &escape($currentpass);
 1284:     $newpass     = &escape($newpass);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1287: 		       $server);
 1288:     if (! $answer) {
 1289: 	&logthis("No reply on password change request to $server ".
 1290: 		 "by $uname in domain $udom.");
 1291:     } elsif ($answer =~ "^ok") {
 1292:         &logthis("$uname in $udom successfully changed their password ".
 1293: 		 "on $server.");
 1294:     } elsif ($answer =~ "^pwchange_failure") {
 1295: 	&logthis("$uname in $udom was unable to change their password ".
 1296: 		 "on $server.  The action was blocked by either lcpasswd ".
 1297: 		 "or pwchange");
 1298:     } elsif ($answer =~ "^non_authorized") {
 1299:         &logthis("$uname in $udom did not get their password correct when ".
 1300: 		 "attempting to change it on $server.");
 1301:     } elsif ($answer =~ "^auth_mode_error") {
 1302:         &logthis("$uname in $udom attempted to change their password despite ".
 1303: 		 "not being locally or internally authenticated on $server.");
 1304:     } elsif ($answer =~ "^unknown_user") {
 1305:         &logthis("$uname in $udom attempted to change their password ".
 1306: 		 "on $server but were unable to because $server is not ".
 1307: 		 "their home server.");
 1308:     } elsif ($answer =~ "^refused") {
 1309: 	&logthis("$server refused to change $uname in $udom password because ".
 1310: 		 "it was sent an unencrypted request to change the password.");
 1311:     } elsif ($answer =~ "invalid_client") {
 1312:         &logthis("$server refused to change $uname in $udom password because ".
 1313:                  "it was a reset by e-mail originating from an invalid server.");
 1314:     } elsif ($answer =~ "^prioruse") {
 1315:        &logthis("$server refused to change $uname in $udom password because ".
 1316:                 "the password had been used before");
 1317:     }
 1318:     return $answer;
 1319: }
 1320: 
 1321: # ----------------------- Try to determine user's current authentication scheme
 1322: 
 1323: sub queryauthenticate {
 1324:     my ($uname,$udom)=@_;
 1325:     my $uhome=&homeserver($uname,$udom);
 1326:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1328: 	return 'no_host';
 1329:     }
 1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1333:     }
 1334:     return $answer;
 1335: }
 1336: 
 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
 1338: 
 1339: sub authenticate {
 1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1341:     $upass=&escape($upass);
 1342:     $uname= &LONCAPA::clean_username($uname);
 1343:     my $uhome=&homeserver($uname,$udom,1);
 1344:     my $newhome;
 1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1346: # Maybe the machine was offline and only re-appeared again recently?
 1347:         &reconlonc();
 1348: # One more
 1349: 	$uhome=&homeserver($uname,$udom,1);
 1350:         if (($uhome eq 'no_host') && $checkdefauth) {
 1351:             if (defined(&domain($udom,'primary'))) {
 1352:                 $newhome=&domain($udom,'primary');
 1353:             }
 1354:             if ($newhome ne '') {
 1355:                 $uhome = $newhome;
 1356:             }
 1357:         }
 1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1360: 	    return 'no_host';
 1361:         }
 1362:     }
 1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1364:     if ($answer eq 'authorized') {
 1365:         if ($newhome) {
 1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1367:             return 'no_account_on_host'; 
 1368:         } else {
 1369:             &logthis("User $uname at $udom authorized by $uhome");
 1370:             return $uhome;
 1371:         }
 1372:     }
 1373:     if ($answer eq 'non_authorized') {
 1374: 	&logthis("User $uname at $udom rejected by $uhome");
 1375: 	return 'no_host';
 1376:     }
 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1378:     return 'no_host';
 1379: }
 1380: 
 1381: sub can_switchserver {
 1382:     my ($udom,$home) = @_;
 1383:     my ($canswitch,@intdoms);
 1384:     my $internet_names = &get_internet_names($home);
 1385:     if (ref($internet_names) eq 'ARRAY') {
 1386:         @intdoms = @{$internet_names};
 1387:     }
 1388:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1389:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1390:         $canswitch = 1;
 1391:     } else {
 1392:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1393:          my $serverhomedom = &host_domain($serverhomeID);
 1394:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1395:          my %udomdefaults = &get_domain_defaults($udom);
 1396:          my $remoterev = &get_server_loncaparev('',$home);
 1397:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1398:                                         $udomdefaults{'remotesessions'},
 1399:                                         $defdomdefaults{'hostedsessions'});
 1400:     }
 1401:     return $canswitch;
 1402: }
 1403: 
 1404: sub can_host_session {
 1405:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1406:     my $canhost = 1;
 1407:     my $host_idn = &internet_dom($lonhost);
 1408:     if (ref($remotesessions) eq 'HASH') {
 1409:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1410:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1411:                 $canhost = 0;
 1412:             } else {
 1413:                 $canhost = 1;
 1414:             }
 1415:         }
 1416:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1417:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1418:                 $canhost = 1;
 1419:             } else {
 1420:                 $canhost = 0;
 1421:             }
 1422:         }
 1423:         if ($canhost) {
 1424:             if ($remotesessions->{'version'} ne '') {
 1425:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1426:                 if ($reqmajor ne '' && $reqminor ne '') {
 1427:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1428:                         my $major = $1;
 1429:                         my $minor = $2;
 1430:                         if (($major < $reqmajor ) ||
 1431:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1432:                             $canhost = 0;
 1433:                         }
 1434:                     } else {
 1435:                         $canhost = 0;
 1436:                     }
 1437:                 }
 1438:             }
 1439:         }
 1440:     }
 1441:     if ($canhost) {
 1442:         if (ref($hostedsessions) eq 'HASH') {
 1443:             my $uprimary_id = &domain($udom,'primary');
 1444:             my $uint_dom = &internet_dom($uprimary_id);
 1445:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1446:                 if (($uint_dom ne '') && 
 1447:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1448:                     $canhost = 0;
 1449:                 } else {
 1450:                     $canhost = 1;
 1451:                 }
 1452:             }
 1453:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1454:                 if (($uint_dom ne '') && 
 1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1456:                     $canhost = 1;
 1457:                 } else {
 1458:                     $canhost = 0;
 1459:                 }
 1460:             }
 1461:         }
 1462:     }
 1463:     return $canhost;
 1464: }
 1465: 
 1466: sub spare_can_host {
 1467:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1468:     my $canhost=1;
 1469:     my $try_server_hostname = &hostname($try_server);
 1470:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1471:     my $serverhomedom = &host_domain($serverhomeID);
 1472:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1473:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1474:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1475:             $canhost = 0;
 1476:         }
 1477:     }
 1478:     if ($canhost) {
 1479:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1480:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1481:                 unless (&shared_institution($udom,$try_server)) {
 1482:                     $canhost = 0;
 1483:                 }
 1484:             }
 1485:         }
 1486:     }
 1487:     if (($canhost) && ($uint_dom)) {
 1488:         my @intdoms;
 1489:         my $internet_names = &get_internet_names($try_server);
 1490:         if (ref($internet_names) eq 'ARRAY') {
 1491:             @intdoms = @{$internet_names};
 1492:         }
 1493:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1494:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1495:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1496:                                          $remotesessions,
 1497:                                          $defdomdefaults{'hostedsessions'});
 1498:         }
 1499:     }
 1500:     return $canhost;
 1501: }
 1502: 
 1503: sub this_host_spares {
 1504:     my ($dom) = @_;
 1505:     my ($dom_in_use,$lonhost_in_use,$result);
 1506:     my @hosts = &current_machine_ids();
 1507:     foreach my $lonhost (@hosts) {
 1508:         if (&host_domain($lonhost) eq $dom) {
 1509:             $dom_in_use = $dom;
 1510:             $lonhost_in_use = $lonhost;
 1511:             last;
 1512:         }
 1513:     }
 1514:     if ($dom_in_use ne '') {
 1515:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1516:     }
 1517:     if (ref($result) ne 'HASH') {
 1518:         $lonhost_in_use = $perlvar{'lonHostID'};
 1519:         $dom_in_use = &host_domain($lonhost_in_use);
 1520:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1521:         if (ref($result) ne 'HASH') {
 1522:             $result = \%spareid;
 1523:         }
 1524:     }
 1525:     return $result;
 1526: }
 1527: 
 1528: sub spares_for_offload  {
 1529:     my ($dom_in_use,$lonhost_in_use) = @_;
 1530:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1531:     if (defined($cached)) {
 1532:         return $result;
 1533:     } else {
 1534:         my $cachetime = 60*60*24;
 1535:         my %domconfig =
 1536:             &get_dom('configuration',['usersessions'],$dom_in_use);
 1537:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1538:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1539:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1540:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1541:                 }
 1542:             }
 1543:         }
 1544:     }
 1545:     return;
 1546: }
 1547: 
 1548: sub get_lonbalancer_config {
 1549:     my ($servers) = @_;
 1550:     my ($currbalancer,$currtargets);
 1551:     if (ref($servers) eq 'HASH') {
 1552:         foreach my $server (keys(%{$servers})) {
 1553:             my %what = (
 1554:                          spareid => 1,
 1555:                          perlvar => 1,
 1556:                        );
 1557:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1558:             if ($result eq 'ok') {
 1559:                 if (ref($returnhash) eq 'HASH') {
 1560:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1561:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1562:                             $currbalancer = $server;
 1563:                             $currtargets = {};
 1564:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1565:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1566:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1567:                                 }
 1568:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1569:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1570:                                 }
 1571:                             }
 1572:                             last;
 1573:                         }
 1574:                     }
 1575:                 }
 1576:             }
 1577:         }
 1578:     }
 1579:     return ($currbalancer,$currtargets);
 1580: }
 1581: 
 1582: sub check_loadbalancing {
 1583:     my ($uname,$udom,$caller) = @_;
 1584:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1585:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1586:     my $lonhost = $perlvar{'lonHostID'};
 1587:     my @hosts = &current_machine_ids();
 1588:     my $uprimary_id = &domain($udom,'primary');
 1589:     my $uintdom = &internet_dom($uprimary_id);
 1590:     my $intdom = &internet_dom($lonhost);
 1591:     my $serverhomedom = &host_domain($lonhost);
 1592:     my $domneedscache;
 1593:     my $cachetime = 60*60*24;
 1594: 
 1595:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1596:         $dom_in_use = $udom;
 1597:         $homeintdom = 1;
 1598:     } else {
 1599:         $dom_in_use = $serverhomedom;
 1600:     }
 1601:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1602:     unless (defined($cached)) {
 1603:         my %domconfig =
 1604:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
 1605:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1606:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1607:         } else {
 1608:             $domneedscache = $dom_in_use;
 1609:         }
 1610:     }
 1611:     if (ref($result) eq 'HASH') {
 1612:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1613:             &check_balancer_result($result,@hosts);
 1614:         if ($is_balancer) {
 1615:             if (ref($currrules) eq 'HASH') {
 1616:                 if ($homeintdom) {
 1617:                     if ($uname ne '') {
 1618:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1619:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1620:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1621:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1622:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1623:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1624:                             }
 1625:                         }
 1626:                         if ($rule_in_effect eq '') {
 1627:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1628:                             if ($userenv{'inststatus'} ne '') {
 1629:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1630:                                 my ($othertitle,$usertypes,$types) =
 1631:                                     &Apache::loncommon::sorted_inst_types($udom);
 1632:                                 if (ref($types) eq 'ARRAY') {
 1633:                                     foreach my $type (@{$types}) {
 1634:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1635:                                             if (exists($currrules->{$type})) {
 1636:                                                 $rule_in_effect = $currrules->{$type};
 1637:                                             }
 1638:                                         }
 1639:                                     }
 1640:                                 }
 1641:                             } else {
 1642:                                 if (exists($currrules->{'default'})) {
 1643:                                     $rule_in_effect = $currrules->{'default'};
 1644:                                 }
 1645:                             }
 1646:                         }
 1647:                     } else {
 1648:                         if (exists($currrules->{'default'})) {
 1649:                             $rule_in_effect = $currrules->{'default'};
 1650:                         }
 1651:                     }
 1652:                 } else {
 1653:                     if ($currrules->{'_LC_external'} ne '') {
 1654:                         $rule_in_effect = $currrules->{'_LC_external'};
 1655:                     }
 1656:                 }
 1657:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1658:                                                        $uname,$udom);
 1659:             }
 1660:         }
 1661:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1662:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1663:         unless (defined($cached)) {
 1664:             my %domconfig =
 1665:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
 1666:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1667:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1668:             } else {
 1669:                 $domneedscache = $serverhomedom;
 1670:             }
 1671:         }
 1672:         if (ref($result) eq 'HASH') {
 1673:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1674:                 &check_balancer_result($result,@hosts);
 1675:             if ($is_balancer) {
 1676:                 if (ref($currrules) eq 'HASH') {
 1677:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1678:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1679:                     }
 1680:                 }
 1681:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1682:                                                        $uname,$udom);
 1683:             }
 1684:         } else {
 1685:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1686:                 $is_balancer = 1;
 1687:                 $offloadto = &this_host_spares($dom_in_use);
 1688:             }
 1689:             unless (defined($cached)) {
 1690:                 $domneedscache = $serverhomedom;
 1691:             }
 1692:         }
 1693:     } else {
 1694:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1695:             $is_balancer = 1;
 1696:             $offloadto = &this_host_spares($dom_in_use);
 1697:         }
 1698:         unless (defined($cached)) {
 1699:             $domneedscache = $serverhomedom;
 1700:         }
 1701:     }
 1702:     if ($domneedscache) {
 1703:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1704:     }
 1705:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1706:         my $lowest_load = 30000;
 1707:         if (ref($offloadto) eq 'HASH') {
 1708:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1709:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1710:                     ($otherserver,$lowest_load) =
 1711:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1712:                 }
 1713:             }
 1714:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1715: 
 1716:             if (!$found_server) {
 1717:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1718:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1719:                         ($otherserver,$lowest_load) =
 1720:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1721:                     }
 1722:                 }
 1723:             }
 1724:         } elsif (ref($offloadto) eq 'ARRAY') {
 1725:             if (@{$offloadto} == 1) {
 1726:                 $otherserver = $offloadto->[0];
 1727:             } elsif (@{$offloadto} > 1) {
 1728:                 foreach my $try_server (@{$offloadto}) {
 1729:                     ($otherserver,$lowest_load) =
 1730:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1731:                 }
 1732:             }
 1733:         }
 1734:         unless ($caller eq 'login') {
 1735:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1736:                 $is_balancer = 0;
 1737:                 if ($uname ne '' && $udom ne '') {
 1738:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1739:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1740:                                  'user.loadbalcheck.time' => time});
 1741:                     }
 1742:                 }
 1743:             }
 1744:         }
 1745:     }
 1746:     if (($is_balancer) && (!$homeintdom)) {
 1747:         undef($setcookie);
 1748:     }
 1749:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1750: }
 1751: 
 1752: sub check_balancer_result {
 1753:     my ($result,@hosts) = @_;
 1754:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1755:     if (ref($result) eq 'HASH') {
 1756:         if ($result->{'lonhost'} ne '') {
 1757:             my $currbalancer = $result->{'lonhost'};
 1758:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1759:                 $is_balancer = 1;
 1760:                 $currtargets = $result->{'targets'};
 1761:                 $currrules = $result->{'rules'};
 1762:             }
 1763:             $dom_balancers = $currbalancer;
 1764:         } else {
 1765:             if (keys(%{$result})) {
 1766:                 foreach my $key (keys(%{$result})) {
 1767:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1768:                         (ref($result->{$key}) eq 'HASH')) {
 1769:                         $is_balancer = 1;
 1770:                         $currrules = $result->{$key}{'rules'};
 1771:                         $currtargets = $result->{$key}{'targets'};
 1772:                         $setcookie = $result->{$key}{'cookie'};
 1773:                         last;
 1774:                     }
 1775:                 }
 1776:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1777:             }
 1778:         }
 1779:     }
 1780:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1781: }
 1782: 
 1783: sub get_loadbalancer_targets {
 1784:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1785:     my $offloadto;
 1786:     if ($rule_in_effect eq 'none') {
 1787:         return [$perlvar{'lonHostID'}];
 1788:     } elsif ($rule_in_effect eq '') {
 1789:         $offloadto = $currtargets;
 1790:     } else {
 1791:         if ($rule_in_effect eq 'homeserver') {
 1792:             my $homeserver = &homeserver($uname,$udom);
 1793:             if ($homeserver ne 'no_host') {
 1794:                 $offloadto = [$homeserver];
 1795:             }
 1796:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1797:             my %domconfig =
 1798:                 &get_dom('configuration',['loadbalancing'],$udom);
 1799:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1800:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1801:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1802:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1803:                     }
 1804:                 }
 1805:             } else {
 1806:                 my %servers = &internet_dom_servers($udom);
 1807:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1808:                 if (&hostname($remotebalancer) ne '') {
 1809:                     $offloadto = [$remotebalancer];
 1810:                 }
 1811:             }
 1812:         } elsif (&hostname($rule_in_effect) ne '') {
 1813:             $offloadto = [$rule_in_effect];
 1814:         }
 1815:     }
 1816:     return $offloadto;
 1817: }
 1818: 
 1819: sub internet_dom_servers {
 1820:     my ($dom) = @_;
 1821:     my (%uniqservers,%servers);
 1822:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1823:     my @machinedoms = &machine_domains($primaryserver);
 1824:     foreach my $mdom (@machinedoms) {
 1825:         my %currservers = %servers;
 1826:         my %server = &get_servers($mdom);
 1827:         %servers = (%currservers,%server);
 1828:     }
 1829:     my %by_hostname;
 1830:     foreach my $id (keys(%servers)) {
 1831:         push(@{$by_hostname{$servers{$id}}},$id);
 1832:     }
 1833:     foreach my $hostname (sort(keys(%by_hostname))) {
 1834:         if (@{$by_hostname{$hostname}} > 1) {
 1835:             my $match = 0;
 1836:             foreach my $id (@{$by_hostname{$hostname}}) {
 1837:                 if (&host_domain($id) eq $dom) {
 1838:                     $uniqservers{$id} = $hostname;
 1839:                     $match = 1;
 1840:                 }
 1841:             }
 1842:             unless ($match) {
 1843:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1844:             }
 1845:         } else {
 1846:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1847:         }
 1848:     }
 1849:     return %uniqservers;
 1850: }
 1851: 
 1852: sub trusted_domains {
 1853:     my ($cmdtype,$calldom) = @_;
 1854:     my ($trusted,$untrusted);
 1855:     if (&domain($calldom) eq '') {
 1856:         return ($trusted,$untrusted);
 1857:     }
 1858:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1859:         return ($trusted,$untrusted);
 1860:     }
 1861:     my $callprimary = &domain($calldom,'primary');
 1862:     my $intcalldom = &internet_dom($callprimary);
 1863:     if ($intcalldom eq '') {
 1864:         return ($trusted,$untrusted);
 1865:     }
 1866: 
 1867:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
 1868:     unless (defined($cached)) {
 1869:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
 1870:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1871:         $trustconfig = $domconfig{'trust'};
 1872:     }
 1873:     if (ref($trustconfig)) {
 1874:         my (%possexc,%possinc,@allexc,@allinc); 
 1875:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1876:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1877:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1878:             }
 1879:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1880:                 $possinc{$intcalldom} = 1;
 1881:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1882:             }
 1883:         }
 1884:         if (keys(%possexc)) {
 1885:             if (keys(%possinc)) {
 1886:                 foreach my $key (sort(keys(%possexc))) {
 1887:                     next if ($key eq $intcalldom);
 1888:                     unless ($possinc{$key}) {
 1889:                         push(@allexc,$key);
 1890:                     }
 1891:                 }
 1892:             } else {
 1893:                 @allexc = sort(keys(%possexc));
 1894:             }
 1895:         }
 1896:         if (keys(%possinc)) {
 1897:             $possinc{$intcalldom} = 1;
 1898:             @allinc = sort(keys(%possinc));
 1899:         }
 1900:         if ((@allexc > 0) || (@allinc > 0)) {
 1901:             my %doms_by_intdom;
 1902:             my %allintdoms = &all_host_intdom();
 1903:             my %alldoms = &all_host_domain();
 1904:             foreach my $key (%allintdoms) {
 1905:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1906:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1907:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1908:                     }
 1909:                 } else {
 1910:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1911:                 }
 1912:             }
 1913:             foreach my $exc (@allexc) {
 1914:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1915:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1916:                 }
 1917:             }
 1918:             foreach my $inc (@allinc) {
 1919:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1920:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1921:                 }
 1922:             }
 1923:         }
 1924:     }
 1925:     return ($trusted,$untrusted);
 1926: }
 1927: 
 1928: sub will_trust {
 1929:     my ($cmdtype,$domain,$possdom) = @_;
 1930:     return 1 if ($domain eq $possdom);
 1931:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1932:     my $willtrust; 
 1933:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1934:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1935:             $willtrust = 1;
 1936:         }
 1937:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1938:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1939:             $willtrust = 1;
 1940:         }
 1941:     } else {
 1942:         $willtrust = 1;
 1943:     }
 1944:     return $willtrust;
 1945: }
 1946: 
 1947: # ---------------------- Find the homebase for a user from domain's lib servers
 1948: 
 1949: my %homecache;
 1950: sub homeserver {
 1951:     my ($uname,$udom,$ignoreBadCache)=@_;
 1952:     my $index="$uname:$udom";
 1953: 
 1954:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1955: 
 1956:     my %servers = &get_servers($udom,'library');
 1957:     foreach my $tryserver (keys(%servers)) {
 1958:         next if ($ignoreBadCache ne 'true' && 
 1959: 		 exists($badServerCache{$tryserver}));
 1960: 
 1961: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1962: 	if ($answer eq 'found') {
 1963: 	    delete($badServerCache{$tryserver}); 
 1964: 	    return $homecache{$index}=$tryserver;
 1965: 	} elsif ($answer eq 'no_host') {
 1966: 	    $badServerCache{$tryserver}=1;
 1967: 	}
 1968:     }    
 1969:     return 'no_host';
 1970: }
 1971: 
 1972: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1973: 
 1974: sub idget {
 1975:     my ($udom,$idsref,$namespace)=@_;
 1976:     my %returnhash=();
 1977:     my @ids=(); 
 1978:     if (ref($idsref) eq 'ARRAY') {
 1979:         @ids = @{$idsref};
 1980:     } else {
 1981:         return %returnhash; 
 1982:     }
 1983:     if ($namespace eq '') {
 1984:         $namespace = 'ids';
 1985:     }
 1986:     
 1987:     my %servers = &get_servers($udom,'library');
 1988:     foreach my $tryserver (keys(%servers)) {
 1989: 	my $idlist=join('&', map { &escape($_); } @ids);
 1990: 	if ($namespace eq 'ids') {
 1991: 	    $idlist=~tr/A-Z/a-z/;
 1992: 	}
 1993: 	my $reply;
 1994: 	if ($namespace eq 'ids') {
 1995: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1996: 	} else {
 1997: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1998: 	}
 1999: 	my @answer=();
 2000: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2001: 	    @answer=split(/\&/,$reply);
 2002: 	}                    ;
 2003: 	my $i;
 2004: 	for ($i=0;$i<=$#ids;$i++) {
 2005: 	    if ($answer[$i]) {
 2006: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2007: 	    }
 2008: 	}
 2009:     }
 2010:     return %returnhash;
 2011: }
 2012: 
 2013: # ------------------------------------- Find the IDs behind a list of usernames
 2014: 
 2015: sub idrget {
 2016:     my ($udom,@unames)=@_;
 2017:     my %returnhash=();
 2018:     foreach my $uname (@unames) {
 2019:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2020:     }
 2021:     return %returnhash;
 2022: }
 2023: 
 2024: # Store away a list of names and associated student/employee IDs or clicker IDs
 2025: 
 2026: sub idput {
 2027:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2028:     my %servers=();
 2029:     my %ids=();
 2030:     my %byid = ();
 2031:     if (ref($idsref) eq 'HASH') {
 2032:         %ids=%{$idsref};
 2033:     }
 2034:     if ($namespace eq '') {
 2035:         $namespace = 'ids'; 
 2036:     }
 2037:     foreach my $uname (keys(%ids)) {
 2038: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2039:         if ($uhom eq '') {
 2040:             $uhom=&homeserver($uname,$udom);
 2041:         }
 2042:         if ($uhom ne 'no_host') {
 2043:             my $esc_unam=&escape($uname);
 2044:             if ($namespace eq 'ids') {
 2045:                 my $id=&escape($ids{$uname});
 2046:                 $id=~tr/A-Z/a-z/;
 2047:                 my $esc_unam=&escape($uname);
 2048:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2049:             } else {
 2050:                 my @currids = split(/,/,$ids{$uname});
 2051:                 foreach my $id (@currids) {
 2052:                     $byid{$uhom}{$id} .= $uname.',';
 2053:                 }
 2054:             }
 2055:         }
 2056:     }
 2057:     if ($namespace eq 'clickers') {
 2058:         foreach my $server (keys(%byid)) {
 2059:             if (ref($byid{$server}) eq 'HASH') {
 2060:                 foreach my $id (keys(%{$byid{$server}})) {
 2061:                     $byid{$server} =~ s/,$//;
 2062:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2063:                 }
 2064:             }
 2065:         }
 2066:     }
 2067:     foreach my $server (keys(%servers)) {
 2068:         $servers{$server} =~ s/\&$//;
 2069:         if ($namespace eq 'ids') {     
 2070:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2071:         } else {
 2072:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2073:         }
 2074:     }
 2075: }
 2076: 
 2077: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2078: 
 2079: sub iddel {
 2080:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2081:     my %result=();
 2082:     my %ids=();
 2083:     my %byid = ();
 2084:     if (ref($idshashref) eq 'HASH') {
 2085:         %ids=%{$idshashref};
 2086:     } else {
 2087:         return %result;
 2088:     }
 2089:     if ($namespace eq '') {
 2090:         $namespace = 'ids';
 2091:     }
 2092:     my %servers=();
 2093:     while (my ($id,$unamestr) = each(%ids)) {
 2094:         if ($namespace eq 'ids') {
 2095:             my $uhom = $uhome;
 2096:             if ($uhom eq '') { 
 2097:                 $uhom=&homeserver($unamestr,$udom);
 2098:             }
 2099:             if ($uhom ne 'no_host') {
 2100:                 $servers{$uhom}.='&'.&escape($id);
 2101:             }
 2102:          } else {
 2103:             my @curritems = split(/,/,$ids{$id});
 2104:             foreach my $uname (@curritems) {
 2105:                 my $uhom = $uhome;
 2106:                 if ($uhom eq '') {
 2107:                     $uhom=&homeserver($uname,$udom);
 2108:                 }
 2109:                 if ($uhom ne 'no_host') { 
 2110:                     $byid{$uhom}{$id} .= $uname.',';
 2111:                 }
 2112:             }
 2113:         }
 2114:     }
 2115:     if ($namespace eq 'clickers') {
 2116:         foreach my $server (keys(%byid)) {
 2117:             if (ref($byid{$server}) eq 'HASH') {
 2118:                 foreach my $id (keys(%{$byid{$server}})) {
 2119:                     $byid{$server}{$id} =~ s/,$//;
 2120:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2121:                 }
 2122:             }
 2123:         }
 2124:     }
 2125:     foreach my $server (keys(%servers)) {
 2126:         $servers{$server} =~ s/\&$//;
 2127:         if ($namespace eq 'ids') {
 2128:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2129:         } elsif ($namespace eq 'clickers') {
 2130:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2131:         }
 2132:     }
 2133:     return %result;
 2134: }
 2135: 
 2136: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2137: 
 2138: sub updateclickers {
 2139:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2140:     my %clickers;
 2141:     if (ref($idshashref) eq 'HASH') {
 2142:         %clickers=%{$idshashref};
 2143:     } else {
 2144:         return;
 2145:     }
 2146:     my $items='';
 2147:     foreach my $item (keys(%clickers)) {
 2148:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2149:     }
 2150:     $items=~s/\&$//;
 2151:     my $request = "updateclickers:$udom:$action:$items";
 2152:     if ($critical) {
 2153:         return &critical($request,$uhome);
 2154:     } else {
 2155:         return &reply($request,$uhome);
 2156:     }
 2157: }
 2158: 
 2159: # ------------------------------dump from db file owned by domainconfig user
 2160: sub dump_dom {
 2161:     my ($namespace, $udom, $regexp) = @_;
 2162: 
 2163:     $udom ||= $env{'user.domain'};
 2164: 
 2165:     return () unless $udom;
 2166: 
 2167:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2168: }
 2169: 
 2170: # ------------------------------------------ get items from domain db files   
 2171: 
 2172: sub get_dom {
 2173:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2174:     return if ($udom eq 'public');
 2175:     my $items='';
 2176:     foreach my $item (@$storearr) {
 2177:         $items.=&escape($item).'&';
 2178:     }
 2179:     $items=~s/\&$//;
 2180:     if (!$udom) {
 2181:         $udom=$env{'user.domain'};
 2182:         return if ($udom eq 'public');
 2183:         if (defined(&domain($udom,'primary'))) {
 2184:             $uhome=&domain($udom,'primary');
 2185:         } else {
 2186:             undef($uhome);
 2187:         }
 2188:     } else {
 2189:         if (!$uhome) {
 2190:             if (defined(&domain($udom,'primary'))) {
 2191:                 $uhome=&domain($udom,'primary');
 2192:             }
 2193:         }
 2194:     }
 2195:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2196:         my $rep;
 2197:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2198:             # domain information is hosted on this machine
 2199:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2200:         } else {
 2201:             if ($encrypt) {
 2202:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2203:             } else {
 2204:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2205:             }
 2206:         }
 2207:         my %returnhash;
 2208:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2209:             return %returnhash;
 2210:         }
 2211:         my @pairs=split(/\&/,$rep);
 2212:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2213:             return @pairs;
 2214:         }
 2215:         my $i=0;
 2216:         foreach my $item (@$storearr) {
 2217:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2218:             $i++;
 2219:         }
 2220:         return %returnhash;
 2221:     } else {
 2222:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2223:     }
 2224: }
 2225: 
 2226: # -------------------------------------------- put items in domain db files 
 2227: 
 2228: sub put_dom {
 2229:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2230:     if (!$udom) {
 2231:         $udom=$env{'user.domain'};
 2232:         if (defined(&domain($udom,'primary'))) {
 2233:             $uhome=&domain($udom,'primary');
 2234:         } else {
 2235:             undef($uhome);
 2236:         }
 2237:     } else {
 2238:         if (!$uhome) {
 2239:             if (defined(&domain($udom,'primary'))) {
 2240:                 $uhome=&domain($udom,'primary');
 2241:             }
 2242:         }
 2243:     } 
 2244:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2245:         my $items='';
 2246:         foreach my $item (keys(%$storehash)) {
 2247:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2248:         }
 2249:         $items=~s/\&$//;
 2250:         if ($encrypt) {
 2251:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2252:         } else {
 2253:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2254:         }
 2255:     } else {
 2256:         &logthis("put_dom failed - no homeserver and/or domain");
 2257:     }
 2258: }
 2259: 
 2260: # --------------------- newput for items in db file owned by domainconfig user
 2261: sub newput_dom {
 2262:     my ($namespace,$storehash,$udom) = @_;
 2263:     my $result;
 2264:     if (!$udom) {
 2265:         $udom=$env{'user.domain'};
 2266:     }
 2267:     if ($udom) {
 2268:         my $uname = &get_domainconfiguser($udom);
 2269:         $result = &newput($namespace,$storehash,$udom,$uname);
 2270:     }
 2271:     return $result;
 2272: }
 2273: 
 2274: # --------------------- delete for items in db file owned by domainconfig user
 2275: sub del_dom {
 2276:     my ($namespace,$storearr,$udom)=@_;
 2277:     if (ref($storearr) eq 'ARRAY') {
 2278:         if (!$udom) {
 2279:             $udom=$env{'user.domain'};
 2280:         }
 2281:         if ($udom) {
 2282:             my $uname = &get_domainconfiguser($udom); 
 2283:             return &del($namespace,$storearr,$udom,$uname);
 2284:         }
 2285:     }
 2286: }
 2287: 
 2288: sub store_dom {
 2289:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2290:     $$storehash{'ip'}=&get_requestor_ip();
 2291:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2292:     my $namevalue='';
 2293:     foreach my $key (keys(%{$storehash})) {
 2294:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2295:     }
 2296:     $namevalue=~s/\&$//;
 2297:     if (grep { $_ eq $home } current_machine_ids()) {
 2298:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2299:     } else {
 2300:         if ($namespace eq 'private') {
 2301:             return 'refused';
 2302:         } elsif ($encrypt) {
 2303:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2304:         } else {
 2305:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2306:         }
 2307:     }
 2308: }
 2309: 
 2310: sub restore_dom {
 2311:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2312:     my $answer;
 2313:     if (grep { $_ eq $home } current_machine_ids()) {
 2314:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2315:     } elsif ($namespace ne 'private') {
 2316:         if ($encrypt) {
 2317:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2318:         } else {
 2319:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2320:         }
 2321:     }
 2322:     my %returnhash=();
 2323:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2324:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2325:         foreach my $line (split(/\&/,$answer)) {
 2326:             my ($name,$value)=split(/\=/,$line);
 2327:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2328:         }
 2329:         my $version;
 2330:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2331:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2332:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2333:             }
 2334:         }
 2335:     }
 2336:     return %returnhash;
 2337: }
 2338: 
 2339: # ----------------------------------construct domainconfig user for a domain 
 2340: sub get_domainconfiguser {
 2341:     my ($udom) = @_;
 2342:     return $udom.'-domainconfig';
 2343: }
 2344: 
 2345: sub retrieve_inst_usertypes {
 2346:     my ($udom) = @_;
 2347:     my (%returnhash,@order);
 2348:     my %domdefs = &get_domain_defaults($udom);
 2349:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2350:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2351:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2352:     } else {
 2353:         if (defined(&domain($udom,'primary'))) {
 2354:             my $uhome=&domain($udom,'primary');
 2355:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2356:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2357:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2358:                 return (\%returnhash,\@order);
 2359:             }
 2360:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2361:             my @pairs=split(/\&/,$hashitems);
 2362:             foreach my $item (@pairs) {
 2363:                 my ($key,$value)=split(/=/,$item,2);
 2364:                 $key = &unescape($key);
 2365:                 next if ($key =~ /^error: 2 /);
 2366:                 $returnhash{$key}=&thaw_unescape($value);
 2367:             }
 2368:             my @esc_order = split(/\&/,$orderitems);
 2369:             foreach my $item (@esc_order) {
 2370:                 push(@order,&unescape($item));
 2371:             }
 2372:         } else {
 2373:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2374:         }
 2375:         return (\%returnhash,\@order);
 2376:     }
 2377: }
 2378: 
 2379: sub is_domainimage {
 2380:     my ($url) = @_;
 2381:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2382:         if (&domain($1) ne '') {
 2383:             return '1';
 2384:         }
 2385:     }
 2386:     return;
 2387: }
 2388: 
 2389: sub inst_directory_query {
 2390:     my ($srch) = @_;
 2391:     my $udom = $srch->{'srchdomain'};
 2392:     my %results;
 2393:     my $homeserver = &domain($udom,'primary');
 2394:     my $outcome;
 2395:     if ($homeserver ne '') {
 2396:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2397:             if ($srch->{'srchby'} eq 'email') {
 2398:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2399:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2400:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2401:                     (($major == 2) && ($minor < 12))) {
 2402:                     return;
 2403:                 }
 2404:             }
 2405:         }
 2406: 	my $queryid=&reply("querysend:instdirsearch:".
 2407: 			   &escape($srch->{'srchby'}).':'.
 2408: 			   &escape($srch->{'srchterm'}).':'.
 2409: 			   &escape($srch->{'srchtype'}),$homeserver);
 2410: 	my $host=&hostname($homeserver);
 2411: 	if ($queryid !~/^\Q$host\E\_/) {
 2412: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2413: 	    return;
 2414: 	}
 2415: 	my $response = &get_query_reply($queryid);
 2416: 	my $maxtries = 5;
 2417: 	my $tries = 1;
 2418: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2419: 	    $response = &get_query_reply($queryid);
 2420: 	    $tries ++;
 2421: 	}
 2422: 
 2423:         if (!&error($response) && $response ne 'refused') {
 2424:             if ($response eq 'unavailable') {
 2425:                 $outcome = $response;
 2426:             } else {
 2427:                 $outcome = 'ok';
 2428:                 my @matches = split(/\n/,$response);
 2429:                 foreach my $match (@matches) {
 2430:                     my ($key,$value) = split(/=/,$match);
 2431:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2432:                 }
 2433:             }
 2434:         }
 2435:     }
 2436:     return ($outcome,%results);
 2437: }
 2438: 
 2439: sub usersearch {
 2440:     my ($srch) = @_;
 2441:     my $dom = $srch->{'srchdomain'};
 2442:     my %results;
 2443:     my %libserv = &all_library();
 2444:     my $query = 'usersearch';
 2445:     foreach my $tryserver (keys(%libserv)) {
 2446:         if (&host_domain($tryserver) eq $dom) {
 2447:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2448:                 if ($srch->{'srchby'} eq 'email') {
 2449:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2450:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2451:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2452:                              (($major == 2) && ($minor < 12)));
 2453:                 }
 2454:             }
 2455:             my $host=&hostname($tryserver);
 2456:             my $queryid=
 2457:                 &reply("querysend:".&escape($query).':'.
 2458:                        &escape($srch->{'srchby'}).':'.
 2459:                        &escape($srch->{'srchtype'}).':'.
 2460:                        &escape($srch->{'srchterm'}),$tryserver);
 2461:             if ($queryid !~/^\Q$host\E\_/) {
 2462:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2463:                 next;
 2464:             }
 2465:             my $reply = &get_query_reply($queryid);
 2466:             my $maxtries = 1;
 2467:             my $tries = 1;
 2468:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2469:                 $reply = &get_query_reply($queryid);
 2470:                 $tries ++;
 2471:             }
 2472:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2473:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2474:             } else {
 2475:                 my @matches;
 2476:                 if ($reply =~ /\n/) {
 2477:                     @matches = split(/\n/,$reply);
 2478:                 } else {
 2479:                     @matches = split(/\&/,$reply);
 2480:                 }
 2481:                 foreach my $match (@matches) {
 2482:                     my ($uname,$udom,%userhash);
 2483:                     foreach my $entry (split(/:/,$match)) {
 2484:                         my ($key,$value) =
 2485:                             map {&unescape($_);} split(/=/,$entry);
 2486:                         $userhash{$key} = $value;
 2487:                         if ($key eq 'username') {
 2488:                             $uname = $value;
 2489:                         } elsif ($key eq 'domain') {
 2490:                             $udom = $value;
 2491:                         }
 2492:                     }
 2493:                     $results{$uname.':'.$udom} = \%userhash;
 2494:                 }
 2495:             }
 2496:         }
 2497:     }
 2498:     return %results;
 2499: }
 2500: 
 2501: sub get_instuser {
 2502:     my ($udom,$uname,$id) = @_;
 2503:     my $homeserver = &domain($udom,'primary');
 2504:     my ($outcome,%results);
 2505:     if ($homeserver ne '') {
 2506:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2507:                            &escape($id).':'.&escape($udom),$homeserver);
 2508:         my $host=&hostname($homeserver);
 2509:         if ($queryid !~/^\Q$host\E\_/) {
 2510:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2511:             return;
 2512:         }
 2513:         my $response = &get_query_reply($queryid);
 2514:         my $maxtries = 5;
 2515:         my $tries = 1;
 2516:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2517:             $response = &get_query_reply($queryid);
 2518:             $tries ++;
 2519:         }
 2520:         if (!&error($response) && $response ne 'refused') {
 2521:             if ($response eq 'unavailable') {
 2522:                 $outcome = $response;
 2523:             } else {
 2524:                 $outcome = 'ok';
 2525:                 my @matches = split(/\n/,$response);
 2526:                 foreach my $match (@matches) {
 2527:                     my ($key,$value) = split(/=/,$match);
 2528:                     $results{&unescape($key)} = &thaw_unescape($value);
 2529:                 }
 2530:             }
 2531:         }
 2532:     }
 2533:     my %userinfo;
 2534:     if (ref($results{$uname}) eq 'HASH') {
 2535:         %userinfo = %{$results{$uname}};
 2536:     } 
 2537:     return ($outcome,%userinfo);
 2538: }
 2539: 
 2540: sub get_multiple_instusers {
 2541:     my ($udom,$users,$caller) = @_;
 2542:     my ($outcome,$results);
 2543:     if (ref($users) eq 'HASH') {
 2544:         my $count = keys(%{$users}); 
 2545:         my $requested = &freeze_escape($users);
 2546:         my $homeserver = &domain($udom,'primary');
 2547:         if ($homeserver ne '') {
 2548:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2549:             my $host=&hostname($homeserver);
 2550:             if ($queryid !~/^\Q$host\E\_/) {
 2551:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2552:                          ' for host: '.$homeserver.'in domain '.$udom);
 2553:                 return ($outcome,$results);
 2554:             }
 2555:             my $response = &get_query_reply($queryid);
 2556:             my $maxtries = 5;
 2557:             if ($count > 100) {
 2558:                 $maxtries = 1+int($count/20);
 2559:             }
 2560:             my $tries = 1;
 2561:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2562:                 $response = &get_query_reply($queryid);
 2563:                 $tries ++;
 2564:             }
 2565:             if ($response eq '') {
 2566:                 $results = {};
 2567:                 foreach my $key (keys(%{$users})) {
 2568:                     my ($uname,$id);
 2569:                     if ($caller eq 'id') {
 2570:                         $id = $key;
 2571:                     } else {
 2572:                         $uname = $key;
 2573:                     }
 2574:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2575:                     $outcome = $resp;
 2576:                     if ($resp eq 'ok') {
 2577:                         %{$results} = (%{$results}, %info);
 2578:                     } else {
 2579:                         last;
 2580:                     }
 2581:                 }
 2582:             } elsif(!&error($response) && ($response ne 'refused')) {
 2583:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2584:                     $outcome = $response;
 2585:                 } else {
 2586:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2587:                     if ($outcome eq 'ok') {
 2588:                         $results = &thaw_unescape($userdata); 
 2589:                     }
 2590:                 }
 2591:             }
 2592:         }
 2593:     }
 2594:     return ($outcome,$results);
 2595: }
 2596: 
 2597: sub inst_rulecheck {
 2598:     my ($udom,$uname,$id,$item,$rules) = @_;
 2599:     my %returnhash;
 2600:     if ($udom ne '') {
 2601:         if (ref($rules) eq 'ARRAY') {
 2602:             @{$rules} = map {&escape($_);} (@{$rules});
 2603:             my $rulestr = join(':',@{$rules});
 2604:             my $homeserver=&domain($udom,'primary');
 2605:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2606:                 my $response;
 2607:                 if ($item eq 'username') {                
 2608:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2609:                                               ':'.&escape($uname).':'.$rulestr,
 2610:                                               $homeserver));
 2611:                 } elsif ($item eq 'id') {
 2612:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2613:                                               ':'.&escape($id).':'.$rulestr,
 2614:                                               $homeserver));
 2615:                 } elsif ($item eq 'selfcreate') {
 2616:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2617:                                                &escape($udom).':'.&escape($uname).
 2618:                                               ':'.$rulestr,$homeserver));
 2619:                 } elsif ($item eq 'unamemap') {
 2620:                     $response=&unescape(&reply('instunamemapcheck:'.
 2621:                                                &escape($udom).':'.&escape($uname).
 2622:                                               ':'.$rulestr,$homeserver));
 2623:                 }
 2624:                 if ($response ne 'refused') {
 2625:                     my @pairs=split(/\&/,$response);
 2626:                     foreach my $item (@pairs) {
 2627:                         my ($key,$value)=split(/=/,$item,2);
 2628:                         $key = &unescape($key);
 2629:                         next if ($key =~ /^error: 2 /);
 2630:                         $returnhash{$key}=&thaw_unescape($value);
 2631:                     }
 2632:                 }
 2633:             }
 2634:         }
 2635:     }
 2636:     return %returnhash;
 2637: }
 2638: 
 2639: sub inst_userrules {
 2640:     my ($udom,$check) = @_;
 2641:     my (%ruleshash,@ruleorder);
 2642:     if ($udom ne '') {
 2643:         my $homeserver=&domain($udom,'primary');
 2644:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2645:             my $response;
 2646:             if ($check eq 'id') {
 2647:                 $response=&reply('instidrules:'.&escape($udom),
 2648:                                  $homeserver);
 2649:             } elsif ($check eq 'email') {
 2650:                 $response=&reply('instemailrules:'.&escape($udom),
 2651:                                  $homeserver);
 2652:             } elsif ($check eq 'unamemap') {
 2653:                 $response=&reply('unamemaprules:'.&escape($udom),
 2654:                                  $homeserver); 
 2655:             } else {
 2656:                 $response=&reply('instuserrules:'.&escape($udom),
 2657:                                  $homeserver);
 2658:             }
 2659:             if (($response ne 'refused') && ($response ne 'error') && 
 2660:                 ($response ne 'unknown_cmd') && 
 2661:                 ($response ne 'no_such_host')) {
 2662:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2663:                 my @pairs=split(/\&/,$hashitems);
 2664:                 foreach my $item (@pairs) {
 2665:                     my ($key,$value)=split(/=/,$item,2);
 2666:                     $key = &unescape($key);
 2667:                     next if ($key =~ /^error: 2 /);
 2668:                     $ruleshash{$key}=&thaw_unescape($value);
 2669:                 }
 2670:                 my @esc_order = split(/\&/,$orderitems);
 2671:                 foreach my $item (@esc_order) {
 2672:                     push(@ruleorder,&unescape($item));
 2673:                 }
 2674:             }
 2675:         }
 2676:     }
 2677:     return (\%ruleshash,\@ruleorder);
 2678: }
 2679: 
 2680: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2681: 
 2682: sub get_domain_defaults {
 2683:     my ($domain,$ignore_cache) = @_;
 2684:     return if (($domain eq '') || ($domain eq 'public'));
 2685:     my $cachetime = 60*60*24;
 2686:     unless ($ignore_cache) {
 2687:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2688:         if (defined($cached)) {
 2689:             if (ref($result) eq 'HASH') {
 2690:                 return %{$result};
 2691:             }
 2692:         }
 2693:     }
 2694:     my %domdefaults;
 2695:     my %domconfig =
 2696:          &get_dom('configuration',['defaults','quotas',
 2697:                                   'requestcourses','inststatus',
 2698:                                   'coursedefaults','usersessions',
 2699:                                   'requestauthor','selfenrollment',
 2700:                                   'coursecategories','ssl','autoenroll',
 2701:                                   'trust','helpsettings','wafproxy',
 2702:                                   'ltisec','toolsec'],$domain);
 2703:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2704:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2705:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2706:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2707:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2708:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2709:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2710:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2711:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2712:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2713:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2714:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2715:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2716:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2717:     } else {
 2718:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2719:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2720:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2721:     }
 2722:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2723:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2724:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2725:         } else {
 2726:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2727:         }
 2728:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2729:         foreach my $item (@usertools) {
 2730:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2731:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2732:             }
 2733:         }
 2734:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2735:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2736:         }
 2737:     }
 2738:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2739:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2740:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2741:         }
 2742:     }
 2743:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2744:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2745:     }
 2746:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2747:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2748:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2749:         }
 2750:     }
 2751:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2752:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2753:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2754:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2755:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2756:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2757:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2758:         }
 2759:         foreach my $type (@coursetypes) {
 2760:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2761:                 unless ($type eq 'community') {
 2762:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2763:                 }
 2764:             }
 2765:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2766:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2767:             }
 2768:             if ($domdefaults{'postsubmit'} eq 'on') {
 2769:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2770:                     $domdefaults{$type.'postsubtimeout'} = 
 2771:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2772:                 }
 2773:             }
 2774:         }
 2775:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2776:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2777:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2778:                 if (@clonecodes) {
 2779:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2780:                 }
 2781:             }
 2782:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2783:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2784:         }
 2785:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2786:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2787:         }
 2788:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2789:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2790:         }
 2791:     }
 2792:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2793:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2794:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2795:         }
 2796:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2797:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2798:         }
 2799:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2800:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2801:         }
 2802:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2803:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2804:         }
 2805:     }
 2806:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2807:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2808:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2809:                             'approval','limit');
 2810:             foreach my $type (@coursetypes) {
 2811:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2812:                     my @mgrdc = ();
 2813:                     foreach my $item (@settings) {
 2814:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2815:                             push(@mgrdc,$item);
 2816:                         }
 2817:                     }
 2818:                     if (@mgrdc) {
 2819:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2820:                     }
 2821:                 }
 2822:             }
 2823:         }
 2824:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2825:             foreach my $type (@coursetypes) {
 2826:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2827:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2828:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2829:                     }
 2830:                 }
 2831:             }
 2832:         }
 2833:     }
 2834:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2835:         $domdefaults{'catauth'} = 'std';
 2836:         $domdefaults{'catunauth'} = 'std';
 2837:         if ($domconfig{'coursecategories'}{'auth'}) {
 2838:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2839:         }
 2840:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2841:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2842:         }
 2843:     }
 2844:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2845:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2846:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2847:         }
 2848:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2849:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2850:         }
 2851:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2852:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2853:         }
 2854:     }
 2855:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2856:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2857:         foreach my $prefix (@prefixes) {
 2858:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2859:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2860:             }
 2861:         }
 2862:     }
 2863:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2864:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2865:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2866:     }
 2867:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2868:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2869:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2870:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2871:         }
 2872:     }
 2873:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2874:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2875:             if ($domconfig{'wafproxy'}{$item}) {
 2876:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2877:             }
 2878:         }
 2879:     }
 2880:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2881:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2882:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2883:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2884:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2885:         }
 2886:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2887:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2888:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2889:             }
 2890:         }
 2891:     }
 2892:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2893:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2894:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2895:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2896:         }
 2897:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2898:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2899:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2900:             }
 2901:         }
 2902:     }
 2903:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2904:     return %domdefaults;
 2905: }
 2906: 
 2907: sub get_dom_cats {
 2908:     my ($dom) = @_;
 2909:     return unless (&domain($dom));
 2910:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2911:     unless (defined($cached)) {
 2912:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2913:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2914:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2915:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2916:             } else {
 2917:                 $cats = {};
 2918:             }
 2919:         } else {
 2920:             $cats = {};
 2921:         }
 2922:         &do_cache_new('cats',$dom,$cats,3600);
 2923:     }
 2924:     return $cats;
 2925: }
 2926: 
 2927: sub get_dom_instcats {
 2928:     my ($dom) = @_;
 2929:     return unless (&domain($dom));
 2930:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2931:     unless (defined($cached)) {
 2932:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2933:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2934:         if ($totcodes > 0) {
 2935:             my $caller = 'global';
 2936:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2937:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2938:                 $instcats = {
 2939:                                 totcodes => $totcodes,
 2940:                                 codes => \%codes,
 2941:                                 codetitles => \@codetitles,
 2942:                                 cat_titles => \%cat_titles,
 2943:                                 cat_order => \%cat_order,
 2944:                             };
 2945:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2946:             }
 2947:         }
 2948:     }
 2949:     return $instcats;
 2950: }
 2951: 
 2952: sub retrieve_instcodes {
 2953:     my ($coursecodes,$dom) = @_;
 2954:     my $totcodes;
 2955:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2956:     foreach my $course (keys(%courses)) {
 2957:         if (ref($courses{$course}) eq 'HASH') {
 2958:             if ($courses{$course}{'inst_code'} ne '') {
 2959:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2960:                 $totcodes ++;
 2961:             }
 2962:         }
 2963:     }
 2964:     return $totcodes;
 2965: }
 2966: 
 2967: sub course_portal_url {
 2968:     my ($cnum,$cdom,$r) = @_;
 2969:     my $chome = &homeserver($cnum,$cdom);
 2970:     my $hostname = &hostname($chome);
 2971:     my $protocol = $protocol{$chome};
 2972:     $protocol = 'http' if ($protocol ne 'https');
 2973:     my %domdefaults = &get_domain_defaults($cdom);
 2974:     my $firsturl;
 2975:     if ($domdefaults{'portal_def'}) {
 2976:         $firsturl = $domdefaults{'portal_def'};
 2977:     } else {
 2978:         my $alias = &use_proxy_alias($r,$chome);
 2979:         $hostname = $alias if ($alias ne '');
 2980:         $firsturl = $protocol.'://'.$hostname;
 2981:     }
 2982:     return $firsturl;
 2983: }
 2984: 
 2985: sub url_prefix {
 2986:     my ($r,$dom,$home,$context) = @_;
 2987:     my $prefix;
 2988:     my %domdefs = &get_domain_defaults($dom);
 2989:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 2990:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 2991:             $prefix = $1;
 2992:         }
 2993:     }
 2994:     if ($prefix eq '') {
 2995:         my $hostname = &hostname($home);
 2996:         my $protocol = $protocol{$home};
 2997:         $protocol = 'http' if ($protocol{$home} ne 'https');
 2998:         my $alias = &use_proxy_alias($r,$home);
 2999:         $hostname = $alias if ($alias ne '');
 3000:         $prefix = $protocol.'://'.$hostname;
 3001:     }
 3002:     return $prefix;
 3003: }
 3004: 
 3005: # --------------------------------------------- Get domain config for passwords
 3006: 
 3007: sub get_passwdconf {
 3008:     my ($dom) = @_;
 3009:     my (%passwdconf,$gotconf,$lookup);
 3010:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3011:     if (defined($cached)) {
 3012:         if (ref($result) eq 'HASH') {
 3013:             %passwdconf = %{$result};
 3014:             $gotconf = 1;
 3015:         }
 3016:     }
 3017:     unless ($gotconf) {
 3018:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3019:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3020:             %passwdconf = %{$domconfig{'passwords'}};
 3021:         }
 3022:         my $cachetime = 24*60*60;
 3023:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3024:     }
 3025:     return %passwdconf;
 3026: }
 3027: 
 3028: # --------------------------------------------------- Assign a key to a student
 3029: 
 3030: sub assign_access_key {
 3031: #
 3032: # a valid key looks like uname:udom#comments
 3033: # comments are being appended
 3034: #
 3035:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3036:     $kdom=
 3037:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3038:     $knum=
 3039:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3040:     $cdom=
 3041:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3042:     $cnum=
 3043:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3044:     $udom=$env{'user.name'} unless (defined($udom));
 3045:     $uname=$env{'user.domain'} unless (defined($uname));
 3046:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3047:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3048:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3049:                                                   # assigned to this person
 3050:                                                   # - this should not happen,
 3051:                                                   # unless something went wrong
 3052:                                                   # the first time around
 3053: # ready to assign
 3054:         $logentry=$1.'; '.$logentry;
 3055:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3056:                                                  $kdom,$knum) eq 'ok') {
 3057: # key now belongs to user
 3058: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3059:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3060:                 &appenv({'environment.'.$envkey => $ckey});
 3061:                 return 'ok';
 3062:             } else {
 3063:                 return 
 3064:   'error: Count not permanently assign key, will need to be re-entered later.';
 3065: 	    }
 3066:         } else {
 3067:             return 'error: Could not assign key, try again later.';
 3068:         }
 3069:     } elsif (!$existing{$ckey}) {
 3070: # the key does not exist
 3071: 	return 'error: The key does not exist';
 3072:     } else {
 3073: # the key is somebody else's
 3074: 	return 'error: The key is already in use';
 3075:     }
 3076: }
 3077: 
 3078: # ------------------------------------------ put an additional comment on a key
 3079: 
 3080: sub comment_access_key {
 3081: #
 3082: # a valid key looks like uname:udom#comments
 3083: # comments are being appended
 3084: #
 3085:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3086:     $cdom=
 3087:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3088:     $cnum=
 3089:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3090:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3091:     if ($existing{$ckey}) {
 3092:         $existing{$ckey}.='; '.$logentry;
 3093: # ready to assign
 3094:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3095:                                                  $cdom,$cnum) eq 'ok') {
 3096: 	    return 'ok';
 3097:         } else {
 3098: 	    return 'error: Count not store comment.';
 3099:         }
 3100:     } else {
 3101: # the key does not exist
 3102: 	return 'error: The key does not exist';
 3103:     }
 3104: }
 3105: 
 3106: # ------------------------------------------------------ Generate a set of keys
 3107: 
 3108: sub generate_access_keys {
 3109:     my ($number,$cdom,$cnum,$logentry)=@_;
 3110:     $cdom=
 3111:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3112:     $cnum=
 3113:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3114:     unless (&allowed('mky',$cdom)) { return 0; }
 3115:     unless (($cdom) && ($cnum)) { return 0; }
 3116:     if ($number>10000) { return 0; }
 3117:     sleep(2); # make sure don't get same seed twice
 3118:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3119:     my $total=0;
 3120:     for (my $i=1;$i<=$number;$i++) {
 3121:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3122:                   sprintf("%lx",int(100000*rand)).'-'.
 3123:                   sprintf("%lx",int(100000*rand));
 3124:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3125:        $newkey=~s/0/h/g; # and also 0 and O
 3126:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3127:        if ($existing{$newkey}) {
 3128:            $i--;
 3129:        } else {
 3130: 	  if (&put('accesskeys',
 3131:               { $newkey => '# generated '.localtime().
 3132:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3133:                            '; '.$logentry },
 3134: 		   $cdom,$cnum) eq 'ok') {
 3135:               $total++;
 3136: 	  }
 3137:        }
 3138:     }
 3139:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3140:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3141:     return $total;
 3142: }
 3143: 
 3144: # ------------------------------------------------------- Validate an accesskey
 3145: 
 3146: sub validate_access_key {
 3147:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3148:     $cdom=
 3149:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3150:     $cnum=
 3151:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3152:     $udom=$env{'user.domain'} unless (defined($udom));
 3153:     $uname=$env{'user.name'} unless (defined($uname));
 3154:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3155:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3156: }
 3157: 
 3158: # ------------------------------------- Find the section of student in a course
 3159: sub devalidate_getsection_cache {
 3160:     my ($udom,$unam,$courseid)=@_;
 3161:     my $hashid="$udom:$unam:$courseid";
 3162:     &devalidate_cache_new('getsection',$hashid);
 3163: }
 3164: 
 3165: sub courseid_to_courseurl {
 3166:     my ($courseid) = @_;
 3167:     #already url style courseid
 3168:     return $courseid if ($courseid =~ m{^/});
 3169: 
 3170:     if (exists($env{'course.'.$courseid.'.num'})) {
 3171: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3172: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3173: 	return "/$cdom/$cnum";
 3174:     }
 3175: 
 3176:     my %courseinfo=&coursedescription($courseid);
 3177:     if (exists($courseinfo{'num'})) {
 3178: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3179:     }
 3180: 
 3181:     return undef;
 3182: }
 3183: 
 3184: sub getsection {
 3185:     my ($udom,$unam,$courseid)=@_;
 3186:     my $cachetime=1800;
 3187: 
 3188:     my $hashid="$udom:$unam:$courseid";
 3189:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3190:     if (defined($cached)) { return $result; }
 3191: 
 3192:     my %Pending; 
 3193:     my %Expired;
 3194:     #
 3195:     # Each role can either have not started yet (pending), be active, 
 3196:     #    or have expired.
 3197:     #
 3198:     # If there is an active role, we are done.
 3199:     #
 3200:     # If there is more than one role which has not started yet, 
 3201:     #     choose the one which will start sooner
 3202:     # If there is one role which has not started yet, return it.
 3203:     #
 3204:     # If there is more than one expired role, choose the one which ended last.
 3205:     # If there is a role which has expired, return it.
 3206:     #
 3207:     $courseid = &courseid_to_courseurl($courseid);
 3208:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3209:     foreach my $key (keys(%roleshash)) {
 3210:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3211:         my $section=$1;
 3212:         if ($key eq $courseid.'_st') { $section=''; }
 3213:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3214:         my $now=time;
 3215:         if (defined($end) && $end && ($now > $end)) {
 3216:             $Expired{$end}=$section;
 3217:             next;
 3218:         }
 3219:         if (defined($start) && $start && ($now < $start)) {
 3220:             $Pending{$start}=$section;
 3221:             next;
 3222:         }
 3223:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3224:     }
 3225:     #
 3226:     # Presumedly there will be few matching roles from the above
 3227:     # loop and the sorting time will be negligible.
 3228:     if (scalar(keys(%Pending))) {
 3229:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3230:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3231:     } 
 3232:     if (scalar(keys(%Expired))) {
 3233:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3234:         my $time = pop(@sorted);
 3235:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3236:     }
 3237:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3238: }
 3239: 
 3240: sub save_cache {
 3241:     &purge_remembered();
 3242:     #&Apache::loncommon::validate_page();
 3243:     undef(%env);
 3244:     undef($env_loaded);
 3245: }
 3246: 
 3247: my $to_remember=-1;
 3248: my %remembered;
 3249: my %accessed;
 3250: my $kicks=0;
 3251: my $hits=0;
 3252: sub make_key {
 3253:     my ($name,$id) = @_;
 3254:     if (length($id) > 65 
 3255: 	&& length(&escape($id)) > 200) {
 3256: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3257:     }
 3258:     return &escape($name.':'.$id);
 3259: }
 3260: 
 3261: sub devalidate_cache_new {
 3262:     my ($name,$id,$debug) = @_;
 3263:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3264:     my $remembered_id=$name.':'.$id;
 3265:     $id=&make_key($name,$id);
 3266:     $memcache->delete($id);
 3267:     delete($remembered{$remembered_id});
 3268:     delete($accessed{$remembered_id});
 3269: }
 3270: 
 3271: sub is_cached_new {
 3272:     my ($name,$id,$debug) = @_;
 3273:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3274:     if (exists($remembered{$remembered_id})) {
 3275: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3276: 	$accessed{$remembered_id}=[&gettimeofday()];
 3277: 	$hits++;
 3278: 	return ($remembered{$remembered_id},1);
 3279:     }
 3280:     $id=&make_key($name,$id);
 3281:     my $value = $memcache->get($id);
 3282:     if (!(defined($value))) {
 3283: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3284: 	return (undef,undef);
 3285:     }
 3286:     if ($value eq '__undef__') {
 3287: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3288: 	$value=undef;
 3289:     }
 3290:     &make_room($remembered_id,$value,$debug);
 3291:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3292:     return ($value,1);
 3293: }
 3294: 
 3295: sub do_cache_new {
 3296:     my ($name,$id,$value,$time,$debug) = @_;
 3297:     my $remembered_id=$name.':'.$id;
 3298:     $id=&make_key($name,$id);
 3299:     my $setvalue=$value;
 3300:     if (!defined($setvalue)) {
 3301: 	$setvalue='__undef__';
 3302:     }
 3303:     if (!defined($time) ) {
 3304: 	$time=600;
 3305:     }
 3306:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3307:     my $result = $memcache->set($id,$setvalue,$time);
 3308:     if (! $result) {
 3309: 	&logthis("caching of id -> $id  failed");
 3310: 	$memcache->disconnect_all();
 3311:     }
 3312:     # need to make a copy of $value
 3313:     &make_room($remembered_id,$value,$debug);
 3314:     return $value;
 3315: }
 3316: 
 3317: sub make_room {
 3318:     my ($remembered_id,$value,$debug)=@_;
 3319: 
 3320:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3321:                                     : $value;
 3322:     if ($to_remember<0) { return; }
 3323:     $accessed{$remembered_id}=[&gettimeofday()];
 3324:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3325:     my $to_kick;
 3326:     my $max_time=0;
 3327:     foreach my $other (keys(%accessed)) {
 3328: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3329: 	    $to_kick=$other;
 3330: 	    $max_time=&tv_interval($accessed{$other});
 3331: 	}
 3332:     }
 3333:     delete($remembered{$to_kick});
 3334:     delete($accessed{$to_kick});
 3335:     $kicks++;
 3336:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3337:     return;
 3338: }
 3339: 
 3340: sub purge_remembered {
 3341:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3342:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3343:     undef(%remembered);
 3344:     undef(%accessed);
 3345: }
 3346: # ------------------------------------- Read an entry from a user's environment
 3347: 
 3348: sub userenvironment {
 3349:     my ($udom,$unam,@what)=@_;
 3350:     my $items;
 3351:     foreach my $item (@what) {
 3352:         $items.=&escape($item).'&';
 3353:     }
 3354:     $items=~s/\&$//;
 3355:     my %returnhash=();
 3356:     my $uhome = &homeserver($unam,$udom);
 3357:     unless ($uhome eq 'no_host') {
 3358:         my @answer=split(/\&/, 
 3359:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3360:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3361:             return %returnhash;
 3362:         }
 3363:         my $i;
 3364:         for ($i=0;$i<=$#what;$i++) {
 3365: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3366:         }
 3367:     }
 3368:     return %returnhash;
 3369: }
 3370: 
 3371: # ---------------------------------------------------------- Get a studentphoto
 3372: sub studentphoto {
 3373:     my ($udom,$unam,$ext) = @_;
 3374:     my $home=&homeserver($unam,$udom);
 3375:     if (defined($env{'request.course.id'})) {
 3376:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3377:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3378:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3379:             } else {
 3380:                 my ($result,$perm_reqd)=
 3381: 		    &auto_photo_permission($unam,$udom);
 3382:                 if ($result eq 'ok') {
 3383:                     if (!($perm_reqd eq 'yes')) {
 3384:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3385:                     }
 3386:                 }
 3387:             }
 3388:         }
 3389:     } else {
 3390:         my ($result,$perm_reqd) = 
 3391: 	    &auto_photo_permission($unam,$udom);
 3392:         if ($result eq 'ok') {
 3393:             if (!($perm_reqd eq 'yes')) {
 3394:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3395:             }
 3396:         }
 3397:     }
 3398:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3399: }
 3400: 
 3401: sub retrievestudentphoto {
 3402:     my ($udom,$unam,$ext,$type) = @_;
 3403:     my $home=&homeserver($unam,$udom);
 3404:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3405:     if ($ret eq 'ok') {
 3406:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3407:         if ($type eq 'thumbnail') {
 3408:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3409:         }
 3410:         my $tokenurl=&tokenwrapper($url);
 3411:         return $tokenurl;
 3412:     } else {
 3413:         if ($type eq 'thumbnail') {
 3414:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3415:         } else { 
 3416:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3417:         }
 3418:     }
 3419: }
 3420: 
 3421: # -------------------------------------------------------------------- New chat
 3422: 
 3423: sub chatsend {
 3424:     my ($newentry,$anon,$group)=@_;
 3425:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3426:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3427:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3428:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3429: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3430: 		   &escape($newentry)).':'.$group,$chome);
 3431: }
 3432: 
 3433: # ------------------------------------------ Find current version of a resource
 3434: 
 3435: sub getversion {
 3436:     my $fname=&clutter(shift);
 3437:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3438:     return &currentversion(&filelocation('',$fname));
 3439: }
 3440: 
 3441: sub currentversion {
 3442:     my $fname=shift;
 3443:     my $author=$fname;
 3444:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3445:     my ($udom,$uname)=split(/\//,$author);
 3446:     my $home=&homeserver($uname,$udom);
 3447:     if ($home eq 'no_host') { 
 3448:         return -1; 
 3449:     }
 3450:     my $answer=&reply("currentversion:$fname",$home);
 3451:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3452: 	return -1;
 3453:     }
 3454:     return $answer;
 3455: }
 3456: 
 3457: #
 3458: # Return special version number of resource if set by override, empty otherwise
 3459: #
 3460: sub usedversion {
 3461:     my $fname=shift;
 3462:     unless ($fname) { $fname=$env{'request.uri'}; }
 3463:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3464:     if ($urlversion) { return $urlversion; }
 3465:     return '';
 3466: }
 3467: 
 3468: # ----------------------------- Subscribe to a resource, return URL if possible
 3469: 
 3470: sub subscribe {
 3471:     my $fname=shift;
 3472:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3473:     $fname=~s/[\n\r]//g;
 3474:     my $author=$fname;
 3475:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3476:     my ($udom,$uname)=split(/\//,$author);
 3477:     my $home=homeserver($uname,$udom);
 3478:     if ($home eq 'no_host') {
 3479:         return 'not_found';
 3480:     }
 3481:     my $answer=reply("sub:$fname",$home);
 3482:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3483: 	$answer.=' by '.$home;
 3484:     }
 3485:     return $answer;
 3486: }
 3487:     
 3488: # -------------------------------------------------------------- Replicate file
 3489: 
 3490: sub repcopy {
 3491:     my $filename=shift;
 3492:     $filename=~s/\/+/\//g;
 3493:     my $londocroot = $perlvar{'lonDocRoot'};
 3494:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3495:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3496:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3497: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3498: 	return &repcopy_userfile($filename);
 3499:     }
 3500:     $filename=~s/[\n\r]//g;
 3501:     my $transname="$filename.in.transfer";
 3502: # FIXME: this should flock
 3503:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3504:     my $remoteurl=subscribe($filename);
 3505:     if ($remoteurl =~ /^con_lost by/) {
 3506: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3507:            return 'unavailable';
 3508:     } elsif ($remoteurl eq 'not_found') {
 3509: 	   #&logthis("Subscribe returned not_found: $filename");
 3510: 	   return 'not_found';
 3511:     } elsif ($remoteurl =~ /^rejected by/) {
 3512: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3513:            return 'forbidden';
 3514:     } elsif ($remoteurl eq 'directory') {
 3515:            return 'ok';
 3516:     } else {
 3517:         my $author=$filename;
 3518:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3519:         my ($udom,$uname)=split(/\//,$author);
 3520:         my $home=homeserver($uname,$udom);
 3521:         unless ($home eq $perlvar{'lonHostID'}) {
 3522:            my @parts=split(/\//,$filename);
 3523:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3524:            if ($path ne "$londocroot/res") {
 3525:                &logthis("Malconfiguration for replication: $filename");
 3526: 	       return 'bad_request';
 3527:            }
 3528:            my $count;
 3529:            for ($count=5;$count<$#parts;$count++) {
 3530:                $path.="/$parts[$count]";
 3531:                if ((-e $path)!=1) {
 3532: 		   mkdir($path,0777);
 3533:                }
 3534:            }
 3535:            my $request=new HTTP::Request('GET',"$remoteurl");
 3536:            my $response;
 3537:            if ($remoteurl =~ m{/raw/}) {
 3538:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3539:            } else {
 3540:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3541:            }
 3542:            if ($response->is_error()) {
 3543: 	       unlink($transname);
 3544:                my $message=$response->status_line;
 3545:                &logthis("<font color=\"blue\">WARNING:"
 3546:                        ." LWP get: $message: $filename</font>");
 3547:                return 'unavailable';
 3548:            } else {
 3549: 	       if ($remoteurl!~/\.meta$/) {
 3550:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3551:                   my $mresponse;
 3552:                   if ($remoteurl =~ m{/raw/}) {
 3553:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3554:                   } else {
 3555:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3556:                   }
 3557:                   if ($mresponse->is_error()) {
 3558: 		      unlink($filename.'.meta');
 3559:                       &logthis(
 3560:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3561:                   }
 3562: 	       }
 3563:                rename($transname,$filename);
 3564:                return 'ok';
 3565:            }
 3566:        }
 3567:     }
 3568: }
 3569: 
 3570: # ------------------------------------------------- Unsubscribe from a resource
 3571: 
 3572: sub unsubscribe {
 3573:     my ($fname) = @_;
 3574:     my $answer;
 3575:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3576:     $fname=~s/[\n\r]//g;
 3577:     my $author=$fname;
 3578:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3579:     my ($udom,$uname)=split(/\//,$author);
 3580:     my $home=homeserver($uname,$udom);
 3581:     if ($home eq 'no_host') {
 3582:         $answer = 'no_host';
 3583:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3584:         $answer = 'home';
 3585:     } else {
 3586:         my $defdom = $perlvar{'lonDefDomain'};
 3587:         if (&will_trust('content',$defdom,$udom)) {
 3588:             $answer = reply("unsub:$fname",$home);
 3589:         } else {
 3590:             $answer = 'untrusted';
 3591:         }
 3592:     }
 3593:     return $answer;
 3594: }
 3595: 
 3596: # ------------------------------------------------ Get server side include body
 3597: sub ssi_body {
 3598:     my ($filelink,%form)=@_;
 3599:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3600:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3601:     }
 3602:     my $output='';
 3603:     my $response;
 3604:     if ($filelink=~/^https?\:/) {
 3605:        ($output,$response)=&externalssi($filelink);
 3606:     } else {
 3607:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3608:        $filelink .= 'inhibitmenu=yes';
 3609:        ($output,$response)=&ssi($filelink,%form);
 3610:     }
 3611:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3612:     $output=~s/^.*?\<body[^\>]*\>//si;
 3613:     $output=~s/\<\/body\s*\>.*?$//si;
 3614:     if (wantarray) {
 3615:         return ($output, $response);
 3616:     } else {
 3617:         return $output;
 3618:     }
 3619: }
 3620: 
 3621: # --------------------------------------------------------- Server Side Include
 3622: 
 3623: sub absolute_url {
 3624:     my ($host_name,$unalias,$keep_proto) = @_;
 3625:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3626:     if ($host_name eq '') {
 3627: 	$host_name = $ENV{'SERVER_NAME'};
 3628:     }
 3629:     if ($unalias) {
 3630:         my $alias = &get_proxy_alias();
 3631:         if ($alias eq $host_name) {
 3632:             my $lonhost = $perlvar{'lonHostID'};
 3633:             my $hostname = &hostname($lonhost);
 3634:             my $lcproto; 
 3635:             if (($keep_proto) || ($hostname eq '')) {
 3636:                 $lcproto = $protocol;
 3637:             } else {
 3638:                 $lcproto = $protocol{$lonhost};
 3639:                 $lcproto = 'http' if ($lcproto ne 'https');
 3640:                 $lcproto .= '://';
 3641:             }
 3642:             unless ($hostname eq '') {
 3643:                 return $lcproto.$hostname;
 3644:             }
 3645:         }
 3646:     }
 3647:     return $protocol.$host_name;
 3648: }
 3649: 
 3650: #
 3651: #   Server side include.
 3652: # Parameters:
 3653: #  fn     Possibly encrypted resource name/id.
 3654: #  form   Hash that describes how the rendering should be done
 3655: #         and other things.
 3656: # Returns:
 3657: #   Scalar context: The content of the response.
 3658: #   Array context:  2 element list of the content and the full response object.
 3659: #     
 3660: sub ssi {
 3661: 
 3662:     my ($fn,%form)=@_;
 3663:     my ($host,$request,$response);
 3664:     $host = &absolute_url('',1);
 3665: 
 3666:     $form{'no_update_last_known'}=1;
 3667:     &Apache::lonenc::check_encrypt(\$fn);
 3668:     if (%form) {
 3669:       $request=new HTTP::Request('POST',$host.$fn);
 3670:       $request->content(join('&',map { 
 3671:             my $name = escape($_);
 3672:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3673:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3674:             : &escape($form{$_}) );    
 3675:         } keys(%form)));
 3676:     } else {
 3677:       $request=new HTTP::Request('GET',$host.$fn);
 3678:     }
 3679: 
 3680:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3681:     my $lonhost = $perlvar{'lonHostID'};
 3682:     my $islocal;
 3683:     if (($env{'request.course.id'}) &&
 3684:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3685:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3686:         ($form{'grade_symb'} ne '') &&
 3687:         (&allowed('mgr',$env{'request.course.id'}.
 3688:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3689:         $islocal = 1;
 3690:     }
 3691:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3692:                                              '','','',$islocal);
 3693: 
 3694:     if (wantarray) {
 3695: 	return ($response->content, $response);
 3696:     } else {
 3697: 	return $response->content;
 3698:     }
 3699: }
 3700: 
 3701: sub externalssi {
 3702:     my ($url)=@_;
 3703:     my $request=new HTTP::Request('GET',$url);
 3704:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3705:     if (wantarray) {
 3706:         return ($response->content, $response);
 3707:     } else {
 3708:         return $response->content;
 3709:     }
 3710: }
 3711: 
 3712: 
 3713: # If the local copy of a replicated resource is outdated, trigger a  
 3714: # connection from the homeserver to flush the delayed queue. If no update 
 3715: # happens, remove local copies of outdated resource (and corresponding
 3716: # metadata file).
 3717: 
 3718: sub remove_stale_resfile {
 3719:     my ($url) = @_;
 3720:     my $removed;
 3721:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3722:         my $audom = $1;
 3723:         my $auname = $2;
 3724:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3725:             my $homeserver = &homeserver($auname,$audom);
 3726:             unless (($homeserver eq 'no_host') ||
 3727:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3728:                 my $fname = &filelocation('',$url);
 3729:                 if (-e $fname) {
 3730:                     my $hostname = &hostname($homeserver);
 3731:                     if ($hostname) {
 3732:                         my $protocol = $protocol{$homeserver};
 3733:                         $protocol = 'http' if ($protocol ne 'https');
 3734:                         my $uri = &declutter($url);
 3735:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3736:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3737:                         if ($response->is_success()) {
 3738:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3739:                             my $locmodtime = (stat($fname))[9];
 3740:                             if ($locmodtime < $remmodtime) {
 3741:                                 my $stale;
 3742:                                 my $answer = &reply('pong',$homeserver);
 3743:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3744:                                     sleep(0.2);
 3745:                                     $locmodtime = (stat($fname))[9];
 3746:                                     if ($locmodtime < $remmodtime) {
 3747:                                         my $posstransfer = $fname.'.in.transfer';
 3748:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3749:                                             $removed = 1;
 3750:                                         } else {
 3751:                                             $stale = 1;
 3752:                                         }
 3753:                                     } else {
 3754:                                         $removed = 1;
 3755:                                     }
 3756:                                 } else {
 3757:                                     $stale = 1;
 3758:                                 }
 3759:                                 if ($stale) {
 3760:                                     if (unlink($fname)) {
 3761:                                         if ($uri!~/\.meta$/) {
 3762:                                             if (-e $fname.'.meta') {
 3763:                                                 unlink($fname.'.meta');
 3764:                                             }
 3765:                                         }
 3766:                                         my $unsubresult = &unsubscribe($fname);
 3767:                                         unless ($unsubresult eq 'ok') {
 3768:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3769:                                         }
 3770:                                         $removed = 1;
 3771:                                     }
 3772:                                 }
 3773:                             }
 3774:                         }
 3775:                     }
 3776:                 }
 3777:             }
 3778:         }
 3779:     }
 3780:     return $removed;
 3781: }
 3782: 
 3783: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3784: 
 3785: sub allowuploaded {
 3786:     my ($srcurl,$url)=@_;
 3787:     $url=&clutter(&declutter($url));
 3788:     my $dir=$url;
 3789:     $dir=~s/\/[^\/]+$//;
 3790:     my %httpref=();
 3791:     my $httpurl=&hreflocation('',$url);
 3792:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3793:     &Apache::lonnet::appenv(\%httpref);
 3794: }
 3795: 
 3796: #
 3797: # Determine if the current user should be able to edit a particular resource,
 3798: # when viewing in course context.
 3799: # (a) When viewing resource used to determine if "Edit" item is included in 
 3800: #     Functions.
 3801: # (b) When displaying folder contents in course editor, used to determine if
 3802: #     "Edit" link will be displayed alongside resource.
 3803: #
 3804: #  input: six args -- filename (decluttered), course number, course domain,
 3805: #                   url, symb (if registered) and group (if this is a group
 3806: #                   item -- e.g., bulletin board, group page etc.).
 3807: #  output: array of five scalars -- 
 3808: #          $cfile -- url for file editing if editable on current server
 3809: #          $home -- homeserver of resource (i.e., for author if published,
 3810: #                                           or course if uploaded.).
 3811: #          $switchserver --  1 if server switch will be needed.
 3812: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3813: #          $forceview -- 1 if icon/link should be to go to view mode
 3814: #
 3815: 
 3816: sub can_edit_resource {
 3817:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3818:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3819: #
 3820: # For aboutme pages user can only edit his/her own.
 3821: #
 3822:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3823:         my ($sdom,$sname) = ($1,$2);
 3824:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3825:             $home = $env{'user.home'};
 3826:             $cfile = $resurl;
 3827:             if ($env{'form.forceedit'}) {
 3828:                 $forceview = 1;
 3829:             } else {
 3830:                 $forceedit = 1;
 3831:             }
 3832:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3833:         } else {
 3834:             return;
 3835:         }
 3836:     }
 3837: 
 3838:     if ($env{'request.course.id'}) {
 3839:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3840:         if ($group ne '') {
 3841: # if this is a group homepage or group bulletin board, check group privs
 3842:             my $allowed = 0;
 3843:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3844:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3845:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3846:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3847:                     $allowed = 1;
 3848:                 }
 3849:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3850:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3851:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3852:                     $allowed = 1;
 3853:                 }
 3854:             }
 3855:             if ($allowed) {
 3856:                 $home=&homeserver($cnum,$cdom);
 3857:                 if ($env{'form.forceedit'}) {
 3858:                     $forceview = 1;
 3859:                 } else {
 3860:                     $forceedit = 1;
 3861:                 }
 3862:                 $cfile = $resurl;
 3863:             } else {
 3864:                 return;
 3865:             }
 3866:         } else {
 3867:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3868:                 unless (&allowed('opa',$env{'request.course.id'})) {
 3869:                     return;
 3870:                 }
 3871:             } elsif (!$crsedit) {
 3872: #
 3873: # No edit allowed where CC has switched to student role.
 3874: #
 3875:                 return;
 3876:             }
 3877:         }
 3878:     }
 3879: 
 3880:     if ($file ne '') {
 3881:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3882:             if (&is_course_upload($file,$cnum,$cdom)) {
 3883:                 $uploaded = 1;
 3884:                 $incourse = 1;
 3885:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3886:                     $cfile = &hreflocation('',$file);
 3887:                     if ($env{'form.forceedit'}) {
 3888:                         $forceview = 1;
 3889:                     } else {
 3890:                         $forceedit = 1;
 3891:                     }
 3892:                 }
 3893:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3894:                 $incourse = 1;
 3895:                 if ($env{'form.forceedit'}) {
 3896:                     $forceview = 1;
 3897:                 } else {
 3898:                     $forceedit = 1;
 3899:                 }
 3900:                 $cfile = $resurl;
 3901:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3902:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3903:                     $incourse = 1;
 3904:                     if ($env{'form.forceedit'}) {
 3905:                         $forceview = 1;
 3906:                     } else {
 3907:                         $forceedit = 1;
 3908:                     }
 3909:                     $cfile = $resurl;
 3910:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3911:                     $incourse = 1;
 3912:                     $cfile = $resurl.'/smpedit';
 3913:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3914:                     $incourse = 1;
 3915:                     if ($env{'form.forceedit'}) {
 3916:                         $forceview = 1;
 3917:                     } else {
 3918:                         $forceedit = 1;
 3919:                     }
 3920:                     $cfile = $resurl;
 3921:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3922:                     my ($map,$id,$res) = &decode_symb($symb);
 3923:                     if ($map =~ /\.page$/) {
 3924:                         $incourse = 1;
 3925:                         if ($env{'form.forceedit'}) {
 3926:                             $forceview = 1;
 3927:                             $cfile = $map;
 3928:                         } else {
 3929:                             $forceedit = 1;
 3930:                             $cfile =  '/adm/wrapper'.$resurl;
 3931:                         }
 3932:                     }
 3933:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3934:                     $incourse = 1;
 3935:                     if ($env{'form.forceedit'}) {
 3936:                         $forceview = 1;
 3937:                     } else {
 3938:                         $forceedit = 1;
 3939:                     }
 3940:                     $cfile = $resurl;
 3941:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3942:                     $incourse = 1;
 3943:                     if ($env{'form.forceedit'}) {
 3944:                         $forceview = 1;
 3945:                     } else {
 3946:                         $forceedit = 1;
 3947:                     }
 3948:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3949:                 }
 3950:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3951:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3952:                 if (&is_on_map($template)) { 
 3953:                     $incourse = 1;
 3954:                     $forceview = 1;
 3955:                     $cfile = $template;
 3956:                 }
 3957:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3958:                 $incourse = 1;
 3959:                 if ($env{'form.forceedit'}) {
 3960:                     $forceview = 1;
 3961:                 } else {
 3962:                     $forceedit = 1;
 3963:                 }
 3964:                 $cfile = $resurl;
 3965:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3966:                 $incourse = 1;
 3967:                 if ($env{'form.forceedit'}) {
 3968:                     $forceview = 1;
 3969:                 } else {
 3970:                     $forceedit = 1;
 3971:                 }
 3972:                 $cfile = $resurl;
 3973:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3974:                 $incourse = 1;
 3975:                 $forceview = 1;
 3976:                 if ($symb) {
 3977:                     my ($map,$id,$res)=&decode_symb($symb);
 3978:                     $env{'request.symb'} = $symb;
 3979:                     $cfile = &clutter($res);
 3980:                 } else {
 3981:                     $cfile = $env{'form.suppurl'};
 3982:                     my $escfile = &unescape($cfile);
 3983:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3984:                         $cfile = '/adm/wrapper'.$escfile;
 3985:                     } else {
 3986:                         $escfile =~ s{^http://}{};
 3987:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3988:                     }
 3989:                 }
 3990:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3991:                 if ($env{'form.forceedit'}) {
 3992:                     $forceview = 1;
 3993:                 } else {
 3994:                     $forceedit = 1;
 3995:                 }
 3996:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3997:             }
 3998:         }
 3999:         if ($uploaded || $incourse) {
 4000:             $home=&homeserver($cnum,$cdom);
 4001:         } elsif ($file !~ m{/$}) {
 4002:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4003:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4004:             # Check that the user has permission to edit this resource
 4005:             my $setpriv = 1;
 4006:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4007:             if (defined($cfudom)) {
 4008:                 $home=&homeserver($cfuname,$cfudom);
 4009:                 $cfile=$file;
 4010:             }
 4011:         }
 4012:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4013:             (($home ne '') && ($home ne 'no_host'))) {
 4014:             my @ids=&current_machine_ids();
 4015:             unless (grep(/^\Q$home\E$/,@ids)) {
 4016:                 $switchserver=1;
 4017:             }
 4018:         }
 4019:     }
 4020:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4021: }
 4022: 
 4023: sub is_course_upload {
 4024:     my ($file,$cnum,$cdom) = @_;
 4025:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4026:     $uploadpath =~ s{^\/}{};
 4027:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4028:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4029:         return 1;
 4030:     }
 4031:     return;
 4032: }
 4033: 
 4034: sub in_course {
 4035:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4036:     if ($hideprivileged) {
 4037:         my $skipuser;
 4038:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4039:         my @possdoms = ($cdom);  
 4040:         if ($coursehash{'checkforpriv'}) { 
 4041:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4042:         }
 4043:         if (&privileged($uname,$udom,\@possdoms)) {
 4044:             $skipuser = 1;
 4045:             if ($coursehash{'nothideprivileged'}) {
 4046:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4047:                     my $user;
 4048:                     if ($item =~ /:/) {
 4049:                         $user = $item;
 4050:                     } else {
 4051:                         $user = join(':',split(/[\@]/,$item));
 4052:                     }
 4053:                     if ($user eq $uname.':'.$udom) {
 4054:                         undef($skipuser);
 4055:                         last;
 4056:                     }
 4057:                 }
 4058:             }
 4059:             if ($skipuser) {
 4060:                 return 0;
 4061:             }
 4062:         }
 4063:     }
 4064:     $type ||= 'any';
 4065:     if (!defined($cdom) || !defined($cnum)) {
 4066:         my $cid  = $env{'request.course.id'};
 4067:         $cdom = $env{'course.'.$cid.'.domain'};
 4068:         $cnum = $env{'course.'.$cid.'.num'};
 4069:     }
 4070:     my $typesref;
 4071:     if (($type eq 'any') || ($type eq 'all')) {
 4072:         $typesref = ['active','previous','future'];
 4073:     } elsif ($type eq 'previous' || $type eq 'future') {
 4074:         $typesref = [$type];
 4075:     }
 4076:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4077:                               $typesref,undef,[$cdom]);
 4078:     my ($tmp) = keys(%roles);
 4079:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4080:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4081:     if (@course_roles > 0) {
 4082:         return 1;
 4083:     }
 4084:     return 0;
 4085: }
 4086: 
 4087: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4088: # input: action, courseID, current domain, intended
 4089: #        path to file, source of file, instruction to parse file for objects,
 4090: #        ref to hash for embedded objects,
 4091: #        ref to hash for codebase of java objects.
 4092: #        reference to scalar to accommodate mime type determined
 4093: #          from File::MMagic if $parser = parse.
 4094: #
 4095: # output: url to file (if action was uploaddoc), 
 4096: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4097: #
 4098: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4099: # course.
 4100: #
 4101: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4102: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4103: #          course's home server.
 4104: #
 4105: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4106: #          be copied from $source (current location) to 
 4107: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4108: #         and will then be copied to
 4109: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4110: #         course's home server.
 4111: #
 4112: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4113: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4114: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4115: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4116: #         in course's home server.
 4117: #
 4118: 
 4119: sub process_coursefile {
 4120:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4121:         $mimetype)=@_;
 4122:     my $fetchresult;
 4123:     my $home=&homeserver($docuname,$docudom);
 4124:     if ($action eq 'propagate') {
 4125:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4126: 			     $home);
 4127:     } else {
 4128:         my $fpath = '';
 4129:         my $fname = $file;
 4130:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4131:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4132:         my $filepath = &build_filepath($fpath);
 4133:         if ($action eq 'copy') {
 4134:             if ($source eq '') {
 4135:                 $fetchresult = 'no source file';
 4136:                 return $fetchresult;
 4137:             } else {
 4138:                 my $destination = $filepath.'/'.$fname;
 4139:                 rename($source,$destination);
 4140:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4141:                                  $home);
 4142:             }
 4143:         } elsif ($action eq 'uploaddoc') {
 4144:             open(my $fh,'>',$filepath.'/'.$fname);
 4145:             print $fh $env{'form.'.$source};
 4146:             close($fh);
 4147:             if ($parser eq 'parse') {
 4148:                 my $mm = new File::MMagic;
 4149:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4150:                 if ($type eq 'text/html') {
 4151:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4152:                     unless ($parse_result eq 'ok') {
 4153:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4154:                     }
 4155:                 }
 4156:                 if (ref($mimetype)) {
 4157:                     $$mimetype = $type;
 4158:                 } 
 4159:             }
 4160:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4161:                                  $home);
 4162:             if ($fetchresult eq 'ok') {
 4163:                 return '/uploaded/'.$fpath.'/'.$fname;
 4164:             } else {
 4165:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4166:                         ' to host '.$home.': '.$fetchresult);
 4167:                 return '/adm/notfound.html';
 4168:             }
 4169:         }
 4170:     }
 4171:     unless ( $fetchresult eq 'ok') {
 4172:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4173:              ' to host '.$home.': '.$fetchresult);
 4174:     }
 4175:     return $fetchresult;
 4176: }
 4177: 
 4178: sub build_filepath {
 4179:     my ($fpath) = @_;
 4180:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4181:     unless ($fpath eq '') {
 4182:         my @parts=split('/',$fpath);
 4183:         foreach my $part (@parts) {
 4184:             $filepath.= '/'.$part;
 4185:             if ((-e $filepath)!=1) {
 4186:                 mkdir($filepath,0777);
 4187:             }
 4188:         }
 4189:     }
 4190:     return $filepath;
 4191: }
 4192: 
 4193: sub store_edited_file {
 4194:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4195:     my $file = $primary_url;
 4196:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4197:     my $fpath = '';
 4198:     my $fname = $file;
 4199:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4200:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4201:     my $filepath = &build_filepath($fpath);
 4202:     open(my $fh,'>',$filepath.'/'.$fname);
 4203:     print $fh $content;
 4204:     close($fh);
 4205:     my $home=&homeserver($docuname,$docudom);
 4206:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4207: 			  $home);
 4208:     if ($$fetchresult eq 'ok') {
 4209:         return '/uploaded/'.$fpath.'/'.$fname;
 4210:     } else {
 4211:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4212: 		 ' to host '.$home.': '.$$fetchresult);
 4213:         return '/adm/notfound.html';
 4214:     }
 4215: }
 4216: 
 4217: sub clean_filename {
 4218:     my ($fname,$args)=@_;
 4219: # Replace Windows backslashes by forward slashes
 4220:     $fname=~s/\\/\//g;
 4221:     if (!$args->{'keep_path'}) {
 4222:         # Get rid of everything but the actual filename
 4223: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4224:     }
 4225: # Replace spaces by underscores
 4226:     $fname=~s/\s+/\_/g;
 4227: # Transliterate non-ascii text to ascii
 4228:     my $lang = &Apache::lonlocal::current_language();
 4229:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4230: # Replace all other weird characters by nothing
 4231:     $fname=~s{[^/\w\.\-]}{}g;
 4232: # Replace all .\d. sequences with _\d. so they no longer look like version
 4233: # numbers
 4234:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4235: # Replace three or more adjacent underscores with one for consistency 
 4236: # with loncfile::filename_check() so complete url can be extracted by
 4237: # lonnet::decode_symb()
 4238:     $fname=~s/_{3,}/_/g;
 4239:     return $fname;
 4240: }
 4241: 
 4242: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4243: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4244: # image with the same aspect ratio as the original, but with dimensions which do 
 4245: # not exceed $resizewidth and $resizeheight.
 4246:  
 4247: sub resizeImage {
 4248:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4249:     my $ima = Image::Magick->new;
 4250:     my $resized;
 4251:     if (-e $img_path) {
 4252:         $ima->Read($img_path);
 4253:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4254:             my $width = $ima->Get('width');
 4255:             my $height = $ima->Get('height');
 4256:             if ($width > $resizewidth) {
 4257: 	        my $factor = $width/$resizewidth;
 4258:                 my $newheight = $height/$factor;
 4259:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4260:                 $resized = 1;
 4261:             }
 4262:         }
 4263:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4264:             my $width = $ima->Get('width');
 4265:             my $height = $ima->Get('height');
 4266:             if ($height > $resizeheight) {
 4267:                 my $factor = $height/$resizeheight;
 4268:                 my $newwidth = $width/$factor;
 4269:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4270:                 $resized = 1;
 4271:             }
 4272:         }
 4273:         if ($resized) {
 4274:             $ima->Write($img_path);
 4275:         }
 4276:     }
 4277:     return;
 4278: }
 4279: 
 4280: # --------------- Take an uploaded file and put it into the userfiles directory
 4281: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4282: #                    the desired filename is in $env{"form.$formname.filename"}
 4283: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4284: #                                    canceloverwrite, scantron, toollogo  or ''.
 4285: #                   if 'coursedoc': upload to the current course
 4286: #                   if 'existingfile': write file to tmp/overwrites directory 
 4287: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4288: #                   $context is passed as argument to &finishuserfileupload
 4289: #        $subdir - directory in userfile to store the file into
 4290: #        $parser - instruction to parse file for objects ($parser = parse) or
 4291: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4292: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4293: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4294: #        $allfiles - reference to hash for embedded objects
 4295: #        $codebase - reference to hash for codebase of java objects
 4296: #        $destuname - username for permanent storage of uploaded file
 4297: #        $destudom - domain for permanaent storage of uploaded file
 4298: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4299: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4300: #        $resizewidth - width (pixels) to which to resize uploaded image
 4301: #        $resizeheight - height (pixels) to which to resize uploaded image
 4302: #        $mimetype - reference to scalar to accommodate mime type determined
 4303: #                    from File::MMagic.
 4304: # 
 4305: # output: url of file in userspace, or error: <message> 
 4306: #             or /adm/notfound.html if failure to upload occurse
 4307: 
 4308: sub userfileupload {
 4309:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4310:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4311:     if (!defined($subdir)) { $subdir='unknown'; }
 4312:     my $fname=$env{'form.'.$formname.'.filename'};
 4313:     $fname=&clean_filename($fname);
 4314:     # See if there is anything left
 4315:     unless ($fname) { return 'error: no uploaded file'; }
 4316:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4317:     if ($fname =~ /^\./) {
 4318:         my ($s,$usec) = &gettimeofday();
 4319:         while (length($usec) < 6) {
 4320:             $usec = '0'.$usec;
 4321:         }
 4322:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4323:     }
 4324:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4325:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4326:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4327:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4328:         my $now = time;
 4329:         my $filepath;
 4330:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4331:              $filepath = 'tmp/helprequests/'.$now;
 4332:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4333:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4334:                          '_'.$env{'user.domain'}.'/pending';
 4335:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4336:             my ($docuname,$docudom);
 4337:             if ($destudom =~ /^$match_domain$/) {
 4338:                 $docudom = $destudom;
 4339:             } else {
 4340:                 $docudom = $env{'user.domain'};
 4341:             }
 4342:             if ($destuname =~ /^$match_username$/) {
 4343:                 $docuname = $destuname;
 4344:             } else {
 4345:                 $docuname = $env{'user.name'};
 4346:             }
 4347:             if (exists($env{'form.group'})) {
 4348:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4349:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4350:             }
 4351:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4352:             if ($context eq 'canceloverwrite') {
 4353:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4354:                 if (-e  $tempfile) {
 4355:                     my @info = stat($tempfile);
 4356:                     if ($info[9] eq $env{'form.timestamp'}) {
 4357:                         unlink($tempfile);
 4358:                     }
 4359:                 }
 4360:                 return;
 4361:             }
 4362:         }
 4363:         # Create the directory if not present
 4364:         my @parts=split(/\//,$filepath);
 4365:         my $fullpath = $perlvar{'lonDaemons'};
 4366:         for (my $i=0;$i<@parts;$i++) {
 4367:             $fullpath .= '/'.$parts[$i];
 4368:             if ((-e $fullpath)!=1) {
 4369:                 mkdir($fullpath,0777);
 4370:             }
 4371:         }
 4372:         open(my $fh,'>',$fullpath.'/'.$fname);
 4373:         print $fh $env{'form.'.$formname};
 4374:         close($fh);
 4375:         if ($context eq 'existingfile') {
 4376:             my @info = stat($fullpath.'/'.$fname);
 4377:             return ($fullpath.'/'.$fname,$info[9]);
 4378:         } else {
 4379:             return $fullpath.'/'.$fname;
 4380:         }
 4381:     }
 4382:     if ($subdir eq 'scantron') {
 4383:         $fname = 'scantron_orig_'.$fname;
 4384:     } else {
 4385:         $fname="$subdir/$fname";
 4386:     }
 4387:     if ($context eq 'coursedoc') {
 4388: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4389: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4390:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4391:             return &finishuserfileupload($docuname,$docudom,
 4392: 					 $formname,$fname,$parser,$allfiles,
 4393: 					 $codebase,$thumbwidth,$thumbheight,
 4394:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4395:         } else {
 4396:             if ($env{'form.folder'}) {
 4397:                 $fname=$env{'form.folder'}.'/'.$fname;
 4398:             }
 4399:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4400: 				       $fname,$formname,$parser,
 4401: 				       $allfiles,$codebase,$mimetype);
 4402:         }
 4403:     } elsif (defined($destuname)) {
 4404:         my $docuname=$destuname;
 4405:         my $docudom=$destudom;
 4406: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4407: 				     $parser,$allfiles,$codebase,
 4408:                                      $thumbwidth,$thumbheight,
 4409:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4410:     } else {
 4411:         my $docuname=$env{'user.name'};
 4412:         my $docudom=$env{'user.domain'};
 4413:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4414:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4415:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4416:         }
 4417: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4418: 				     $parser,$allfiles,$codebase,
 4419:                                      $thumbwidth,$thumbheight,
 4420:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4421:     }
 4422: }
 4423: 
 4424: sub finishuserfileupload {
 4425:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4426:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4427:     my $path=$docudom.'/'.$docuname.'/';
 4428:     my $filepath=$perlvar{'lonDocRoot'};
 4429:   
 4430:     my ($fnamepath,$file,$fetchthumb);
 4431:     $file=$fname;
 4432:     if ($fname=~m|/|) {
 4433:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4434: 	$path.=$fnamepath.'/';
 4435:     }
 4436:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4437:     my $count;
 4438:     for ($count=4;$count<=$#parts;$count++) {
 4439:         $filepath.="/$parts[$count]";
 4440:         if ((-e $filepath)!=1) {
 4441: 	    mkdir($filepath,0777);
 4442:         }
 4443:     }
 4444: 
 4445: # Save the file
 4446:     {
 4447: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4448: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4449: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4450: 	    return '/adm/notfound.html';
 4451: 	}
 4452:         if ($context eq 'overwrite') {
 4453:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4454:             my $target = $filepath.'/'.$file;
 4455:             if (-e $source) {
 4456:                 my @info = stat($source);
 4457:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4458:                     unless (&File::Copy::move($source,$target)) {
 4459:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4460:                         return "Moving from $source failed";
 4461:                     }
 4462:                 } else {
 4463:                     return "Temporary file: $source had unexpected date/time for last modification";
 4464:                 }
 4465:             } else {
 4466:                 return "Temporary file: $source missing";
 4467:             }
 4468:         } elsif (!print FH ($env{'form.'.$formname})) {
 4469: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4470: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4471: 	    return '/adm/notfound.html';
 4472: 	}
 4473: 	close(FH);
 4474:         if ($resizewidth && $resizeheight) {
 4475:             my $mm = new File::MMagic;
 4476:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4477:             if ($mime_type =~ m{^image/}) {
 4478: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4479:             }  
 4480: 	}
 4481:     }
 4482:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4483:         if (ref($mimetype)) {
 4484:             if ($$mimetype eq '') {
 4485:                 my $mm = new File::MMagic;
 4486:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4487:                 $$mimetype = $type;
 4488:             }
 4489:         }
 4490:     }
 4491:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4492:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4493:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4494:                                                        $allfiles,$codebase);
 4495:             unless ($parse_result eq 'ok') {
 4496:                 &logthis('Failed to parse '.$filepath.$file.
 4497: 	   	         ' for embedded media: '.$parse_result); 
 4498:             }
 4499:         }
 4500:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4501:         my $format = $env{'form.scantron_format'};
 4502:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4503:     }
 4504:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4505:         my $input = $filepath.'/'.$file;
 4506:         my $output = $filepath.'/'.'tn-'.$file;
 4507:         my $makethumb; 
 4508:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4509:         if ($context eq 'toollogo') {
 4510:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4511:             if ($fullwidth ne '' && $fullheight ne '') {
 4512:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4513:                     $makethumb = 1;
 4514:                 }
 4515:             }
 4516:         } else {
 4517:             $makethumb = 1;
 4518:         }
 4519:         if ($makethumb) {
 4520:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4521:             system({$args[0]} @args);
 4522:             if (-e $filepath.'/'.'tn-'.$file) {
 4523:                 $fetchthumb  = 1; 
 4524:             }
 4525:         }
 4526:     }
 4527:  
 4528: # Notify homeserver to grep it
 4529: #
 4530:     my $docuhome=&homeserver($docuname,$docudom);	
 4531:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4532:     if ($fetchresult eq 'ok') {
 4533:         if ($fetchthumb) {
 4534:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4535:             if ($thumbresult ne 'ok') {
 4536:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4537:                          $docuhome.': '.$thumbresult);
 4538:             }
 4539:         }
 4540: #
 4541: # Return the URL to it
 4542:         return '/uploaded/'.$path.$file;
 4543:     } else {
 4544:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4545: 		 ': '.$fetchresult);
 4546:         return '/adm/notfound.html';
 4547:     }
 4548: }
 4549: 
 4550: sub extract_embedded_items {
 4551:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4552:     my @state = ();
 4553:     my (%lastids,%related,%shockwave,%flashvars);
 4554:     my %javafiles = (
 4555:                       codebase => '',
 4556:                       code => '',
 4557:                       archive => ''
 4558:                     );
 4559:     my %mediafiles = (
 4560:                       src => '',
 4561:                       movie => '',
 4562:                      );
 4563:     my $p;
 4564:     if ($content) {
 4565:         $p = HTML::LCParser->new($content);
 4566:     } else {
 4567:         $p = HTML::LCParser->new($fullpath);
 4568:     }
 4569:     while (my $t=$p->get_token()) {
 4570: 	if ($t->[0] eq 'S') {
 4571: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4572: 	    push(@state, $tagname);
 4573:             if (lc($tagname) eq 'allow') {
 4574:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4575:             }
 4576: 	    if (lc($tagname) eq 'img') {
 4577: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4578: 	    }
 4579: 	    if (lc($tagname) eq 'a') {
 4580:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4581:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4582:                 }
 4583: 	    }
 4584:             if (lc($tagname) eq 'script') {
 4585:                 my $src;
 4586:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4587:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4588:                 } else {
 4589:                     if ($attr->{'src'} ne '') {
 4590:                         $src = $attr->{'src'};
 4591:                         &add_filetype($allfiles,$src,'src');
 4592:                     }
 4593:                 }
 4594:                 my $text = $p->get_trimmed_text();
 4595:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4596:                     my @swfargs = split(/,/,$1);
 4597:                     foreach my $item (@swfargs) {
 4598:                         $item =~ s/["']//g;
 4599:                         $item =~ s/^\s+//;
 4600:                         $item =~ s/\s+$//;
 4601:                     }
 4602:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4603:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4604:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4605:                         } else {
 4606:                             $related{$swfargs[0]} = [$swfargs[2]];
 4607:                         }
 4608:                     }
 4609:                 }
 4610:             }
 4611:             if (lc($tagname) eq 'link') {
 4612:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4613:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4614:                 }
 4615:             }
 4616: 	    if (lc($tagname) eq 'object' ||
 4617: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4618: 		foreach my $item (keys(%javafiles)) {
 4619: 		    $javafiles{$item} = '';
 4620: 		}
 4621:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4622:                     $lastids{lc($tagname)} = $attr->{'id'};
 4623:                 }
 4624: 	    }
 4625: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4626: 		my $name = lc($attr->{'name'});
 4627: 		foreach my $item (keys(%javafiles)) {
 4628: 		    if ($name eq $item) {
 4629: 			$javafiles{$item} = $attr->{'value'};
 4630: 			last;
 4631: 		    }
 4632: 		}
 4633:                 my $pathfrom;
 4634: 		foreach my $item (keys(%mediafiles)) {
 4635: 		    if ($name eq $item) {
 4636:                         $pathfrom = $attr->{'value'};
 4637:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4638: 			&add_filetype($allfiles,$pathfrom,$name);
 4639: 			last;
 4640: 		    }
 4641: 		}
 4642:                 if ($name eq 'flashvars') {
 4643:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4644:                 }
 4645:                 if ($pathfrom ne '') {
 4646:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4647:                                          $pathfrom);
 4648:                 }
 4649: 	    }
 4650: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4651: 		foreach my $item (keys(%javafiles)) {
 4652: 		    if ($attr->{$item}) {
 4653: 			$javafiles{$item} = $attr->{$item};
 4654: 			last;
 4655: 		    }
 4656: 		}
 4657: 		foreach my $item (keys(%mediafiles)) {
 4658: 		    if ($attr->{$item}) {
 4659: 			&add_filetype($allfiles,$attr->{$item},$item);
 4660: 			last;
 4661: 		    }
 4662: 		}
 4663:                 if (lc($tagname) eq 'embed') {
 4664:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4665:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4666:                                              $attr->{'src'});
 4667:                     }
 4668:                 }
 4669: 	    }
 4670:             if (lc($tagname) eq 'iframe') {
 4671:                 my $src = $attr->{'src'} ;
 4672:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4673:                     &add_filetype($allfiles,$src,'src');
 4674:                 } elsif ($src =~ m{^/}) {
 4675:                     if ($env{'request.course.id'}) {
 4676:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4677:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4678:                         my $url = &hreflocation('',$fullpath);
 4679:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4680:                             my $relpath = $1;
 4681:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4682:                                 &add_filetype($allfiles,$1,'src');
 4683:                             }
 4684:                         }
 4685:                     }
 4686:                 }
 4687:             }
 4688:             if ($t->[4] =~ m{/>$}) {
 4689:                 pop(@state);
 4690:             }
 4691: 	} elsif ($t->[0] eq 'E') {
 4692: 	    my ($tagname) = ($t->[1]);
 4693: 	    if ($javafiles{'codebase'} ne '') {
 4694: 		$javafiles{'codebase'} .= '/';
 4695: 	    }  
 4696: 	    if (lc($tagname) eq 'applet' ||
 4697: 		lc($tagname) eq 'object' ||
 4698: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4699: 		) {
 4700: 		foreach my $item (keys(%javafiles)) {
 4701: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4702: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4703: 			&add_filetype($allfiles,$file,$item);
 4704: 		    }
 4705: 		}
 4706: 	    } 
 4707: 	    pop @state;
 4708: 	}
 4709:     }
 4710:     foreach my $id (sort(keys(%flashvars))) {
 4711:         if ($shockwave{$id} ne '') {
 4712:             my @pairs = split(/\&/,$flashvars{$id});
 4713:             foreach my $pair (@pairs) {
 4714:                 my ($key,$value) = split(/\=/,$pair);
 4715:                 if ($key eq 'thumb') {
 4716:                     &add_filetype($allfiles,$value,$key);
 4717:                 } elsif ($key eq 'content') {
 4718:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4719:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4720:                     if ($ext ne '') {
 4721:                         &add_filetype($allfiles,$path.$value,$ext);
 4722:                     }
 4723:                 }
 4724:             }
 4725:         }
 4726:     }
 4727:     return 'ok';
 4728: }
 4729: 
 4730: sub add_filetype {
 4731:     my ($allfiles,$file,$type)=@_;
 4732:     if (exists($allfiles->{$file})) {
 4733: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4734: 	    push(@{$allfiles->{$file}}, &escape($type));
 4735: 	}
 4736:     } else {
 4737: 	@{$allfiles->{$file}} = (&escape($type));
 4738:     }
 4739: }
 4740: 
 4741: sub embedded_dependency {
 4742:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4743:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4744:         if (($identifier ne '') &&
 4745:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4746:             ($pathfrom ne '')) {
 4747:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4748:             foreach my $dep (@{$related->{$identifier}}) {
 4749:                 &add_filetype($allfiles,$path.$dep,'object');
 4750:             }
 4751:         }
 4752:     }
 4753:     return;
 4754: }
 4755: 
 4756: sub check_dimensions {
 4757:     my ($inputfile) = @_;
 4758:     my ($fullwidth,$fullheight);
 4759:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4760:         my $mm = new File::MMagic;
 4761:         my $mime_type = $mm->checktype_filename($inputfile);
 4762:         if ($mime_type =~ m{^image/}) {
 4763:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4764:                 my $imageinfo = <PIPE>;
 4765:                 if (!close(PIPE)) {
 4766:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4767:                 }
 4768:                 chomp($imageinfo);
 4769:                 my ($fullsize) =
 4770:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4771:                 if ($fullsize) {
 4772:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4773:                 }
 4774:             }
 4775:         }
 4776:     }
 4777:     return ($fullwidth,$fullheight);
 4778: }
 4779: 
 4780: sub bubblesheet_converter {
 4781:     my ($cdom,$fullpath,$config,$format) = @_;
 4782:     if ((&domain($cdom) ne '') &&
 4783:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4784:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4785:         my (%csvcols,%csvoptions);
 4786:         if (ref($config->{'fields'}) eq 'HASH') {  
 4787:             %csvcols = %{$config->{'fields'}};
 4788:         }
 4789:         if (ref($config->{'options'}) eq 'HASH') {
 4790:             %csvoptions = %{$config->{'options'}};
 4791:         }
 4792:         my %csvbynum = reverse(%csvcols);
 4793:         my %scantronconf = &get_scantron_config($format,$cdom);
 4794:         if (keys(%scantronconf)) {
 4795:             my %bynum = (
 4796:                           $scantronconf{CODEstart} => 'CODEstart',
 4797:                           $scantronconf{IDstart}   => 'IDstart',
 4798:                           $scantronconf{PaperID}   => 'PaperID',
 4799:                           $scantronconf{FirstName} => 'FirstName',
 4800:                           $scantronconf{LastName}  => 'LastName',
 4801:                           $scantronconf{Qstart}    => 'Qstart',
 4802:                         );
 4803:             my @ordered;
 4804:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4805:                 push(@ordered,$bynum{$item});
 4806:             }
 4807:             my %mapstart = (
 4808:                               CODEstart => 'CODE',
 4809:                               IDstart   => 'ID',
 4810:                               PaperID   => 'PaperID',
 4811:                               FirstName => 'FirstName',
 4812:                               LastName  => 'LastName',
 4813:                               Qstart    => 'FirstQuestion',
 4814:                            );
 4815:             my %maplength = (
 4816:                               CODEstart => 'CODElength',
 4817:                               IDstart   => 'IDlength',
 4818:                               PaperID   => 'PaperIDlength',
 4819:                               FirstName => 'FirstNamelength',
 4820:                               LastName  => 'LastNamelength',
 4821:             );
 4822:             if (open(my $fh,'<',$fullpath)) {
 4823:                 my $output;
 4824:                 my %lettdig = &letter_to_digits();
 4825:                 my %diglett = reverse(%lettdig);
 4826:                 my $numletts = scalar(keys(%lettdig));
 4827:                 my $num = 0;
 4828:                 while (my $line=<$fh>) {
 4829:                     $num ++;
 4830:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4831:                     $line =~ s{[\r\n]+$}{};
 4832:                     my %found;
 4833:                     my @values = split(/,/,$line,-1);
 4834:                     my ($qstart,$record);
 4835:                     for (my $i=0; $i<@values; $i++) {
 4836:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4837:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4838:                             if ($values[$i] eq '') {
 4839:                                 $values[$i] = $scantronconf{'Qoff'};
 4840:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4841:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4842:                                     $values[$i] = $lettdig{uc($values[$i])};
 4843:                                 }
 4844:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4845:                                 if ($values[$i] =~ /^[0-9]$/) {
 4846:                                     $values[$i] = $diglett{$values[$i]};
 4847:                                 }
 4848:                             } else {
 4849:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4850:                                     my $digit;
 4851:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4852:                                         $digit = $lettdig{uc($values[$i])}-1;
 4853:                                         if ($values[$i] eq 'J') {
 4854:                                             $digit += $numletts;
 4855:                                         }
 4856:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4857:                                         $digit = $values[$i]-1;
 4858:                                         if ($values[$i] eq '0') {
 4859:                                             $digit += $numletts;
 4860:                                         }
 4861:                                     }
 4862:                                     my $qval='';
 4863:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4864:                                         if ($j == $digit) {
 4865:                                             $qval .= $scantronconf{'Qon'};
 4866:                                         } else {
 4867:                                             $qval .= $scantronconf{'Qoff'};
 4868:                                         }
 4869:                                     }
 4870:                                     $values[$i] = $qval;
 4871:                                 }
 4872:                             }
 4873:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4874:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4875:                             }
 4876:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4877:                             if ($numblank > 0) {
 4878:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4879:                             }
 4880:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4881:                                 $qstart = $i;
 4882:                                 $found{$csvbynum{$i}} = $values[$i];
 4883:                             } else {
 4884:                                 $found{'FirstQuestion'} .= $values[$i];
 4885:                             }
 4886:                         } elsif (exists($csvbynum{$i})) {
 4887:                             if ($csvoptions{'rem'}) {
 4888:                                 $values[$i] =~ s/^\s+//;
 4889:                             }
 4890:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4891:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4892:                                     $values[$i] = '0'.$values[$i];
 4893:                                 }
 4894:                             }
 4895:                             $found{$csvbynum{$i}} = $values[$i];
 4896:                         }
 4897:                     }
 4898:                     foreach my $item (@ordered) {
 4899:                         my $currlength = 1+length($record);
 4900:                         my $numspaces = $scantronconf{$item} - $currlength;
 4901:                         if ($numspaces > 0) {
 4902:                             $record .= (' ' x $numspaces);
 4903:                         }
 4904:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4905:                             unless ($item eq 'Qstart') {
 4906:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4907:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4908:                                 }
 4909:                             }
 4910:                             $record .= $found{$mapstart{$item}};
 4911:                         }
 4912:                     }
 4913:                     $output .= "$record\n";
 4914:                 }
 4915:                 close($fh);
 4916:                 if ($output) {
 4917:                     if (open(my $fh,'>',$fullpath)) {
 4918:                         print $fh $output;
 4919:                         close($fh);
 4920:                     }
 4921:                 }
 4922:             }
 4923:         }
 4924:         return;
 4925:     }
 4926: }
 4927: 
 4928: sub letter_to_digits {
 4929:     my %lettdig = (
 4930:                     A => 1,
 4931:                     B => 2,
 4932:                     C => 3,
 4933:                     D => 4,
 4934:                     E => 5,
 4935:                     F => 6,
 4936:                     G => 7,
 4937:                     H => 8,
 4938:                     I => 9,
 4939:                     J => 0,
 4940:                   );
 4941:     return %lettdig;
 4942: }
 4943: 
 4944: sub get_scantron_config {
 4945:     my ($which,$cdom) = @_;
 4946:     my @lines = &get_scantronformat_file($cdom);
 4947:     my %config;
 4948:     #FIXME probably should move to XML it has already gotten a bit much now
 4949:     foreach my $line (@lines) {
 4950:         my ($name,$descrip)=split(/:/,$line);
 4951:         if ($name ne $which ) { next; }
 4952:         chomp($line);
 4953:         my @config=split(/:/,$line);
 4954:         $config{'name'}=$config[0];
 4955:         $config{'description'}=$config[1];
 4956:         $config{'CODElocation'}=$config[2];
 4957:         $config{'CODEstart'}=$config[3];
 4958:         $config{'CODElength'}=$config[4];
 4959:         $config{'IDstart'}=$config[5];
 4960:         $config{'IDlength'}=$config[6];
 4961:         $config{'Qstart'}=$config[7];
 4962:         $config{'Qlength'}=$config[8];
 4963:         $config{'Qoff'}=$config[9];
 4964:         $config{'Qon'}=$config[10];
 4965:         $config{'PaperID'}=$config[11];
 4966:         $config{'PaperIDlength'}=$config[12];
 4967:         $config{'FirstName'}=$config[13];
 4968:         $config{'FirstNamelength'}=$config[14];
 4969:         $config{'LastName'}=$config[15];
 4970:         $config{'LastNamelength'}=$config[16];
 4971:         $config{'BubblesPerRow'}=$config[17];
 4972:         last;
 4973:     }
 4974:     return %config;
 4975: }
 4976: 
 4977: sub get_scantronformat_file {
 4978:     my ($cdom) = @_;
 4979:     if ($cdom eq '') {
 4980:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4981:     }
 4982:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4983:     my $gottab = 0;
 4984:     my @lines;
 4985:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4986:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4987:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4988:             if ($formatfile ne '-1') {
 4989:                 @lines = split("\n",$formatfile,-1);
 4990:                 $gottab = 1;
 4991:             }
 4992:         }
 4993:     }
 4994:     if (!$gottab) {
 4995:         my $confname = $cdom.'-domainconfig';
 4996:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4997:         my $formatfile = &getfile($default);
 4998:         if ($formatfile ne '-1') {
 4999:             @lines = split("\n",$formatfile,-1);
 5000:             $gottab = 1;
 5001:         }
 5002:     }
 5003:     if (!$gottab) {
 5004:         my @domains = &current_machine_domains();
 5005:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5006:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5007:                 @lines = <$fh>;
 5008:                 close($fh);
 5009:             }
 5010:         } else {
 5011:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5012:                 @lines = <$fh>;
 5013:                 close($fh);
 5014:             }
 5015:         }
 5016:         chomp(@lines);
 5017:     }
 5018:     return @lines;
 5019: }
 5020: 
 5021: sub removeuploadedurl {
 5022:     my ($url)=@_;	
 5023:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5024:     return &removeuserfile($uname,$udom,$fname);
 5025: }
 5026: 
 5027: sub removeuserfile {
 5028:     my ($docuname,$docudom,$fname)=@_;
 5029:     my $home=&homeserver($docuname,$docudom);    
 5030:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5031:     if ($result eq 'ok') {	
 5032:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5033:             my $metafile = $fname.'.meta';
 5034:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5035: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5036:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5037:             my $sqlresult = 
 5038:                 &update_portfolio_table($docuname,$docudom,$file,
 5039:                                         'portfolio_metadata',$group,
 5040:                                         'delete');
 5041:         }
 5042:     }
 5043:     return $result;
 5044: }
 5045: 
 5046: sub mkdiruserfile {
 5047:     my ($docuname,$docudom,$dir)=@_;
 5048:     my $home=&homeserver($docuname,$docudom);
 5049:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5050: }
 5051: 
 5052: sub renameuserfile {
 5053:     my ($docuname,$docudom,$old,$new)=@_;
 5054:     my $home=&homeserver($docuname,$docudom);
 5055:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5056:                         &escape("$old").':'.&escape("$new"),$home);
 5057:     if ($result eq 'ok') {
 5058:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5059:             my $oldmeta = $old.'.meta';
 5060:             my $newmeta = $new.'.meta';
 5061:             my $metaresult = 
 5062:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5063: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5064:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5065:             my $sqlresult = 
 5066:                 &update_portfolio_table($docuname,$docudom,$file,
 5067:                                         'portfolio_metadata',$group,
 5068:                                         'delete');
 5069:         }
 5070:     }
 5071:     return $result;
 5072: }
 5073: 
 5074: # ------------------------------------------------------------------------- Log
 5075: 
 5076: sub log {
 5077:     my ($dom,$nam,$hom,$what)=@_;
 5078:     return critical("log:$dom:$nam:$what",$hom);
 5079: }
 5080: 
 5081: # ------------------------------------------------------------------ Course Log
 5082: #
 5083: # This routine flushes several buffers of non-mission-critical nature
 5084: #
 5085: 
 5086: sub flushcourselogs {
 5087:     &logthis('Flushing log buffers');
 5088: #
 5089: # course logs
 5090: # This is a log of all transactions in a course, which can be used
 5091: # for data mining purposes
 5092: #
 5093: # It also collects the courseid database, which lists last transaction
 5094: # times and course titles for all courseids
 5095: #
 5096:     my %courseidbuffer=();
 5097:     foreach my $crsid (keys(%courselogs)) {
 5098:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5099: 		          &escape($courselogs{$crsid}),
 5100: 		          $coursehombuf{$crsid}) eq 'ok') {
 5101: 	    delete $courselogs{$crsid};
 5102:         } else {
 5103:             &logthis('Failed to flush log buffer for '.$crsid);
 5104:             if (length($courselogs{$crsid})>40000) {
 5105:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5106:                         " exceeded maximum size, deleting.</font>");
 5107:                delete $courselogs{$crsid};
 5108:             }
 5109:         }
 5110:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5111:             'description' => $coursedescrbuf{$crsid},
 5112:             'inst_code'    => $courseinstcodebuf{$crsid},
 5113:             'type'        => $coursetypebuf{$crsid},
 5114:             'owner'       => $courseownerbuf{$crsid},
 5115:         };
 5116:     }
 5117: #
 5118: # Write course id database (reverse lookup) to homeserver of courses 
 5119: # Is used in pickcourse
 5120: #
 5121:     foreach my $crs_home (keys(%courseidbuffer)) {
 5122:         my $response = &courseidput(&host_domain($crs_home),
 5123:                                     $courseidbuffer{$crs_home},
 5124:                                     $crs_home,'timeonly');
 5125:     }
 5126: #
 5127: # File accesses
 5128: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5129: #
 5130:     foreach my $entry (keys(%accesshash)) {
 5131:         if ($entry =~ /___count$/) {
 5132:             my ($dom,$name);
 5133:             ($dom,$name,undef)=
 5134: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5135:             if (! defined($dom) || $dom eq '' || 
 5136:                 ! defined($name) || $name eq '') {
 5137:                 my $cid = $env{'request.course.id'};
 5138: #
 5139: # FIXME 11/29/2021
 5140: # Typo in rev. 1.458 (2003/12/09)??
 5141: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5142: #
 5143: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5144: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5145: # in a nohist_accesscount.db file for the user rather than the course.
 5146: #
 5147: # That said there is a lot of noise in the data being stored.
 5148: # So counts for prtspool/  and adm/ etc. are recorded.
 5149: #
 5150: # A review of which items ending '___count' are written to %accesshash should likely be 
 5151: # made before deciding whether to set these to 'course.' instead of 'request.'
 5152: #
 5153: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5154: # accesses for things which are not published resources, regardless of course, and
 5155: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5156: # anyone in the course for things which are not published resources.
 5157: #
 5158: # For an author, nohist_accesscount.db ends up having records for other items
 5159: # mixed up with the legitimate access counts for the author's published resources.
 5160: #
 5161:                 $dom  = $env{'request.'.$cid.'.domain'};
 5162:                 $name = $env{'request.'.$cid.'.num'};
 5163:             }
 5164:             my $value = $accesshash{$entry};
 5165:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5166:             my %temphash=($url => $value);
 5167:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5168:             if ($result eq 'ok') {
 5169:                 delete $accesshash{$entry};
 5170:             }
 5171:         } else {
 5172:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5173:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5174:             my %temphash=($entry => $accesshash{$entry});
 5175:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5176:                 delete $accesshash{$entry};
 5177:             }
 5178:         }
 5179:     }
 5180: #
 5181: # Roles
 5182: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5183: #
 5184:     foreach my $entry (keys(%userrolehash)) {
 5185:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5186: 	    split(/\:/,$entry);
 5187:         if (&put('nohist_userroles',
 5188:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5189:                 $rudom,$runame) eq 'ok') {
 5190: 	    delete $userrolehash{$entry};
 5191:         }
 5192:     }
 5193: #
 5194: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5195: #
 5196:     my %domrolebuffer = ();
 5197:     foreach my $entry (keys(%domainrolehash)) {
 5198:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5199:         if ($domrolebuffer{$rudom}) {
 5200:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5201:                       '='.&escape($domainrolehash{$entry});
 5202:         } else {
 5203:             $domrolebuffer{$rudom}.=&escape($entry).
 5204:                       '='.&escape($domainrolehash{$entry});
 5205:         }
 5206:         delete $domainrolehash{$entry};
 5207:     }
 5208:     foreach my $dom (keys(%domrolebuffer)) {
 5209: 	my %servers;
 5210: 	if (defined(&domain($dom,'primary'))) {
 5211: 	    my $primary=&domain($dom,'primary');
 5212: 	    my $hostname=&hostname($primary);
 5213: 	    $servers{$primary} = $hostname;
 5214: 	} else { 
 5215: 	    %servers = &get_servers($dom,'library');
 5216: 	}
 5217: 	foreach my $tryserver (keys(%servers)) {
 5218: 	    if (&reply('domroleput:'.$dom.':'.
 5219: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5220: 		last;
 5221: 	    } else {  
 5222: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5223: 	    }
 5224:         }
 5225:     }
 5226:     $dumpcount++;
 5227: }
 5228: 
 5229: sub courselog {
 5230:     my $what=shift;
 5231:     $what=time.':'.$what;
 5232:     unless ($env{'request.course.id'}) { return ''; }
 5233:     $coursedombuf{$env{'request.course.id'}}=
 5234:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5235:     $coursenumbuf{$env{'request.course.id'}}=
 5236:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5237:     $coursehombuf{$env{'request.course.id'}}=
 5238:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5239:     $coursedescrbuf{$env{'request.course.id'}}=
 5240:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5241:     $courseinstcodebuf{$env{'request.course.id'}}=
 5242:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5243:     $courseownerbuf{$env{'request.course.id'}}=
 5244:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5245:     $coursetypebuf{$env{'request.course.id'}}=
 5246:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5247:     if (defined $courselogs{$env{'request.course.id'}}) {
 5248: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5249:     } else {
 5250: 	$courselogs{$env{'request.course.id'}}.=$what;
 5251:     }
 5252:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5253: 	&flushcourselogs();
 5254:     }
 5255: }
 5256: 
 5257: sub courseacclog {
 5258:     my $fnsymb=shift;
 5259:     unless ($env{'request.course.id'}) { return ''; }
 5260:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5261:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5262:         $what.=':POST';
 5263:         # FIXME: Probably ought to escape things....
 5264: 	foreach my $key (keys(%env)) {
 5265:             if ($key=~/^form\.(.*)/) {
 5266:                 my $formitem = $1;
 5267:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5268:                     $what.=':'.$formitem.'='.$env{$key};
 5269:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5270:                     if ($formitem eq 'proctorpassword') {
 5271:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5272:                     } else {
 5273:                         $what.=':'.$formitem.'='.$env{$key};
 5274:                     }
 5275:                 }
 5276:             }
 5277:         }
 5278:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5279:         # FIXME: We should not be depending on a form parameter that someone
 5280:         # editing lonsearchcat.pm might change in the future.
 5281:         if ($env{'form.phase'} eq 'course_search') {
 5282:             $what.= ':POST';
 5283:             # FIXME: Probably ought to escape things....
 5284:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5285:                                  'crsdiscuss') {
 5286:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5287:             }
 5288:         }
 5289:     }
 5290:     &courselog($what);
 5291: }
 5292: 
 5293: sub countacc {
 5294:     my $url=&declutter(shift);
 5295:     return if (! defined($url) || $url eq '');
 5296:     unless ($env{'request.course.id'}) { return ''; }
 5297: #
 5298: # Mark that this url was used in this course
 5299: #
 5300:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5301: #
 5302: # Increase the access count for this resource in this child process
 5303: #
 5304:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5305:     $accesshash{$key}++;
 5306: }
 5307: 
 5308: sub linklog {
 5309:     my ($from,$to)=@_;
 5310:     $from=&declutter($from);
 5311:     $to=&declutter($to);
 5312:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5313:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5314: }
 5315: 
 5316: sub statslog {
 5317:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5318:     if ($users<2) { return; }
 5319:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5320:             'course'       => $env{'request.course.id'},
 5321:             'sections'     => '"all"',
 5322:             'num_students' => $users,
 5323:             'part'         => $part,
 5324:             'symb'         => $symb,
 5325:             'mean_tries'   => $av_attempts,
 5326:             'deg_of_diff'  => $degdiff});
 5327:     foreach my $key (keys(%dynstore)) {
 5328:         $accesshash{$key}=$dynstore{$key};
 5329:     }
 5330: }
 5331:   
 5332: sub userrolelog {
 5333:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5334:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5335:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5336:        $userrolehash
 5337:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5338:                     =$tend.':'.$tstart;
 5339:     }
 5340:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5341:        $userrolehash
 5342:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5343:                     =$tend.':'.$tstart;
 5344:     }
 5345:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5346:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5347:        $domainrolehash
 5348:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5349:                     = $tend.':'.$tstart;
 5350:     }
 5351: }
 5352: 
 5353: sub courserolelog {
 5354:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5355:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5356:         my $cdom = $1;
 5357:         my $cnum = $2;
 5358:         my $sec = $3;
 5359:         my $namespace = 'rolelog';
 5360:         my %storehash = (
 5361:                            role    => $trole,
 5362:                            start   => $tstart,
 5363:                            end     => $tend,
 5364:                            selfenroll => $selfenroll,
 5365:                            context    => $context,
 5366:                         );
 5367:         if ($trole eq 'gr') {
 5368:             $namespace = 'groupslog';
 5369:             $storehash{'group'} = $sec;
 5370:         } else {
 5371:             $storehash{'section'} = $sec;
 5372:         }
 5373:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5374:                    $domain,$cnum,$cdom);
 5375:         if (($trole ne 'st') || ($sec ne '')) {
 5376:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5377:         }
 5378:     }
 5379:     return;
 5380: }
 5381: 
 5382: sub domainrolelog {
 5383:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5384:     if ($area =~ m{^/($match_domain)/$}) {
 5385:         my $cdom = $1;
 5386:         my $domconfiguser = &get_domainconfiguser($cdom);
 5387:         my $namespace = 'rolelog';
 5388:         my %storehash = (
 5389:                            role    => $trole,
 5390:                            start   => $tstart,
 5391:                            end     => $tend,
 5392:                            context => $context,
 5393:                         );
 5394:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5395:                    $domain,$domconfiguser,$cdom);
 5396:     }
 5397:     return;
 5398: 
 5399: }
 5400: 
 5401: sub coauthorrolelog {
 5402:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5403:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5404:         my $audom = $1;
 5405:         my $auname = $2;
 5406:         my $namespace = 'rolelog';
 5407:         my %storehash = (
 5408:                            role    => $trole,
 5409:                            start   => $tstart,
 5410:                            end     => $tend,
 5411:                            context => $context,
 5412:                         );
 5413:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5414:                    $domain,$auname,$audom);
 5415:     }
 5416:     return;
 5417: }
 5418: 
 5419: sub get_course_adv_roles {
 5420:     my ($cid,$codes) = @_;
 5421:     $cid=$env{'request.course.id'} unless (defined($cid));
 5422:     my %coursehash=&coursedescription($cid);
 5423:     my $crstype = &Apache::loncommon::course_type($cid);
 5424:     my %nothide=();
 5425:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5426:         if ($user !~ /:/) {
 5427: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5428:         } else {
 5429:             $nothide{$user}=1;
 5430:         }
 5431:     }
 5432:     my @possdoms = ($coursehash{'domain'});
 5433:     if ($coursehash{'checkforpriv'}) {
 5434:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5435:     }
 5436:     my %returnhash=();
 5437:     my %dumphash=
 5438:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5439:     my $now=time;
 5440:     my %privileged;
 5441:     foreach my $entry (keys(%dumphash)) {
 5442: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5443:         if (($tstart) && ($tstart<0)) { next; }
 5444:         if (($tend) && ($tend<$now)) { next; }
 5445:         if (($tstart) && ($now<$tstart)) { next; }
 5446:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5447: 	if ($username eq '' || $domain eq '') { next; }
 5448:         if ((&privileged($username,$domain,\@possdoms)) &&
 5449:             (!$nothide{$username.':'.$domain})) { next; }
 5450: 	if ($role eq 'cr') { next; }
 5451:         if ($codes) {
 5452:             if ($section) { $role .= ':'.$section; }
 5453:             if ($returnhash{$role}) {
 5454:                 $returnhash{$role}.=','.$username.':'.$domain;
 5455:             } else {
 5456:                 $returnhash{$role}=$username.':'.$domain;
 5457:             }
 5458:         } else {
 5459:             my $key=&plaintext($role,$crstype);
 5460:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5461:             if ($returnhash{$key}) {
 5462: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5463:             } else {
 5464:                 $returnhash{$key}=$username.':'.$domain;
 5465:             }
 5466:         }
 5467:     }
 5468:     return %returnhash;
 5469: }
 5470: 
 5471: sub get_my_roles {
 5472:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5473:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5474:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5475:     my (%dumphash,%nothide);
 5476:     if ($context eq 'userroles') {
 5477:         %dumphash = &dump('roles',$udom,$uname);
 5478:     } else {
 5479:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5480:         if ($hidepriv) {
 5481:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5482:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5483:                 if ($user !~ /:/) {
 5484:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5485:                 } else {
 5486:                     $nothide{$user} = 1;
 5487:                 }
 5488:             }
 5489:         }
 5490:     }
 5491:     my %returnhash=();
 5492:     my $now=time;
 5493:     my %privileged;
 5494:     foreach my $entry (keys(%dumphash)) {
 5495:         my ($role,$tend,$tstart);
 5496:         if ($context eq 'userroles') {
 5497:             next if ($entry =~ /^rolesdef/);
 5498: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5499:         } else {
 5500:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5501:         }
 5502:         if (($tstart) && ($tstart<0)) { next; }
 5503:         my $status = 'active';
 5504:         if (($tend) && ($tend<=$now)) {
 5505:             $status = 'previous';
 5506:         } 
 5507:         if (($tstart) && ($now<$tstart)) {
 5508:             $status = 'future';
 5509:         }
 5510:         if (ref($types) eq 'ARRAY') {
 5511:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5512:                 next;
 5513:             } 
 5514:         } else {
 5515:             if ($status ne 'active') {
 5516:                 next;
 5517:             }
 5518:         }
 5519:         my ($rolecode,$username,$domain,$section,$area);
 5520:         if ($context eq 'userroles') {
 5521:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5522:             (undef,$domain,$username,$section) = split(/\//,$area);
 5523:         } else {
 5524:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5525:         }
 5526:         if (ref($roledoms) eq 'ARRAY') {
 5527:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5528:                 next;
 5529:             }
 5530:         }
 5531:         if (ref($roles) eq 'ARRAY') {
 5532:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5533:                 if ($role =~ /^cr\//) {
 5534:                     if (!grep(/^cr$/,@{$roles})) {
 5535:                         next;
 5536:                     }
 5537:                 } elsif ($role =~ /^gr\//) {
 5538:                     if (!grep(/^gr$/,@{$roles})) {
 5539:                         next;
 5540:                     }
 5541:                 } else {
 5542:                     next;
 5543:                 }
 5544:             }
 5545:         }
 5546:         if ($hidepriv) {
 5547:             my @privroles = ('dc','su');
 5548:             if ($context eq 'userroles') {
 5549:                 next if (grep(/^\Q$role\E$/,@privroles));
 5550:             } else {
 5551:                 my $possdoms = [$domain];
 5552:                 if (ref($roledoms) eq 'ARRAY') {
 5553:                    push(@{$possdoms},@{$roledoms}); 
 5554:                 }
 5555:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5556:                     if (!$nothide{$username.':'.$domain}) {
 5557:                         next;
 5558:                     }
 5559:                 }
 5560:             }
 5561:         }
 5562:         if ($withsec) {
 5563:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5564:                 $tstart.':'.$tend;
 5565:         } else {
 5566:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5567:         }
 5568:     }
 5569:     return %returnhash;
 5570: }
 5571: 
 5572: sub get_all_adhocroles {
 5573:     my ($dom) = @_;
 5574:     my @roles_by_num = ();
 5575:     my %domdefaults = &get_domain_defaults($dom);
 5576:     my (%description,%access_in_dom,%access_info);
 5577:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5578:         my $count = 0;
 5579:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5580:         my %ordered;
 5581:         foreach my $role (sort(keys(%domcurrent))) {
 5582:             my ($order,$desc,$access_in_dom);
 5583:             if (ref($domcurrent{$role}) eq 'HASH') {
 5584:                 $order = $domcurrent{$role}{'order'};
 5585:                 $desc = $domcurrent{$role}{'desc'};
 5586:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5587:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5588:             }
 5589:             if ($order eq '') {
 5590:                 $order = $count;
 5591:             }
 5592:             $ordered{$order} = $role;
 5593:             if ($desc ne '') {
 5594:                 $description{$role} = $desc;
 5595:             } else {
 5596:                 $description{$role}= $role;
 5597:             }
 5598:             $count++;
 5599:         }
 5600:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5601:             push(@roles_by_num,$ordered{$item});
 5602:         }
 5603:     }
 5604:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5605: }
 5606: 
 5607: sub get_my_adhocroles {
 5608:     my ($cid,$checkreg) = @_;
 5609:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5610:     if ($env{'request.course.id'} eq $cid) {
 5611:         $cdom = $env{'course.'.$cid.'.domain'};
 5612:         $cnum = $env{'course.'.$cid.'.num'};
 5613:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5614:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5615:         $cdom = $1;
 5616:         $cnum = $2;
 5617:         %info = &get('environment',['internal.coursecode'],
 5618:                      $cdom,$cnum);
 5619:     }
 5620:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5621:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5622:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5623:         if ($rosterhash{$user} ne '') {
 5624:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5625:             return ([],{}) if ($type eq 'auto');
 5626:         }
 5627:     }
 5628:     if (($cdom ne '') && ($cnum ne ''))  {
 5629:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5630:             my $then=$env{'user.login.time'};
 5631:             my $update=$env{'user.update.time'};
 5632:             if (!$update) {
 5633:                 $update = $then;
 5634:             }
 5635:             my @liveroles;
 5636:             foreach my $role ('dh','da') {
 5637:                 if ($env{"user.role.$role./$cdom/"}) {
 5638:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5639:                     my $limit = $update;
 5640:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5641:                         $limit = $then;
 5642:                     }
 5643:                     my $activerole = 1;
 5644:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5645:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5646:                     if ($activerole) {
 5647:                         push(@liveroles,$role);
 5648:                     }
 5649:                 }
 5650:             }
 5651:             if (@liveroles) {
 5652:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5653:                     my ($accessref,$accessinfo,%access_in_dom);
 5654:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5655:                     if (ref($roles_by_num) eq 'ARRAY') {
 5656:                         if (@{$roles_by_num}) {
 5657:                             my %settings;
 5658:                             if ($env{'request.course.id'} eq $cid) {
 5659:                                 foreach my $envkey (keys(%env)) {
 5660:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5661:                                         $settings{$1} = $env{$envkey};
 5662:                                     }
 5663:                                 }
 5664:                             } else {
 5665:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5666:                             }
 5667:                             my %setincrs;
 5668:                             if ($settings{'internal.adhocaccess'}) {
 5669:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5670:                             }
 5671:                             my @statuses;
 5672:                             if ($env{'environment.inststatus'}) {
 5673:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5674:                             }
 5675:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5676:                             if (ref($accessref) eq 'HASH') {
 5677:                                 %access_in_dom = %{$accessref};
 5678:                             }
 5679:                             foreach my $role (@{$roles_by_num}) {
 5680:                                 my ($curraccess,@okstatus,@personnel);
 5681:                                 if ($setincrs{$role}) {
 5682:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5683:                                     if ($curraccess eq 'status') {
 5684:                                         @okstatus = split(/\&/,$rest);
 5685:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5686:                                         @personnel = split(/\&/,$rest);
 5687:                                     }
 5688:                                 } else {
 5689:                                     $curraccess = $access_in_dom{$role};
 5690:                                     if (ref($accessinfo) eq 'HASH') {
 5691:                                         if ($curraccess eq 'status') {
 5692:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5693:                                                 @okstatus = @{$accessinfo->{$role}};
 5694:                                             }
 5695:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5696:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5697:                                                 @personnel = @{$accessinfo->{$role}};
 5698:                                             }
 5699:                                         }
 5700:                                     }
 5701:                                 }
 5702:                                 if ($curraccess eq 'none') {
 5703:                                     next;
 5704:                                 } elsif ($curraccess eq 'all') {
 5705:                                     push(@possroles,$role);
 5706:                                 } elsif ($curraccess eq 'dh') {
 5707:                                     if (grep(/^dh$/,@liveroles)) {
 5708:                                         push(@possroles,$role);
 5709:                                     } else {
 5710:                                         next;
 5711:                                     }
 5712:                                 } elsif ($curraccess eq 'da') {
 5713:                                     if (grep(/^da$/,@liveroles)) {
 5714:                                         push(@possroles,$role);
 5715:                                     } else {
 5716:                                         next;
 5717:                                     }
 5718:                                 } elsif ($curraccess eq 'status') {
 5719:                                     if (@okstatus) {
 5720:                                         if (!@statuses) {
 5721:                                             if (grep(/^default$/,@okstatus)) {
 5722:                                                 push(@possroles,$role);
 5723:                                             }
 5724:                                         } else {
 5725:                                             foreach my $status (@okstatus) {
 5726:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5727:                                                     push(@possroles,$role);
 5728:                                                     last;
 5729:                                                 }
 5730:                                             }
 5731:                                         }
 5732:                                     }
 5733:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5734:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5735:                                         if ($curraccess eq 'exc') {
 5736:                                             push(@possroles,$role);
 5737:                                         }
 5738:                                     } elsif ($curraccess eq 'inc') {
 5739:                                         push(@possroles,$role);
 5740:                                     }
 5741:                                 }
 5742:                             }
 5743:                         }
 5744:                     }
 5745:                 }
 5746:             }
 5747:         }
 5748:     }
 5749:     unless (ref($description) eq 'HASH') {
 5750:         if (ref($roles_by_num) eq 'ARRAY') {
 5751:             my %desc;
 5752:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5753:             $description = \%desc;
 5754:         } else {
 5755:             $description = {};
 5756:         }
 5757:     }
 5758:     return (\@possroles,$description);
 5759: }
 5760: 
 5761: # ----------------------------------------------------- Frontpage Announcements
 5762: #
 5763: #
 5764: 
 5765: sub postannounce {
 5766:     my ($server,$text)=@_;
 5767:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5768:     unless ($text=~/\w/) { $text=''; }
 5769:     return &reply('setannounce:'.&escape($text),$server);
 5770: }
 5771: 
 5772: sub getannounce {
 5773: 
 5774:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5775: 	my $announcement='';
 5776: 	while (my $line = <$fh>) { $announcement .= $line; }
 5777: 	close($fh);
 5778: 	if ($announcement=~/\w/) { 
 5779: 	    return 
 5780:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5781:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5782: 	} else {
 5783: 	    return '';
 5784: 	}
 5785:     } else {
 5786: 	return '';
 5787:     }
 5788: }
 5789: 
 5790: # ---------------------------------------------------------- Course ID routines
 5791: # Deal with domain's nohist_courseid.db files
 5792: #
 5793: 
 5794: sub courseidput {
 5795:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5796:     return unless (ref($storehash) eq 'HASH');
 5797:     my $outcome;
 5798:     if ($caller eq 'timeonly') {
 5799:         my $cids = '';
 5800:         foreach my $item (keys(%$storehash)) {
 5801:             $cids.=&escape($item).'&';
 5802:         }
 5803:         $cids=~s/\&$//;
 5804:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5805:                           $coursehome);       
 5806:     } else {
 5807:         my $items = '';
 5808:         foreach my $item (keys(%$storehash)) {
 5809:             $items.= &escape($item).'='.
 5810:                      &freeze_escape($$storehash{$item}).'&';
 5811:         }
 5812:         $items=~s/\&$//;
 5813:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5814:                           $coursehome);
 5815:     }
 5816:     if ($outcome eq 'unknown_cmd') {
 5817:         my $what;
 5818:         foreach my $cid (keys(%$storehash)) {
 5819:             $what .= &escape($cid).'=';
 5820:             foreach my $item ('description','inst_code','owner','type') {
 5821:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5822:             }
 5823:             $what =~ s/\:$/&/;
 5824:         }
 5825:         $what =~ s/\&$//;  
 5826:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5827:     } else {
 5828:         return $outcome;
 5829:     }
 5830: }
 5831: 
 5832: sub courseiddump {
 5833:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5834:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5835:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5836:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5837:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5838:     my $as_hash = 1;
 5839:     my %returnhash;
 5840:     if (!$domfilter) { $domfilter=''; }
 5841:     my %libserv = &all_library();
 5842:     foreach my $tryserver (keys(%libserv)) {
 5843:         if ( (  $hostidflag == 1 
 5844: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5845: 	     || (!defined($hostidflag)) ) {
 5846: 
 5847: 	    if (($domfilter eq '') ||
 5848: 		(&host_domain($tryserver) eq $domfilter)) {
 5849:                 my $rep;
 5850:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5851:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5852:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5853:                                 &escape($descfilter), &escape($instcodefilter), 
 5854:                                 &escape($ownerfilter), &escape($coursefilter),
 5855:                                 &escape($typefilter), &escape($regexp_ok), 
 5856:                                 $as_hash, &escape($selfenrollonly), 
 5857:                                 &escape($catfilter), $showhidden, $caller, 
 5858:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5859:                                 &escape($createdbefore), &escape($createdafter), 
 5860:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5861:                                 $reqcrsdom,&escape($reqinstcode))));
 5862:                 } else {
 5863:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5864:                              $sincefilter.':'.&escape($descfilter).':'.
 5865:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5866:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5867:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5868:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5869:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5870:                              &escape($cc_clone).':'.$cloneonly.':'.
 5871:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5872:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5873:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5874:                 }
 5875:                      
 5876:                 my @pairs=split(/\&/,$rep);
 5877:                 foreach my $item (@pairs) {
 5878:                     my ($key,$value)=split(/\=/,$item,2);
 5879:                     $key = &unescape($key);
 5880:                     next if ($key =~ /^error: 2 /);
 5881:                     my $result = &thaw_unescape($value);
 5882:                     if (ref($result) eq 'HASH') {
 5883:                         $returnhash{$key}=$result;
 5884:                     } else {
 5885:                         my @responses = split(/:/,$value);
 5886:                         my @items = ('description','inst_code','owner','type');
 5887:                         for (my $i=0; $i<@responses; $i++) {
 5888:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5889:                         }
 5890:                     }
 5891:                 }
 5892:             }
 5893:         }
 5894:     }
 5895:     return %returnhash;
 5896: }
 5897: 
 5898: sub courselastaccess {
 5899:     my ($cdom,$cnum,$hostidref) = @_;
 5900:     my %returnhash;
 5901:     if ($cdom && $cnum) {
 5902:         my $chome = &homeserver($cnum,$cdom);
 5903:         if ($chome ne 'no_host') {
 5904:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5905:             &extract_lastaccess(\%returnhash,$rep);
 5906:         }
 5907:     } else {
 5908:         if (!$cdom) { $cdom=''; }
 5909:         my %libserv = &all_library();
 5910:         foreach my $tryserver (keys(%libserv)) {
 5911:             if (ref($hostidref) eq 'ARRAY') {
 5912:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5913:             } 
 5914:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5915:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5916:                 &extract_lastaccess(\%returnhash,$rep);
 5917:             }
 5918:         }
 5919:     }
 5920:     return %returnhash;
 5921: }
 5922: 
 5923: sub extract_lastaccess {
 5924:     my ($returnhash,$rep) = @_;
 5925:     if (ref($returnhash) eq 'HASH') {
 5926:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5927:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5928:                  $rep eq '') {
 5929:             my @pairs=split(/\&/,$rep);
 5930:             foreach my $item (@pairs) {
 5931:                 my ($key,$value)=split(/\=/,$item,2);
 5932:                 $key = &unescape($key);
 5933:                 next if ($key =~ /^error: 2 /);
 5934:                 $returnhash->{$key} = &thaw_unescape($value);
 5935:             }
 5936:         }
 5937:     }
 5938:     return;
 5939: }
 5940: 
 5941: # ---------------------------------------------------------- DC e-mail
 5942: 
 5943: sub dcmailput {
 5944:     my ($domain,$msgid,$message,$server)=@_;
 5945:     my $status = &critical(
 5946:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5947:        &escape($message),$server);
 5948:     return $status;
 5949: }
 5950: 
 5951: sub dcmaildump {
 5952:     my ($dom,$startdate,$enddate,$senders) = @_;
 5953:     my %returnhash=();
 5954: 
 5955:     if (defined(&domain($dom,'primary'))) {
 5956:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5957:                                                          &escape($enddate).':';
 5958: 	my @esc_senders=map { &escape($_)} @$senders;
 5959: 	$cmd.=&escape(join('&',@esc_senders));
 5960: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5961:             my ($key,$value) = split(/\=/,$line,2);
 5962:             if (($key) && ($value)) {
 5963:                 $returnhash{&unescape($key)} = &unescape($value);
 5964:             }
 5965:         }
 5966:     }
 5967:     return %returnhash;
 5968: }
 5969: # ---------------------------------------------------------- Domain roles
 5970: 
 5971: sub get_domain_roles {
 5972:     my ($dom,$roles,$startdate,$enddate)=@_;
 5973:     if ((!defined($startdate)) || ($startdate eq '')) {
 5974:         $startdate = '.';
 5975:     }
 5976:     if ((!defined($enddate)) || ($enddate eq '')) {
 5977:         $enddate = '.';
 5978:     }
 5979:     my $rolelist;
 5980:     if (ref($roles) eq 'ARRAY') {
 5981:         $rolelist = join('&',@{$roles});
 5982:     }
 5983:     my %personnel = ();
 5984: 
 5985:     my %servers = &get_servers($dom,'library');
 5986:     foreach my $tryserver (keys(%servers)) {
 5987: 	%{$personnel{$tryserver}}=();
 5988: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5989: 					    &escape($startdate).':'.
 5990: 					    &escape($enddate).':'.
 5991: 					    &escape($rolelist), $tryserver))) {
 5992: 	    my ($key,$value) = split(/\=/,$line,2);
 5993: 	    if (($key) && ($value)) {
 5994: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5995: 	    }
 5996: 	}
 5997:     }
 5998:     return %personnel;
 5999: }
 6000: 
 6001: sub get_active_domroles {
 6002:     my ($dom,$roles) = @_;
 6003:     return () unless (ref($roles) eq 'ARRAY');
 6004:     my $now = time;
 6005:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6006:     my %domroles;
 6007:     foreach my $server (keys(%dompersonnel)) {
 6008:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6009:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6010:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6011:         }
 6012:     }
 6013:     return %domroles;
 6014: }
 6015: 
 6016: # ----------------------------------------------------------- Interval timing 
 6017: 
 6018: {
 6019: # Caches needed for speedup of navmaps
 6020: # We don't want to cache this for very long at all (5 seconds at most)
 6021: # 
 6022: # The user for whom we cache
 6023: my $cachedkey='';
 6024: # The cached times for this user
 6025: my %cachedtimes=();
 6026: # When this was last done
 6027: my $cachedtime='';
 6028: 
 6029: sub load_all_first_access {
 6030:     my ($uname,$udom,$ignorecache)=@_;
 6031:     if (($cachedkey eq $uname.':'.$udom) &&
 6032:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6033:         (!$ignorecache)) {
 6034:         return;
 6035:     }
 6036:     $cachedtime=time;
 6037:     $cachedkey=$uname.':'.$udom;
 6038:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6039: }
 6040: 
 6041: sub get_first_access {
 6042:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6043:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6044:     if ($argsymb) { $symb=$argsymb; }
 6045:     my ($map,$id,$res)=&decode_symb($symb);
 6046:     if ($argmap) { $map = $argmap; }
 6047:     if ($type eq 'course') {
 6048: 	$res='course';
 6049:     } elsif ($type eq 'map') {
 6050: 	$res=&symbread($map);
 6051:     } else {
 6052: 	$res=$symb;
 6053:     }
 6054:     &load_all_first_access($uname,$udom,$ignorecache);
 6055:     return $cachedtimes{"$courseid\0$res"};
 6056: }
 6057: 
 6058: sub set_first_access {
 6059:     my ($type,$interval)=@_;
 6060:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6061:     my ($map,$id,$res)=&decode_symb($symb);
 6062:     if ($type eq 'course') {
 6063: 	$res='course';
 6064:     } elsif ($type eq 'map') {
 6065: 	$res=&symbread($map);
 6066:     } else {
 6067: 	$res=$symb;
 6068:     }
 6069:     $cachedkey='';
 6070:     my $firstaccess=&get_first_access($type,$symb,$map);
 6071:     if ($firstaccess) {
 6072:         &logthis("First access time already set ($firstaccess) when attempting ".
 6073:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6074:                  "in $courseid");
 6075:         return 'already_set';
 6076:     } else {
 6077:         my $start = time;
 6078: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6079:                           $udom,$uname);
 6080:         if ($putres eq 'ok') {
 6081:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6082:                  $udom,$uname); 
 6083:             &appenv(
 6084:                      {
 6085:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6086:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6087:                      }
 6088:                   );
 6089:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6090:                 $cachedtimes{"$courseid\0$res"} = $start;
 6091:             }
 6092:         } elsif ($putres ne 'refused') {
 6093:             &logthis("Result: $putres when attempting to set first access time ".
 6094:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6095:         }
 6096:         return $putres;
 6097:     }
 6098:     return 'already_set';
 6099: }
 6100: }
 6101: 
 6102: # --------------------------------------------- Set Expire Date for Spreadsheet
 6103: 
 6104: sub expirespread {
 6105:     my ($uname,$udom,$stype,$usymb)=@_;
 6106:     my $cid=$env{'request.course.id'}; 
 6107:     if ($cid) {
 6108:        my $now=time;
 6109:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6110:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6111:                             $env{'course.'.$cid.'.num'}.
 6112: 	        	    ':nohist_expirationdates:'.
 6113:                             &escape($key).'='.$now,
 6114:                             $env{'course.'.$cid.'.home'})
 6115:     }
 6116:     return 'ok';
 6117: }
 6118: 
 6119: # ----------------------------------------------------- Devalidate Spreadsheets
 6120: 
 6121: sub devalidate {
 6122:     my ($symb,$uname,$udom)=@_;
 6123:     my $cid=$env{'request.course.id'}; 
 6124:     if ($cid) {
 6125:         # delete the stored spreadsheets for
 6126:         # - the student level sheet of this user in course's homespace
 6127:         # - the assessment level sheet for this resource 
 6128:         #   for this user in user's homespace
 6129: 	# - current conditional state info
 6130: 	my $key=$uname.':'.$udom.':';
 6131:         my $status=
 6132: 	    &del('nohist_calculatedsheets',
 6133: 		 [$key.'studentcalc:'],
 6134: 		 $env{'course.'.$cid.'.domain'},
 6135: 		 $env{'course.'.$cid.'.num'})
 6136: 		.' '.
 6137: 	    &del('nohist_calculatedsheets_'.$cid,
 6138: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6139:         unless ($status eq 'ok ok') {
 6140:            &logthis('Could not devalidate spreadsheet '.
 6141:                     $uname.' at '.$udom.' for '.
 6142: 		    $symb.': '.$status);
 6143:         }
 6144: 	&delenv('user.state.'.$cid);
 6145:     }
 6146: }
 6147: 
 6148: sub get_scalar {
 6149:     my ($string,$end) = @_;
 6150:     my $value;
 6151:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6152: 	$value = $1;
 6153:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6154: 	$value = $1;
 6155:     }
 6156:     return &unescape($value);
 6157: }
 6158: 
 6159: sub array2str {
 6160:   my (@array) = @_;
 6161:   my $result=&arrayref2str(\@array);
 6162:   $result=~s/^__ARRAY_REF__//;
 6163:   $result=~s/__END_ARRAY_REF__$//;
 6164:   return $result;
 6165: }
 6166: 
 6167: sub arrayref2str {
 6168:   my ($arrayref) = @_;
 6169:   my $result='__ARRAY_REF__';
 6170:   foreach my $elem (@$arrayref) {
 6171:     if(ref($elem) eq 'ARRAY') {
 6172:       $result.=&arrayref2str($elem).'&';
 6173:     } elsif(ref($elem) eq 'HASH') {
 6174:       $result.=&hashref2str($elem).'&';
 6175:     } elsif(ref($elem)) {
 6176:       #print("Got a ref of ".(ref($elem))." skipping.");
 6177:     } else {
 6178:       $result.=&escape($elem).'&';
 6179:     }
 6180:   }
 6181:   $result=~s/\&$//;
 6182:   $result .= '__END_ARRAY_REF__';
 6183:   return $result;
 6184: }
 6185: 
 6186: sub hash2str {
 6187:   my (%hash) = @_;
 6188:   my $result=&hashref2str(\%hash);
 6189:   $result=~s/^__HASH_REF__//;
 6190:   $result=~s/__END_HASH_REF__$//;
 6191:   return $result;
 6192: }
 6193: 
 6194: sub hashref2str {
 6195:   my ($hashref)=@_;
 6196:   my $result='__HASH_REF__';
 6197:   foreach my $key (sort(keys(%$hashref))) {
 6198:     if (ref($key) eq 'ARRAY') {
 6199:       $result.=&arrayref2str($key).'=';
 6200:     } elsif (ref($key) eq 'HASH') {
 6201:       $result.=&hashref2str($key).'=';
 6202:     } elsif (ref($key)) {
 6203:       $result.='=';
 6204:       #print("Got a ref of ".(ref($key))." skipping.");
 6205:     } else {
 6206: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6207:     }
 6208: 
 6209:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6210:       $result.=&arrayref2str($hashref->{$key}).'&';
 6211:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6212:       $result.=&hashref2str($hashref->{$key}).'&';
 6213:     } elsif(ref($hashref->{$key})) {
 6214:        $result.='&';
 6215:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6216:     } else {
 6217:       $result.=&escape($hashref->{$key}).'&';
 6218:     }
 6219:   }
 6220:   $result=~s/\&$//;
 6221:   $result .= '__END_HASH_REF__';
 6222:   return $result;
 6223: }
 6224: 
 6225: sub str2hash {
 6226:     my ($string)=@_;
 6227:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6228:     return %$hash;
 6229: }
 6230: 
 6231: sub str2hashref {
 6232:   my ($string) = @_;
 6233: 
 6234:   my %hash;
 6235: 
 6236:   if($string !~ /^__HASH_REF__/) {
 6237:       if (! ($string eq '' || !defined($string))) {
 6238: 	  $hash{'error'}='Not hash reference';
 6239:       }
 6240:       return (\%hash, $string);
 6241:   }
 6242: 
 6243:   $string =~ s/^__HASH_REF__//;
 6244: 
 6245:   while($string !~ /^__END_HASH_REF__/) {
 6246:       #key
 6247:       my $key='';
 6248:       if($string =~ /^__HASH_REF__/) {
 6249:           ($key, $string)=&str2hashref($string);
 6250:           if(defined($key->{'error'})) {
 6251:               $hash{'error'}='Bad data';
 6252:               return (\%hash, $string);
 6253:           }
 6254:       } elsif($string =~ /^__ARRAY_REF__/) {
 6255:           ($key, $string)=&str2arrayref($string);
 6256:           if($key->[0] eq 'Array reference error') {
 6257:               $hash{'error'}='Bad data';
 6258:               return (\%hash, $string);
 6259:           }
 6260:       } else {
 6261:           $string =~ s/^(.*?)=//;
 6262: 	  $key=&unescape($1);
 6263:       }
 6264:       $string =~ s/^=//;
 6265: 
 6266:       #value
 6267:       my $value='';
 6268:       if($string =~ /^__HASH_REF__/) {
 6269:           ($value, $string)=&str2hashref($string);
 6270:           if(defined($value->{'error'})) {
 6271:               $hash{'error'}='Bad data';
 6272:               return (\%hash, $string);
 6273:           }
 6274:       } elsif($string =~ /^__ARRAY_REF__/) {
 6275:           ($value, $string)=&str2arrayref($string);
 6276:           if($value->[0] eq 'Array reference error') {
 6277:               $hash{'error'}='Bad data';
 6278:               return (\%hash, $string);
 6279:           }
 6280:       } else {
 6281: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6282:       }
 6283:       $string =~ s/^&//;
 6284: 
 6285:       $hash{$key}=$value;
 6286:   }
 6287: 
 6288:   $string =~ s/^__END_HASH_REF__//;
 6289: 
 6290:   return (\%hash, $string);
 6291: }
 6292: 
 6293: sub str2array {
 6294:     my ($string)=@_;
 6295:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6296:     return @$array;
 6297: }
 6298: 
 6299: sub str2arrayref {
 6300:   my ($string) = @_;
 6301:   my @array;
 6302: 
 6303:   if($string !~ /^__ARRAY_REF__/) {
 6304:       if (! ($string eq '' || !defined($string))) {
 6305: 	  $array[0]='Array reference error';
 6306:       }
 6307:       return (\@array, $string);
 6308:   }
 6309: 
 6310:   $string =~ s/^__ARRAY_REF__//;
 6311: 
 6312:   while($string !~ /^__END_ARRAY_REF__/) {
 6313:       my $value='';
 6314:       if($string =~ /^__HASH_REF__/) {
 6315:           ($value, $string)=&str2hashref($string);
 6316:           if(defined($value->{'error'})) {
 6317:               $array[0] ='Array reference error';
 6318:               return (\@array, $string);
 6319:           }
 6320:       } elsif($string =~ /^__ARRAY_REF__/) {
 6321:           ($value, $string)=&str2arrayref($string);
 6322:           if($value->[0] eq 'Array reference error') {
 6323:               $array[0] ='Array reference error';
 6324:               return (\@array, $string);
 6325:           }
 6326:       } else {
 6327: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6328:       }
 6329:       $string =~ s/^&//;
 6330: 
 6331:       push(@array, $value);
 6332:   }
 6333: 
 6334:   $string =~ s/^__END_ARRAY_REF__//;
 6335: 
 6336:   return (\@array, $string);
 6337: }
 6338: 
 6339: # -------------------------------------------------------------------Temp Store
 6340: 
 6341: sub tmpreset {
 6342:   my ($symb,$namespace,$domain,$stuname) = @_;
 6343:   if (!$symb) {
 6344:     $symb=&symbread();
 6345:     if (!$symb) { $symb= $env{'request.url'}; }
 6346:   }
 6347:   $symb=escape($symb);
 6348: 
 6349:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6350:   $namespace=~s/\//\_/g;
 6351:   $namespace=~s/\W//g;
 6352: 
 6353:   if (!$domain) { $domain=$env{'user.domain'}; }
 6354:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6355:   if ($domain eq 'public' && $stuname eq 'public') {
 6356:       $stuname=&get_requestor_ip();
 6357:   }
 6358:   my $path=LONCAPA::tempdir();
 6359:   my %hash;
 6360:   if (tie(%hash,'GDBM_File',
 6361: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6362: 	  &GDBM_WRCREAT(),0640)) {
 6363:     foreach my $key (keys(%hash)) {
 6364:       if ($key=~ /:$symb/) {
 6365: 	delete($hash{$key});
 6366:       }
 6367:     }
 6368:   }
 6369: }
 6370: 
 6371: sub tmpstore {
 6372:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6373: 
 6374:   if (!$symb) {
 6375:     $symb=&symbread();
 6376:     if (!$symb) { $symb= $env{'request.url'}; }
 6377:   }
 6378:   $symb=escape($symb);
 6379: 
 6380:   if (!$namespace) {
 6381:     # I don't think we would ever want to store this for a course.
 6382:     # it seems this will only be used if we don't have a course.
 6383:     #$namespace=$env{'request.course.id'};
 6384:     #if (!$namespace) {
 6385:       $namespace=$env{'request.state'};
 6386:     #}
 6387:   }
 6388:   $namespace=~s/\//\_/g;
 6389:   $namespace=~s/\W//g;
 6390:   if (!$domain) { $domain=$env{'user.domain'}; }
 6391:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6392:   if ($domain eq 'public' && $stuname eq 'public') {
 6393:       $stuname=&get_requestor_ip();
 6394:   }
 6395:   my $now=time;
 6396:   my %hash;
 6397:   my $path=LONCAPA::tempdir();
 6398:   if (tie(%hash,'GDBM_File',
 6399: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6400: 	  &GDBM_WRCREAT(),0640)) {
 6401:     $hash{"version:$symb"}++;
 6402:     my $version=$hash{"version:$symb"};
 6403:     my $allkeys=''; 
 6404:     foreach my $key (keys(%$storehash)) {
 6405:       $allkeys.=$key.':';
 6406:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6407:     }
 6408:     $hash{"$version:$symb:timestamp"}=$now;
 6409:     $allkeys.='timestamp';
 6410:     $hash{"$version:keys:$symb"}=$allkeys;
 6411:     if (untie(%hash)) {
 6412:       return 'ok';
 6413:     } else {
 6414:       return "error:$!";
 6415:     }
 6416:   } else {
 6417:     return "error:$!";
 6418:   }
 6419: }
 6420: 
 6421: # -----------------------------------------------------------------Temp Restore
 6422: 
 6423: sub tmprestore {
 6424:   my ($symb,$namespace,$domain,$stuname) = @_;
 6425: 
 6426:   if (!$symb) {
 6427:     $symb=&symbread();
 6428:     if (!$symb) { $symb= $env{'request.url'}; }
 6429:   }
 6430:   $symb=escape($symb);
 6431: 
 6432:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6433: 
 6434:   if (!$domain) { $domain=$env{'user.domain'}; }
 6435:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6436:   if ($domain eq 'public' && $stuname eq 'public') {
 6437:       $stuname=&get_requestor_ip();
 6438:   }
 6439:   my %returnhash;
 6440:   $namespace=~s/\//\_/g;
 6441:   $namespace=~s/\W//g;
 6442:   my %hash;
 6443:   my $path=LONCAPA::tempdir();
 6444:   if (tie(%hash,'GDBM_File',
 6445: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6446: 	  &GDBM_READER(),0640)) {
 6447:     my $version=$hash{"version:$symb"};
 6448:     $returnhash{'version'}=$version;
 6449:     my $scope;
 6450:     for ($scope=1;$scope<=$version;$scope++) {
 6451:       my $vkeys=$hash{"$scope:keys:$symb"};
 6452:       my @keys=split(/:/,$vkeys);
 6453:       my $key;
 6454:       $returnhash{"$scope:keys"}=$vkeys;
 6455:       foreach $key (@keys) {
 6456: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6457: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6458:       }
 6459:     }
 6460:     if (!(untie(%hash))) {
 6461:       return "error:$!";
 6462:     }
 6463:   } else {
 6464:     return "error:$!";
 6465:   }
 6466:   return %returnhash;
 6467: }
 6468: 
 6469: # ----------------------------------------------------------------------- Store
 6470: 
 6471: sub store {
 6472:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6473:     my $home='';
 6474: 
 6475:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6476: 
 6477:     $symb=&symbclean($symb);
 6478:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6479: 
 6480:     if (!$domain) { $domain=$env{'user.domain'}; }
 6481:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6482: 
 6483:     &devalidate($symb,$stuname,$domain);
 6484: 
 6485:     $symb=escape($symb);
 6486:     if (!$namespace) { 
 6487:        unless ($namespace=$env{'request.course.id'}) { 
 6488:           return ''; 
 6489:        } 
 6490:     }
 6491:     if (!$home) { $home=$env{'user.home'}; }
 6492: 
 6493:     $$storehash{'ip'}=&get_requestor_ip();
 6494:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6495: 
 6496:     my $namevalue='';
 6497:     foreach my $key (keys(%$storehash)) {
 6498:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6499:     }
 6500:     $namevalue=~s/\&$//;
 6501:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6502:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6503: }
 6504: 
 6505: # -------------------------------------------------------------- Critical Store
 6506: 
 6507: sub cstore {
 6508:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6509:     my $home='';
 6510: 
 6511:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6512: 
 6513:     $symb=&symbclean($symb);
 6514:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6515: 
 6516:     if (!$domain) { $domain=$env{'user.domain'}; }
 6517:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6518: 
 6519:     &devalidate($symb,$stuname,$domain);
 6520: 
 6521:     $symb=escape($symb);
 6522:     if (!$namespace) { 
 6523:        unless ($namespace=$env{'request.course.id'}) { 
 6524:           return ''; 
 6525:        } 
 6526:     }
 6527:     if (!$home) { $home=$env{'user.home'}; }
 6528: 
 6529:     $$storehash{'ip'}=&get_requestor_ip();
 6530:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6531: 
 6532:     my $namevalue='';
 6533:     foreach my $key (keys(%$storehash)) {
 6534:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6535:     }
 6536:     $namevalue=~s/\&$//;
 6537:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6538:     return critical
 6539:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6540: }
 6541: 
 6542: # --------------------------------------------------------------------- Restore
 6543: 
 6544: sub restore {
 6545:     my ($symb,$namespace,$domain,$stuname) = @_;
 6546:     my $home='';
 6547: 
 6548:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6549: 
 6550:     if (!$symb) {
 6551:         return if ($namespace eq 'courserequests');
 6552:         unless ($symb=escape(&symbread())) { return ''; }
 6553:     } else {
 6554:         unless ($namespace eq 'courserequests') {
 6555:             $symb=&escape(&symbclean($symb));
 6556:         }
 6557:     }
 6558:     if (!$namespace) { 
 6559:        unless ($namespace=$env{'request.course.id'}) { 
 6560:           return ''; 
 6561:        } 
 6562:     }
 6563:     if (!$domain) { $domain=$env{'user.domain'}; }
 6564:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6565:     if (!$home) { $home=$env{'user.home'}; }
 6566:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6567: 
 6568:     my %returnhash=();
 6569:     foreach my $line (split(/\&/,$answer)) {
 6570: 	my ($name,$value)=split(/\=/,$line);
 6571:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6572:     }
 6573:     my $version;
 6574:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6575:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6576:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6577:        }
 6578:     }
 6579:     return %returnhash;
 6580: }
 6581: 
 6582: # ---------------------------------------------------------- Course Description
 6583: #
 6584: #  
 6585: 
 6586: sub coursedescription {
 6587:     my ($courseid,$args)=@_;
 6588:     $courseid=~s/^\///;
 6589:     $courseid=~s/\_/\//g;
 6590:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6591:     my $chome=&homeserver($cnum,$cdomain);
 6592:     my $normalid=$cdomain.'_'.$cnum;
 6593:     # need to always cache even if we get errors otherwise we keep 
 6594:     # trying and trying and trying to get the course description.
 6595:     my %envhash=();
 6596:     my %returnhash=();
 6597:     
 6598:     my $expiretime=600;
 6599:     if ($env{'request.course.id'} eq $normalid) {
 6600: 	$expiretime=120;
 6601:     }
 6602: 
 6603:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6604:     if (!$args->{'freshen_cache'}
 6605: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6606: 	foreach my $key (keys(%env)) {
 6607: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6608: 	    my ($setting) = $1;
 6609: 	    $returnhash{$setting} = $env{$key};
 6610: 	}
 6611: 	return %returnhash;
 6612:     }
 6613: 
 6614:     # get the data again
 6615: 
 6616:     if (!$args->{'one_time'}) {
 6617: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6618:     }
 6619: 
 6620:     if ($chome ne 'no_host') {
 6621:        %returnhash=&dump('environment',$cdomain,$cnum);
 6622:        if (!exists($returnhash{'con_lost'})) {
 6623: 	   my $username = $env{'user.name'}; # Defult username
 6624: 	   if(defined $args->{'user'}) {
 6625: 	       $username = $args->{'user'};
 6626: 	   }
 6627:            $returnhash{'home'}= $chome;
 6628: 	   $returnhash{'domain'} = $cdomain;
 6629: 	   $returnhash{'num'} = $cnum;
 6630:            if (!defined($returnhash{'type'})) {
 6631:                $returnhash{'type'} = 'Course';
 6632:            }
 6633:            while (my ($name,$value) = each %returnhash) {
 6634:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6635:            }
 6636:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6637:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6638: 	       $username.'_'.$cdomain.'_'.$cnum;
 6639:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6640:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6641:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6642:        }
 6643:     }
 6644:     if (!$args->{'one_time'}) {
 6645: 	&appenv(\%envhash);
 6646:     }
 6647:     return %returnhash;
 6648: }
 6649: 
 6650: sub update_released_required {
 6651:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6652:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6653:         $cid = $env{'request.course.id'};
 6654:         $cdom = $env{'course.'.$cid.'.domain'};
 6655:         $cnum = $env{'course.'.$cid.'.num'};
 6656:         $chome = $env{'course.'.$cid.'.home'};
 6657:     }
 6658:     if ($needsrelease) {
 6659:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6660:         my $needsupdate;
 6661:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6662:             $needsupdate = 1;
 6663:         } else {
 6664:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6665:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6666:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6667:                 $needsupdate = 1;
 6668:             }
 6669:         }
 6670:         if ($needsupdate) {
 6671:             my %needshash = (
 6672:                              'internal.releaserequired' => $needsrelease,
 6673:                             );
 6674:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6675:             if ($putresult eq 'ok') {
 6676:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6677:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6678:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6679:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6680:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6681:                 }
 6682:             }
 6683:         }
 6684:     }
 6685:     return;
 6686: }
 6687: 
 6688: # -------------------------------------------------See if a user is privileged
 6689: 
 6690: sub privileged {
 6691:     my ($username,$domain,$possdomains,$possroles)=@_;
 6692:     my $now = time;
 6693:     my $roles;
 6694:     if (ref($possroles) eq 'ARRAY') {
 6695:         $roles = $possroles; 
 6696:     } else {
 6697:         $roles = ['dc','su'];
 6698:     }
 6699:     if (ref($possdomains) eq 'ARRAY') {
 6700:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6701:         foreach my $dom (@{$possdomains}) {
 6702:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6703:                 (ref($privileged{$dom}) eq 'HASH')) {
 6704:                 foreach my $role (@{$roles}) {
 6705:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6706:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6707:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6708:                             return 1 unless (($end && $end < $now) ||
 6709:                                              ($start && $start > $now));
 6710:                         }
 6711:                     }
 6712:                 }
 6713:             }
 6714:         }
 6715:     } else {
 6716:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6717:         my $now = time;
 6718: 
 6719:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6720:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6721:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6722:                 return 1 unless ($tend && $tend < $now) 
 6723:                         or ($tstart && $tstart > $now);
 6724:             }
 6725:         }
 6726:     }
 6727:     return 0;
 6728: }
 6729: 
 6730: sub privileged_by_domain {
 6731:     my ($domains,$roles) = @_;
 6732:     my %privileged = ();
 6733:     my $cachetime = 60*60*24;
 6734:     my $now = time;
 6735:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6736:         return %privileged;
 6737:     }
 6738:     foreach my $dom (@{$domains}) {
 6739:         next if (ref($privileged{$dom}) eq 'HASH');
 6740:         my $needroles;
 6741:         foreach my $role (@{$roles}) {
 6742:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6743:             if (defined($cached)) {
 6744:                 if (ref($result) eq 'HASH') {
 6745:                     $privileged{$dom}{$role} = $result;
 6746:                 }
 6747:             } else {
 6748:                 $needroles = 1;
 6749:             }
 6750:         }
 6751:         if ($needroles) {
 6752:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6753:             $privileged{$dom} = {};
 6754:             foreach my $server (keys(%dompersonnel)) {
 6755:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6756:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6757:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6758:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6759:                         next if ($end && $end < $now);
 6760:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6761:                             $dompersonnel{$server}{$item};
 6762:                     }
 6763:                 }
 6764:             }
 6765:             if (ref($privileged{$dom}) eq 'HASH') {
 6766:                 foreach my $role (@{$roles}) {
 6767:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6768:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6769:                     } else {
 6770:                         my %hash = ();
 6771:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6772:                     }
 6773:                 }
 6774:             }
 6775:         }
 6776:     }
 6777:     return %privileged;
 6778: }
 6779: 
 6780: # -------------------------------------------------------- Get user privileges
 6781: 
 6782: sub rolesinit {
 6783:     my ($domain, $username) = @_;
 6784:     my %userroles = ('user.login.time' => time);
 6785:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6786: 
 6787:     # firstaccess and timerinterval are related to timed maps/resources. 
 6788:     # also, blocking can be triggered by an activating timer
 6789:     # it's saved in the user's %env.
 6790:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6791:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6792:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6793:         %timerintchk, %timerintenv);
 6794: 
 6795:     foreach my $key (keys(%firstaccess)) {
 6796:         my ($cid, $rest) = split(/\0/, $key);
 6797:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6798:     }
 6799: 
 6800:     foreach my $key (keys(%timerinterval)) {
 6801:         my ($cid,$rest) = split(/\0/,$key);
 6802:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6803:     }
 6804: 
 6805:     my %allroles=();
 6806:     my %allgroups=();
 6807: 
 6808:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6809:         my $role = $rolesdump{$area};
 6810:         $area =~ s/\_\w\w$//;
 6811: 
 6812:         my ($trole, $tend, $tstart, $group_privs);
 6813: 
 6814:         if ($role =~ /^cr/) {
 6815:         # Custom role, defined by a user 
 6816:         # e.g., user.role.cr/msu/smith/mynewrole
 6817:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6818:                 $trole = $1;
 6819:                 ($tend, $tstart) = split('_', $2);
 6820:             } else {
 6821:                 $trole = $role;
 6822:             }
 6823:         } elsif ($role =~ m|^gr/|) {
 6824:         # Role of member in a group, defined within a course/community
 6825:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6826:             ($trole, $tend, $tstart) = split(/_/, $role);
 6827:             next if $tstart eq '-1';
 6828:             ($trole, $group_privs) = split(/\//, $trole);
 6829:             $group_privs = &unescape($group_privs);
 6830:         } else {
 6831:         # Just a normal role, defined in roles.tab
 6832:             ($trole, $tend, $tstart) = split(/_/,$role);
 6833:         }
 6834: 
 6835:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6836:                  $username);
 6837:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6838: 
 6839:         # role expired or not available yet?
 6840:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6841:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6842: 
 6843:         next if $area eq '' or $trole eq '';
 6844: 
 6845:         my $spec = "$trole.$area";
 6846:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6847: 
 6848:         if ($trole =~ /^cr\//) {
 6849:         # Custom role, defined by a user
 6850:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6851:         } elsif ($trole eq 'gr') {
 6852:         # Role of a member in a group, defined within a course/community
 6853:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6854:             next;
 6855:         } else {
 6856:         # Normal role, defined in roles.tab
 6857:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6858:         }
 6859: 
 6860:         my $cid = $tdomain.'_'.$trest;
 6861:         unless ($firstaccchk{$cid}) {
 6862:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6863:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6864:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6865:                         $coursetimerstarts{$cid}{$item}; 
 6866:                 }
 6867:             }
 6868:             $firstaccchk{$cid} = 1;
 6869:         }
 6870:         unless ($timerintchk{$cid}) {
 6871:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6872:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6873:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6874:                        $coursetimerintervals{$cid}{$item};
 6875:                 }
 6876:             }
 6877:             $timerintchk{$cid} = 1;
 6878:         }
 6879:     }
 6880: 
 6881:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6882:                                                           \%allroles, \%allgroups);
 6883:     $env{'user.adv'} = $userroles{'user.adv'};
 6884:     $env{'user.rar'} = $userroles{'user.rar'};
 6885: 
 6886:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6887: }
 6888: 
 6889: sub set_arearole {
 6890:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6891:     unless ($nolog) {
 6892: # log the associated role with the area
 6893:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6894:     }
 6895:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6896: }
 6897: 
 6898: sub custom_roleprivs {
 6899:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6900:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6901:     my $homsvr = &homeserver($rauthor,$rdomain);
 6902:     if (&hostname($homsvr) ne '') {
 6903:         my ($rdummy,$roledef)=
 6904:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6905:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6906:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6907:             if (defined($syspriv)) {
 6908:                 if ($trest =~ /^$match_community$/) {
 6909:                     $syspriv =~ s/bre\&S//; 
 6910:                 }
 6911:                 $$allroles{'cm./'}.=':'.$syspriv;
 6912:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6913:             }
 6914:             if ($tdomain ne '') {
 6915:                 if (defined($dompriv)) {
 6916:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6917:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6918:                 }
 6919:                 if (($trest ne '') && (defined($coursepriv))) {
 6920:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6921:                         my $rolename = $1;
 6922:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6923:                     }
 6924:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6925:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6926:                 }
 6927:             }
 6928:         }
 6929:     }
 6930: }
 6931: 
 6932: sub course_adhocrole_privs {
 6933:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6934:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6935:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6936:         my (%currprivs,%storeprivs);
 6937:         foreach my $item (split(/:/,$coursepriv)) {
 6938:             my ($priv,$restrict) = split(/\&/,$item);
 6939:             $currprivs{$priv} = $restrict;
 6940:         }
 6941:         my (%possadd,%possremove,%full);
 6942:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6943:             my ($priv,$restrict)=split(/\&/,$item);
 6944:             $full{$priv} = $restrict;
 6945:         }
 6946:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6947:             next if ($item eq '');
 6948:             my ($rule,$rest) = split(/=/,$item);
 6949:             next unless (($rule eq 'off') || ($rule eq 'on'));
 6950:             foreach my $priv (split(/:/,$rest)) {
 6951:                 if ($priv ne '') {
 6952:                     if ($rule eq 'off') {
 6953:                         $possremove{$priv} = 1;
 6954:                     } else {
 6955:                         $possadd{$priv} = 1;
 6956:                     }
 6957:                 }
 6958:             }
 6959:         }
 6960:         foreach my $priv (sort(keys(%full))) {
 6961:             if (exists($currprivs{$priv})) {
 6962:                 unless (exists($possremove{$priv})) {
 6963:                     $storeprivs{$priv} = $currprivs{$priv};
 6964:                 }
 6965:             } elsif (exists($possadd{$priv})) {
 6966:                 $storeprivs{$priv} = $full{$priv};
 6967:             }
 6968:         }
 6969:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6970:     }
 6971:     return $coursepriv;
 6972: }
 6973: 
 6974: sub group_roleprivs {
 6975:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6976:     my $access = 1;
 6977:     my $now = time;
 6978:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6979:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6980:     if ($access) {
 6981:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6982:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6983:     }
 6984: }
 6985: 
 6986: sub standard_roleprivs {
 6987:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6988:     if (defined($pr{$trole.':s'})) {
 6989:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6990:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6991:     }
 6992:     if ($tdomain ne '') {
 6993:         if (defined($pr{$trole.':d'})) {
 6994:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6995:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6996:         }
 6997:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6998:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6999:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7000:         }
 7001:     }
 7002: }
 7003: 
 7004: sub set_userprivs {
 7005:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7006:     my $author=0;
 7007:     my $adv=0;
 7008:     my $rar=0;
 7009:     my %grouproles = ();
 7010:     if (keys(%{$allgroups}) > 0) {
 7011:         my @groupkeys; 
 7012:         foreach my $role (keys(%{$allroles})) {
 7013:             push(@groupkeys,$role);
 7014:         }
 7015:         if (ref($groups_roles) eq 'HASH') {
 7016:             foreach my $key (keys(%{$groups_roles})) {
 7017:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7018:                     push(@groupkeys,$key);
 7019:                 }
 7020:             }
 7021:         }
 7022:         if (@groupkeys > 0) {
 7023:             foreach my $role (@groupkeys) {
 7024:                 my ($trole,$area,$sec,$extendedarea);
 7025:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7026:                     $trole = $1;
 7027:                     $area = $2;
 7028:                     $sec = $3;
 7029:                     $extendedarea = $area.$sec;
 7030:                     if (exists($$allgroups{$area})) {
 7031:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7032:                             my $spec = $trole.'.'.$extendedarea;
 7033:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7034:                                                 $$allgroups{$area}{$group};
 7035:                         }
 7036:                     }
 7037:                 }
 7038:             }
 7039:         }
 7040:     }
 7041:     foreach my $group (keys(%grouproles)) {
 7042:         $$allroles{$group} = $grouproles{$group};
 7043:     }
 7044:     foreach my $role (keys(%{$allroles})) {
 7045:         my %thesepriv;
 7046:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7047:         foreach my $item (split(/:/,$$allroles{$role})) {
 7048:             if ($item ne '') {
 7049:                 my ($privilege,$restrictions)=split(/&/,$item);
 7050:                 if ($restrictions eq '') {
 7051:                     $thesepriv{$privilege}='F';
 7052:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7053:                     $thesepriv{$privilege}.=$restrictions;
 7054:                 }
 7055:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7056:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7057:             }
 7058:         }
 7059:         my $thesestr='';
 7060:         foreach my $priv (sort(keys(%thesepriv))) {
 7061: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7062: 	}
 7063:         $userroles->{'user.priv.'.$role} = $thesestr;
 7064:     }
 7065:     return ($author,$adv,$rar);
 7066: }
 7067: 
 7068: sub role_status {
 7069:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7070:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7071:         my ($one,$two) = split(m{\./},$rolekey,2);
 7072:         (undef,undef,$$role) = split(/\./,$one,3);
 7073:         unless (!defined($$role) || $$role eq '') {
 7074:             $$where = '/'.$two;
 7075:             $$trolecode=$$role.'.'.$$where;
 7076:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7077:             $$tstatus='is';
 7078:             if ($$tstart && $$tstart>$update) {
 7079:                 $$tstatus='future';
 7080:                 if ($$tstart<$now) {
 7081:                     if ($$tstart && $$tstart>$refresh) {
 7082:                         if (($$where ne '') && ($$role ne '')) {
 7083:                             my (%allroles,%allgroups,$group_privs,
 7084:                                 %groups_roles,@rolecodes);
 7085:                             my %userroles = (
 7086:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7087:                             );
 7088:                             @rolecodes = ('cm'); 
 7089:                             my $spec=$$role.'.'.$$where;
 7090:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7091:                             if ($$role =~ /^cr\//) {
 7092:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7093:                                 push(@rolecodes,'cr');
 7094:                             } elsif ($$role eq 'gr') {
 7095:                                 push(@rolecodes,$$role);
 7096:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7097:                                                     $env{'user.name'});
 7098:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7099:                                 (undef,my $group_privs) = split(/\//,$trole);
 7100:                                 $group_privs = &unescape($group_privs);
 7101:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7102:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7103:                                 &get_groups_roles($tdomain,$trest,
 7104:                                                   \%course_roles,\@rolecodes,
 7105:                                                   \%groups_roles);
 7106:                             } else {
 7107:                                 push(@rolecodes,$$role);
 7108:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7109:                             }
 7110:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7111:                                                                    \%groups_roles);
 7112:                             &appenv(\%userroles,\@rolecodes);
 7113:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7114:                         }
 7115:                     }
 7116:                     $$tstatus = 'is';
 7117:                 }
 7118:             }
 7119:             if ($$tend) {
 7120:                 if ($$tend<$update) {
 7121:                     $$tstatus='expired';
 7122:                 } elsif ($$tend<$now) {
 7123:                     $$tstatus='will_not';
 7124:                 }
 7125:             }
 7126:         }
 7127:     }
 7128: }
 7129: 
 7130: sub get_groups_roles {
 7131:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7132:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7133:                   (ref($rolecodes) eq 'ARRAY') && 
 7134:                   (ref($groups_roles) eq 'HASH')); 
 7135:     if (keys(%{$cdom_courseroles}) > 0) {
 7136:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7137:         if ($cdom ne '' && $cnum ne '') {
 7138:             foreach my $key (keys(%{$cdom_courseroles})) {
 7139:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7140:                     my $crsrole = $1;
 7141:                     my $crssec = $2;
 7142:                     if ($crsrole =~ /^cr/) {
 7143:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7144:                             push(@{$rolecodes},'cr');
 7145:                         }
 7146:                     } else {
 7147:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7148:                             push(@{$rolecodes},$crsrole);
 7149:                         }
 7150:                     }
 7151:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7152:                     if ($crssec ne '') {
 7153:                         $rolekey .= "/$crssec";
 7154:                     }
 7155:                     $rolekey .= './';
 7156:                     $groups_roles->{$rolekey} = $rolecodes;
 7157:                 }
 7158:             }
 7159:         }
 7160:     }
 7161:     return;
 7162: }
 7163: 
 7164: sub delete_env_groupprivs {
 7165:     my ($where,$courseroles,$possroles) = @_;
 7166:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7167:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7168:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7169:         %{$courseroles->{$udom}} =
 7170:             &get_my_roles('','','userroles',['active'],
 7171:                           $possroles,[$udom],1);
 7172:     }
 7173:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7174:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7175:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7176:             my $area = '/'.$cdom.'/'.$cnum;
 7177:             my $privkey = "user.priv.$crsrole.$area";
 7178:             if ($crssec ne '') {
 7179:                 $privkey .= '/'.$crssec;
 7180:             }
 7181:             $privkey .= ".$area/$group";
 7182:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7183:         }
 7184:     }
 7185:     return;
 7186: }
 7187: 
 7188: sub check_adhoc_privs {
 7189:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7190:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7191:     if ($sec) {
 7192:         $cckey .= '/'.$sec;
 7193:     } 
 7194:     my $setprivs;
 7195:     if ($env{$cckey}) {
 7196:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7197:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7198:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7199:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7200:             $setprivs = 1;
 7201:         }
 7202:     } else {
 7203:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7204:         $setprivs = 1;
 7205:     }
 7206:     return $setprivs;
 7207: }
 7208: 
 7209: sub set_adhoc_privileges {
 7210: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7211:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7212:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7213:     if ($sec ne '') {
 7214:         $area .= '/'.$sec;
 7215:     }
 7216:     my $spec = $role.'.'.$area;
 7217:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7218:                                   $env{'user.name'},1);
 7219:     my %rolehash = ();
 7220:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7221:         my $rolename = $1;
 7222:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7223:         my %domdef = &get_domain_defaults($dcdom);
 7224:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7225:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7226:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7227:             }
 7228:         }
 7229:     } else {
 7230:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7231:     }
 7232:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7233:     &appenv(\%userroles,[$role,'cm']);
 7234:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7235:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7236:             ($caller eq 'tiny')) {
 7237:         &appenv( {'request.role'        => $spec,
 7238:                   'request.role.domain' => $dcdom,
 7239:                   'request.course.sec'  => $sec,
 7240:                  }
 7241:                );
 7242:         my $tadv=0;
 7243:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7244:         &appenv({'request.role.adv'    => $tadv});
 7245:     }
 7246: }
 7247: 
 7248: # --------------------------------------------------------------- get interface
 7249: 
 7250: sub get {
 7251:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7252:    my $items='';
 7253:    foreach my $item (@$storearr) {
 7254:        $items.=&escape($item).'&';
 7255:    }
 7256:    $items=~s/\&$//;
 7257:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7258:    if (!$uname) { $uname=$env{'user.name'}; }
 7259:    my $uhome=&homeserver($uname,$udomain);
 7260: 
 7261:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7262:    my @pairs=split(/\&/,$rep);
 7263:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7264:      return @pairs;
 7265:    }
 7266:    my %returnhash=();
 7267:    my $i=0;
 7268:    foreach my $item (@$storearr) {
 7269:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7270:       $i++;
 7271:    }
 7272:    return %returnhash;
 7273: }
 7274: 
 7275: # --------------------------------------------------------------- del interface
 7276: 
 7277: sub del {
 7278:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7279:    my $items='';
 7280:    foreach my $item (@$storearr) {
 7281:        $items.=&escape($item).'&';
 7282:    }
 7283: 
 7284:    $items=~s/\&$//;
 7285:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7286:    if (!$uname) { $uname=$env{'user.name'}; }
 7287:    my $uhome=&homeserver($uname,$udomain);
 7288:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7289: }
 7290: 
 7291: # -------------------------------------------------------------- dump interface
 7292: 
 7293: sub unserialize {
 7294:     my ($rep, $escapedkeys) = @_;
 7295: 
 7296:     return {} if $rep =~ /^error/;
 7297: 
 7298:     my %returnhash=();
 7299: 	foreach my $item (split(/\&/,$rep)) {
 7300: 	    my ($key, $value) = split(/=/, $item, 2);
 7301: 	    $key = unescape($key) unless $escapedkeys;
 7302: 	    next if $key =~ /^error: 2 /;
 7303: 	    $returnhash{$key} = &thaw_unescape($value);
 7304: 	}
 7305:     #return %returnhash;
 7306:     return \%returnhash;
 7307: }        
 7308: 
 7309: # see Lond::dump_with_regexp
 7310: # if $escapedkeys hash keys won't get unescaped.
 7311: sub dump {
 7312:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7313:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7314:     if (!$uname) { $uname=$env{'user.name'}; }
 7315:     my $uhome=&homeserver($uname,$udomain);
 7316: 
 7317:     if ($regexp) {
 7318:         $regexp=&escape($regexp);
 7319:     } else {
 7320:         $regexp='.';
 7321:     }
 7322:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7323:         # user is hosted on this machine
 7324:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7325:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7326:         return %{unserialize($reply, $escapedkeys)};
 7327:     }
 7328:     my $rep;
 7329:     if ($encrypt) {
 7330:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7331:     } else {
 7332:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7333:     }
 7334:     my @pairs=split(/\&/,$rep);
 7335:     my %returnhash=();
 7336:     if (!($rep =~ /^error/ )) {
 7337: 	foreach my $item (@pairs) {
 7338: 	    my ($key,$value)=split(/=/,$item,2);
 7339:         $key = unescape($key) unless $escapedkeys;
 7340:         #$key = &unescape($key);
 7341: 	    next if ($key =~ /^error: 2 /);
 7342: 	    $returnhash{$key}=&thaw_unescape($value);
 7343: 	}
 7344:     }
 7345:     return %returnhash;
 7346: }
 7347: 
 7348: 
 7349: # --------------------------------------------------------- dumpstore interface
 7350: 
 7351: sub dumpstore {
 7352:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7353:    # same as dump but keys must be escaped. They may contain colon separated
 7354:    # lists of values that may themself contain colons (e.g. symbs).
 7355:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7356: }
 7357: 
 7358: # -------------------------------------------------------------- keys interface
 7359: 
 7360: sub getkeys {
 7361:    my ($namespace,$udomain,$uname)=@_;
 7362:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7363:    if (!$uname) { $uname=$env{'user.name'}; }
 7364:    my $uhome=&homeserver($uname,$udomain);
 7365:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7366:    my @keyarray=();
 7367:    foreach my $key (split(/\&/,$rep)) {
 7368:       next if ($key =~ /^error: 2 /);
 7369:       push(@keyarray,&unescape($key));
 7370:    }
 7371:    return @keyarray;
 7372: }
 7373: 
 7374: # --------------------------------------------------------------- currentdump
 7375: sub currentdump {
 7376:    my ($courseid,$sdom,$sname)=@_;
 7377:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7378:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7379:    $sname    = $env{'user.name'}         if (! defined($sname));
 7380:    my $uhome = &homeserver($sname,$sdom);
 7381:    my $rep;
 7382: 
 7383:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7384:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7385:                    $courseid)));
 7386:    } else {
 7387:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7388:    }
 7389: 
 7390:    return if ($rep =~ /^(error:|no_such_host)/);
 7391:    #
 7392:    my %returnhash=();
 7393:    #
 7394:    if ($rep eq 'unknown_cmd') {
 7395:        # an old lond will not know currentdump
 7396:        # Do a dump and make it look like a currentdump
 7397:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7398:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7399:        my %hash = @tmp;
 7400:        @tmp=();
 7401:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7402:    } else {
 7403:        my @pairs=split(/\&/,$rep);
 7404:        foreach my $pair (@pairs) {
 7405:            my ($key,$value)=split(/=/,$pair,2);
 7406:            my ($symb,$param) = split(/:/,$key);
 7407:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7408:                                                         &thaw_unescape($value);
 7409:        }
 7410:    }
 7411:    return %returnhash;
 7412: }
 7413: 
 7414: sub convert_dump_to_currentdump{
 7415:     my %hash = %{shift()};
 7416:     my %returnhash;
 7417:     # Code ripped from lond, essentially.  The only difference
 7418:     # here is the unescaping done by lonnet::dump().  Conceivably
 7419:     # we might run in to problems with parameter names =~ /^v\./
 7420:     while (my ($key,$value) = each(%hash)) {
 7421:         my ($v,$symb,$param) = split(/:/,$key);
 7422: 	$symb  = &unescape($symb);
 7423: 	$param = &unescape($param);
 7424:         next if ($v eq 'version' || $symb eq 'keys');
 7425:         next if (exists($returnhash{$symb}) &&
 7426:                  exists($returnhash{$symb}->{$param}) &&
 7427:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7428:         $returnhash{$symb}->{$param}=$value;
 7429:         $returnhash{$symb}->{'v.'.$param}=$v;
 7430:     }
 7431:     #
 7432:     # Remove all of the keys in the hashes which keep track of
 7433:     # the version of the parameter.
 7434:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7435:         # use a foreach because we are going to delete from the hash.
 7436:         foreach my $key (keys(%$param_hash)) {
 7437:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7438:         }
 7439:     }
 7440:     return \%returnhash;
 7441: }
 7442: 
 7443: # ------------------------------------------------------ critical inc interface
 7444: 
 7445: sub cinc {
 7446:     return &inc(@_,'critical');
 7447: }
 7448: 
 7449: # --------------------------------------------------------------- inc interface
 7450: 
 7451: sub inc {
 7452:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7453:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7454:     if (!$uname) { $uname=$env{'user.name'}; }
 7455:     my $uhome=&homeserver($uname,$udomain);
 7456:     my $items='';
 7457:     if (! ref($store)) {
 7458:         # got a single value, so use that instead
 7459:         $items = &escape($store).'=&';
 7460:     } elsif (ref($store) eq 'SCALAR') {
 7461:         $items = &escape($$store).'=&';        
 7462:     } elsif (ref($store) eq 'ARRAY') {
 7463:         $items = join('=&',map {&escape($_);} @{$store});
 7464:     } elsif (ref($store) eq 'HASH') {
 7465:         while (my($key,$value) = each(%{$store})) {
 7466:             $items.= &escape($key).'='.&escape($value).'&';
 7467:         }
 7468:     }
 7469:     $items=~s/\&$//;
 7470:     if ($critical) {
 7471: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7472:     } else {
 7473: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7474:     }
 7475: }
 7476: 
 7477: # --------------------------------------------------------------- put interface
 7478: 
 7479: sub put {
 7480:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7481:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7482:    if (!$uname) { $uname=$env{'user.name'}; }
 7483:    my $uhome=&homeserver($uname,$udomain);
 7484:    my $items='';
 7485:    foreach my $item (keys(%$storehash)) {
 7486:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7487:    }
 7488:    $items=~s/\&$//;
 7489:    if ($encrypt) {
 7490:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7491:    } else {
 7492:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7493:    }
 7494: }
 7495: 
 7496: # ------------------------------------------------------------ newput interface
 7497: 
 7498: sub newput {
 7499:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7500:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7501:    if (!$uname) { $uname=$env{'user.name'}; }
 7502:    my $uhome=&homeserver($uname,$udomain);
 7503:    my $items='';
 7504:    foreach my $key (keys(%$storehash)) {
 7505:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7506:    }
 7507:    $items=~s/\&$//;
 7508:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7509: }
 7510: 
 7511: # ---------------------------------------------------------  putstore interface
 7512: 
 7513: sub putstore {
 7514:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7515:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7516:    if (!$uname) { $uname=$env{'user.name'}; }
 7517:    my $uhome=&homeserver($uname,$udomain);
 7518:    my $items='';
 7519:    foreach my $key (keys(%$storehash)) {
 7520:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7521:    }
 7522:    $items=~s/\&$//;
 7523:    my $esc_symb=&escape($symb);
 7524:    my $esc_v=&escape($version);
 7525:    my $reply =
 7526:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7527: 	      $uhome);
 7528:    if (($tolog) && ($reply eq 'ok')) {
 7529:        my $namevalue='';
 7530:        foreach my $key (keys(%{$storehash})) {
 7531:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7532:        }
 7533:        my $ip = &get_requestor_ip();
 7534:        $namevalue .= 'ip='.&escape($ip).
 7535:                      '&host='.&escape($perlvar{'lonHostID'}).
 7536:                      '&version='.$esc_v.
 7537:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7538:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7539:    }
 7540:    if ($reply eq 'unknown_cmd') {
 7541:        # gfall back to way things use to be done
 7542:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7543: 			    $uname);
 7544:    }
 7545:    return $reply;
 7546: }
 7547: 
 7548: sub old_putstore {
 7549:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7550:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7551:     if (!$uname) { $uname=$env{'user.name'}; }
 7552:     my $uhome=&homeserver($uname,$udomain);
 7553:     my %newstorehash;
 7554:     foreach my $item (keys(%$storehash)) {
 7555: 	my $key = $version.':'.&escape($symb).':'.$item;
 7556: 	$newstorehash{$key} = $storehash->{$item};
 7557:     }
 7558:     my $items='';
 7559:     my %allitems = ();
 7560:     foreach my $item (keys(%newstorehash)) {
 7561: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7562: 	    my $key = $1.':keys:'.$2;
 7563: 	    $allitems{$key} .= $3.':';
 7564: 	}
 7565: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7566:     }
 7567:     foreach my $item (keys(%allitems)) {
 7568: 	$allitems{$item} =~ s/\:$//;
 7569: 	$items.= $item.'='.$allitems{$item}.'&';
 7570:     }
 7571:     $items=~s/\&$//;
 7572:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7573: }
 7574: 
 7575: # ------------------------------------------------------ critical put interface
 7576: 
 7577: sub cput {
 7578:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7579:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7580:    if (!$uname) { $uname=$env{'user.name'}; }
 7581:    my $uhome=&homeserver($uname,$udomain);
 7582:    my $items='';
 7583:    foreach my $item (keys(%$storehash)) {
 7584:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7585:    }
 7586:    $items=~s/\&$//;
 7587:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7588: }
 7589: 
 7590: # -------------------------------------------------------------- eget interface
 7591: 
 7592: sub eget {
 7593:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7594:    my $items='';
 7595:    foreach my $item (@$storearr) {
 7596:        $items.=&escape($item).'&';
 7597:    }
 7598:    $items=~s/\&$//;
 7599:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7600:    if (!$uname) { $uname=$env{'user.name'}; }
 7601:    my $uhome=&homeserver($uname,$udomain);
 7602:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7603:    my @pairs=split(/\&/,$rep);
 7604:    my %returnhash=();
 7605:    my $i=0;
 7606:    foreach my $item (@$storearr) {
 7607:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7608:       $i++;
 7609:    }
 7610:    return %returnhash;
 7611: }
 7612: 
 7613: # ------------------------------------------------------------ tmpput interface
 7614: sub tmpput {
 7615:     my ($storehash,$server,$context)=@_;
 7616:     my $items='';
 7617:     foreach my $item (keys(%$storehash)) {
 7618: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7619:     }
 7620:     $items=~s/\&$//;
 7621:     if (defined($context)) {
 7622:         $items .= ':'.&escape($context);
 7623:     }
 7624:     return &reply("tmpput:$items",$server);
 7625: }
 7626: 
 7627: # ------------------------------------------------------------ tmpget interface
 7628: sub tmpget {
 7629:     my ($token,$server)=@_;
 7630:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7631:     my $rep=&reply("tmpget:$token",$server);
 7632:     my %returnhash;
 7633:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7634:         return %returnhash;
 7635:     }
 7636:     foreach my $item (split(/\&/,$rep)) {
 7637: 	my ($key,$value)=split(/=/,$item);
 7638: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7639:     }
 7640:     return %returnhash;
 7641: }
 7642: 
 7643: # ------------------------------------------------------------ tmpdel interface
 7644: sub tmpdel {
 7645:     my ($token,$server)=@_;
 7646:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7647:     return &reply("tmpdel:$token",$server);
 7648: }
 7649: 
 7650: # ------------------------------------------------------------ get_timebased_id 
 7651: 
 7652: sub get_timebased_id {
 7653:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7654:         $maxtries) = @_;
 7655:     my ($newid,$error,$dellock);
 7656:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7657:         return ('','ok','invalid call to get suffix');
 7658:     }
 7659: 
 7660: # set defaults for any optional args for which values were not supplied
 7661:     if ($who eq '') {
 7662:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7663:     }
 7664:     if (!$locktries) {
 7665:         $locktries = 3;
 7666:     }
 7667:     if (!$maxtries) {
 7668:         $maxtries = 10;
 7669:     }
 7670:     
 7671:     if (($cdom eq '') || ($cnum eq '')) {
 7672:         if ($env{'request.course.id'}) {
 7673:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7674:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7675:         }
 7676:         if (($cdom eq '') || ($cnum eq '')) {
 7677:             return ('','ok','call to get suffix not in course context');
 7678:         }
 7679:     }
 7680: 
 7681: # construct locking item
 7682:     my $lockhash = {
 7683:                       $prefix."\0".'locked_'.$keyid => $who,
 7684:                    };
 7685:     my $tries = 0;
 7686: 
 7687: # attempt to get lock on nohist_$namespace file
 7688:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7689:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7690:         $tries ++;
 7691:         sleep 1;
 7692:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7693:     }
 7694: 
 7695: # attempt to get unique identifier, based on current timestamp
 7696:     if ($gotlock eq 'ok') {
 7697:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7698:         my $id = time;
 7699:         $newid = $id;
 7700:         if ($idtype eq 'addcode') {
 7701:             $newid .= &sixnum_code();
 7702:         }
 7703:         my $idtries = 0;
 7704:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7705:             if ($idtype eq 'concat') {
 7706:                 $newid = $id.$idtries;
 7707:             } elsif ($idtype eq 'addcode') {
 7708:                 $newid = $newid.&sixnum_code();
 7709:             } else {
 7710:                 $newid ++;
 7711:             }
 7712:             $idtries ++;
 7713:         }
 7714:         if (!exists($inuse{$prefix."\0".$newid})) {
 7715:             my %new_item =  (
 7716:                               $prefix."\0".$newid => $who,
 7717:                             );
 7718:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7719:                                                  $cdom,$cnum);
 7720:             if ($putresult ne 'ok') {
 7721:                 undef($newid);
 7722:                 $error = 'error saving new item: '.$putresult;
 7723:             }
 7724:         } else {
 7725:              undef($newid);
 7726:              $error = ('error: no unique suffix available for the new item ');
 7727:         }
 7728: #  remove lock
 7729:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7730:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7731:     } else {
 7732:         $error = "error: could not obtain lockfile\n";
 7733:         $dellock = 'ok';
 7734:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7735:             $dellock = 'nolock';
 7736:         }
 7737:     }
 7738:     return ($newid,$dellock,$error);
 7739: }
 7740: 
 7741: sub sixnum_code {
 7742:     my $code;
 7743:     for (0..6) {
 7744:         $code .= int( rand(9) );
 7745:     }
 7746:     return $code;
 7747: }
 7748: 
 7749: # -------------------------------------------------- portfolio access checking
 7750: 
 7751: sub portfolio_access {
 7752:     my ($requrl,$clientip) = @_;
 7753:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7754:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7755:     if ($result) {
 7756:         my %setters;
 7757:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7758:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7759:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7760:             if (($startblock && $endblock) || ($by_ip)) {
 7761:                 return 'B';
 7762:             }
 7763:         } else {
 7764:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7765:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7766:             if (($startblock && $endblock) || ($by_ip)) {
 7767:                 return 'B';
 7768:             }
 7769:         }
 7770:     }
 7771:     if ($result eq 'ok') {
 7772:        return 'F';
 7773:     } elsif ($result =~ /^[^:]+:guest_/) {
 7774:        return 'A';
 7775:     }
 7776:     return '';
 7777: }
 7778: 
 7779: sub get_portfolio_access {
 7780:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7781: 
 7782:     if (!ref($access_hash)) {
 7783: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7784: 	my %access_controls = &get_access_controls($current_perms,$group,
 7785: 						   $file_name);
 7786: 	$access_hash = $access_controls{$file_name};
 7787:     }
 7788: 
 7789:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7790:     my $now = time;
 7791:     if (ref($access_hash) eq 'HASH') {
 7792:         foreach my $key (keys(%{$access_hash})) {
 7793:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7794:             if ($start > $now) {
 7795:                 next;
 7796:             }
 7797:             if ($end && $end<$now) {
 7798:                 next;
 7799:             }
 7800:             if ($scope eq 'public') {
 7801:                 $public = $key;
 7802:                 last;
 7803:             } elsif ($scope eq 'guest') {
 7804:                 $guest = $key;
 7805:             } elsif ($scope eq 'domains') {
 7806:                 push(@domains,$key);
 7807:             } elsif ($scope eq 'users') {
 7808:                 push(@users,$key);
 7809:             } elsif ($scope eq 'course') {
 7810:                 push(@courses,$key);
 7811:             } elsif ($scope eq 'group') {
 7812:                 push(@groups,$key);
 7813:             } elsif ($scope eq 'ip') {
 7814:                 push(@ips,$key);
 7815:             }
 7816:         }
 7817:         if ($public) {
 7818:             return 'ok';
 7819:         } elsif (@ips > 0) {
 7820:             my $allowed;
 7821:             foreach my $ipkey (@ips) {
 7822:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7823:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7824:                         $allowed = 1;
 7825:                         last; 
 7826:                     }
 7827:                 }
 7828:             }
 7829:             if ($allowed) {
 7830:                 return 'ok';
 7831:             }
 7832:         }
 7833:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7834:             if ($guest) {
 7835:                 return $guest;
 7836:             }
 7837:         } else {
 7838:             if (@domains > 0) {
 7839:                 foreach my $domkey (@domains) {
 7840:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7841:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7842:                             return 'ok';
 7843:                         }
 7844:                     }
 7845:                 }
 7846:             }
 7847:             if (@users > 0) {
 7848:                 foreach my $userkey (@users) {
 7849:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7850:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7851:                             if (ref($item) eq 'HASH') {
 7852:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7853:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7854:                                     return 'ok';
 7855:                                 }
 7856:                             }
 7857:                         }
 7858:                     } 
 7859:                 }
 7860:             }
 7861:             my %roleshash;
 7862:             my @courses_and_groups = @courses;
 7863:             push(@courses_and_groups,@groups); 
 7864:             if (@courses_and_groups > 0) {
 7865:                 my (%allgroups,%allroles); 
 7866:                 my ($start,$end,$role,$sec,$group);
 7867:                 foreach my $envkey (%env) {
 7868:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7869:                         my $cid = $2.'_'.$3; 
 7870:                         if ($1 eq 'gr') {
 7871:                             $group = $4;
 7872:                             $allgroups{$cid}{$group} = $env{$envkey};
 7873:                         } else {
 7874:                             if ($4 eq '') {
 7875:                                 $sec = 'none';
 7876:                             } else {
 7877:                                 $sec = $4;
 7878:                             }
 7879:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7880:                         }
 7881:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7882:                         my $cid = $2.'_'.$3;
 7883:                         if ($4 eq '') {
 7884:                             $sec = 'none';
 7885:                         } else {
 7886:                             $sec = $4;
 7887:                         }
 7888:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7889:                     }
 7890:                 }
 7891:                 if (keys(%allroles) == 0) {
 7892:                     return;
 7893:                 }
 7894:                 foreach my $key (@courses_and_groups) {
 7895:                     my %content = %{$$access_hash{$key}};
 7896:                     my $cnum = $content{'number'};
 7897:                     my $cdom = $content{'domain'};
 7898:                     my $cid = $cdom.'_'.$cnum;
 7899:                     if (!exists($allroles{$cid})) {
 7900:                         next;
 7901:                     }    
 7902:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7903:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7904:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7905:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7906:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7907:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7908:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7909:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7910:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7911:                                         if (grep/^all$/,@sections) {
 7912:                                             return 'ok';
 7913:                                         } else {
 7914:                                             if (grep/^$sec$/,@sections) {
 7915:                                                 return 'ok';
 7916:                                             }
 7917:                                         }
 7918:                                     }
 7919:                                 }
 7920:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7921:                                     if (grep/^none$/,@groups) {
 7922:                                         return 'ok';
 7923:                                     }
 7924:                                 } else {
 7925:                                     if (grep/^all$/,@groups) {
 7926:                                         return 'ok';
 7927:                                     } 
 7928:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7929:                                         if (grep/^$group$/,@groups) {
 7930:                                             return 'ok';
 7931:                                         }
 7932:                                     }
 7933:                                 } 
 7934:                             }
 7935:                         }
 7936:                     }
 7937:                 }
 7938:             }
 7939:             if ($guest) {
 7940:                 return $guest;
 7941:             }
 7942:         }
 7943:     }
 7944:     return;
 7945: }
 7946: 
 7947: sub course_group_datechecker {
 7948:     my ($dates,$now,$status) = @_;
 7949:     my ($start,$end) = split(/\./,$dates);
 7950:     if (!$start && !$end) {
 7951:         return 'ok';
 7952:     }
 7953:     if (grep/^active$/,@{$status}) {
 7954:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7955:             return 'ok';
 7956:         }
 7957:     }
 7958:     if (grep/^previous$/,@{$status}) {
 7959:         if ($end > $now ) {
 7960:             return 'ok';
 7961:         }
 7962:     }
 7963:     if (grep/^future$/,@{$status}) {
 7964:         if ($start > $now) {
 7965:             return 'ok';
 7966:         }
 7967:     }
 7968:     return; 
 7969: }
 7970: 
 7971: sub parse_portfolio_url {
 7972:     my ($url) = @_;
 7973: 
 7974:     my ($type,$udom,$unum,$group,$file_name);
 7975:     
 7976:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7977: 	$type = 1;
 7978:         $udom = $1;
 7979:         $unum = $2;
 7980:         $file_name = $3;
 7981:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7982: 	$type = 2;
 7983:         $udom = $1;
 7984:         $unum = $2;
 7985:         $group = $3;
 7986:         $file_name = $3.'/'.$4;
 7987:     }
 7988:     if (wantarray) {
 7989: 	return ($type,$udom,$unum,$file_name,$group);
 7990:     }
 7991:     return $type;
 7992: }
 7993: 
 7994: sub is_portfolio_url {
 7995:     my ($url) = @_;
 7996:     return scalar(&parse_portfolio_url($url));
 7997: }
 7998: 
 7999: sub is_portfolio_file {
 8000:     my ($file) = @_;
 8001:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8002:         return 1;
 8003:     }
 8004:     return;
 8005: }
 8006: 
 8007: sub is_coursetool_logo {
 8008:     my ($uri) = @_;
 8009:     if ($env{'request.course.id'}) {
 8010:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8011:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8012:             return 1;
 8013:         }
 8014:     }
 8015:     return;
 8016: }
 8017: 
 8018: sub usertools_access {
 8019:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8020:     my ($access,%tools);
 8021:     if ($context eq '') {
 8022:         $context = 'tools';
 8023:     }
 8024:     if ($context eq 'requestcourses') {
 8025:         %tools = (
 8026:                       official   => 1,
 8027:                       unofficial => 1,
 8028:                       community  => 1,
 8029:                       textbook   => 1,
 8030:                       placement  => 1,
 8031:                       lti        => 1,
 8032:                  );
 8033:     } elsif ($context eq 'requestauthor') {
 8034:         %tools = (
 8035:                       requestauthor => 1,
 8036:                  );
 8037:     } else {
 8038:         %tools = (
 8039:                       aboutme   => 1,
 8040:                       blog      => 1,
 8041:                       webdav    => 1,
 8042:                       portfolio => 1,
 8043:                       timezone  => 1,
 8044:                  );
 8045:     }
 8046:     return if (!defined($tools{$tool}));
 8047: 
 8048:     if (($udom eq '') || ($uname eq '')) {
 8049:         $udom = $env{'user.domain'};
 8050:         $uname = $env{'user.name'};
 8051:     }
 8052: 
 8053:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8054:         if ($action ne 'reload') {
 8055:             if ($context eq 'requestcourses') {
 8056:                 return $env{'environment.canrequest.'.$tool};
 8057:             } elsif ($context eq 'requestauthor') {
 8058:                 return $env{'environment.canrequest.author'};
 8059:             } else {
 8060:                 return $env{'environment.availabletools.'.$tool};
 8061:             }
 8062:         }
 8063:     }
 8064: 
 8065:     my ($toolstatus,$inststatus,$envkey);
 8066:     if ($context eq 'requestauthor') {
 8067:         $envkey = $context; 
 8068:     } else {
 8069:         $envkey = $context.'.'.$tool;
 8070:     }
 8071: 
 8072:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8073:          ($action ne 'reload')) {
 8074:         $toolstatus = $env{'environment.'.$envkey};
 8075:         $inststatus = $env{'environment.inststatus'};
 8076:     } else {
 8077:         if (ref($userenvref) eq 'HASH') {
 8078:             $toolstatus = $userenvref->{$envkey};
 8079:             $inststatus = $userenvref->{'inststatus'};
 8080:         } else {
 8081:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8082:             $toolstatus = $userenv{$envkey};
 8083:             $inststatus = $userenv{'inststatus'};
 8084:         }
 8085:     }
 8086: 
 8087:     if ($toolstatus ne '') {
 8088:         if ($toolstatus) {
 8089:             $access = 1;
 8090:         } else {
 8091:             $access = 0;
 8092:         }
 8093:         return $access;
 8094:     }
 8095: 
 8096:     my ($is_adv,%domdef);
 8097:     if (ref($is_advref) eq 'HASH') {
 8098:         $is_adv = $is_advref->{'is_adv'};
 8099:     } else {
 8100:         $is_adv = &is_advanced_user($udom,$uname);
 8101:     }
 8102:     if (ref($domdefref) eq 'HASH') {
 8103:         %domdef = %{$domdefref};
 8104:     } else {
 8105:         %domdef = &get_domain_defaults($udom);
 8106:     }
 8107:     if (ref($domdef{$tool}) eq 'HASH') {
 8108:         if ($is_adv) {
 8109:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8110:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8111:                     $access = 1;
 8112:                 } else {
 8113:                     $access = 0;
 8114:                 }
 8115:                 return $access;
 8116:             }
 8117:         }
 8118:         if ($inststatus ne '') {
 8119:             my ($hasaccess,$hasnoaccess);
 8120:             foreach my $affiliation (split(/:/,$inststatus)) {
 8121:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8122:                     if ($domdef{$tool}{$affiliation}) {
 8123:                         $hasaccess = 1;
 8124:                     } else {
 8125:                         $hasnoaccess = 1;
 8126:                     }
 8127:                 }
 8128:             }
 8129:             if ($hasaccess || $hasnoaccess) {
 8130:                 if ($hasaccess) {
 8131:                     $access = 1;
 8132:                 } elsif ($hasnoaccess) {
 8133:                     $access = 0; 
 8134:                 }
 8135:                 return $access;
 8136:             }
 8137:         } else {
 8138:             if ($domdef{$tool}{'default'} ne '') {
 8139:                 if ($domdef{$tool}{'default'}) {
 8140:                     $access = 1;
 8141:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8142:                     $access = 0;
 8143:                 }
 8144:                 return $access;
 8145:             }
 8146:         }
 8147:     } else {
 8148:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8149:             $access = 1;
 8150:         } else {
 8151:             $access = 0;
 8152:         }
 8153:         return $access;
 8154:     }
 8155: }
 8156: 
 8157: sub is_course_owner {
 8158:     my ($cdom,$cnum,$udom,$uname) = @_;
 8159:     if (($udom eq '') || ($uname eq '')) {
 8160:         $udom = $env{'user.domain'};
 8161:         $uname = $env{'user.name'};
 8162:     }
 8163:     unless (($udom eq '') || ($uname eq '')) {
 8164:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8165:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8166:                 return 1;
 8167:             } else {
 8168:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8169:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8170:                     return 1;
 8171:                 }
 8172:             }
 8173:         }
 8174:     }
 8175:     return;
 8176: }
 8177: 
 8178: sub is_advanced_user {
 8179:     my ($udom,$uname) = @_;
 8180:     if ($udom ne '' && $uname ne '') {
 8181:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8182:             if (wantarray) {
 8183:                 return ($env{'user.adv'},$env{'user.author'});
 8184:             } else {
 8185:                 return $env{'user.adv'};
 8186:             }
 8187:         }
 8188:     }
 8189:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8190:     my %allroles;
 8191:     my ($is_adv,$is_author);
 8192:     foreach my $role (keys(%roleshash)) {
 8193:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8194:         my $area = '/'.$tdomain.'/'.$trest;
 8195:         if ($sec ne '') {
 8196:             $area .= '/'.$sec;
 8197:         }
 8198:         if (($area ne '') && ($trole ne '')) {
 8199:             my $spec=$trole.'.'.$area;
 8200:             if ($trole =~ /^cr\//) {
 8201:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8202:             } elsif ($trole ne 'gr') {
 8203:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8204:             }
 8205:             if ($trole eq 'au') {
 8206:                 $is_author = 1;
 8207:             }
 8208:         }
 8209:     }
 8210:     foreach my $role (keys(%allroles)) {
 8211:         last if ($is_adv);
 8212:         foreach my $item (split(/:/,$allroles{$role})) {
 8213:             if ($item ne '') {
 8214:                 my ($privilege,$restrictions)=split(/&/,$item);
 8215:                 if ($privilege eq 'adv') {
 8216:                     $is_adv = 1;
 8217:                     last;
 8218:                 }
 8219:             }
 8220:         }
 8221:     }
 8222:     if (wantarray) {
 8223:         return ($is_adv,$is_author);
 8224:     }
 8225:     return $is_adv;
 8226: }
 8227: 
 8228: sub check_can_request {
 8229:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8230:     my $canreq = 0;
 8231:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8232:         $uname = $env{'user.name'};
 8233:         $udom = $env{'user.domain'};
 8234:     }
 8235:     my ($types,$typename) = &Apache::loncommon::course_types();
 8236:     my @options = ('approval','validate','autolimit');
 8237:     my $optregex = join('|',@options);
 8238:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8239:         my %willtrust;
 8240:         foreach my $type (@{$types}) {
 8241:             if (&usertools_access($uname,$udom,$type,undef,
 8242:                                   'requestcourses')) {
 8243:                 $canreq ++;
 8244:                 if (ref($request_domains) eq 'HASH') {
 8245:                     push(@{$request_domains->{$type}},$udom);
 8246:                 }
 8247:                 if ($dom eq $udom) {
 8248:                     $can_request->{$type} = 1;
 8249:                 }
 8250:             }
 8251:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8252:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8253:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8254:                 if (@curr > 0) {
 8255:                     foreach my $item (@curr) {
 8256:                         if (ref($request_domains) eq 'HASH') {
 8257:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8258:                             if ($otherdom ne '') {
 8259:                                 unless (exists($willtrust{$otherdom})) {
 8260:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8261:                                 }
 8262:                                 if ($willtrust{$otherdom}) {
 8263:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8264:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8265:                                             push(@{$request_domains->{$type}},$otherdom);
 8266:                                         }
 8267:                                     } else {
 8268:                                         push(@{$request_domains->{$type}},$otherdom);
 8269:                                     }
 8270:                                 }
 8271:                             }
 8272:                         }
 8273:                     }
 8274:                     unless ($dom eq $env{'user.domain'}) {
 8275:                         $canreq ++;
 8276:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8277:                             $can_request->{$type} = 1;
 8278:                         }
 8279:                     }
 8280:                 }
 8281:             }
 8282:         }
 8283:     }
 8284:     return $canreq;
 8285: }
 8286: 
 8287: # ---------------------------------------------- Custom access rule evaluation
 8288: 
 8289: sub customaccess {
 8290:     my ($priv,$uri)=@_;
 8291:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8292:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8293:     $udom = &LONCAPA::clean_domain($udom);
 8294:     $ucrs = &LONCAPA::clean_username($ucrs);
 8295:     my $access=0;
 8296:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8297: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8298: 	if ($type eq 'user') {
 8299: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8300: 		my ($tdom,$tuname)=split(m{/},$scope);
 8301: 		if ($tdom) {
 8302: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8303: 		}
 8304: 		if ($tuname) {
 8305: 		    if ($tuname ne $env{'user.name'}) { next; }
 8306: 		}
 8307: 		$access=($effect eq 'allow');
 8308: 		last;
 8309: 	    }
 8310: 	} else {
 8311: 	    if ($role) {
 8312: 		if ($role ne $urole) { next; }
 8313: 	    }
 8314: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8315: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8316: 		if ($tdom) {
 8317: 		    if ($tdom ne $udom) { next; }
 8318: 		}
 8319: 		if ($tcrs) {
 8320: 		    if ($tcrs ne $ucrs) { next; }
 8321: 		}
 8322: 		if ($tsec) {
 8323: 		    if ($tsec ne $usec) { next; }
 8324: 		}
 8325: 		$access=($effect eq 'allow');
 8326: 		last;
 8327: 	    }
 8328: 	    if ($realm eq '' && $role eq '') {
 8329: 		$access=($effect eq 'allow');
 8330: 	    }
 8331: 	}
 8332:     }
 8333:     return $access;
 8334: }
 8335: 
 8336: # ------------------------------------------------- Check for a user privilege
 8337: 
 8338: sub allowed {
 8339:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8340:     my $ver_orguri=$uri;
 8341:     $uri=&deversion($uri);
 8342:     my $orguri=$uri;
 8343:     $uri=&declutter($uri);
 8344: 
 8345:     if ($priv eq 'evb') {
 8346: # Evade communication block restrictions for specified role in a course or domain
 8347:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8348:             return $1;
 8349:         } else {
 8350:             return;
 8351:         }
 8352:     }
 8353: 
 8354:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8355: # Free bre access to adm and meta resources
 8356:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8357: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8358: 	&& ($priv eq 'bre')) {
 8359: 	return 'F';
 8360:     }
 8361: 
 8362: # Free bre access to user's own portfolio contents
 8363:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8364:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8365: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8366:         my %setters;
 8367:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8368:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8369:         if (($startblock && $endblock) || ($by_ip)) {
 8370:             return 'B';
 8371:         } else {
 8372:             return 'F';
 8373:         }
 8374:     }
 8375: 
 8376: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8377:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8378:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8379:         if (exists($env{'request.course.id'})) {
 8380:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8381:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8382:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8383:                 my $courseprivid=$env{'request.course.id'};
 8384:                 $courseprivid=~s/\_/\//;
 8385:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8386:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8387:                     return $1; 
 8388:                 } else {
 8389:                     if ($env{'request.course.sec'}) {
 8390:                         $courseprivid.='/'.$env{'request.course.sec'};
 8391:                     }
 8392:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8393:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8394:                         return $2;
 8395:                     }
 8396:                 }
 8397:             }
 8398:         }
 8399:     }
 8400: 
 8401: # Free bre to public access
 8402: 
 8403:     if ($priv eq 'bre') {
 8404:         my $copyright;
 8405:         unless ($uri =~ /ext\.tool/) {
 8406:             $copyright=&metadata($uri,'copyright');
 8407:         }
 8408: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8409:            return 'F'; 
 8410:         }
 8411:         if ($copyright eq 'priv') {
 8412:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8413: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8414: 		return '';
 8415:             }
 8416:         }
 8417:         if ($copyright eq 'domain') {
 8418:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8419: 	    unless (($env{'user.domain'} eq $1) ||
 8420:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8421: 		return '';
 8422:             }
 8423:         }
 8424:         if ($env{'request.role'}=~ /li\.\//) {
 8425:             # Library role, so allow browsing of resources in this domain.
 8426:             return 'F';
 8427:         }
 8428:         if ($copyright eq 'custom') {
 8429: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8430:         }
 8431:     }
 8432:     # Domain coordinator is trying to create a course
 8433:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8434:         # uri is the requested domain in this case.
 8435:         # comparison to 'request.role.domain' shows if the user has selected
 8436:         # a role of dc for the domain in question.
 8437:         return 'F' if ($uri eq $env{'request.role.domain'});
 8438:     }
 8439: 
 8440:     my $thisallowed='';
 8441:     my $statecond=0;
 8442:     my $courseprivid='';
 8443: 
 8444:     my $ownaccess;
 8445:     # Community Coordinator or Assistant Co-author browsing resource space.
 8446:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8447:         if ($uri eq '') {
 8448:             $ownaccess = 1;
 8449:         } else {
 8450:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8451:                 my $udom = $env{'user.domain'};
 8452:                 my $uname = $env{'user.name'};
 8453:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8454:                     $ownaccess = 1;
 8455:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8456:                     unless ($uri =~ m{\.\./}) {
 8457:                         $ownaccess = 1;
 8458:                     }
 8459:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8460:                     my $now = time;
 8461:                     if ($uri =~ m{^([^/]+)/?$}) {
 8462:                         my $adom = $1;
 8463:                         foreach my $key (keys(%env)) {
 8464:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8465:                                 my ($start,$end) = split(/\./,$env{$key});
 8466:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8467:                                     $ownaccess = 1;
 8468:                                     last;
 8469:                                 }
 8470:                             }
 8471:                         }
 8472:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8473:                         my $adom = $1;
 8474:                         my $aname = $2;
 8475:                         foreach my $role ('ca','aa') { 
 8476:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8477:                                 my ($start,$end) =
 8478:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8479:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8480:                                     $ownaccess = 1;
 8481:                                     last;
 8482:                                 }
 8483:                             }
 8484:                         }
 8485:                     }
 8486:                 }
 8487:             }
 8488:         }
 8489:     }
 8490: 
 8491: # Course
 8492: 
 8493:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8494:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8495:             $thisallowed.=$1;
 8496:         }
 8497:     }
 8498: 
 8499: # Domain
 8500: 
 8501:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8502:        =~/\Q$priv\E\&([^\:]*)/) {
 8503:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8504:             $thisallowed.=$1;
 8505:         }
 8506:     }
 8507: 
 8508: # User who is not author or co-author might still be able to edit
 8509: # resource of an author in the domain (e.g., if Domain Coordinator).
 8510:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8511:         (&allowed('mdc',$env{'request.course.id'}))) {
 8512:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8513:             $thisallowed.=$1;
 8514:         }
 8515:     }
 8516: 
 8517: # Course: uri itself is a course
 8518:     my $courseuri=$uri;
 8519:     $courseuri=~s/\_(\d)/\/$1/;
 8520:     $courseuri=~s/^([^\/])/\/$1/;
 8521: 
 8522:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8523:        =~/\Q$priv\E\&([^\:]*)/) {
 8524:         if ($priv eq 'mip') {
 8525:             my $rem = $1;
 8526:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8527:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8528:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8529:                 if ($cdom ne '') {
 8530:                     my %passwdconf = &get_passwdconf($cdom);
 8531:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8532:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8533:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8534:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8535:                                 unless (@inststatuses) {
 8536:                                     @inststatuses = ('default');
 8537:                                 }
 8538:                                 foreach my $status (@inststatuses) {
 8539:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8540:                                         $thisallowed.=$rem;
 8541:                                     }
 8542:                                 }
 8543:                             }
 8544:                         }
 8545:                     }
 8546:                 }
 8547:             }
 8548:         } else {
 8549:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8550:                 $thisallowed.=$1;
 8551:             }
 8552:         }
 8553:     }
 8554: 
 8555: # URI is an uploaded document for this course, default permissions don't matter
 8556: # not allowing 'edit' access (editupload) to uploaded course docs
 8557:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8558: 	$thisallowed='';
 8559:         my ($match)=&is_on_map($uri);
 8560:         if ($match) {
 8561:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8562:                   =~/\Q$priv\E\&([^\:]*)/) {
 8563:                 my $value = $1;
 8564:                 my $deeplinkblock;
 8565:                 unless ($nodeeplinkcheck) {
 8566:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8567:                 }
 8568:                 if ($deeplinkblock) {
 8569:                     $thisallowed='D';
 8570:                 } elsif ($noblockcheck) {
 8571:                     $thisallowed.=$value;
 8572:                 } else {
 8573:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8574:                     if (@blockers > 0) {
 8575:                         $thisallowed = 'B';
 8576:                     } else {
 8577:                         $thisallowed.=$value;
 8578:                     }
 8579:                 }
 8580:             }
 8581:         } else {
 8582:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8583:             if ($refuri) {
 8584:                 if ($refuri =~ m|^/adm/|) {
 8585:                     $thisallowed='F';
 8586:                 } else {
 8587:                     $refuri=&declutter($refuri);
 8588:                     my ($match) = &is_on_map($refuri);
 8589:                     if ($match) {
 8590:                         my $deeplinkblock;
 8591:                         unless ($nodeeplinkcheck) {
 8592:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8593:                         }
 8594:                         if ($deeplinkblock) {
 8595:                             $thisallowed='D';
 8596:                         } elsif ($noblockcheck) {
 8597:                             $thisallowed='F';
 8598:                         } else {
 8599:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8600:                             if (@blockers > 0) {
 8601:                                 $thisallowed = 'B';
 8602:                             } else {
 8603:                                 $thisallowed='F';
 8604:                             }
 8605:                         }
 8606:                     }
 8607:                 }
 8608:             }
 8609:         }
 8610:     }
 8611: 
 8612:     if ($priv eq 'bre'
 8613: 	&& $thisallowed ne 'F' 
 8614: 	&& $thisallowed ne '2'
 8615: 	&& &is_portfolio_url($uri)) {
 8616: 	$thisallowed = &portfolio_access($uri,$clientip);
 8617:     }
 8618: 
 8619: # Full access at system, domain or course-wide level? Exit.
 8620:     if ($thisallowed=~/F/) {
 8621: 	return 'F';
 8622:     }
 8623: 
 8624: # If this is generating or modifying users, exit with special codes
 8625: 
 8626:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8627: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8628: 	    my ($audom,$auname)=split('/',$uri);
 8629: # no author name given, so this just checks on the general right to make a co-author in this domain
 8630: 	    unless ($auname) { return $thisallowed; }
 8631: # an author name is given, so we are about to actually make a co-author for a certain account
 8632: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8633: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8634: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8635: 	}
 8636: 	return $thisallowed;
 8637:     }
 8638: #
 8639: # Gathered so far: system, domain and course wide privileges
 8640: #
 8641: # Course: See if uri or referer is an individual resource that is part of 
 8642: # the course
 8643: 
 8644:     if ($env{'request.course.id'}) {
 8645: 
 8646:         if ($priv eq 'bre') {
 8647:             if (&is_coursetool_logo($uri)) {
 8648:                 return 'F';
 8649:             }
 8650:         }
 8651: 
 8652: # If this is modifying password (internal auth) domains must match for user and user's role.
 8653: 
 8654:         if ($priv eq 'mip') {
 8655:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8656:                 return $thisallowed;
 8657:             } else {
 8658:                 return '';
 8659:             }
 8660:         }
 8661: 
 8662:        $courseprivid=$env{'request.course.id'};
 8663:        if ($env{'request.course.sec'}) {
 8664:           $courseprivid.='/'.$env{'request.course.sec'};
 8665:        }
 8666:        $courseprivid=~s/\_/\//;
 8667:        my $checkreferer=1;
 8668:        my ($match,$cond)=&is_on_map($uri);
 8669:        if ($match) {
 8670:            $statecond=$cond;
 8671:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8672:                =~/\Q$priv\E\&([^\:]*)/) {
 8673:                my $value = $1;
 8674:                if ($priv eq 'bre') {
 8675:                    my $deeplinkblock;
 8676:                    unless ($nodeeplinkcheck) {
 8677:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8678:                    }
 8679:                    if ($deeplinkblock) {
 8680:                        $thisallowed = 'D';
 8681:                    } elsif ($noblockcheck) {
 8682:                        $thisallowed.=$value;
 8683:                    } else {
 8684:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8685:                        if (@blockers > 0) {
 8686:                            $thisallowed = 'B';
 8687:                        } else {
 8688:                            $thisallowed.=$value;
 8689:                        }
 8690:                    }
 8691:                } else {
 8692:                    $thisallowed.=$value;
 8693:                }
 8694:                $checkreferer=0;
 8695:            }
 8696:        }
 8697: 
 8698:        if ($checkreferer) {
 8699: 	  my $refuri=$env{'httpref.'.$orguri};
 8700:             unless ($refuri) {
 8701:                 foreach my $key (keys(%env)) {
 8702: 		    if ($key=~/^httpref\..*\*/) {
 8703: 			my $pattern=$key;
 8704:                         $pattern=~s/^httpref\.\/res\///;
 8705:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8706:                         $pattern=~s/\//\\\//g;
 8707:                         if ($orguri=~/$pattern/) {
 8708: 			    $refuri=$env{$key};
 8709:                         }
 8710:                     }
 8711:                 }
 8712:             }
 8713: 
 8714:          if ($refuri) { 
 8715: 	  $refuri=&declutter($refuri);
 8716:           my ($match,$cond)=&is_on_map($refuri);
 8717:             if ($match) {
 8718:               my $refstatecond=$cond;
 8719:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8720:                   =~/\Q$priv\E\&([^\:]*)/) {
 8721:                   my $value = $1;
 8722:                   if ($priv eq 'bre') {
 8723:                       my $deeplinkblock;
 8724:                       unless ($nodeeplinkcheck) {
 8725:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8726:                       }
 8727:                       if ($deeplinkblock) {
 8728:                           $thisallowed = 'D';
 8729:                       } elsif ($noblockcheck) {
 8730:                           $thisallowed.=$value;
 8731:                       } else {
 8732:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8733:                           if (@blockers > 0) {
 8734:                               $thisallowed = 'B';
 8735:                           } else {
 8736:                               $thisallowed.=$value;
 8737:                           }
 8738:                       }
 8739:                   } else {
 8740:                       $thisallowed.=$value;
 8741:                   }
 8742:                   $uri=$refuri;
 8743:                   $statecond=$refstatecond;
 8744:               }
 8745:           }
 8746:         }
 8747:        }
 8748:    }
 8749: 
 8750: #
 8751: # Gathered now: all privileges that could apply, and condition number
 8752: # 
 8753: #
 8754: # Full or no access?
 8755: #
 8756: 
 8757:     if ($thisallowed=~/F/) {
 8758: 	return 'F';
 8759:     }
 8760: 
 8761:     unless ($thisallowed) {
 8762:         return '';
 8763:     }
 8764: 
 8765: # Restrictions exist, deal with them
 8766: #
 8767: #   C:according to course preferences
 8768: #   R:according to resource settings
 8769: #   L:unless locked
 8770: #   X:according to user session state
 8771: #
 8772: 
 8773: # Possibly locked functionality, check all courses
 8774: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8775: # Locks might take effect only after 10 minutes cache expiration for other
 8776: # courses, and 2 minutes for current course, in which user has st or ta role
 8777: # which is neither expired nor a future role (unless current course).
 8778: 
 8779:     my ($needlockcheck,$now,$crsonly);
 8780:     if ($thisallowed=~/L/) {
 8781:         $now = time;
 8782:         if ($priv eq 'bre') {
 8783:             if ($uri ne '') {
 8784:                 if ($orguri =~ m{^/+res/}) {
 8785:                     if ($uri =~ m{^lib/templates/}) {
 8786:                         if ($env{'request.course.id'}) {
 8787:                             $crsonly = 1;
 8788:                             $needlockcheck = 1;
 8789:                         }
 8790:                     } else {
 8791:                         $needlockcheck = 1;
 8792:                     }
 8793:                 } elsif ($env{'request.course.id'}) {
 8794:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8795:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8796:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8797:                         $crsonly = 1;
 8798:                     }
 8799:                     $needlockcheck = 1;
 8800:                 }
 8801:             }
 8802:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8803:             $needlockcheck = 1;
 8804:         }
 8805:     }
 8806:     if ($needlockcheck) {
 8807:         foreach my $envkey (keys(%env)) {
 8808:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8809:                my $courseid=$2;
 8810:                my $roleid=$1.'.'.$2;
 8811:                $courseid=~s/^\///;
 8812:                unless ($env{'request.role'} eq $roleid) {
 8813:                    my ($start,$end) = split(/\./,$env{$envkey});
 8814:                    next unless (($now >= $start) && (!$end || $end > $now));
 8815:                }
 8816:                my $expiretime=600;
 8817:                if ($env{'request.role'} eq $roleid) {
 8818: 		  $expiretime=120;
 8819:                }
 8820: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8821:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8822:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8823: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8824:                }
 8825:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8826:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8827: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8828:                        &log($env{'user.domain'},$env{'user.name'},
 8829:                             $env{'user.home'},
 8830:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8831:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8832:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8833: 		       return '';
 8834:                    }
 8835:                }
 8836:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8837:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8838: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8839:                        &log($env{'user.domain'},$env{'user.name'},
 8840:                             $env{'user.home'},
 8841:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8842:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8843:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8844: 		       return '';
 8845:                    }
 8846:                }
 8847: 	   }
 8848:        }
 8849:     }
 8850: 
 8851: #
 8852: # Rest of the restrictions depend on selected course
 8853: #
 8854: 
 8855:     unless ($env{'request.course.id'}) {
 8856: 	if ($thisallowed eq 'A') {
 8857: 	    return 'A';
 8858:         } elsif ($thisallowed eq 'B') {
 8859:             return 'B';
 8860: 	} else {
 8861: 	    return '1';
 8862: 	}
 8863:     }
 8864: 
 8865: #
 8866: # Now user is definitely in a course
 8867: #
 8868: 
 8869: 
 8870: # Course preferences
 8871: 
 8872:    if ($thisallowed=~/C/) {
 8873:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8874:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8875:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8876: 	   =~/\Q$rolecode\E/) {
 8877: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8878: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8879: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8880: 			$env{'request.course.id'});
 8881: 	   }
 8882:            return '';
 8883:        }
 8884: 
 8885:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8886: 	   =~/\Q$unamedom\E/) {
 8887: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8888: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8889: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8890: 			$env{'request.course.id'});
 8891: 	   }
 8892:            return '';
 8893:        }
 8894:    }
 8895: 
 8896: # Resource preferences
 8897: 
 8898:    if ($thisallowed=~/R/) {
 8899:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8900:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8901: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8902: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8903: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8904: 	   }
 8905: 	   return '';
 8906:        }
 8907:    }
 8908: 
 8909: # Restricted for deeplinked session?
 8910: 
 8911:     if ($env{'request.deeplink.login'}) {
 8912:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8913:             if (!$symb) { $symb=&symbread($uri,1); }
 8914:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8915:                 return '';
 8916:             }
 8917:         }
 8918:     }
 8919: 
 8920: # Restricted by state or randomout?
 8921: 
 8922:    if ($thisallowed=~/X/) {
 8923:       if ($env{'acc.randomout'}) {
 8924: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8925:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8926:             return ''; 
 8927:          }
 8928:       }
 8929:       if (&condval($statecond)) {
 8930: 	 return '2';
 8931:       } else {
 8932:          return '';
 8933:       }
 8934:    }
 8935: 
 8936:     if ($thisallowed eq 'A') {
 8937: 	return 'A';
 8938:     } elsif ($thisallowed eq 'B') {
 8939:         return 'B';
 8940:     } elsif ($thisallowed eq 'D') {
 8941:         return 'D';
 8942:     }
 8943:    return 'F';
 8944: }
 8945: 
 8946: # ------------------------------------------- Check construction space access
 8947: 
 8948: sub constructaccess {
 8949:     my ($url,$setpriv)=@_;
 8950: 
 8951: # We do not allow editing of previous versions of files
 8952:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8953: 
 8954: # Get username and domain from URL
 8955:     my ($ownername,$ownerdomain,$ownerhome);
 8956: 
 8957:     ($ownerdomain,$ownername) =
 8958:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8959: 
 8960: # The URL does not really point to any authorspace, forget it
 8961:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8962: 
 8963: # Now we need to see if the user has access to the authorspace of
 8964: # $ownername at $ownerdomain
 8965: 
 8966:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8967: # Real author for this?
 8968:        $ownerhome = $env{'user.home'};
 8969:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8970:           return ($ownername,$ownerdomain,$ownerhome);
 8971:        }
 8972:     } else {
 8973: # Co-author for this?
 8974:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8975:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8976:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8977:             return ($ownername,$ownerdomain,$ownerhome);
 8978:         }
 8979:         if ($env{'request.course.id'}) {
 8980:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8981:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8982:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8983:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8984:                     return ($ownername,$ownerdomain,$ownerhome);
 8985:                 }
 8986:             }
 8987:         }
 8988:     }
 8989: 
 8990: # We don't have any access right now. If we are not possibly going to do anything about this,
 8991: # we might as well leave
 8992:    unless ($setpriv) { return ''; }
 8993: 
 8994: # Backdoor access?
 8995:     my $allowed=&allowed('eco',$ownerdomain);
 8996: # Nope
 8997:     unless ($allowed) { return ''; }
 8998: # Looks like we may have access, but could be locked by the owner of the construction space
 8999:     if ($allowed eq 'U') {
 9000:         my %blocked=&get('environment',['domcoord.author'],
 9001:                          $ownerdomain,$ownername);
 9002: # Is blocked by owner
 9003:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9004:     }
 9005:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9006: # Grant temporary access
 9007:         my $then=$env{'user.login.time'};
 9008:         my $update=$env{'user.update.time'};
 9009:         if (!$update) { $update = $then; }
 9010:         my $refresh=$env{'user.refresh.time'};
 9011:         if (!$refresh) { $refresh = $update; }
 9012:         my $now = time;
 9013:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9014:                            $now,'ca','constructaccess');
 9015:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9016:         return($ownername,$ownerdomain,$ownerhome);
 9017:     }
 9018: # No business here
 9019:     return '';
 9020: }
 9021: 
 9022: # ----------------------------------------------------------- Content Blocking
 9023: 
 9024: {
 9025: # Caches for faster Course Contents display where content blocking
 9026: # is in operation (i.e., interval param set) for timed quiz.
 9027: #
 9028: # User for whom data are being temporarily cached.
 9029: my $cacheduser='';
 9030: # Course for which data are being temporarily cached.
 9031: my $cachedcid='';
 9032: # Cached blockers for this user (a hash of blocking items). 
 9033: my %cachedblockers=();
 9034: # When the data were last cached.
 9035: my $cachedlast='';
 9036: 
 9037: sub load_all_blockers {
 9038:     my ($uname,$udom)=@_;
 9039:     if (($uname ne '') && ($udom ne '')) { 
 9040:         if (($cacheduser eq $uname.':'.$udom) &&
 9041:             ($cachedcid eq $env{'request.course.id'}) &&
 9042:             (abs($cachedlast-time)<5)) {
 9043:             return;
 9044:         }
 9045:     }
 9046:     $cachedlast=time;
 9047:     $cacheduser=$uname.':'.$udom;
 9048:     $cachedcid=$env{'request.course.id'};
 9049:     %cachedblockers = &get_commblock_resources();
 9050:     return;
 9051: }
 9052: 
 9053: sub get_comm_blocks {
 9054:     my ($cdom,$cnum) = @_;
 9055:     if ($cdom eq '' || $cnum eq '') {
 9056:         return unless ($env{'request.course.id'});
 9057:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9058:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9059:     }
 9060:     my %commblocks;
 9061:     my $hashid=$cdom.'_'.$cnum;
 9062:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9063:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9064:         %commblocks = %{$blocksref};
 9065:     } else {
 9066:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9067:         my $cachetime = 600;
 9068:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9069:     }
 9070:     return %commblocks;
 9071: }
 9072: 
 9073: sub get_commblock_resources {
 9074:     my ($blocks) = @_;
 9075:     my %blockers = ();
 9076:     return %blockers unless ($env{'request.course.id'});
 9077:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9078:     if ($env{'request.course.sec'}) {
 9079:         $courseurl .= '/'.$env{'request.course.sec'};
 9080:     }
 9081:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9082:     my %commblocks;
 9083:     if (ref($blocks) eq 'HASH') {
 9084:         %commblocks = %{$blocks};
 9085:     } else {
 9086:         %commblocks = &get_comm_blocks();
 9087:     }
 9088:     return %blockers unless (keys(%commblocks) > 0); 
 9089:     my $navmap = Apache::lonnavmaps::navmap->new();
 9090:     return %blockers unless (ref($navmap));
 9091:     my $now = time;
 9092:     foreach my $block (keys(%commblocks)) {
 9093:         if ($block =~ /^(\d+)____(\d+)$/) {
 9094:             my ($start,$end) = ($1,$2);
 9095:             if ($start <= $now && $end >= $now) {
 9096:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9097:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9098:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9099:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9100:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9101:                             }
 9102:                         }
 9103:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9104:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9105:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9106:                             }
 9107:                         }
 9108:                     }
 9109:                 }
 9110:             }
 9111:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9112:             my $item = $1;
 9113:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9114:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9115:                     my (@interval,$mapname);
 9116:                     my $type = 'map';
 9117:                     if ($item eq 'course') {
 9118:                         $type = 'course';
 9119:                         @interval=&EXT("resource.0.interval");
 9120:                     } else {
 9121:                         if ($item =~ /___\d+___/) {
 9122:                             $type = 'resource';
 9123:                             @interval=&EXT("resource.0.interval",$item);
 9124:                         } else {
 9125:                             $mapname = &deversion($item);
 9126:                             if (ref($navmap)) {
 9127:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9128:                                 @interval = ($timelimit,'map');
 9129:                             }
 9130:                         }
 9131:                     }
 9132:                     if ($interval[0] =~ /^(\d+)/) {
 9133:                         my $timelimit = $1; 
 9134:                         my $first_access;
 9135:                         if ($type eq 'resource') {
 9136:                             $first_access=&get_first_access($interval[1],$item);
 9137:                         } elsif ($type eq 'map') {
 9138:                             $first_access=&get_first_access($interval[1],undef,$item);
 9139:                         } else {
 9140:                             $first_access=&get_first_access($interval[1]);
 9141:                         }
 9142:                         if ($first_access) {
 9143:                             my $timesup = $first_access+$timelimit;
 9144:                             if ($timesup > $now) {
 9145:                                 my $activeblock;
 9146:                                 if ($type eq 'resource') {
 9147:                                     if (ref($navmap)) {
 9148:                                         my $res = $navmap->getBySymb($item);
 9149:                                         if ($res->answerable()) {
 9150:                                             $activeblock = 1;
 9151:                                         }
 9152:                                     }
 9153:                                 } elsif ($type eq 'map') {
 9154:                                     my $mapsymb = &symbread($mapname,1);
 9155:                                     if (($mapsymb) && (ref($navmap))) {
 9156:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9157:                                         if (ref($mapres)) {
 9158:                                             my $first = $mapres->map_start();
 9159:                                             my $finish = $mapres->map_finish();
 9160:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9161:                                             if (ref($it)) {
 9162:                                                 my $res;
 9163:                                                 while ($res = $it->next(undef,1)) {
 9164:                                                     next unless (ref($res));
 9165:                                                     my $symb = $res->symb();
 9166:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9167:                                                     @interval=&EXT("resource.0.interval",$symb);
 9168:                                                     if ($interval[1] eq 'map') {
 9169:                                                         if ($res->answerable()) {
 9170:                                                             $activeblock = 1;
 9171:                                                             last;
 9172:                                                         }
 9173:                                                     }
 9174:                                                 }
 9175:                                             }
 9176:                                         }
 9177:                                     }
 9178:                                 }
 9179:                                 if ($activeblock) {
 9180:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9181:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9182:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9183:                                          }
 9184:                                     }
 9185:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9186:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9187:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9188:                                         }
 9189:                                     }
 9190:                                 }
 9191:                             }
 9192:                         }
 9193:                     }
 9194:                 }
 9195:             }
 9196:         }
 9197:     }
 9198:     return %blockers;
 9199: }
 9200: 
 9201: sub has_comm_blocking {
 9202:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9203:     my @blockers;
 9204:     return unless ($env{'request.course.id'});
 9205:     return unless ($priv eq 'bre');
 9206:     return if ($env{'request.state'} eq 'construct');
 9207:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9208:     if ($env{'request.course.sec'}) {
 9209:         $courseurl .= '/'.$env{'request.course.sec'};
 9210:     }
 9211:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9212:     my %blockinfo;
 9213:     if (ref($blocks) eq 'HASH') {
 9214:         %blockinfo = &get_commblock_resources($blocks);
 9215:     } else {
 9216:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9217:         %blockinfo = %cachedblockers;
 9218:     }
 9219:     return unless (keys(%blockinfo) > 0);
 9220:     my (%possibles,@symbs);
 9221:     if (!$symb) {
 9222:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9223:     }
 9224:     if ($symb) {
 9225:         @symbs = ($symb);
 9226:     } elsif (keys(%possibles)) { 
 9227:         @symbs = keys(%possibles);
 9228:     }
 9229:     my $noblock;
 9230:     foreach my $symb (@symbs) {
 9231:         last if ($noblock);
 9232:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9233:         foreach my $block (keys(%blockinfo)) {
 9234:             if ($block =~ /^firstaccess____(.+)$/) {
 9235:                 my $item = $1;
 9236:                 unless ($blocked) {
 9237:                     if (($item eq $map) || ($item eq $symb)) {
 9238:                         $noblock = 1;
 9239:                         last;
 9240:                     }
 9241:                 }
 9242:             }
 9243:             if (ref($blockinfo{$block}) eq 'HASH') {
 9244:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9245:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9246:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9247:                             push(@blockers,$block);
 9248:                         }
 9249:                     }
 9250:                 }
 9251:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9252:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9253:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9254:                             push(@blockers,$block);
 9255:                         }
 9256:                     }
 9257:                 }
 9258:             }
 9259:         }
 9260:     }
 9261:     unless ($noblock) { 
 9262:         return @blockers;
 9263:     }
 9264:     return;
 9265: }
 9266: }
 9267: 
 9268: sub deeplink_check {
 9269:     my ($priv,$symb,$uri) = @_;
 9270:     return unless ($env{'request.course.id'});
 9271:     return unless ($priv eq 'bre');
 9272:     return if ($env{'request.state'} eq 'construct');
 9273:     return if ($env{'request.role.adv'});
 9274:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9275:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9276:     my (%possibles,@symbs);
 9277:     if (!$symb) {
 9278:         $symb = &symbread($uri,1,1,1,\%possibles);
 9279:     }
 9280:     if ($symb) {
 9281:         @symbs = ($symb);
 9282:     } elsif (keys(%possibles)) {
 9283:         @symbs = keys(%possibles);
 9284:     }
 9285: 
 9286:     my ($deeplink_symb,$allow);
 9287:     if ($env{'request.deeplink.login'}) {
 9288:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9289:     }
 9290:     foreach my $symb (@symbs) {
 9291:         last if ($allow);
 9292:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9293:         if ($deeplink eq '') {
 9294:             $allow = 1;
 9295:         } else {
 9296:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9297:             if ($state ne 'only') {
 9298:                 $allow = 1;
 9299:             } else {
 9300:                 my $check_deeplink_entry;
 9301:                 if ($protect ne 'none') {
 9302:                     my ($acctype,$item) = split(/:/,$protect);
 9303:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9304:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9305:                             $check_deeplink_entry = 1
 9306:                         }
 9307:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9308:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9309:                             $check_deeplink_entry = 1;
 9310:                         }
 9311:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9312:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9313:                             $check_deeplink_entry = 1;
 9314:                         }
 9315:                     }
 9316:                 }
 9317:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9318:                     if ($scope eq 'res') {
 9319:                         if ($symb eq $deeplink_symb) {
 9320:                             $allow = 1;
 9321:                         }
 9322:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9323:                         my ($map_from_symb,$map_from_login);
 9324:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9325:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9326:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9327:                         } else {
 9328:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9329:                         }
 9330:                         if (($map_from_symb) && ($map_from_login)) {
 9331:                             if ($map_from_symb eq $map_from_login) {
 9332:                                 $allow = 1;
 9333:                             } elsif ($scope eq 'rec') {
 9334:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9335:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9336:                                     $allow = 1;
 9337:                                 }
 9338:                             }
 9339:                         }
 9340:                     }
 9341:                 }
 9342:             }
 9343:         }
 9344:     }
 9345:     return if ($allow);
 9346:     return 1;
 9347: }
 9348: 
 9349: # -------------------------------- Deversion and split uri into path an filename   
 9350: 
 9351: #
 9352: #   Removes the version from a URI and
 9353: #   splits it in to its filename and path to the filename.
 9354: #   Seems like File::Basename could have done this more clearly.
 9355: #   Parameters:
 9356: #      $uri   - input URI
 9357: #   Returns:
 9358: #     Two element list consisting of 
 9359: #     $pathname  - the URI up to and excluding the trailing /
 9360: #     $filename  - The part of the URI following the last /
 9361: #  NOTE:
 9362: #    Another realization of this is simply:
 9363: #    use File::Basename;
 9364: #    ...
 9365: #    $uri = shift;
 9366: #    $filename = basename($uri);
 9367: #    $path     = dirname($uri);
 9368: #    return ($filename, $path);
 9369: #
 9370: #     The implementation below is probably faster however.
 9371: #
 9372: sub split_uri_for_cond {
 9373:     my $uri=&deversion(&declutter(shift));
 9374:     my @uriparts=split(/\//,$uri);
 9375:     my $filename=pop(@uriparts);
 9376:     my $pathname=join('/',@uriparts);
 9377:     return ($pathname,$filename);
 9378: }
 9379: # --------------------------------------------------- Is a resource on the map?
 9380: 
 9381: sub is_on_map {
 9382:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9383:     #Trying to find the conditional for the file
 9384:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9385: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9386:     if ($match) {
 9387: 	return (1,$1);
 9388:     } else {
 9389: 	return (0,0);
 9390:     }
 9391: }
 9392: 
 9393: # --------------------------------------------------------- Get symb from alias
 9394: 
 9395: sub get_symb_from_alias {
 9396:     my $symb=shift;
 9397:     my ($map,$resid,$url)=&decode_symb($symb);
 9398: # Already is a symb
 9399:     if ($url) { return $symb; }
 9400: # Must be an alias
 9401:     my $aliassymb='';
 9402:     my %bighash;
 9403:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9404:                             &GDBM_READER(),0640)) {
 9405:         my $rid=$bighash{'mapalias_'.$symb};
 9406: 	if ($rid) {
 9407: 	    my ($mapid,$resid)=split(/\./,$rid);
 9408: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9409: 				    $resid,$bighash{'src_'.$rid});
 9410: 	}
 9411:         untie %bighash;
 9412:     }
 9413:     return $aliassymb;
 9414: }
 9415: 
 9416: # ----------------------------------------------------------------- Define Role
 9417: 
 9418: sub definerole {
 9419:   if (allowed('mcr','/')) {
 9420:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9421:     foreach my $role (split(':',$sysrole)) {
 9422: 	my ($crole,$cqual)=split(/\&/,$role);
 9423:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9424:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9425: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9426:                return "refused:s:$crole&$cqual"; 
 9427:             }
 9428:         }
 9429:     }
 9430:     foreach my $role (split(':',$domrole)) {
 9431: 	my ($crole,$cqual)=split(/\&/,$role);
 9432:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9433:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9434: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9435:                return "refused:d:$crole&$cqual"; 
 9436:             }
 9437:         }
 9438:     }
 9439:     foreach my $role (split(':',$courole)) {
 9440: 	my ($crole,$cqual)=split(/\&/,$role);
 9441:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9442:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9443: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9444:                return "refused:c:$crole&$cqual"; 
 9445:             }
 9446:         }
 9447:     }
 9448:     my $uhome;
 9449:     if (($uname ne '') && ($udom ne '')) {
 9450:         $uhome = &homeserver($uname,$udom);
 9451:         return $uhome if ($uhome eq 'no_host');
 9452:     } else {
 9453:         $uname = $env{'user.name'};
 9454:         $udom = $env{'user.domain'};
 9455:         $uhome = $env{'user.home'};
 9456:     }
 9457:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9458:                 "$udom:$uname:rolesdef_$rolename=".
 9459:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9460:     return reply($command,$uhome);
 9461:   } else {
 9462:     return 'refused';
 9463:   }
 9464: }
 9465: 
 9466: # ---------------- Make a metadata query against the network of library servers
 9467: 
 9468: sub metadata_query {
 9469:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9470:     my %rhash;
 9471:     my %libserv = &all_library();
 9472:     my @server_list = (defined($server_array) ? @$server_array
 9473:                                               : keys(%libserv) );
 9474:     for my $server (@server_list) {
 9475:         my $domains = ''; 
 9476:         if (ref($domains_hash) eq 'HASH') {
 9477:             $domains = $domains_hash->{$server}; 
 9478:         }
 9479: 	unless ($custom or $customshow) {
 9480: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9481: 	    $rhash{$server}=$reply;
 9482: 	}
 9483: 	else {
 9484: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9485: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9486: 			     $server);
 9487: 	    $rhash{$server}=$reply;
 9488: 	}
 9489:     }
 9490:     return \%rhash;
 9491: }
 9492: 
 9493: # ----------------------------------------- Send log queries and wait for reply
 9494: 
 9495: sub log_query {
 9496:     my ($uname,$udom,$query,%filters)=@_;
 9497:     my $uhome=&homeserver($uname,$udom);
 9498:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9499:     my $uhost=&hostname($uhome);
 9500:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9501:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9502:                        $uhome);
 9503:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9504:     return get_query_reply($queryid);
 9505: }
 9506: 
 9507: # -------------------------- Update MySQL table for portfolio file
 9508: 
 9509: sub update_portfolio_table {
 9510:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9511:     if ($group ne '') {
 9512:         $file_name =~s /^\Q$group\E//;
 9513:     }
 9514:     my $homeserver = &homeserver($uname,$udom);
 9515:     my $queryid=
 9516:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9517:                ':'.&escape($file_name).':'.$action,$homeserver);
 9518:     my $reply = &get_query_reply($queryid);
 9519:     return $reply;
 9520: }
 9521: 
 9522: # -------------------------- Update MySQL allusers table
 9523: 
 9524: sub update_allusers_table {
 9525:     my ($uname,$udom,$names) = @_;
 9526:     my $homeserver = &homeserver($uname,$udom);
 9527:     my $queryid=
 9528:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9529:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9530:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9531:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9532:                'generation='.&escape($names->{'generation'}).'%%'.
 9533:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9534:                'id='.&escape($names->{'id'}),$homeserver);
 9535:     return;
 9536: }
 9537: 
 9538: # ------- Request retrieval of institutional classlists for course(s)
 9539: 
 9540: sub fetch_enrollment_query {
 9541:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9542:     my ($homeserver,$sleep,$loopmax);
 9543:     my $maxtries = 1;
 9544:     if ($context eq 'automated') {
 9545:         $homeserver = $perlvar{'lonHostID'};
 9546:         $sleep = 2;
 9547:         $loopmax = 100;
 9548:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9549:     } else {
 9550:         $homeserver = &homeserver($cnum,$dom);
 9551:     }
 9552:     my $host=&hostname($homeserver);
 9553:     my $cmd = '';
 9554:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9555:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9556:     }
 9557:     $cmd =~ s/%%$//;
 9558:     $cmd = &escape($cmd);
 9559:     my $query = 'fetchenrollment';
 9560:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9561:     unless ($queryid=~/^\Q$host\E\_/) { 
 9562:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9563:         return 'error: '.$queryid;
 9564:     }
 9565:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9566:     my $tries = 1;
 9567:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9568:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9569:         $tries ++;
 9570:     }
 9571:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9572:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9573:     } else {
 9574:         my @responses = split(/:/,$reply);
 9575:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9576:             foreach my $line (@responses) {
 9577:                 my ($key,$value) = split(/=/,$line,2);
 9578:                 $$replyref{$key} = $value;
 9579:             }
 9580:         } else {
 9581:             my $pathname = LONCAPA::tempdir();
 9582:             foreach my $line (@responses) {
 9583:                 my ($key,$value) = split(/=/,$line);
 9584:                 $$replyref{$key} = $value;
 9585:                 if ($value > 0) {
 9586:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9587:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9588:                         my $destname = $pathname.'/'.$filename;
 9589:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9590:                         if ($xml_classlist =~ /^error/) {
 9591:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9592:                         } else {
 9593:                             if ( open(FILE,">",$destname) ) {
 9594:                                 print FILE &unescape($xml_classlist);
 9595:                                 close(FILE);
 9596:                             } else {
 9597:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9598:                             }
 9599:                         }
 9600:                     }
 9601:                 }
 9602:             }
 9603:         }
 9604:         return 'ok';
 9605:     }
 9606:     return 'error';
 9607: }
 9608: 
 9609: sub get_query_reply {
 9610:     my ($queryid,$sleep,$loopmax) = @_;
 9611:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9612:         $sleep = 0.2;
 9613:     }
 9614:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9615:         $loopmax = 100;
 9616:     }
 9617:     my $replyfile=LONCAPA::tempdir().$queryid;
 9618:     my $reply='';
 9619:     for (1..$loopmax) {
 9620: 	sleep($sleep);
 9621:         if (-e $replyfile.'.end') {
 9622: 	    if (open(my $fh,"<",$replyfile)) {
 9623: 		$reply = join('',<$fh>);
 9624: 		close($fh);
 9625: 	   } else { return 'error: reply_file_error'; }
 9626:            return &unescape($reply);
 9627: 	}
 9628:     }
 9629:     return 'timeout:'.$queryid;
 9630: }
 9631: 
 9632: sub courselog_query {
 9633: #
 9634: # possible filters:
 9635: # url: url or symb
 9636: # username
 9637: # domain
 9638: # action: view, submit, grade
 9639: # start: timestamp
 9640: # end: timestamp
 9641: #
 9642:     my (%filters)=@_;
 9643:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9644:     if ($filters{'url'}) {
 9645: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9646:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9647:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9648:     }
 9649:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9650:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9651:     return &log_query($cname,$cdom,'courselog',%filters);
 9652: }
 9653: 
 9654: sub userlog_query {
 9655: #
 9656: # possible filters:
 9657: # action: log check role
 9658: # start: timestamp
 9659: # end: timestamp
 9660: #
 9661:     my ($uname,$udom,%filters)=@_;
 9662:     return &log_query($uname,$udom,'userlog',%filters);
 9663: }
 9664: 
 9665: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9666: 
 9667: sub auto_run {
 9668:     my ($cnum,$cdom) = @_;
 9669:     my $response = 0;
 9670:     my $settings;
 9671:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9672:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9673:         $settings = $domconfig{'autoenroll'};
 9674:         if ($settings->{'run'} eq '1') {
 9675:             $response = 1;
 9676:         }
 9677:     } else {
 9678:         my $homeserver;
 9679:         if (&is_course($cdom,$cnum)) {
 9680:             $homeserver = &homeserver($cnum,$cdom);
 9681:         } else {
 9682:             $homeserver = &domain($cdom,'primary');
 9683:         }
 9684:         if ($homeserver ne 'no_host') {
 9685:             $response = &reply('autorun:'.$cdom,$homeserver);
 9686:         }
 9687:     }
 9688:     return $response;
 9689: }
 9690: 
 9691: sub auto_get_sections {
 9692:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9693:     my $homeserver;
 9694:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9695:         $homeserver = &homeserver($cnum,$cdom);
 9696:     }
 9697:     if (!defined($homeserver)) { 
 9698:         if ($cdom =~ /^$match_domain$/) {
 9699:             $homeserver = &domain($cdom,'primary');
 9700:         }
 9701:     }
 9702:     my @secs;
 9703:     if (defined($homeserver)) {
 9704:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9705:         unless ($response eq 'refused') {
 9706:             @secs = split(/:/,$response);
 9707:         }
 9708:     }
 9709:     return @secs;
 9710: }
 9711: 
 9712: sub auto_new_course {
 9713:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9714:     my $homeserver = &homeserver($cnum,$cdom);
 9715:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9716:     return $response;
 9717: }
 9718: 
 9719: sub auto_validate_courseID {
 9720:     my ($cnum,$cdom,$inst_course_id) = @_;
 9721:     my $homeserver = &homeserver($cnum,$cdom);
 9722:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9723:     return $response;
 9724: }
 9725: 
 9726: sub auto_validate_instcode {
 9727:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9728:     my ($homeserver,$response);
 9729:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9730:         $homeserver = &homeserver($cnum,$cdom);
 9731:     }
 9732:     if (!defined($homeserver)) {
 9733:         if ($cdom =~ /^$match_domain$/) {
 9734:             $homeserver = &domain($cdom,'primary');
 9735:         }
 9736:     }
 9737:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9738:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9739:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9740:     return ($outcome,$description,$defaultcredits);
 9741: }
 9742: 
 9743: sub auto_validate_inst_crosslist {
 9744:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9745:     my ($homeserver,$response);
 9746:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9747:         $homeserver = &homeserver($cnum,$cdom);
 9748:     }
 9749:     if (!defined($homeserver)) {
 9750:         if ($cdom =~ /^$match_domain$/) {
 9751:             $homeserver = &domain($cdom,'primary');
 9752:         }
 9753:     }
 9754:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9755:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9756:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9757:                          &escape($coowner),$homeserver);
 9758:     }
 9759:     return $response;
 9760: }
 9761: 
 9762: sub auto_create_password {
 9763:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9764:     my ($homeserver,$response);
 9765:     my $create_passwd = 0;
 9766:     my $authchk = '';
 9767:     if ($udom =~ /^$match_domain$/) {
 9768:         $homeserver = &domain($udom,'primary');
 9769:     }
 9770:     if ($homeserver eq '') {
 9771:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9772:             $homeserver = &homeserver($cnum,$cdom);
 9773:         }
 9774:     }
 9775:     if ($homeserver eq '') {
 9776:         $authchk = 'nodomain';
 9777:     } else {
 9778:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9779:         if ($response eq 'refused') {
 9780:             $authchk = 'refused';
 9781:         } else {
 9782:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9783:         }
 9784:     }
 9785:     return ($authparam,$create_passwd,$authchk);
 9786: }
 9787: 
 9788: sub auto_photo_permission {
 9789:     my ($cnum,$cdom,$students) = @_;
 9790:     my $homeserver = &homeserver($cnum,$cdom);
 9791:     my ($outcome,$perm_reqd,$conditions) = 
 9792: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9793:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9794: 	return (undef,undef);
 9795:     }
 9796:     return ($outcome,$perm_reqd,$conditions);
 9797: }
 9798: 
 9799: sub auto_checkphotos {
 9800:     my ($uname,$udom,$pid) = @_;
 9801:     my $homeserver = &homeserver($uname,$udom);
 9802:     my ($result,$resulttype);
 9803:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9804: 				   &escape($uname).':'.&escape($pid),
 9805: 				   $homeserver));
 9806:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9807: 	return (undef,undef);
 9808:     }
 9809:     if ($outcome) {
 9810:         ($result,$resulttype) = split(/:/,$outcome);
 9811:     } 
 9812:     return ($result,$resulttype);
 9813: }
 9814: 
 9815: sub auto_photochoice {
 9816:     my ($cnum,$cdom) = @_;
 9817:     my $homeserver = &homeserver($cnum,$cdom);
 9818:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9819: 						       &escape($cdom),
 9820: 						       $homeserver)));
 9821:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9822: 	return (undef,undef);
 9823:     }
 9824:     return ($update,$comment);
 9825: }
 9826: 
 9827: sub auto_photoupdate {
 9828:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9829:     my $homeserver = &homeserver($cnum,$dom);
 9830:     my $host=&hostname($homeserver);
 9831:     my $cmd = '';
 9832:     my $maxtries = 1;
 9833:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9834:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9835:     }
 9836:     $cmd =~ s/%%$//;
 9837:     $cmd = &escape($cmd);
 9838:     my $query = 'institutionalphotos';
 9839:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9840:     unless ($queryid=~/^\Q$host\E\_/) {
 9841:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9842:         return 'error: '.$queryid;
 9843:     }
 9844:     my $reply = &get_query_reply($queryid);
 9845:     my $tries = 1;
 9846:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9847:         $reply = &get_query_reply($queryid);
 9848:         $tries ++;
 9849:     }
 9850:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9851:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9852:     } else {
 9853:         my @responses = split(/:/,$reply);
 9854:         my $outcome = shift(@responses); 
 9855:         foreach my $item (@responses) {
 9856:             my ($key,$value) = split(/=/,$item);
 9857:             $$photo{$key} = $value;
 9858:         }
 9859:         return $outcome;
 9860:     }
 9861:     return 'error';
 9862: }
 9863: 
 9864: sub auto_instcode_format {
 9865:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9866: 	$cat_order) = @_;
 9867:     my $courses = '';
 9868:     my @homeservers;
 9869:     if ($caller eq 'global') {
 9870: 	my %servers = &get_servers($codedom,'library');
 9871: 	foreach my $tryserver (keys(%servers)) {
 9872: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9873: 		push(@homeservers,$tryserver);
 9874: 	    }
 9875:         }
 9876:     } elsif ($caller eq 'requests') {
 9877:         if ($codedom =~ /^$match_domain$/) {
 9878:             my $chome = &domain($codedom,'primary');
 9879:             unless ($chome eq 'no_host') {
 9880:                 push(@homeservers,$chome);
 9881:             }
 9882:         }
 9883:     } else {
 9884:         push(@homeservers,&homeserver($caller,$codedom));
 9885:     }
 9886:     foreach my $code (keys(%{$instcodes})) {
 9887:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9888:     }
 9889:     chop($courses);
 9890:     my $ok_response = 0;
 9891:     my $response;
 9892:     while (@homeservers > 0 && $ok_response == 0) {
 9893:         my $server = shift(@homeservers); 
 9894:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9895:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9896:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9897: 		split(/:/,$response);
 9898:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9899:             push(@{$codetitles},&str2array($codetitles_str));
 9900:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9901:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9902:             $ok_response = 1;
 9903:         }
 9904:     }
 9905:     if ($ok_response) {
 9906:         return 'ok';
 9907:     } else {
 9908:         return $response;
 9909:     }
 9910: }
 9911: 
 9912: sub auto_instcode_defaults {
 9913:     my ($domain,$returnhash,$code_order) = @_;
 9914:     my @homeservers;
 9915: 
 9916:     my %servers = &get_servers($domain,'library');
 9917:     foreach my $tryserver (keys(%servers)) {
 9918: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9919: 	    push(@homeservers,$tryserver);
 9920: 	}
 9921:     }
 9922: 
 9923:     my $response;
 9924:     foreach my $server (@homeservers) {
 9925:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9926:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9927: 	
 9928: 	foreach my $pair (split(/\&/,$response)) {
 9929: 	    my ($name,$value)=split(/\=/,$pair);
 9930: 	    if ($name eq 'code_order') {
 9931: 		@{$code_order} = split(/\&/,&unescape($value));
 9932: 	    } else {
 9933: 		$returnhash->{&unescape($name)}=&unescape($value);
 9934: 	    }
 9935: 	}
 9936: 	return 'ok';
 9937:     }
 9938: 
 9939:     return $response;
 9940: }
 9941: 
 9942: sub auto_possible_instcodes {
 9943:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9944:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9945:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9946:         return;
 9947:     }
 9948:     my (@homeservers,$uhome);
 9949:     if (defined(&domain($domain,'primary'))) {
 9950:         $uhome=&domain($domain,'primary');
 9951:         push(@homeservers,&domain($domain,'primary'));
 9952:     } else {
 9953:         my %servers = &get_servers($domain,'library');
 9954:         foreach my $tryserver (keys(%servers)) {
 9955:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9956:                 push(@homeservers,$tryserver);
 9957:             }
 9958:         }
 9959:     }
 9960:     my $response;
 9961:     foreach my $server (@homeservers) {
 9962:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9963:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9964:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9965:             split(':',$response);
 9966:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9967:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9968:         foreach my $item (split('&',$cat_title)) {   
 9969:             my ($name,$value)=split('=',$item);
 9970:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9971:         }
 9972:         foreach my $item (split('&',$cat_order)) {
 9973:             my ($name,$value)=split('=',$item);
 9974:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9975:         }
 9976:         return 'ok';
 9977:     }
 9978:     return $response;
 9979: }
 9980: 
 9981: sub auto_courserequest_checks {
 9982:     my ($dom) = @_;
 9983:     my ($homeserver,%validations);
 9984:     if ($dom =~ /^$match_domain$/) {
 9985:         $homeserver = &domain($dom,'primary');
 9986:     }
 9987:     unless ($homeserver eq 'no_host') {
 9988:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9989:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9990:             my @items = split(/&/,$response);
 9991:             foreach my $item (@items) {
 9992:                 my ($key,$value) = split('=',$item);
 9993:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9994:             }
 9995:         }
 9996:     }
 9997:     return %validations; 
 9998: }
 9999: 
10000: sub auto_courserequest_validation {
10001:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10002:     my ($homeserver,$response);
10003:     if ($dom =~ /^$match_domain$/) {
10004:         $homeserver = &domain($dom,'primary');
10005:     }
10006:     unless ($homeserver eq 'no_host') {
10007:         my $customdata;
10008:         if (ref($custominfo) eq 'HASH') {
10009:             $customdata = &freeze_escape($custominfo);
10010:         }
10011:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10012:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10013:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10014:                                     $customdata,$homeserver));
10015:     }
10016:     return $response;
10017: }
10018: 
10019: sub auto_validate_class_sec {
10020:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10021:     my $homeserver = &homeserver($cnum,$cdom);
10022:     my $ownerlist;
10023:     if (ref($owners) eq 'ARRAY') {
10024:         $ownerlist = join(',',@{$owners});
10025:     } else {
10026:         $ownerlist = $owners;
10027:     }
10028:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10029:                         &escape($ownerlist).':'.$cdom,$homeserver);
10030:     return $response;
10031: }
10032: 
10033: sub auto_instsec_reformat {
10034:     my ($cdom,$action,$instsecref) = @_;
10035:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10036:     my @homeservers;
10037:     if (defined(&domain($cdom,'primary'))) {
10038:         push(@homeservers,&domain($cdom,'primary'));
10039:     } else {
10040:         my %servers = &get_servers($cdom,'library');
10041:         foreach my $tryserver (keys(%servers)) {
10042:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10043:                 push(@homeservers,$tryserver);
10044:             }
10045:         }
10046:     }
10047:     my $response;
10048:     my %reformatted = %{$instsecref};
10049:     foreach my $server (@homeservers) {
10050:         if (ref($instsecref) eq 'HASH') {
10051:             my $info = &freeze_escape($instsecref);
10052:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10053:                                 $action.':'.$info,$server);
10054:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10055:             my @items = split(/&/,$response);
10056:             foreach my $item (@items) {
10057:                 my ($key,$value) = split(/=/,$item);
10058:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10059:             }
10060:         }
10061:     }
10062:     return %reformatted;
10063: }
10064: 
10065: sub auto_validate_instclasses {
10066:     my ($cdom,$cnum,$owners,$classesref) = @_;
10067:     my ($homeserver,%validations);
10068:     $homeserver = &homeserver($cnum,$cdom);
10069:     unless ($homeserver eq 'no_host') {
10070:         my $ownerlist;
10071:         if (ref($owners) eq 'ARRAY') {
10072:             $ownerlist = join(',',@{$owners});
10073:         } else {
10074:             $ownerlist = $owners;
10075:         }
10076:         if (ref($classesref) eq 'HASH') {
10077:             my $classes = &freeze_escape($classesref);
10078:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10079:                                 ':'.$cdom.':'.$classes,$homeserver);
10080:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10081:                 my @items = split(/&/,$response);
10082:                 foreach my $item (@items) {
10083:                     my ($key,$value) = split('=',$item);
10084:                     $validations{&unescape($key)} = &thaw_unescape($value);
10085:                 }
10086:             }
10087:         }
10088:     }
10089:     return %validations;
10090: }
10091: 
10092: sub auto_crsreq_update {
10093:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10094:         $code,$accessstart,$accessend,$inbound) = @_;
10095:     my ($homeserver,%crsreqresponse);
10096:     if ($cdom =~ /^$match_domain$/) {
10097:         $homeserver = &domain($cdom,'primary');
10098:     }
10099:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10100:         my $info;
10101:         if (ref($inbound) eq 'HASH') {
10102:             $info = &freeze_escape($inbound);
10103:         }
10104:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10105:                             ':'.&escape($action).':'.&escape($ownername).':'.
10106:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10107:                             &escape($title).':'.&escape($code).':'.
10108:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10109:                             $homeserver);
10110:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10111:             my @items = split(/&/,$response);
10112:             foreach my $item (@items) {
10113:                 my ($key,$value) = split('=',$item);
10114:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10115:             }
10116:         }
10117:     }
10118:     return \%crsreqresponse;
10119: }
10120: 
10121: sub auto_export_grades {
10122:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10123:     my ($homeserver,%exportresponse);
10124:     if ($cdom =~ /^$match_domain$/) {
10125:         $homeserver = &domain($cdom,'primary');
10126:     }
10127:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10128:         my $info;
10129:         if (ref($inforef) eq 'HASH') {
10130:             $info = &freeze_escape($inforef);
10131:         }
10132:         if (ref($gradesref) eq 'HASH') {
10133:             my $grades = &freeze_escape($gradesref);
10134:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10135:                                 $info.':'.$grades,$homeserver);
10136:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10137:                 my @items = split(/&/,$response);
10138:                 foreach my $item (@items) {
10139:                     my ($key,$value) = split('=',$item);
10140:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10141:                 }
10142:             }
10143:         }
10144:     }
10145:     return \%exportresponse;
10146: }
10147: 
10148: sub check_instcode_cloning {
10149:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10150:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10151:         return;
10152:     }
10153:     my $canclone;
10154:     if (@{$code_order} > 0) {
10155:         my $instcoderegexp ='^';
10156:         my @clonecodes = split(/\&/,$cloner);
10157:         foreach my $item (@{$code_order}) {
10158:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10159:                 foreach my $pair (@clonecodes) {
10160:                     my ($key,$val) = split(/\=/,$pair,2);
10161:                     $val = &unescape($val);
10162:                     if ($key eq $item) {
10163:                         $instcoderegexp .= '('.$val.')';
10164:                         last;
10165:                     }
10166:                 }
10167:             } else {
10168:                 $instcoderegexp .= $codedefaults->{$item};
10169:             }
10170:         }
10171:         $instcoderegexp .= '$';
10172:         my (@from,@to);
10173:         eval {
10174:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10175:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10176:         };
10177:         if ((@from > 0) && (@to > 0)) {
10178:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10179:             if (!@diffs) {
10180:                 $canclone = 1;
10181:             }
10182:         }
10183:     }
10184:     return $canclone;
10185: }
10186: 
10187: sub default_instcode_cloning {
10188:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10189:     my (%codedefaults,@code_order,$canclone);
10190:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10191:         %codedefaults = %{$codedefaultsref};
10192:         @code_order = @{$codeorderref};
10193:     } elsif ($clonedom) {
10194:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10195:     }
10196:     if (($domdefclone) && (@code_order)) {
10197:         my @clonecodes = split(/\+/,$domdefclone);
10198:         my $instcoderegexp ='^';
10199:         foreach my $item (@code_order) {
10200:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10201:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10202:             } else {
10203:                 $instcoderegexp .= $codedefaults{$item};
10204:             }
10205:         }
10206:         $instcoderegexp .= '$';
10207:         my (@from,@to);
10208:         eval {
10209:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10210:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10211:         };
10212:         if ((@from > 0) && (@to > 0)) {
10213:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10214:             if (!@diffs) {
10215:                 $canclone = 1;
10216:             }
10217:         }
10218:     }
10219:     return $canclone;
10220: }
10221: 
10222: # ------------------------------------------------------- Course Group routines
10223: 
10224: sub get_coursegroups {
10225:     my ($cdom,$cnum,$group,$namespace) = @_;
10226:     return(&dump($namespace,$cdom,$cnum,$group));
10227: }
10228: 
10229: sub modify_coursegroup {
10230:     my ($cdom,$cnum,$groupsettings) = @_;
10231:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10232: }
10233: 
10234: sub toggle_coursegroup_status {
10235:     my ($cdom,$cnum,$group,$action) = @_;
10236:     my ($from_namespace,$to_namespace);
10237:     if ($action eq 'delete') {
10238:         $from_namespace = 'coursegroups';
10239:         $to_namespace = 'deleted_groups';
10240:     } else {
10241:         $from_namespace = 'deleted_groups';
10242:         $to_namespace = 'coursegroups';
10243:     }
10244:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10245:     if (my $tmp = &error(%curr_group)) {
10246:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10247:         return ('read error',$tmp);
10248:     } else {
10249:         my %savedsettings = %curr_group; 
10250:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10251:         my $deloutcome;
10252:         if ($result eq 'ok') {
10253:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10254:         } else {
10255:             return ('write error',$result);
10256:         }
10257:         if ($deloutcome eq 'ok') {
10258:             return 'ok';
10259:         } else {
10260:             return ('delete error',$deloutcome);
10261:         }
10262:     }
10263: }
10264: 
10265: sub modify_group_roles {
10266:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10267:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10268:     my $role = 'gr/'.&escape($userprivs);
10269:     my ($uname,$udom) = split(/:/,$user);
10270:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10271:     if ($result eq 'ok') {
10272:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10273:     }
10274:     return $result;
10275: }
10276: 
10277: sub modify_coursegroup_membership {
10278:     my ($cdom,$cnum,$membership) = @_;
10279:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10280:     return $result;
10281: }
10282: 
10283: sub get_active_groups {
10284:     my ($udom,$uname,$cdom,$cnum) = @_;
10285:     my $now = time;
10286:     my %groups = ();
10287:     foreach my $key (keys(%env)) {
10288:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10289:             my ($start,$end) = split(/\./,$env{$key});
10290:             if (($end!=0) && ($end<$now)) { next; }
10291:             if (($start!=0) && ($start>$now)) { next; }
10292:             if ($1 eq $cdom && $2 eq $cnum) {
10293:                 $groups{$3} = $env{$key} ;
10294:             }
10295:         }
10296:     }
10297:     return %groups;
10298: }
10299: 
10300: sub get_group_membership {
10301:     my ($cdom,$cnum,$group) = @_;
10302:     return(&dump('groupmembership',$cdom,$cnum,$group));
10303: }
10304: 
10305: sub get_users_groups {
10306:     my ($udom,$uname,$courseid) = @_;
10307:     my @usersgroups;
10308:     my $cachetime=1800;
10309: 
10310:     my $hashid="$udom:$uname:$courseid";
10311:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10312:     if (defined($cached)) {
10313:         @usersgroups = split(/:/,$grouplist);
10314:     } else {  
10315:         $grouplist = '';
10316:         my $courseurl = &courseid_to_courseurl($courseid);
10317:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10318:         my $access_end = $env{'course.'.$courseid.
10319:                               '.default_enrollment_end_date'};
10320:         my $now = time;
10321:         foreach my $key (keys(%roleshash)) {
10322:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10323:                 my $group = $1;
10324:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10325:                     my $start = $2;
10326:                     my $end = $1;
10327:                     if ($start == -1) { next; } # deleted from group
10328:                     if (($start!=0) && ($start>$now)) { next; }
10329:                     if (($end!=0) && ($end<$now)) {
10330:                         if ($access_end && $access_end < $now) {
10331:                             if ($access_end - $end < 86400) {
10332:                                 push(@usersgroups,$group);
10333:                             }
10334:                         }
10335:                         next;
10336:                     }
10337:                     push(@usersgroups,$group);
10338:                 }
10339:             }
10340:         }
10341:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10342:         $grouplist = join(':',@usersgroups);
10343:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10344:     }
10345:     return @usersgroups;
10346: }
10347: 
10348: sub devalidate_getgroups_cache {
10349:     my ($udom,$uname,$cdom,$cnum)=@_;
10350:     my $courseid = $cdom.'_'.$cnum;
10351: 
10352:     my $hashid="$udom:$uname:$courseid";
10353:     &devalidate_cache_new('getgroups',$hashid);
10354: }
10355: 
10356: # ------------------------------------------------------------------ Plain Text
10357: 
10358: sub plaintext {
10359:     my ($short,$type,$cid,$forcedefault) = @_;
10360:     if ($short =~ m{^cr/}) {
10361: 	return (split('/',$short))[-1];
10362:     }
10363:     if (!defined($cid)) {
10364:         $cid = $env{'request.course.id'};
10365:     }
10366:     my %rolenames = (
10367:                       Course    => 'std',
10368:                       Community => 'alt1',
10369:                       Placement => 'std',
10370:                     );
10371:     if ($cid ne '') {
10372:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10373:             unless ($forcedefault) {
10374:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10375:                 &Apache::lonlocal::mt_escape(\$roletext);
10376:                 return &Apache::lonlocal::mt($roletext);
10377:             }
10378:         }
10379:     }
10380:     if ((defined($type)) && (defined($rolenames{$type})) &&
10381:         (defined($rolenames{$type})) && 
10382:         (defined($prp{$short}{$rolenames{$type}}))) {
10383:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10384:     } elsif ($cid ne '') {
10385:         my $crstype = $env{'course.'.$cid.'.type'};
10386:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10387:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10388:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10389:         }
10390:     }
10391:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10392: }
10393: 
10394: # ----------------------------------------------------------------- Assign Role
10395: 
10396: sub assignrole {
10397:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10398:         $context)=@_;
10399:     my $mrole;
10400:     if ($role =~ /^cr\//) {
10401:         my $cwosec=$url;
10402:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10403:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10404:            my $refused = 1;
10405:            if ($context eq 'requestcourses') {
10406:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10407:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10408:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10409:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10410:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10411:                            if ($crsenv{'internal.courseowner'} eq
10412:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10413:                                $refused = '';
10414:                            }
10415:                        }
10416:                    }
10417:                }
10418:            }
10419:            if ($refused) {
10420:                &logthis('Refused custom assignrole: '.
10421:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10422:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10423:                return 'refused';
10424:            }
10425:         }
10426:         $mrole='cr';
10427:     } elsif ($role =~ /^gr\//) {
10428:         my $cwogrp=$url;
10429:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10430:         unless (&allowed('mdg',$cwogrp)) {
10431:             &logthis('Refused group assignrole: '.
10432:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10433:                     $env{'user.name'}.' at '.$env{'user.domain'});
10434:             return 'refused';
10435:         }
10436:         $mrole='gr';
10437:     } else {
10438:         my $cwosec=$url;
10439:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10440:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10441:             my $refused;
10442:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10443:                 if (!(&allowed('c'.$role,$url))) {
10444:                     $refused = 1;
10445:                 }
10446:             } else {
10447:                 $refused = 1;
10448:             }
10449:             if ($refused) {
10450:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10451:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10452:                     my %crsenv;
10453:                     if ($role eq 'cc' || $role eq 'co') {
10454:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10455:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10456:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10457:                                 if ($crsenv{'internal.courseowner'} eq 
10458:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10459:                                     $refused = '';
10460:                                 }
10461:                             }
10462:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10463:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10464:                                 if ($crsenv{'internal.courseowner'} eq 
10465:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10466:                                     $refused = '';
10467:                                 }
10468:                             }
10469:                         }
10470:                     }
10471:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10472:                     if ($role eq 'st') {
10473:                         $refused = '';
10474:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10475:                         $refused = '';
10476:                     }
10477:                 } elsif ($context eq 'requestcourses') {
10478:                     my @possroles = ('st','ta','ep','in','cc','co');
10479:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10480:                         my $wrongcc;
10481:                         if ($cnum =~ /^$match_community$/) {
10482:                             $wrongcc = 1 if ($role eq 'cc');
10483:                         } else {
10484:                             $wrongcc = 1 if ($role eq 'co');
10485:                         }
10486:                         unless ($wrongcc) {
10487:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10488:                             if ($crsenv{'internal.courseowner'} eq 
10489:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10490:                                 $refused = '';
10491:                             }
10492:                         }
10493:                     }
10494:                 } elsif ($context eq 'requestauthor') {
10495:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10496:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10497:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10498:                             $refused = '';
10499:                         } else {
10500:                             my %domdefaults = &get_domain_defaults($udom);
10501:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10502:                                 my $checkbystatus;
10503:                                 if ($env{'user.adv'}) { 
10504:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10505:                                     if ($disposition eq 'automatic') {
10506:                                         $refused = '';
10507:                                     } elsif ($disposition eq '') {
10508:                                         $checkbystatus = 1;
10509:                                     } 
10510:                                 } else {
10511:                                     $checkbystatus = 1;
10512:                                 }
10513:                                 if ($checkbystatus) {
10514:                                     if ($env{'environment.inststatus'}) {
10515:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10516:                                         foreach my $type (@inststatuses) {
10517:                                             if (($type ne '') &&
10518:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10519:                                                 $refused = '';
10520:                                             }
10521:                                         }
10522:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10523:                                         $refused = '';
10524:                                     }
10525:                                 }
10526:                             }
10527:                         }
10528:                     }
10529:                 }
10530:                 if ($refused) {
10531:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10532:                              ' '.$role.' '.$end.' '.$start.' by '.
10533: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10534:                     return 'refused';
10535:                 }
10536:             }
10537:         } elsif ($role eq 'au') {
10538:             if ($url ne '/'.$udom.'/') {
10539:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10540:                          ' to assign author role for '.$uname.':'.$udom.
10541:                          ' in domain: '.$url.' refused (wrong domain).');
10542:                 return 'refused';
10543:             }
10544:         }
10545:         $mrole=$role;
10546:     }
10547:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10548:                 "$udom:$uname:$url".'_'."$mrole=$role";
10549:     if ($end) { $command.='_'.$end; }
10550:     if ($start) {
10551: 	if ($end) { 
10552:            $command.='_'.$start; 
10553:         } else {
10554:            $command.='_0_'.$start;
10555:         }
10556:     }
10557:     my $origstart = $start;
10558:     my $origend = $end;
10559:     my $delflag;
10560: # actually delete
10561:     if ($deleteflag) {
10562: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10563: # modify command to delete the role
10564:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10565:                 "$udom:$uname:$url".'_'."$mrole";
10566: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10567: # set start and finish to negative values for userrolelog
10568:            $start=-1;
10569:            $end=-1;
10570:            $delflag = 1;
10571:         }
10572:     }
10573: # send command
10574:     my $answer=&reply($command,&homeserver($uname,$udom));
10575: # log new user role if status is ok
10576:     if ($answer eq 'ok') {
10577: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10578:         if (($role eq 'cc') || ($role eq 'in') ||
10579:             ($role eq 'ep') || ($role eq 'ad') ||
10580:             ($role eq 'ta') || ($role eq 'st') ||
10581:             ($role=~/^cr/) || ($role eq 'gr') ||
10582:             ($role eq 'co')) {
10583: # for course roles, perform group memberships changes triggered by role change.
10584:             unless ($role =~ /^gr/) {
10585:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10586:                                                  $origstart,$selfenroll,$context);
10587:             }
10588:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10589:                            $selfenroll,$context);
10590:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10591:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10592:                  ($role eq 'da')) {
10593:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10594:                            $context);
10595:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10596:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10597:                              $context); 
10598:         }
10599:         if ($role eq 'cc') {
10600:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10601:         }
10602:     }
10603:     return $answer;
10604: }
10605: 
10606: sub autoupdate_coowners {
10607:     my ($url,$end,$start,$uname,$udom) = @_;
10608:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10609:     if (($cdom ne '') && ($cnum ne '')) {
10610:         my $now = time;
10611:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10612:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10613:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10614:             my $instcode = $coursehash{'internal.coursecode'};
10615:             my $xlists = $coursehash{'internal.crosslistings'};
10616:             if ($instcode ne '') {
10617:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10618:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10619:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10620:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10621:                         unless ($result eq 'valid') {
10622:                             if ($xlists ne '') {
10623:                                 foreach my $xlist (split(',',$xlists)) {
10624:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10625:                                     $result =
10626:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10627:                                                                       $inst_crosslist,$uname.':'.$udom);
10628:                                     last if ($result eq 'valid');
10629:                                 }
10630:                             }
10631:                         }
10632:                         if ($result eq 'valid') {
10633:                             if ($coursehash{'internal.co-owners'}) {
10634:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10635:                                     push(@newcoowners,$coowner);
10636:                                 }
10637:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10638:                                     push(@newcoowners,$uname.':'.$udom);
10639:                                 }
10640:                                 @newcoowners = sort(@newcoowners);
10641:                             } else {
10642:                                 push(@newcoowners,$uname.':'.$udom);
10643:                             }
10644:                         } elsif ($coursehash{'internal.co-owners'}) {
10645:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10646:                                 unless ($coowner eq $uname.':'.$udom) {
10647:                                     push(@newcoowners,$coowner);
10648:                                 }
10649:                             }
10650:                             unless (@newcoowners > 0) {
10651:                                 $delcoowners = 1;
10652:                                 $coowners = '';
10653:                             }
10654:                         }
10655:                         if (@newcoowners || $delcoowners) {
10656:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10657:                                             $delcoowners,@newcoowners);
10658:                         }
10659:                     }
10660:                 }
10661:             }
10662:         }
10663:     }
10664: }
10665: 
10666: sub store_coowners {
10667:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10668:     my $cid = $cdom.'_'.$cnum;
10669:     my ($coowners,$delresult,$putresult);
10670:     if (@newcoowners) {
10671:         $coowners = join(',',@newcoowners);
10672:         my %coownershash = (
10673:                             'internal.co-owners' => $coowners,
10674:                            );
10675:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10676:         if ($putresult eq 'ok') {
10677:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10678:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10679:             }
10680:         }
10681:     }
10682:     if ($delcoowners) {
10683:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10684:         if ($delresult eq 'ok') {
10685:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10686:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10687:             }
10688:         }
10689:     }
10690:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10691:         my %crsinfo =
10692:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10693:         if (ref($crsinfo{$cid}) eq 'HASH') {
10694:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10695:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
10696:         }
10697:     }
10698: }
10699: 
10700: # -------------------------------------------------- Modify user authentication
10701: # Overrides without validation
10702: 
10703: sub modifyuserauth {
10704:     my ($udom,$uname,$umode,$upass)=@_;
10705:     my $uhome=&homeserver($uname,$udom);
10706:     my $allowed;
10707:     if (&allowed('mau',$udom)) {
10708:         $allowed = 1;
10709:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10710:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10711:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10712:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10713:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10714:         if (($cdom ne '') && ($cnum ne '')) {
10715:             my $is_owner = &is_course_owner($cdom,$cnum);
10716:             if ($is_owner) {
10717:                 $allowed = 1;
10718:             }
10719:         }
10720:     }
10721:     unless ($allowed) { return 'refused'; }
10722:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10723:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10724:              ' in domain '.$env{'request.role.domain'});  
10725:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10726: 		     &escape($upass),$uhome);
10727:     my $ip = &get_requestor_ip();
10728:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10729:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10730:          '(Remote '.$ip.'): '.$reply);
10731:     &log($udom,,$uname,$uhome,
10732:         'Authentication changed by '.$env{'user.domain'}.', '.
10733:                                      $env{'user.name'}.', '.$umode.
10734:          '(Remote '.$ip.'): '.$reply);
10735:     unless ($reply eq 'ok') {
10736:         &logthis('Authentication mode error: '.$reply);
10737: 	return 'error: '.$reply;
10738:     }   
10739:     return 'ok';
10740: }
10741: 
10742: # --------------------------------------------------------------- Modify a user
10743: 
10744: sub modifyuser {
10745:     my ($udom,    $uname, $uid,
10746:         $umode,   $upass, $first,
10747:         $middle,  $last,  $gene,
10748:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10749:     $udom= &LONCAPA::clean_domain($udom);
10750:     $uname=&LONCAPA::clean_username($uname);
10751:     my $showcandelete = 'none';
10752:     if (ref($candelete) eq 'ARRAY') {
10753:         if (@{$candelete} > 0) {
10754:             $showcandelete = join(', ',@{$candelete});
10755:         }
10756:     }
10757:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10758:              $umode.', '.$first.', '.$middle.', '.
10759: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10760:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10761:                                      ' desiredhome not specified'). 
10762:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10763:              ' in domain '.$env{'request.role.domain'});
10764:     my $uhome=&homeserver($uname,$udom,'true');
10765:     my $newuser;
10766:     if ($uhome eq 'no_host') {
10767:         $newuser = 1;
10768:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10769:                 ($umode eq 'lti')) {
10770:             return 'error: more information needed to create new user';
10771:         }
10772:     }
10773: # ----------------------------------------------------------------- Create User
10774:     if (($uhome eq 'no_host') && 
10775: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10776:         my $unhome='';
10777:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10778:             $unhome = $desiredhome;
10779: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10780: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10781:         } else { # load balancing routine for determining $unhome
10782:             my $loadm=10000000;
10783: 	    my %servers = &get_servers($udom,'library');
10784: 	    foreach my $tryserver (keys(%servers)) {
10785: 		my $answer=reply('load',$tryserver);
10786: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10787: 		    $loadm=$answer;
10788: 		    $unhome=$tryserver;
10789: 		}
10790: 	    }
10791:         }
10792:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10793: 	    return 'error: unable to find a home server for '.$uname.
10794:                    ' in domain '.$udom;
10795:         }
10796:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10797:                          &escape($upass),$unhome);
10798: 	unless ($reply eq 'ok') {
10799:             return 'error: '.$reply;
10800:         }   
10801:         $uhome=&homeserver($uname,$udom,'true');
10802:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10803: 	    return 'error: unable verify users home machine.';
10804:         }
10805:     }   # End of creation of new user
10806: # ---------------------------------------------------------------------- Add ID
10807:     if ($uid) {
10808:        $uid=~tr/A-Z/a-z/;
10809:        my %uidhash=&idrget($udom,$uname);
10810:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10811:          && (!$forceid)) {
10812: 	  unless ($uid eq $uidhash{$uname}) {
10813: 	      return 'error: user id "'.$uid.'" does not match '.
10814:                   'current user id "'.$uidhash{$uname}.'".';
10815:           }
10816:        } else {
10817: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10818:        }
10819:     }
10820: # -------------------------------------------------------------- Add names, etc
10821:     my @tmp=&get('environment',
10822: 		   ['firstname','middlename','lastname','generation','id',
10823:                     'permanentemail','inststatus'],
10824: 		   $udom,$uname);
10825:     my (%names,%oldnames);
10826:     if ($tmp[0] =~ m/^error:.*/) { 
10827:         %names=(); 
10828:     } else {
10829:         %names = @tmp;
10830:         %oldnames = %names;
10831:     }
10832: #
10833: # If name, email and/or uid are blank (e.g., because an uploaded file
10834: # of users did not contain them), do not overwrite existing values
10835: # unless field is in $candelete array ref.  
10836: #
10837: 
10838:     my @fields = ('firstname','middlename','lastname','generation',
10839:                   'permanentemail','id');
10840:     my %newvalues;
10841:     if (ref($candelete) eq 'ARRAY') {
10842:         foreach my $field (@fields) {
10843:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10844:                 if ($field eq 'firstname') {
10845:                     $names{$field} = $first;
10846:                 } elsif ($field eq 'middlename') {
10847:                     $names{$field} = $middle;
10848:                 } elsif ($field eq 'lastname') {
10849:                     $names{$field} = $last;
10850:                 } elsif ($field eq 'generation') { 
10851:                     $names{$field} = $gene;
10852:                 } elsif ($field eq 'permanentemail') {
10853:                     $names{$field} = $email;
10854:                 } elsif ($field eq 'id') {
10855:                     $names{$field}  = $uid;
10856:                 }
10857:             }
10858:         }
10859:     }
10860:     if ($first)  { $names{'firstname'}  = $first; }
10861:     if (defined($middle)) { $names{'middlename'} = $middle; }
10862:     if ($last)   { $names{'lastname'}   = $last; }
10863:     if (defined($gene))   { $names{'generation'} = $gene; }
10864:     if ($email) {
10865:        $email=~s/[^\w\@\.\-\,]//gs;
10866:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10867:     }
10868:     if ($uid) { $names{'id'}  = $uid; }
10869:     if (defined($inststatus)) {
10870:         $names{'inststatus'} = '';
10871:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10872:         if (ref($usertypes) eq 'HASH') {
10873:             my @okstatuses; 
10874:             foreach my $item (split(/:/,$inststatus)) {
10875:                 if (defined($usertypes->{$item})) {
10876:                     push(@okstatuses,$item);  
10877:                 }
10878:             }
10879:             if (@okstatuses) {
10880:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10881:             }
10882:         }
10883:     }
10884:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10885:                  $umode.', '.$first.', '.$middle.', '.
10886:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10887:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10888:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10889:     } else {
10890:         $logmsg .= ' during self creation';
10891:     }
10892:     my $changed;
10893:     if ($newuser) {
10894:         $changed = 1;
10895:     } else {
10896:         foreach my $field (@fields) {
10897:             if ($names{$field} ne $oldnames{$field}) {
10898:                 $changed = 1;
10899:                 last;
10900:             }
10901:         }
10902:     }
10903:     unless ($changed) {
10904:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10905:         &logthis($logmsg);
10906:         return 'ok';
10907:     }
10908:     my $reply = &put('environment', \%names, $udom,$uname);
10909:     if ($reply ne 'ok') { 
10910:         return 'error: '.$reply;
10911:     }
10912:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10913:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
10914:     }
10915:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10916:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10917:     $logmsg = 'Success modifying user '.$logmsg;
10918:     &logthis($logmsg);
10919:     return 'ok';
10920: }
10921: 
10922: # -------------------------------------------------------------- Modify student
10923: 
10924: sub modifystudent {
10925:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10926:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10927:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10928:     if (!$cid) {
10929: 	unless ($cid=$env{'request.course.id'}) {
10930: 	    return 'not_in_class';
10931: 	}
10932:     }
10933: # --------------------------------------------------------------- Make the user
10934:     my $reply=&modifyuser
10935: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10936:          $desiredhome,$email,$inststatus);
10937:     unless ($reply eq 'ok') { return $reply; }
10938:     # This will cause &modify_student_enrollment to get the uid from the
10939:     # student's environment
10940:     $uid = undef if (!$forceid);
10941:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10942:                                         $gene,$usec,$end,$start,$type,$locktype,
10943:                                         $cid,$selfenroll,$context,$credits,$instsec);
10944:     return $reply;
10945: }
10946: 
10947: sub modify_student_enrollment {
10948:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10949:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10950:     my ($cdom,$cnum,$chome);
10951:     if (!$cid) {
10952: 	unless ($cid=$env{'request.course.id'}) {
10953: 	    return 'not_in_class';
10954: 	}
10955: 	$cdom=$env{'course.'.$cid.'.domain'};
10956: 	$cnum=$env{'course.'.$cid.'.num'};
10957:     } else {
10958: 	($cdom,$cnum)=split(/_/,$cid);
10959:     }
10960:     $chome=$env{'course.'.$cid.'.home'};
10961:     if (!$chome) {
10962: 	$chome=&homeserver($cnum,$cdom);
10963:     }
10964:     if (!$chome) { return 'unknown_course'; }
10965:     # Make sure the user exists
10966:     my $uhome=&homeserver($uname,$udom);
10967:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10968: 	return 'error: no such user';
10969:     }
10970:     # Get student data if we were not given enough information
10971:     if (!defined($first)  || $first  eq '' || 
10972:         !defined($last)   || $last   eq '' || 
10973:         !defined($uid)    || $uid    eq '' || 
10974:         !defined($middle) || $middle eq '' || 
10975:         !defined($gene)   || $gene   eq '') {
10976:         # They did not supply us with enough data to enroll the student, so
10977:         # we need to pick up more information.
10978:         my %tmp = &get('environment',
10979:                        ['firstname','middlename','lastname', 'generation','id']
10980:                        ,$udom,$uname);
10981: 
10982:         #foreach my $key (keys(%tmp)) {
10983:         #    &logthis("key $key = ".$tmp{$key});
10984:         #}
10985:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10986:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10987:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10988:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10989:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10990:     }
10991:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10992:     my $user = "$uname:$udom";
10993:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
10994:     my $reply=cput('classlist',
10995: 		   {$user => 
10996: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10997: 		   $cdom,$cnum);
10998:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10999:         &devalidate_getsection_cache($udom,$uname,$cid);
11000:     } else { 
11001: 	return 'error: '.$reply;
11002:     }
11003:     # Add student role to user
11004:     my $uurl='/'.$cid;
11005:     $uurl=~s/\_/\//g;
11006:     if ($usec) {
11007: 	$uurl.='/'.$usec;
11008:     }
11009:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11010:                              $selfenroll,$context);
11011:     if ($result ne 'ok') {
11012:         if ($old_entry{$user} ne '') {
11013:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11014:         } else {
11015:             $reply = &del('classlist',[$user],$cdom,$cnum);
11016:         }
11017:     }
11018:     return $result; 
11019: }
11020: 
11021: sub format_name {
11022:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11023:     my $name;
11024:     if ($first ne 'lastname') {
11025: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11026:     } else {
11027: 	if ($lastname=~/\S/) {
11028: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11029: 	    $name=~s/\s+,/,/;
11030: 	} else {
11031: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11032: 	}
11033:     }
11034:     $name=~s/^\s+//;
11035:     $name=~s/\s+$//;
11036:     $name=~s/\s+/ /g;
11037:     return $name;
11038: }
11039: 
11040: # ------------------------------------------------- Write to course preferences
11041: 
11042: sub writecoursepref {
11043:     my ($courseid,%prefs)=@_;
11044:     $courseid=~s/^\///;
11045:     $courseid=~s/\_/\//g;
11046:     my ($cdomain,$cnum)=split(/\//,$courseid);
11047:     my $chome=homeserver($cnum,$cdomain);
11048:     if (($chome eq '') || ($chome eq 'no_host')) { 
11049: 	return 'error: no such course';
11050:     }
11051:     my $cstring='';
11052:     foreach my $pref (keys(%prefs)) {
11053: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11054:     }
11055:     $cstring=~s/\&$//;
11056:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11057: }
11058: 
11059: # ---------------------------------------------------------- Make/modify course
11060: 
11061: sub createcourse {
11062:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11063:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11064:     $url=&declutter($url);
11065:     my $cid='';
11066:     if ($context eq 'requestcourses') {
11067:         my $can_create = 0;
11068:         my ($ownername,$ownerdom) = split(':',$course_owner);
11069:         if ($udom eq $ownerdom) {
11070:             my $reload;
11071:             if (($callercontext eq 'auto') &&
11072:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11073:                 $reload = 'reload';
11074:             }
11075:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11076:                                   $context)) {
11077:                 $can_create = 1;
11078:             }
11079:         } else {
11080:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11081:                                            $category);
11082:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11083:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11084:                 if (@curr > 0) {
11085:                     my @options = qw(approval validate autolimit);
11086:                     my $optregex = join('|',@options);
11087:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11088:                         $can_create = 1;
11089:                     }
11090:                 }
11091:             }
11092:         }
11093:         if ($can_create) {
11094:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11095:                 unless (&allowed('ccc',$udom)) {
11096:                     return 'refused'; 
11097:                 }
11098:             }
11099:         } else {
11100:             return 'refused';
11101:         }
11102:     } elsif (!&allowed('ccc',$udom)) {
11103:         return 'refused';
11104:     }
11105: # --------------------------------------------------------------- Get Unique ID
11106:     my $uname;
11107:     if ($cnum =~ /^$match_courseid$/) {
11108:         my $chome=&homeserver($cnum,$udom,'true');
11109:         if (($chome eq '') || ($chome eq 'no_host')) {
11110:             $uname = $cnum;
11111:         } else {
11112:             $uname = &generate_coursenum($udom,$crstype);
11113:         }
11114:     } else {
11115:         $uname = &generate_coursenum($udom,$crstype);
11116:     }
11117:     return $uname if ($uname =~ /^error/);
11118: # -------------------------------------------------- Check supplied server name
11119:     if (!defined($course_server)) {
11120:         if (defined(&domain($udom,'primary'))) {
11121:             $course_server = &domain($udom,'primary');
11122:         } else {
11123:             $course_server = $env{'user.home'}; 
11124:         }
11125:     }
11126:     my %host_servers =
11127:         &get_servers($udom,'library');
11128:     unless ($host_servers{$course_server}) {
11129:         return 'error: invalid home server for course: '.$course_server;
11130:     }
11131: # ------------------------------------------------------------- Make the course
11132:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11133:                       $course_server);
11134:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11135:     my $uhome=&homeserver($uname,$udom,'true');
11136:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11137: 	return 'error: no such course';
11138:     }
11139: # ----------------------------------------------------------------- Course made
11140: # log existence
11141:     my $now = time;
11142:     my $newcourse = {
11143:                     $udom.'_'.$uname => {
11144:                                      description => $description,
11145:                                      inst_code   => $inst_code,
11146:                                      owner       => $course_owner,
11147:                                      type        => $crstype,
11148:                                      creator     => $env{'user.name'}.':'.
11149:                                                     $env{'user.domain'},
11150:                                      created     => $now,
11151:                                      context     => $context,
11152:                                                 },
11153:                     };
11154:     &courseidput($udom,$newcourse,$uhome,'notime');
11155: # set toplevel url
11156:     my $topurl=$url;
11157:     unless ($nonstandard) {
11158: # ------------------------------------------ For standard courses, make top url
11159:         my $mapurl=&clutter($url);
11160:         if ($mapurl eq '/res/') { $mapurl=''; }
11161:         $env{'form.initmap'}=(<<ENDINITMAP);
11162: <map>
11163: <resource id="1" type="start"></resource>
11164: <resource id="2" src="$mapurl"></resource>
11165: <resource id="3" type="finish"></resource>
11166: <link index="1" from="1" to="2"></link>
11167: <link index="2" from="2" to="3"></link>
11168: </map>
11169: ENDINITMAP
11170:         $topurl=&declutter(
11171:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11172:                           );
11173:     }
11174: # ----------------------------------------------------------- Write preferences
11175:     &writecoursepref($udom.'_'.$uname,
11176:                      ('description'              => $description,
11177:                       'url'                      => $topurl,
11178:                       'internal.creator'         => $env{'user.name'}.':'.
11179:                                                     $env{'user.domain'},
11180:                       'internal.created'         => $now,
11181:                       'internal.creationcontext' => $context)
11182:                     );
11183:     return '/'.$udom.'/'.$uname;
11184: }
11185: 
11186: # ------------------------------------------------------------------- Create ID
11187: sub generate_coursenum {
11188:     my ($udom,$crstype) = @_;
11189:     my $domdesc = &domain($udom);
11190:     return 'error: invalid domain' if ($domdesc eq '');
11191:     my $first;
11192:     if ($crstype eq 'Community') {
11193:         $first = '0';
11194:     } else {
11195:         $first = int(1+rand(9)); 
11196:     } 
11197:     my $uname=$first.
11198:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11199:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11200:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11201: # ----------------------------------------------- Make sure that does not exist
11202:     my $uhome=&homeserver($uname,$udom,'true');
11203:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11204:         if ($crstype eq 'Community') {
11205:             $first = '0';
11206:         } else {
11207:             $first = int(1+rand(9));
11208:         }
11209:         $uname=$first.
11210:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11211:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11212:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11213:         $uhome=&homeserver($uname,$udom,'true');
11214:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11215:             return 'error: unable to generate unique course-ID';
11216:         }
11217:     }
11218:     return $uname;
11219: }
11220: 
11221: sub is_course {
11222:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11223:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11224: 
11225:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11226:     my $uhome=&homeserver($cnum,$cdom);
11227:     my $iscourse;
11228:     if (grep { $_ eq $uhome } current_machine_ids()) {
11229:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11230:     } else {
11231:         my $hashid = $cdom.':'.$cnum;
11232:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11233:         unless (defined($cached)) {
11234:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11235:                                         $cnum,undef,undef,'.');
11236:             $iscourse = 0;
11237:             if (exists($courses{$cdom.'_'.$cnum})) {
11238:                 $iscourse = 1;
11239:             }
11240:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11241:         }
11242:     }
11243:     return unless ($iscourse);
11244:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11245: }
11246: 
11247: sub store_userdata {
11248:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11249:     my $result;
11250:     if ($datakey ne '') {
11251:         if (ref($storehash) eq 'HASH') {
11252:             if ($udom eq '' || $uname eq '') {
11253:                 $udom = $env{'user.domain'};
11254:                 $uname = $env{'user.name'};
11255:             }
11256:             my $uhome=&homeserver($uname,$udom);
11257:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11258:                 $result = 'error: no_host';
11259:             } else {
11260:                 $storehash->{'ip'} = &get_requestor_ip();
11261:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11262: 
11263:                 my $namevalue='';
11264:                 foreach my $key (keys(%{$storehash})) {
11265:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11266:                 }
11267:                 $namevalue=~s/\&$//;
11268:                 unless ($namespace eq 'courserequests') {
11269:                     $datakey = &escape($datakey);
11270:                 }
11271:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11272:                                   $namevalue,$uhome);
11273:             }
11274:         } else {
11275:             $result = 'error: data to store was not a hash reference'; 
11276:         }
11277:     } else {
11278:         $result= 'error: invalid requestkey'; 
11279:     }
11280:     return $result;
11281: }
11282: 
11283: # ---------------------------------------------------------- Assign Custom Role
11284: 
11285: sub assigncustomrole {
11286:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11287:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11288:                        $end,$start,$deleteflag,$selfenroll,$context);
11289: }
11290: 
11291: # ----------------------------------------------------------------- Revoke Role
11292: 
11293: sub revokerole {
11294:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11295:     my $now=time;
11296:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11297: }
11298: 
11299: # ---------------------------------------------------------- Revoke Custom Role
11300: 
11301: sub revokecustomrole {
11302:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11303:     my $now=time;
11304:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11305:            $deleteflag,$selfenroll,$context);
11306: }
11307: 
11308: # ------------------------------------------------------------ Disk usage
11309: sub diskusage {
11310:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11311:     $directorypath =~ s/\/$//;
11312:     my $listing=&reply('du2:'.&escape($directorypath).':'
11313:                        .&escape($getpropath).':'.&escape($uname).':'
11314:                        .&escape($udom),homeserver($uname,$udom));
11315:     if ($listing eq 'unknown_cmd') {
11316:         if ($getpropath) {
11317:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11318:         }
11319:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11320:     }
11321:     return $listing;
11322: }
11323: 
11324: sub is_locked {
11325:     my ($file_name, $domain, $user, $which) = @_;
11326:     my @check;
11327:     my $is_locked;
11328:     push (@check,$file_name);
11329:     my %locked = &get('file_permissions',\@check,
11330: 		      $env{'user.domain'},$env{'user.name'});
11331:     my ($tmp)=keys(%locked);
11332:     if ($tmp=~/^error:/) { undef(%locked); }
11333:     
11334:     if (ref($locked{$file_name}) eq 'ARRAY') {
11335:         $is_locked = 'false';
11336:         foreach my $entry (@{$locked{$file_name}}) {
11337:            if (ref($entry) eq 'ARRAY') {
11338:                $is_locked = 'true';
11339:                if (ref($which) eq 'ARRAY') {
11340:                    push(@{$which},$entry);
11341:                } else {
11342:                    last;
11343:                }
11344:            }
11345:        }
11346:     } else {
11347:         $is_locked = 'false';
11348:     }
11349:     return $is_locked;
11350: }
11351: 
11352: sub declutter_portfile {
11353:     my ($file) = @_;
11354:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11355:     return $file;
11356: }
11357: 
11358: # ------------------------------------------------------------- Mark as Read Only
11359: 
11360: sub mark_as_readonly {
11361:     my ($domain,$user,$files,$what) = @_;
11362:     my %current_permissions = &dump('file_permissions',$domain,$user);
11363:     my ($tmp)=keys(%current_permissions);
11364:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11365:     foreach my $file (@{$files}) {
11366: 	$file = &declutter_portfile($file);
11367:         push(@{$current_permissions{$file}},$what);
11368:     }
11369:     &put('file_permissions',\%current_permissions,$domain,$user);
11370:     return;
11371: }
11372: 
11373: # ------------------------------------------------------------Save Selected Files
11374: 
11375: sub save_selected_files {
11376:     my ($user, $path, @files) = @_;
11377:     my $filename = $user."savedfiles";
11378:     my @other_files = &files_not_in_path($user, $path);
11379:     open (OUT,'>',LONCAPA::tempdir().$filename);
11380:     foreach my $file (@files) {
11381:         print (OUT $env{'form.currentpath'}.$file."\n");
11382:     }
11383:     foreach my $file (@other_files) {
11384:         print (OUT $file."\n");
11385:     }
11386:     close (OUT);
11387:     return 'ok';
11388: }
11389: 
11390: sub clear_selected_files {
11391:     my ($user) = @_;
11392:     my $filename = $user."savedfiles";
11393:     open (OUT,'>',LONCAPA::tempdir().$filename);
11394:     print (OUT undef);
11395:     close (OUT);
11396:     return ("ok");    
11397: }
11398: 
11399: sub files_in_path {
11400:     my ($user, $path) = @_;
11401:     my $filename = $user."savedfiles";
11402:     my %return_files;
11403:     open (IN,'<',LONCAPA::tempdir().$filename);
11404:     while (my $line_in = <IN>) {
11405:         chomp ($line_in);
11406:         my @paths_and_file = split (m!/!, $line_in);
11407:         my $file_part = pop (@paths_and_file);
11408:         my $path_part = join ('/', @paths_and_file);
11409:         $path_part.='/';
11410:         my $path_and_file = $path_part.$file_part;
11411:         if ($path_part eq $path) {
11412:             $return_files{$file_part}= 'selected';
11413:         }
11414:     }
11415:     close (IN);
11416:     return (\%return_files);
11417: }
11418: 
11419: # called in portfolio select mode, to show files selected NOT in current directory
11420: sub files_not_in_path {
11421:     my ($user, $path) = @_;
11422:     my $filename = $user."savedfiles";
11423:     my @return_files;
11424:     my $path_part;
11425:     open(IN, '<',LONCAPA::tempdir().$filename);
11426:     while (my $line = <IN>) {
11427:         #ok, I know it's clunky, but I want it to work
11428:         my @paths_and_file = split(m|/|, $line);
11429:         my $file_part = pop(@paths_and_file);
11430:         chomp($file_part);
11431:         my $path_part = join('/', @paths_and_file);
11432:         $path_part .= '/';
11433:         my $path_and_file = $path_part.$file_part;
11434:         if ($path_part ne $path) {
11435:             push(@return_files, ($path_and_file));
11436:         }
11437:     }
11438:     close(OUT);
11439:     return (@return_files);
11440: }
11441: 
11442: #------------------------------Submitted/Handedback Portfolio Files Versioning
11443:  
11444: sub portfiles_versioning {
11445:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11446:     my $portfolio_root = '/userfiles/portfolio';
11447:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11448:     foreach my $file (@{$portfiles}) {
11449:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11450:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11451:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11452:         my $getpropath = 1;
11453:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11454:                                              $stu_name,$getpropath);
11455:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11456:         my $new_answer = 
11457:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11458:         if ($new_answer ne 'problem getting file') {
11459:             push(@{$versioned_portfiles}, $directory.$new_answer);
11460:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11461:                               [$symb,$env{'request.course.id'},'graded']);
11462:         }
11463:     }
11464: }
11465: 
11466: sub get_next_version {
11467:     my ($answer_name, $answer_ext, $dir_list) = @_;
11468:     my $version;
11469:     if (ref($dir_list) eq 'ARRAY') {
11470:         foreach my $row (@{$dir_list}) {
11471:             my ($file) = split(/\&/,$row,2);
11472:             my ($file_name,$file_version,$file_ext) =
11473:                 &file_name_version_ext($file);
11474:             if (($file_name eq $answer_name) &&
11475:                 ($file_ext eq $answer_ext)) {
11476:                      # gets here if filename and extension match,
11477:                      # regardless of version
11478:                 if ($file_version ne '') {
11479:                     # a versioned file is found  so save it for later
11480:                     if ($file_version > $version) {
11481:                         $version = $file_version;
11482:                     }
11483:                 }
11484:             }
11485:         }
11486:     }
11487:     $version ++;
11488:     return($version);
11489: }
11490: 
11491: sub version_selected_portfile {
11492:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11493:     my ($answer_name,$answer_ver,$answer_ext) =
11494:         &file_name_version_ext($file_name);
11495:     my $new_answer;
11496:     $env{'form.copy'} =
11497:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11498:     if($env{'form.copy'} eq '-1') {
11499:         $new_answer = 'problem getting file';
11500:     } else {
11501:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11502:         my $copy_result = 
11503:             &finishuserfileupload($stu_name,$domain,'copy',
11504:                                   '/portfolio'.$directory.$new_answer);
11505:     }
11506:     undef($env{'form.copy'});
11507:     return ($new_answer);
11508: }
11509: 
11510: sub file_name_version_ext {
11511:     my ($file)=@_;
11512:     my @file_parts = split(/\./, $file);
11513:     my ($name,$version,$ext);
11514:     if (@file_parts > 1) {
11515:         $ext=pop(@file_parts);
11516:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11517:             $version=pop(@file_parts);
11518:         }
11519:         $name=join('.',@file_parts);
11520:     } else {
11521:         $name=join('.',@file_parts);
11522:     }
11523:     return($name,$version,$ext);
11524: }
11525: 
11526: #----------------------------------------------Get portfolio file permissions
11527: 
11528: sub get_portfile_permissions {
11529:     my ($domain,$user) = @_;
11530:     my %current_permissions = &dump('file_permissions',$domain,$user);
11531:     my ($tmp)=keys(%current_permissions);
11532:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11533:     return \%current_permissions;
11534: }
11535: 
11536: #---------------------------------------------Get portfolio file access controls
11537: 
11538: sub get_access_controls {
11539:     my ($current_permissions,$group,$file) = @_;
11540:     my %access;
11541:     my $real_file = $file;
11542:     $file =~ s/\.meta$//;
11543:     if (defined($file)) {
11544:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11545:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11546:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11547:             }
11548:         }
11549:     } else {
11550:         foreach my $key (keys(%{$current_permissions})) {
11551:             if ($key =~ /\0accesscontrol$/) {
11552:                 if (defined($group)) {
11553:                     if ($key !~ m-^\Q$group\E/-) {
11554:                         next;
11555:                     }
11556:                 }
11557:                 my ($fullpath) = split(/\0/,$key);
11558:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11559:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11560:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11561:                     }
11562:                 }
11563:             }
11564:         }
11565:     }
11566:     return %access;
11567: }
11568: 
11569: sub modify_access_controls {
11570:     my ($file_name,$changes,$domain,$user)=@_;
11571:     my ($outcome,$deloutcome);
11572:     my %store_permissions;
11573:     my %new_values;
11574:     my %new_control;
11575:     my %translation;
11576:     my @deletions = ();
11577:     my $now = time;
11578:     if (exists($$changes{'activate'})) {
11579:         if (ref($$changes{'activate'}) eq 'HASH') {
11580:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11581:             my $numnew = scalar(@newitems);
11582:             for (my $i=0; $i<$numnew; $i++) {
11583:                 my $newkey = $newitems[$i];
11584:                 my $newid = &Apache::loncommon::get_cgi_id();
11585:                 if ($newkey =~ /^\d+:/) { 
11586:                     $newkey =~ s/^(\d+)/$newid/;
11587:                     $translation{$1} = $newid;
11588:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11589:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11590:                     $translation{$1} = $newid;
11591:                 }
11592:                 $new_values{$file_name."\0".$newkey} = 
11593:                                           $$changes{'activate'}{$newitems[$i]};
11594:                 $new_control{$newkey} = $now;
11595:             }
11596:         }
11597:     }
11598:     my %todelete;
11599:     my %changed_items;
11600:     foreach my $action ('delete','update') {
11601:         if (exists($$changes{$action})) {
11602:             if (ref($$changes{$action}) eq 'HASH') {
11603:                 foreach my $key (keys(%{$$changes{$action}})) {
11604:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11605:                     if ($action eq 'delete') { 
11606:                         $todelete{$itemnum} = 1;
11607:                     } else {
11608:                         $changed_items{$itemnum} = $key;
11609:                     }
11610:                 }
11611:             }
11612:         }
11613:     }
11614:     # get lock on access controls for file.
11615:     my $lockhash = {
11616:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11617:                                                        ':'.$env{'user.domain'},
11618:                    }; 
11619:     my $tries = 0;
11620:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11621:    
11622:     while (($gotlock ne 'ok') && $tries < 10) {
11623:         $tries ++;
11624:         sleep(0.1);
11625:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11626:     }
11627:     if ($gotlock eq 'ok') {
11628:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11629:         my ($tmp)=keys(%curr_permissions);
11630:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11631:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11632:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11633:             if (ref($curr_controls) eq 'HASH') {
11634:                 foreach my $control_item (keys(%{$curr_controls})) {
11635:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11636:                     if (defined($todelete{$itemnum})) {
11637:                         push(@deletions,$file_name."\0".$control_item);
11638:                     } else {
11639:                         if (defined($changed_items{$itemnum})) {
11640:                             $new_control{$changed_items{$itemnum}} = $now;
11641:                             push(@deletions,$file_name."\0".$control_item);
11642:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11643:                         } else {
11644:                             $new_control{$control_item} = $$curr_controls{$control_item};
11645:                         }
11646:                     }
11647:                 }
11648:             }
11649:         }
11650:         my ($group);
11651:         if (&is_course($domain,$user)) {
11652:             ($group,my $file) = split(/\//,$file_name,2);
11653:         }
11654:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11655:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11656:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11657:         #  remove lock
11658:         my @del_lock = ($file_name."\0".'locked_access_records');
11659:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11660:         my $sqlresult =
11661:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11662:                                     $group);
11663:     } else {
11664:         $outcome = "error: could not obtain lockfile\n";  
11665:     }
11666:     return ($outcome,$deloutcome,\%new_values,\%translation);
11667: }
11668: 
11669: sub make_public_indefinitely {
11670:     my (@requrl) = @_;
11671:     return &automated_portfile_access('public',\@requrl);
11672: }
11673: 
11674: sub automated_portfile_access {
11675:     my ($accesstype,$addsref,$delsref,$info) = @_;
11676:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11677:         return 'invalid';
11678:     }
11679:     my %urls;
11680:     if (ref($addsref) eq 'ARRAY') {
11681:         foreach my $requrl (@{$addsref}) {
11682:             if (&is_portfolio_url($requrl)) {
11683:                 unless (exists($urls{$requrl})) {
11684:                     $urls{$requrl} = 'add';
11685:                 }
11686:             }
11687:         }
11688:     }
11689:     if (ref($delsref) eq 'ARRAY') {
11690:         foreach my $requrl (@{$delsref}) { 
11691:             if (&is_portfolio_url($requrl)) {
11692:                 unless (exists($urls{$requrl})) {
11693:                     $urls{$requrl} = 'delete'; 
11694:                 }
11695:             }
11696:         }
11697:     }
11698:     unless (keys(%urls)) {
11699:         return 'invalid';
11700:     }
11701:     my $ip;
11702:     if ($accesstype eq 'ip') {
11703:         if (ref($info) eq 'HASH') {
11704:             if ($info->{'ip'} ne '') {
11705:                 $ip = $info->{'ip'};
11706:             }
11707:         }
11708:         if ($ip eq '') {
11709:             return 'invalid';
11710:         }
11711:     }
11712:     my $errors;
11713:     my $now = time;
11714:     my %current_perms;
11715:     foreach my $requrl (sort(keys(%urls))) {
11716:         my $action;
11717:         if ($urls{$requrl} eq 'add') {
11718:             $action = 'activate';
11719:         } else {
11720:             $action = 'none';
11721:         }
11722:         my $aclnum = 0;
11723:         my (undef,$udom,$unum,$file_name,$group) =
11724:             &parse_portfolio_url($requrl);
11725:         unless (exists($current_perms{$unum.':'.$udom})) {
11726:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11727:         }
11728:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11729:                                                    $group,$file_name);
11730:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11731:             my ($num,$scope,$end,$start) = 
11732:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11733:             if ($scope eq $accesstype) {
11734:                 if (($start <= $now) && ($end == 0)) {
11735:                     if ($accesstype eq 'ip') {
11736:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11737:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11738:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11739:                                     if ($urls{$requrl} eq 'add') {
11740:                                         $action = 'none';
11741:                                         last;
11742:                                     } else {
11743:                                         $action = 'delete';
11744:                                         $aclnum = $num;
11745:                                         last;
11746:                                     }
11747:                                 }
11748:                             }
11749:                         }
11750:                     } elsif ($accesstype eq 'public') {
11751:                         if ($urls{$requrl} eq 'add') {
11752:                             $action = 'none';
11753:                             last;
11754:                         } else {
11755:                             $action = 'delete';
11756:                             $aclnum = $num;
11757:                             last;
11758:                         }
11759:                     }
11760:                 } elsif ($accesstype eq 'public') {
11761:                     $action = 'update';
11762:                     $aclnum = $num;
11763:                     last;
11764:                 }
11765:             }
11766:         }
11767:         if ($action eq 'none') {
11768:             next;
11769:         } else {
11770:             my %changes;
11771:             my $newend = 0;
11772:             my $newstart = $now;
11773:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11774:             $changes{$action}{$newkey} = {
11775:                 type => $accesstype,
11776:                 time => {
11777:                     start => $newstart,
11778:                     end   => $newend,
11779:                 },
11780:             };
11781:             if ($accesstype eq 'ip') {
11782:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11783:             }
11784:             my ($outcome,$deloutcome,$new_values,$translation) =
11785:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11786:             unless ($outcome eq 'ok') {
11787:                 $errors .= $outcome.' ';
11788:             }
11789:         }
11790:     }
11791:     if ($errors) {
11792:         $errors =~ s/\s$//;
11793:         return $errors;
11794:     } else {
11795:         return 'ok';
11796:     }
11797: }
11798: 
11799: #------------------------------------------------------Get Marked as Read Only
11800: 
11801: sub get_marked_as_readonly {
11802:     my ($domain,$user,$what,$group) = @_;
11803:     my $current_permissions = &get_portfile_permissions($domain,$user);
11804:     my @readonly_files;
11805:     my $cmp1=$what;
11806:     if (ref($what)) { $cmp1=join('',@{$what}) };
11807:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11808:         if (defined($group)) {
11809:             if ($file_name !~ m-^\Q$group\E/-) {
11810:                 next;
11811:             }
11812:         }
11813:         if (ref($value) eq "ARRAY"){
11814:             foreach my $stored_what (@{$value}) {
11815:                 my $cmp2=$stored_what;
11816:                 if (ref($stored_what) eq 'ARRAY') {
11817:                     $cmp2=join('',@{$stored_what});
11818:                 }
11819:                 if ($cmp1 eq $cmp2) {
11820:                     push(@readonly_files, $file_name);
11821:                     last;
11822:                 } elsif (!defined($what)) {
11823:                     push(@readonly_files, $file_name);
11824:                     last;
11825:                 }
11826:             }
11827:         }
11828:     }
11829:     return @readonly_files;
11830: }
11831: #-----------------------------------------------------------Get Marked as Read Only Hash
11832: 
11833: sub get_marked_as_readonly_hash {
11834:     my ($current_permissions,$group,$what) = @_;
11835:     my %readonly_files;
11836:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11837:         if (defined($group)) {
11838:             if ($file_name !~ m-^\Q$group\E/-) {
11839:                 next;
11840:             }
11841:         }
11842:         if (ref($value) eq "ARRAY"){
11843:             foreach my $stored_what (@{$value}) {
11844:                 if (ref($stored_what) eq 'ARRAY') {
11845:                     foreach my $lock_descriptor(@{$stored_what}) {
11846:                         if ($lock_descriptor eq 'graded') {
11847:                             $readonly_files{$file_name} = 'graded';
11848:                         } elsif ($lock_descriptor eq 'handback') {
11849:                             $readonly_files{$file_name} = 'handback';
11850:                         } else {
11851:                             if (!exists($readonly_files{$file_name})) {
11852:                                 $readonly_files{$file_name} = 'locked';
11853:                             }
11854:                         }
11855:                     }
11856:                 } 
11857:             }
11858:         } 
11859:     }
11860:     return %readonly_files;
11861: }
11862: # ------------------------------------------------------------ Unmark as Read Only
11863: 
11864: sub unmark_as_readonly {
11865:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11866:     # for portfolio submissions, $what contains [$symb,$crsid] 
11867:     my ($domain,$user,$what,$file_name,$group) = @_;
11868:     $file_name = &declutter_portfile($file_name);
11869:     my $symb_crs = $what;
11870:     if (ref($what)) { $symb_crs=join('',@$what); }
11871:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11872:     my ($tmp)=keys(%current_permissions);
11873:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11874:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11875:     foreach my $file (@readonly_files) {
11876: 	my $clean_file = &declutter_portfile($file);
11877: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11878: 	my $current_locks = $current_permissions{$file};
11879:         my @new_locks;
11880:         my @del_keys;
11881:         if (ref($current_locks) eq "ARRAY"){
11882:             foreach my $locker (@{$current_locks}) {
11883:                 my $compare=$locker;
11884:                 if (ref($locker) eq 'ARRAY') {
11885:                     $compare=join('',@{$locker});
11886:                     if ($compare ne $symb_crs) {
11887:                         push(@new_locks, $locker);
11888:                     }
11889:                 }
11890:             }
11891:             if (scalar(@new_locks) > 0) {
11892:                 $current_permissions{$file} = \@new_locks;
11893:             } else {
11894:                 push(@del_keys, $file);
11895:                 &del('file_permissions',\@del_keys, $domain, $user);
11896:                 delete($current_permissions{$file});
11897:             }
11898:         }
11899:     }
11900:     &put('file_permissions',\%current_permissions,$domain,$user);
11901:     return;
11902: }
11903: 
11904: # ------------------------------------------------------------ Directory lister
11905: 
11906: sub dirlist {
11907:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11908:     $uri=~s/^\///;
11909:     $uri=~s/\/$//;
11910:     my ($udom, $uname);
11911:     if ($getuserdir) {
11912:         $udom = $userdomain;
11913:         $uname = $username;
11914:     } else {
11915:         (undef,$udom,$uname)=split(/\//,$uri);
11916:         if(defined($userdomain)) {
11917:             $udom = $userdomain;
11918:         }
11919:         if(defined($username)) {
11920:             $uname = $username;
11921:         }
11922:     }
11923:     my ($dirRoot,$listing,@listing_results);
11924: 
11925:     $dirRoot = $perlvar{'lonDocRoot'};
11926:     if (defined($getpropath)) {
11927:         $dirRoot = &propath($udom,$uname);
11928:         $dirRoot =~ s/\/$//;
11929:     } elsif (defined($getuserdir)) {
11930:         my $subdir=$uname.'__';
11931:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11932:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11933:                    ."/$udom/$subdir/$uname";
11934:     } elsif (defined($alternateRoot)) {
11935:         $dirRoot = $alternateRoot;
11936:     }
11937: 
11938:     if($udom) {
11939:         if($uname) {
11940:             my $uhome = &homeserver($uname,$udom);
11941:             if ($uhome eq 'no_host') {
11942:                 return ([],'no_host');
11943:             }
11944:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11945:                               .$getuserdir.':'.&escape($dirRoot)
11946:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11947:             if ($listing eq 'unknown_cmd') {
11948:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11949:             } else {
11950:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11951:             }
11952:             if ($listing eq 'unknown_cmd') {
11953:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11954:                 @listing_results = split(/:/,$listing);
11955:             } else {
11956:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11957:             }
11958:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11959:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11960:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11961:                 return ([],$listing);
11962:             } else {
11963:                 return (\@listing_results);
11964:             }
11965:         } elsif(!$alternateRoot) {
11966:             my (%allusers,%listerror);
11967: 	    my %servers = &get_servers($udom,'library');
11968:  	    foreach my $tryserver (keys(%servers)) {
11969:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11970:                                   &escape($udom),$tryserver);
11971:                 if ($listing eq 'unknown_cmd') {
11972: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11973: 				      $udom, $tryserver);
11974:                 } else {
11975:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11976:                 }
11977: 		if ($listing eq 'unknown_cmd') {
11978: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11979: 				      $udom, $tryserver);
11980: 		    @listing_results = split(/:/,$listing);
11981: 		} else {
11982: 		    @listing_results =
11983: 			map { &unescape($_); } split(/:/,$listing);
11984: 		}
11985:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11986:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11987:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11988:                     $listerror{$tryserver} = $listing;
11989:                 } else {
11990: 		    foreach my $line (@listing_results) {
11991: 			my ($entry) = split(/&/,$line,2);
11992: 			$allusers{$entry} = 1;
11993: 		    }
11994: 		}
11995:             }
11996:             my @alluserslist=();
11997:             foreach my $user (sort(keys(%allusers))) {
11998:                 push(@alluserslist,$user.'&user');
11999:             }
12000: 
12001:             if (!%listerror) {
12002:                 # no errors
12003:                 return (\@alluserslist);
12004:             } elsif (scalar(keys(%servers)) == 1) {
12005:                 # one library server, one error 
12006:                 my ($key) = keys(%listerror);
12007:                 return (\@alluserslist, $listerror{$key});
12008:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12009:                 # con_lost indicates that we might miss data from at least one
12010:                 # library server
12011:                 return (\@alluserslist, 'con_lost');
12012:             } else {
12013:                 # multiple library servers and no con_lost -> data should be
12014:                 # complete. 
12015:                 return (\@alluserslist);
12016:             }
12017: 
12018:         } else {
12019:             return ([],'missing username');
12020:         }
12021:     } elsif(!defined($getpropath)) {
12022:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12023:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12024:         return (\@all_domains);
12025:     } else {
12026:         return ([],'missing domain');
12027:     }
12028: }
12029: 
12030: # --------------------------------------------- GetFileTimestamp
12031: # This function utilizes dirlist and returns the date stamp for
12032: # when it was last modified.  It will also return an error of -1
12033: # if an error occurs
12034: 
12035: sub GetFileTimestamp {
12036:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12037:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12038:     $studentName   = &LONCAPA::clean_username($studentName);
12039:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12040:                                     undef,$getuserdir);
12041:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12042:         return -1;
12043:     }
12044:     if (ref($fileref) eq 'ARRAY') {
12045:         my @stats = split('&',$fileref->[0]);
12046:         # @stats contains first the filename, then the stat output
12047:         return $stats[10]; # so this is 10 instead of 9.
12048:     } else {
12049:         return -1;
12050:     }
12051: }
12052: 
12053: sub stat_file {
12054:     my ($uri) = @_;
12055:     $uri = &clutter_with_no_wrapper($uri);
12056: 
12057:     my ($udom,$uname,$file);
12058:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12059: 	($udom,$uname,$file) =
12060: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12061: 	$file = 'userfiles/'.$file;
12062:     }
12063:     if ($uri =~ m-^/res/-) {
12064: 	($udom,$uname) = 
12065: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12066: 	$file = $uri;
12067:     }
12068: 
12069:     if (!$udom || !$uname || !$file) {
12070: 	# unable to handle the uri
12071: 	return ();
12072:     }
12073:     my $getpropath;
12074:     if ($file =~ /^userfiles\//) {
12075:         $getpropath = 1;
12076:     }
12077:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12078:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12079:         return ();
12080:     } else {
12081:         if (ref($listref) eq 'ARRAY') {
12082:             my @stats = split('&',$listref->[0]);
12083: 	    shift(@stats); #filename is first
12084: 	    return @stats;
12085:         }
12086:     }
12087:     return ();
12088: }
12089: 
12090: # --------------------------------------------------------- recursedirs
12091: # Recursive function to traverse either a specific user's Authoring Space
12092: # or corresponding Published Resource Space, and populate the hash ref:
12093: # $dirhashref with URLs of all directories, and if $filehashref hash
12094: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12095: # or .rights files in resource space, and .meta, .save, .log, .bak and
12096: # .rights files in Authoring Space.
12097: #
12098: # Inputs:
12099: #
12100: # $is_home - true if current server is home server for user's space
12101: # $recurse - if true will also traverse subdirectories recursively
12102: # $include - reference to hash containing allowed file extensions.  If provided,
12103: #             files which do not have a matching extension will be ignored.
12104: # $exclude - reference to hash containing excluded file extensions.  If provided,
12105: #             files which have a matching extension will be ignored.
12106: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12107: #             directory with first file found (with acceptable extension).
12108: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12109: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12110: # $relpath - Current path (relative to top level).
12111: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12112: # $filehashref - reference to hash to populate with URLs of files (Optional)
12113: #
12114: # Returns: nothing
12115: #
12116: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12117: #
12118: # Currently used by interface/londocs.pm to create linked select boxes for
12119: # directory and filename to import a Course "Author" resource into a course, and
12120: # also to create linked select boxes for Authoring Space and Directory to choose
12121: # save location for creation of a new "standard" problem from the Course Editor.
12122: #
12123: 
12124: sub recursedirs {
12125:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12126:     return unless (ref($dirhashref) eq 'HASH');
12127:     my $docroot = $perlvar{'lonDocRoot'};
12128:     my $currpath = $docroot.$toppath;
12129:     if ($relpath ne '') {
12130:         $currpath .= "/$relpath";
12131:     }
12132:     my ($savefile,$checkinc,$checkexc);
12133:     if (ref($filehashref)) {
12134:         $savefile = 1;
12135:     }
12136:     if (ref($include) eq 'HASH') {
12137:         $checkinc = 1;
12138:     }
12139:     if (ref($exclude) eq 'HASH') {
12140:         $checkexc = 1;
12141:     }
12142:     if ($is_home) {
12143:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12144:             my $filecount = 0;
12145:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12146:                 next if ($item eq '');
12147:                 if (-d "$currpath/$item") {
12148:                     my $newpath;
12149:                     if ($relpath ne '') {
12150:                         $newpath = "$relpath/$item";
12151:                     } else {
12152:                         $newpath = $item;
12153:                     }
12154:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12155:                     if ($recurse) {
12156:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12157:                     }
12158:                 } elsif (($savefile) || ($relpath eq '')) {
12159:                     next if ($nonemptydir && $filecount);
12160:                     if ($checkinc || $checkexc) {
12161:                         my ($extension) = ($item =~ /\.(\w+)$/);
12162:                         if ($checkinc) {
12163:                             next unless ($extension && $include->{$extension});
12164:                         }
12165:                         if ($checkexc) {
12166:                             next if ($extension && $exclude->{$extension});
12167:                         }
12168:                     }
12169:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12170:                         $dirhashref->{'/'} = 1;
12171:                     }
12172:                     if ($savefile) {
12173:                         if ($relpath eq '') {
12174:                             $filehashref->{'/'}{$item} = 1;
12175:                         } else {
12176:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12177:                         }
12178:                     }
12179:                     $filecount ++;
12180:                 }
12181:             }
12182:             closedir($dirh);
12183:         }
12184:     } else {
12185:         my ($dirlistref,$listerror) =
12186:             &dirlist($toppath.$relpath);
12187:         my @dir_lines;
12188:         my $dirptr=16384;
12189:         if (ref($dirlistref) eq 'ARRAY') {
12190:             my $filecount = 0;
12191:             foreach my $dir_line (sort
12192:                               {
12193:                                   my ($afile)=split('&',$a,2);
12194:                                   my ($bfile)=split('&',$b,2);
12195:                                   return (lc($afile) cmp lc($bfile));
12196:                               } (@{$dirlistref})) {
12197:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12198:                     split(/\&/,$dir_line,16);
12199:                 $item =~ s/\s+$//;
12200:                 next if (($item =~ /^\.\.?$/) || ($obs));
12201:                 if ($dirptr&$testdir) {
12202:                     my $newpath;
12203:                     if ($relpath) {
12204:                         $newpath = "$relpath/$item";
12205:                     } else {
12206:                         $newpath = $item;
12207:                     }
12208:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12209:                     if ($recurse) {
12210:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12211:                     }
12212:                 } elsif (($savefile) || ($relpath eq '')) {
12213:                     next if ($nonemptydir && $filecount);
12214:                     if ($checkinc || $checkexc) {
12215:                         my $extension;
12216:                         if ($checkinc) {
12217:                             next unless ($extension && $include->{$extension});
12218:                         }
12219:                         if ($checkexc) {
12220:                             next if ($extension && $exclude->{$extension});
12221:                         }
12222:                     }
12223:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12224:                         $dirhashref->{'/'} = 1;
12225:                     }
12226:                     if ($savefile) {
12227:                         if ($relpath eq '') {
12228:                             $filehashref->{'/'}{$item} = 1;
12229:                         } else {
12230:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12231:                         }
12232:                     }
12233:                     $filecount ++; 
12234:                 }
12235:             }
12236:         }
12237:     }
12238:     if ($addtopdir) {
12239:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12240:             $dirhashref->{'/'} = 1;
12241:         }
12242:     }
12243:     return;
12244: }
12245: 
12246: sub priv_exclude {
12247:     return {
12248:              meta => 1,
12249:              save => 1,
12250:              log => 1,
12251:              bak => 1,
12252:              rights => 1,
12253:              DS_Store => 1,
12254:            };
12255: }
12256: 
12257: # -------------------------------------------------------- Value of a Condition
12258: 
12259: # gets the value of a specific preevaluated condition
12260: #    stored in the string  $env{user.state.<cid>}
12261: # or looks up a condition reference in the bighash and if if hasn't
12262: # already been evaluated recurses into docondval to get the value of
12263: # the condition, then memoizing it to 
12264: #   $env{user.state.<cid>.<condition>}
12265: sub directcondval {
12266:     my $number=shift;
12267:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12268: 	&Apache::lonuserstate::evalstate();
12269:     }
12270:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12271: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12272:     } elsif ($number =~ /^_/) {
12273: 	my $sub_condition;
12274: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12275: 		&GDBM_READER(),0640)) {
12276: 	    $sub_condition=$bighash{'conditions'.$number};
12277: 	    untie(%bighash);
12278: 	}
12279: 	my $value = &docondval($sub_condition);
12280: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12281: 	return $value;
12282:     }
12283:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12284:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12285:     } else {
12286:        return 2;
12287:     }
12288: }
12289: 
12290: # get the collection of conditions for this resource
12291: sub condval {
12292:     my $condidx=shift;
12293:     my $allpathcond='';
12294:     foreach my $cond (split(/\|/,$condidx)) {
12295: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12296: 	    $allpathcond.=
12297: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12298: 	}
12299:     }
12300:     $allpathcond=~s/\|$//;
12301:     return &docondval($allpathcond);
12302: }
12303: 
12304: #evaluates an expression of conditions
12305: sub docondval {
12306:     my ($allpathcond) = @_;
12307:     my $result=0;
12308:     if ($env{'request.course.id'}
12309: 	&& defined($allpathcond)) {
12310: 	my $operand='|';
12311: 	my @stack;
12312: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12313: 	    if ($chunk eq '(') {
12314: 		push @stack,($operand,$result);
12315: 	    } elsif ($chunk eq ')') {
12316: 		my $before=pop @stack;
12317: 		if (pop @stack eq '&') {
12318: 		    $result=$result>$before?$before:$result;
12319: 		} else {
12320: 		    $result=$result>$before?$result:$before;
12321: 		}
12322: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12323: 		$operand=$chunk;
12324: 	    } else {
12325: 		my $new=directcondval($chunk);
12326: 		if ($operand eq '&') {
12327: 		    $result=$result>$new?$new:$result;
12328: 		} else {
12329: 		    $result=$result>$new?$result:$new;
12330: 		}
12331: 	    }
12332: 	}
12333:     }
12334:     return $result;
12335: }
12336: 
12337: # ---------------------------------------------------- Devalidate courseresdata
12338: 
12339: sub devalidatecourseresdata {
12340:     my ($coursenum,$coursedomain)=@_;
12341:     my $hashid=$coursenum.':'.$coursedomain;
12342:     &devalidate_cache_new('courseres',$hashid);
12343: }
12344: 
12345: 
12346: # --------------------------------------------------- Course Resourcedata Query
12347: #
12348: #  Parameters:
12349: #      $coursenum    - Number of the course.
12350: #      $coursedomain - Domain at which the course was created.
12351: #  Returns:
12352: #     A hash of the course parameters along (I think) with timestamps
12353: #     and version info.
12354: 
12355: sub get_courseresdata {
12356:     my ($coursenum,$coursedomain)=@_;
12357:     my $coursehom=&homeserver($coursenum,$coursedomain);
12358:     my $hashid=$coursenum.':'.$coursedomain;
12359:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12360:     my %dumpreply;
12361:     unless (defined($cached)) {
12362: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12363: 	$result=\%dumpreply;
12364: 	my ($tmp) = keys(%dumpreply);
12365: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12366: 	    &do_cache_new('courseres',$hashid,$result,600);
12367: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12368: 	    return $tmp;
12369: 	} elsif ($tmp =~ /^(error)/) {
12370: 	    $result=undef;
12371: 	    &do_cache_new('courseres',$hashid,$result,600);
12372: 	}
12373:     }
12374:     return $result;
12375: }
12376: 
12377: sub devalidateuserresdata {
12378:     my ($uname,$udom)=@_;
12379:     my $hashid="$udom:$uname";
12380:     &devalidate_cache_new('userres',$hashid);
12381: }
12382: 
12383: sub get_userresdata {
12384:     my ($uname,$udom)=@_;
12385:     #most student don\'t have any data set, check if there is some data
12386:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12387: 
12388:     my $hashid="$udom:$uname";
12389:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12390:     if (!defined($cached)) {
12391: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12392: 	$result=\%resourcedata;
12393: 	&do_cache_new('userres',$hashid,$result,600);
12394:     }
12395:     my ($tmp)=keys(%$result);
12396:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12397: 	return $result;
12398:     }
12399:     #error 2 occurs when the .db doesn't exist
12400:     if ($tmp!~/error: 2 /) {
12401:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12402: 	    &logthis("<font color=\"blue\">WARNING:".
12403: 		     " Trying to get resource data for ".
12404: 		     $uname." at ".$udom.": ".
12405: 		     $tmp."</font>");
12406:         }
12407:     } elsif ($tmp=~/error: 2 /) {
12408: 	#&EXT_cache_set($udom,$uname);
12409: 	&do_cache_new('userres',$hashid,undef,600);
12410: 	undef($tmp); # not really an error so don't send it back
12411:     }
12412:     return $tmp;
12413: }
12414: #----------------------------------------------- resdata - return resource data
12415: #  Purpose:
12416: #    Return resource data for either users or for a course.
12417: #  Parameters:
12418: #     $name      - Course/user name.
12419: #     $domain    - Name of the domain the user/course is registered on.
12420: #     $type      - Type of thing $name is (must be 'course' or 'user')
12421: #     $mapp      - decluttered URL of enclosing map  
12422: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12423: #     $recurseup - Ref to array of map URLs, starting with map containing
12424: #                  $mapp up through hierarchy of nested maps to top level map.  
12425: #     $courseid  - CourseID (first part of param identifier).
12426: #     $modifier  - Middle part of param identifier.
12427: #     $what      - Last part of param identifier.
12428: #     @which     - Array of names of resources desired.
12429: #  Returns:
12430: #     The value of the first reasource in @which that is found in the
12431: #     resource hash.
12432: #  Exceptional Conditions:
12433: #     If the $type passed in is not valid (not the string 'course' or 
12434: #     'user', an undefined  reference is returned.
12435: #     If none of the resources are found, an undef is returned
12436: sub resdata {
12437:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12438:         $modifier,$what,@which)=@_;
12439:     my $result;
12440:     if ($type eq 'course') {
12441: 	$result=&get_courseresdata($name,$domain);
12442:     } elsif ($type eq 'user') {
12443: 	$result=&get_userresdata($name,$domain);
12444:     }
12445:     if (!ref($result)) { return $result; }    
12446:     foreach my $item (@which) {
12447:         if ($item->[1] eq 'course') {
12448:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12449:                 unless ($$recursed) {
12450:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12451:                     $$recursed = 1;
12452:                 }
12453:                 foreach my $item (@${recurseup}) {
12454:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12455:                     last if (defined($result->{$norecursechk}));
12456:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12457:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12458:                 }
12459:             }
12460:         }
12461:         if (defined($result->{$item->[0]})) {
12462: 	    return [$result->{$item->[0]},$item->[1]];
12463: 	}
12464:     }
12465:     return undef;
12466: }
12467: 
12468: sub get_domain_lti {
12469:     my ($cdom,$context) = @_;
12470:     my ($name,$cachename,%lti);
12471:     if ($context eq 'consumer') {
12472:         $name = 'ltitools';
12473:     } elsif ($context eq 'provider') {
12474:         $name = 'lti';
12475:     } elsif ($context eq 'linkprot') {
12476:         $name = 'ltisec';
12477:     } else {
12478:         return %lti;
12479:     }
12480: 
12481:     if ($context eq 'linkprot') {
12482:         $cachename = $context;
12483:     } else {
12484:         $cachename = $name;
12485:     }
12486:     
12487:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12488:     if (defined($cached)) {
12489:         if (ref($result) eq 'HASH') {
12490:             %lti = %{$result};
12491:         }
12492:     } else {
12493:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12494:         if (ref($domconfig{$name}) eq 'HASH') {
12495:             if ($context eq 'linkprot') {
12496:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12497:                     %lti = %{$domconfig{$name}{'linkprot'}};
12498:                 }
12499:             } else {
12500:                 %lti = %{$domconfig{$name}};
12501:             }
12502:             if (($context eq 'consumer') && (keys(%lti))) {
12503:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12504:                 if (ref($encdomconfig{$name}) eq 'HASH') {
12505:                     foreach my $id (keys(%lti)) {
12506:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12507:                             foreach my $item ('key','secret') {
12508:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12509:                             }
12510:                         }
12511:                     }
12512:                 }
12513:             }
12514:         }
12515:         my $cachetime = 24*60*60;
12516:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12517:     }
12518:     return %lti;
12519: }
12520: 
12521: sub get_course_lti {
12522:     my ($cnum,$cdom) = @_;
12523:     my $hashid=$cdom.'_'.$cnum;
12524:     my %courselti;
12525:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12526:     if (defined($cached)) {
12527:         if (ref($result) eq 'HASH') {
12528:             %courselti = %{$result};
12529:         }
12530:     } else {
12531:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12532:         my $cachetime = 24*60*60;
12533:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12534:     }
12535:     return %courselti;
12536: }
12537: 
12538: sub courselti_itemid {
12539:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12540:     my ($chome,$itemid);
12541:     $chome = &homeserver($cnum,$cdom);
12542:     return if ($chome eq 'no_host');
12543:     if (ref($params) eq 'HASH') {
12544:         my $rep;
12545:         if (grep { $_ eq $chome } current_machine_ids()) {
12546:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12547:         } else {
12548:             my $escurl = &escape($url);
12549:             my $escmethod = &escape($method);
12550:             my $items = &freeze_escape($params);
12551:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12552:         }
12553:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12554:                 ($rep eq 'unknown_cmd')) {
12555:             $itemid = $rep;
12556:         }
12557:     }
12558:     return $itemid;
12559: }
12560: 
12561: sub domainlti_itemid {
12562:     my ($cdom,$url,$method,$params,$context) = @_;
12563:     my ($primary_id,$itemid);
12564:     $primary_id = &domain($cdom,'primary');
12565:     return if ($primary_id eq '');
12566:     if (ref($params) eq 'HASH') {
12567:         my $rep;
12568:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12569:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12570:         } else {
12571:             my $cnum = '';
12572:             my $escurl = &escape($url);
12573:             my $escmethod = &escape($method);
12574:             my $items = &freeze_escape($params);
12575:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12576:         }
12577:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12578:                 ($rep eq 'unknown_cmd')) {
12579:             $itemid = $rep;
12580:         }
12581:     }
12582:     return $itemid;
12583: }
12584: 
12585: sub count_supptools {
12586:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
12587:     my $hashid=$cnum.':'.$cdom;
12588:     my ($numexttools,$cached);
12589:     unless ($ignorecache) {
12590:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12591:     }
12592:     unless (defined($cached)) {
12593:         my $chome=&homeserver($cnum,$cdom);
12594:         $numexttools = 0;
12595:         unless ($chome eq 'no_host') {
12596:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12597:             if (ref($supplemental) eq 'HASH') {
12598:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12599:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12600:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12601:                             $numexttools ++;
12602:                         }
12603:                     }
12604:                 }
12605:             }
12606:         }
12607:         &do_cache_new('supptools',$hashid,$numexttools,600);
12608:     }
12609:     return $numexttools;
12610: }
12611: 
12612: sub has_unhidden_suppfiles {
12613:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12614:     my $hashid=$cnum.':'.$cdom;
12615:     my ($showsupp,$cached);
12616:     unless ($ignorecache) {
12617:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
12618:     }
12619:     unless (defined($cached)) {
12620:         my $chome=&homeserver($cnum,$cdom);
12621:         unless ($chome eq 'no_host') {
12622:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
12623:             if (ref($supplemental) eq 'HASH') {
12624:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12625:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12626:                         next if ($key =~ /\.sequence$/);
12627:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12628:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12629:                                 unless ($supplemental->{'hidden'}->{$id}) {
12630:                                     $showsupp = 1;
12631:                                     last;
12632:                                 }
12633:                             }
12634:                         }
12635:                         last if ($showsupp);
12636:                     }
12637:                 }
12638:             }
12639:         }
12640:         &do_cache_new('showsupp',$hashid,$showsupp,600);
12641:     }
12642:     return $showsupp;
12643: }
12644: 
12645: #
12646: # EXT resource caching routines
12647: #
12648: 
12649: {
12650: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12651: #
12652: # The course for which we cache
12653: my $cachedmapkey='';
12654: # The cached recursive maps for this course
12655: my %cachedmaps=();
12656: # When this was last done
12657: my $cachedmaptime='';
12658: 
12659: sub clear_EXT_cache_status {
12660:     &delenv('cache.EXT.');
12661: }
12662: 
12663: sub EXT_cache_status {
12664:     my ($target_domain,$target_user) = @_;
12665:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12666:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12667:         # We know already the user has no data
12668:         return 1;
12669:     } else {
12670:         return 0;
12671:     }
12672: }
12673: 
12674: sub EXT_cache_set {
12675:     my ($target_domain,$target_user) = @_;
12676:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12677:     #&appenv({$cachename => time});
12678: }
12679: 
12680: # --------------------------------------------------------- Value of a Variable
12681: sub EXT {
12682: 
12683:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12684:     unless ($varname) { return ''; }
12685:     #get real user name/domain, courseid and symb
12686:     my $courseid;
12687:     my $publicuser;
12688:     if ($symbparm) {
12689: 	$symbparm=&get_symb_from_alias($symbparm);
12690:     }
12691:     if (!($uname && $udom)) {
12692:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12693:       if (!$symbparm) {	$symbparm=$cursymb; }
12694:     } else {
12695: 	$courseid=$env{'request.course.id'};
12696:     }
12697:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12698:     my $rest;
12699:     if (defined($therest[0])) {
12700:        $rest=join('.',@therest);
12701:     } else {
12702:        $rest='';
12703:     }
12704: 
12705:     my $qualifierrest=$qualifier;
12706:     if ($rest) { $qualifierrest.='.'.$rest; }
12707:     my $spacequalifierrest=$space;
12708:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12709:     if ($realm eq 'user') {
12710: # --------------------------------------------------------------- user.resource
12711: 	if ($space eq 'resource') {
12712: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12713: 		  || defined($Apache::lonhomework::parsing_a_task))
12714: 		 &&
12715: 		 ($symbparm eq &symbread()) ) {
12716: 		# if we are in the middle of processing the resource the
12717: 		# get the value we are planning on committing
12718:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12719:                     return $Apache::lonhomework::results{$qualifierrest};
12720:                 } else {
12721:                     return $Apache::lonhomework::history{$qualifierrest};
12722:                 }
12723: 	    } else {
12724: 		my %restored;
12725: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12726: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12727: 		} else {
12728: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12729: 		}
12730: 		return $restored{$qualifierrest};
12731: 	    }
12732: # ----------------------------------------------------------------- user.access
12733:         } elsif ($space eq 'access') {
12734: 	    # FIXME - not supporting calls for a specific user
12735:             return &allowed($qualifier,$rest);
12736: # ------------------------------------------ user.preferences, user.environment
12737:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12738: 	    if (($uname eq $env{'user.name'}) &&
12739: 		($udom eq $env{'user.domain'})) {
12740: 		return $env{join('.',('environment',$qualifierrest))};
12741: 	    } else {
12742: 		my %returnhash;
12743: 		if (!$publicuser) {
12744: 		    %returnhash=&userenvironment($udom,$uname,
12745: 						 $qualifierrest);
12746: 		}
12747: 		return $returnhash{$qualifierrest};
12748: 	    }
12749: # ----------------------------------------------------------------- user.course
12750:         } elsif ($space eq 'course') {
12751: 	    # FIXME - not supporting calls for a specific user
12752:             return $env{join('.',('request.course',$qualifier))};
12753: # ------------------------------------------------------------------- user.role
12754:         } elsif ($space eq 'role') {
12755: 	    # FIXME - not supporting calls for a specific user
12756:             my ($role,$where)=split(/\./,$env{'request.role'});
12757:             if ($qualifier eq 'value') {
12758: 		return $role;
12759:             } elsif ($qualifier eq 'extent') {
12760:                 return $where;
12761:             }
12762: # ----------------------------------------------------------------- user.domain
12763:         } elsif ($space eq 'domain') {
12764:             return $udom;
12765: # ------------------------------------------------------------------- user.name
12766:         } elsif ($space eq 'name') {
12767:             return $uname;
12768: # ---------------------------------------------------- Any other user namespace
12769:         } else {
12770: 	    my %reply;
12771: 	    if (!$publicuser) {
12772: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12773: 	    }
12774: 	    return $reply{$qualifierrest};
12775:         }
12776:     } elsif ($realm eq 'query') {
12777: # ---------------------------------------------- pull stuff out of query string
12778:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12779: 						[$spacequalifierrest]);
12780: 	return $env{'form.'.$spacequalifierrest}; 
12781:    } elsif ($realm eq 'request') {
12782: # ------------------------------------------------------------- request.browser
12783:         if ($space eq 'browser') {
12784:             return $env{'browser.'.$qualifier};
12785: # ------------------------------------------------------------ request.filename
12786:         } else {
12787:             return $env{'request.'.$spacequalifierrest};
12788:         }
12789:     } elsif ($realm eq 'course') {
12790: # ---------------------------------------------------------- course.description
12791:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12792:     } elsif ($realm eq 'resource') {
12793: 
12794: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12795: 	    if (!$symbparm) { $symbparm=&symbread(); }
12796: 	}
12797: 
12798:         if ($qualifier eq '') {
12799: 	    if ($space eq 'title') {
12800: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12801: 	        return &gettitle($symbparm);
12802: 	    }
12803: 	
12804: 	    if ($space eq 'map') {
12805: 	        my ($map) = &decode_symb($symbparm);
12806: 	        return &symbread($map);
12807: 	    }
12808:             if ($space eq 'maptitle') {
12809:                 my ($map) = &decode_symb($symbparm);
12810:                 return &gettitle($map);
12811:             }
12812: 	    if ($space eq 'filename') {
12813: 	        if ($symbparm) {
12814: 		    return &clutter((&decode_symb($symbparm))[2]);
12815: 	        }
12816: 	        return &hreflocation('',$env{'request.filename'});
12817: 	    }
12818: 
12819:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12820:                 if ($space eq 'visibleparts') {
12821:                     my $navmap = Apache::lonnavmaps::navmap->new();
12822:                     my $item;
12823:                     if (ref($navmap)) {
12824:                         my $res = $navmap->getBySymb($symbparm);
12825:                         my $parts = $res->parts();
12826:                         if (ref($parts) eq 'ARRAY') {
12827:                             $item = join(',',@{$parts});
12828:                         }
12829:                         undef($navmap);
12830:                     }
12831:                     return $item;
12832:                 }
12833:             }
12834:         }
12835: 
12836: 	my ($section, $group, @groups, @recurseup, $recursed);
12837:         if (ref($recurseupref) eq 'ARRAY') {
12838:             @recurseup = @{$recurseupref};
12839:             $recursed = 1;
12840:         }
12841: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12842:         if (($courseid eq '') && ($cid)) {
12843:             $courseid = $cid;
12844:         }
12845: 	if (($symbparm && $courseid) && 
12846: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12847: 
12848: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12849: 
12850: # ----------------------------------------------------- Cascading lookup scheme
12851: 	    my $symbp=$symbparm;
12852: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12853: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12854:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12855: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12856: 	    if (($env{'user.name'} eq $uname) &&
12857: 		($env{'user.domain'} eq $udom)) {
12858: 		$section=$env{'request.course.sec'};
12859:                 @groups = split(/:/,$env{'request.course.groups'});  
12860:                 @groups=&sort_course_groups($courseid,@groups); 
12861: 	    } else {
12862: 		if (! defined($usection)) {
12863: 		    $section=&getsection($udom,$uname,$courseid);
12864: 		} else {
12865: 		    $section = $usection;
12866: 		}
12867:                 @groups = &get_users_groups($udom,$uname,$courseid);
12868: 	    }
12869: 
12870: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12871: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12872:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12873: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12874: 
12875: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12876: 	    my $courselevelr=$courseid.'.'.$symbparm;
12877:             $courseleveli=$courseid.'.'.$recurseparm;
12878: 	    $courselevelm=$courseid.'.'.$mapparm;
12879: 
12880: # ----------------------------------------------------------- first, check user
12881: 
12882: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12883:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12884: 				       ([$courselevelr,'resource'],
12885: 					[$courselevelm,'map'     ],
12886:                                         [$courseleveli,'map'     ],
12887: 					[$courselevel, 'course'  ]));
12888: 	    if (defined($userreply)) { return &get_reply($userreply); }
12889: 
12890: # ------------------------------------------------ second, check some of course
12891:             my $coursereply;
12892:             if (@groups > 0) {
12893:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12894:                                        $recurseparm,$mapparm,$spacequalifierrest,
12895:                                        $mapp,\$recursed,\@recurseup);
12896:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12897:             }
12898: 
12899: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12900: 				  $env{'course.'.$courseid.'.domain'},
12901: 				  'course',$mapp,\$recursed,\@recurseup,
12902:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12903: 				  ([$seclevelr,   'resource'],
12904: 				   [$seclevelm,   'map'     ],
12905:                                    [$secleveli,   'map'     ],
12906: 				   [$seclevel,    'course'  ],
12907: 				   [$courselevelr,'resource']));
12908: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12909: 
12910: # ------------------------------------------------------ third, check map parms
12911: 	    my %parmhash=();
12912: 	    my $thisparm='';
12913: 	    if (tie(%parmhash,'GDBM_File',
12914: 		    $env{'request.course.fn'}.'_parms.db',
12915: 		    &GDBM_READER(),0640)) {
12916: 		$thisparm=$parmhash{$symbparm};
12917: 		untie(%parmhash);
12918: 	    }
12919: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12920: 	}
12921: # ------------------------------------------ fourth, look in resource metadata
12922:  
12923:         my $what = $spacequalifierrest;
12924: 	$what=~s/\./\_/;
12925: 	my $filename;
12926: 	if (!$symbparm) { $symbparm=&symbread(); }
12927: 	if ($symbparm) {
12928: 	    $filename=(&decode_symb($symbparm))[2];
12929: 	} else {
12930: 	    $filename=$env{'request.filename'};
12931: 	}
12932:         my $toolsymb;
12933:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12934:             $toolsymb = $symbparm;
12935:         }
12936: 	my $metadata=&metadata($filename,$what,$toolsymb);
12937: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12938: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12939: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12940: 
12941: # ----------------------------------------------- fifth, look in rest of course
12942: 	if ($symbparm && defined($courseid) && 
12943: 	    $courseid eq $env{'request.course.id'}) {
12944: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12945: 				     $env{'course.'.$courseid.'.domain'},
12946: 				     'course',$mapp,\$recursed,\@recurseup,
12947:                                      $courseid,'.',$spacequalifierrest,
12948: 				     ([$courselevelm,'map'   ],
12949:                                       [$courseleveli,'map'   ],
12950: 				      [$courselevel, 'course']));
12951: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12952: 	}
12953: # ------------------------------------------------------------------ Cascade up
12954: 	unless ($space eq '0') {
12955: 	    my @parts=split(/_/,$space);
12956: 	    my $id=pop(@parts);
12957: 	    my $part=join('_',@parts);
12958: 	    if ($part eq '') { $part='0'; }
12959: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12960: 				 $symbparm,$udom,$uname,$section,1);
12961: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12962: 	}
12963: 	if ($recurse) { return undef; }
12964: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12965: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12966: # ---------------------------------------------------- Any other user namespace
12967:     } elsif ($realm eq 'environment') {
12968: # ----------------------------------------------------------------- environment
12969: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12970: 	    return $env{'environment.'.$spacequalifierrest};
12971: 	} else {
12972: 	    if ($uname eq 'anonymous' && $udom eq '') {
12973: 		return '';
12974: 	    }
12975: 	    my %returnhash=&userenvironment($udom,$uname,
12976: 					    $spacequalifierrest);
12977: 	    return $returnhash{$spacequalifierrest};
12978: 	}
12979:     } elsif ($realm eq 'system') {
12980: # ----------------------------------------------------------------- system.time
12981: 	if ($space eq 'time') {
12982: 	    return time;
12983:         }
12984:     } elsif ($realm eq 'server') {
12985: # ----------------------------------------------------------------- system.time
12986: 	if ($space eq 'name') {
12987: 	    return $ENV{'SERVER_NAME'};
12988:         }
12989:     } elsif ($realm eq 'client') {
12990:         if ($space eq 'remote_addr') {
12991:             return &get_requestor_ip();
12992:         }
12993:     }
12994:     return '';
12995: }
12996: 
12997: sub get_reply {
12998:     my ($reply_value) = @_;
12999:     if (ref($reply_value) eq 'ARRAY') {
13000:         if (wantarray) {
13001: 	    return @$reply_value;
13002:         }
13003:         return $reply_value->[0];
13004:     } else {
13005:         return $reply_value;
13006:     }
13007: }
13008: 
13009: sub check_group_parms {
13010:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13011:         $recursed,$recurseupref) = @_;
13012:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13013:                   [$what,'course']);
13014:     my $coursereply;
13015:     foreach my $group (@{$groups}) {
13016:         my @groupitems = ();
13017:         foreach my $level (@levels) {
13018:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13019:              push(@groupitems,[$item,$level->[1]]);
13020:         }
13021:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13022:                                    $env{'course.'.$courseid.'.domain'},
13023:                                    'course',$mapp,$recursed,$recurseupref,
13024:                                    $courseid,'.['.$group.'].',$what,
13025:                                    @groupitems);
13026:         last if (defined($coursereply));
13027:     }
13028:     return $coursereply;
13029: }
13030: 
13031: sub get_map_hierarchy {
13032:     my ($mapname,$courseid) = @_;
13033:     my @recurseup = ();
13034:     if ($mapname) {
13035:         if (($cachedmapkey eq $courseid) &&
13036:             (abs($cachedmaptime-time)<5)) {
13037:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13038:                 return @{$cachedmaps{$mapname}};
13039:             }
13040:         }
13041:         my $navmap = Apache::lonnavmaps::navmap->new();
13042:         if (ref($navmap)) {
13043:             @recurseup = $navmap->recurseup_maps($mapname);
13044:             undef($navmap);
13045:             $cachedmaps{$mapname} = \@recurseup;
13046:             $cachedmaptime=time;
13047:             $cachedmapkey=$courseid;
13048:         }
13049:     }
13050:     return @recurseup;
13051: }
13052: 
13053: }
13054: 
13055: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13056:     my ($courseid,@groups) = @_;
13057:     @groups = sort(@groups);
13058:     return @groups;
13059: }
13060: 
13061: sub packages_tab_default {
13062:     my ($uri,$varname,$toolsymb)=@_;
13063:     my (undef,$part,$name)=split(/\./,$varname);
13064: 
13065:     my (@extension,@specifics,$do_default);
13066:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13067: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13068: 	if ($pack_type eq 'default') {
13069: 	    $do_default=1;
13070: 	} elsif ($pack_type eq 'extension') {
13071: 	    push(@extension,[$package,$pack_type,$pack_part]);
13072: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13073: 	    # only look at packages defaults for packages that this id is
13074: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13075: 	}
13076:     }
13077:     # first look for a package that matches the requested part id
13078:     foreach my $package (@specifics) {
13079: 	my (undef,$pack_type,$pack_part)=@{$package};
13080: 	next if ($pack_part ne $part);
13081: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13082: 	    return $packagetab{"$pack_type&$name&default"};
13083: 	}
13084:     }
13085:     # look for any possible matching non extension_ package
13086:     foreach my $package (@specifics) {
13087: 	my (undef,$pack_type,$pack_part)=@{$package};
13088: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13089: 	    return $packagetab{"$pack_type&$name&default"};
13090: 	}
13091: 	if ($pack_type eq 'part') { $pack_part='0'; }
13092: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13093: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13094: 	}
13095:     }
13096:     # look for any posible extension_ match
13097:     foreach my $package (@extension) {
13098: 	my ($package,$pack_type)=@{$package};
13099: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13100: 	    return $packagetab{"$pack_type&$name&default"};
13101: 	}
13102: 	if (defined($packagetab{$package."&$name&default"})) {
13103: 	    return $packagetab{$package."&$name&default"};
13104: 	}
13105:     }
13106:     # look for a global default setting
13107:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13108: 	return $packagetab{"default&$name&default"};
13109:     }
13110:     return undef;
13111: }
13112: 
13113: sub add_prefix_and_part {
13114:     my ($prefix,$part)=@_;
13115:     my $keyroot;
13116:     if (defined($prefix) && $prefix !~ /^__/) {
13117: 	# prefix that has a part already
13118: 	$keyroot=$prefix;
13119:     } elsif (defined($prefix)) {
13120: 	# prefix that is missing a part
13121: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13122:     } else {
13123: 	# no prefix at all
13124: 	if (defined($part)) { $keyroot='_'.$part; }
13125:     }
13126:     return $keyroot;
13127: }
13128: 
13129: # ---------------------------------------------------------------- Get metadata
13130: 
13131: my %metaentry;
13132: my %importedpartids;
13133: my %importedrespids;
13134: sub metadata {
13135:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13136:     $uri=&declutter($uri);
13137:     # if it is a non metadata possible uri return quickly
13138:     if (($uri eq '') || 
13139: 	(($uri =~ m|^/*adm/|) && 
13140: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13141:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13142: 	return undef;
13143:     }
13144:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13145: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13146: 	return undef;
13147:     }
13148:     my $filename=$uri;
13149:     $uri=~s/\.meta$//;
13150: #
13151: # Is the metadata already cached?
13152: # Look at timestamp of caching
13153: # Everything is cached by the main uri, libraries are never directly cached
13154: #
13155:     if (!defined($liburi)) {
13156: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13157: 	if (defined($cached)) { return $result->{':'.$what}; }
13158:     }
13159: 
13160: #
13161: # If the uri is for an external tool the file from
13162: # which metadata should be retrieved depends on whether
13163: # the tool had been configured to be gradable (set in the Course
13164: # Editor or Resource Editor).
13165: #
13166: # If a valid symb has been included as the third arg in the call
13167: # to &metadata() that can be used to retrieve the value of
13168: # parameter_0_gradable set for the resource, and included in the
13169: # uploaded map containing the tool. The value is retrieved via
13170: # &EXT(), if a valid symb is available.  Otherwise the value of
13171: # gradable in the exttool_$marker.db file for the tool instance
13172: # is retrieved via &get().
13173: #
13174: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13175: # hiddenresource and encrypturl (during course initialization)
13176: # the map-level parameter for resource.0.gradable included in the 
13177: # uploaded map containing the tool will not yet have been stored
13178: # in the user_course_parms.db file for the user's session, so in 
13179: # this case fall back to retrieving gradable status from the
13180: # exttool_$marker.db file.
13181: #
13182: # In order to avoid an infinite loop, &metadata() will return
13183: # before a call to &EXT(), if the uri is for an external tool
13184: # and the $what for which metadata is being requested is
13185: # parameter_0_gradable or 0_gradable.
13186: #
13187: 
13188:     if ($uri =~ /ext\.tool$/) {
13189:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13190:             return;
13191:         } else {
13192:             my ($checked,$use_passback);
13193:             if ($toolsymb ne '') {
13194:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13195:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13196:                     $checked = 1;
13197:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13198:                         $use_passback = 1;
13199:                     }
13200:                 }
13201:             }
13202:             unless ($checked) {
13203:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13204:                 $marker=~s/\D//g;
13205:                 if ($marker) {
13206:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13207:                     $use_passback = $toolsettings{'gradable'};
13208:                 }
13209:             }
13210:             if ($use_passback) {
13211:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13212:             } else {
13213:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13214:             }
13215:         }
13216:     }
13217: 
13218:     {
13219: # Imported parts would go here
13220:         my @origfiletagids=();
13221:         my $importedparts=0;
13222: 
13223: # Imported responseids would go here
13224:         my $importedresponses=0;
13225: #
13226: # Is this a recursive call for a library?
13227: #
13228: #	if (! exists($metacache{$uri})) {
13229: #	    $metacache{$uri}={};
13230: #	}
13231: 	my $cachetime = 60*60;
13232:         if ($liburi) {
13233: 	    $liburi=&declutter($liburi);
13234:             $filename=$liburi;
13235:         } else {
13236: 	    &devalidate_cache_new('meta',$uri);
13237: 	    undef(%metaentry);
13238: 	}
13239:         my %metathesekeys=();
13240:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13241: 	my $metastring;
13242: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13243: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13244: 	    $metastring = 
13245: 		&Apache::lonnet::ssi_body($which,
13246: 					  ('grade_target' => 'meta'));
13247: 	    $cachetime = 1; # only want this cached in the child not long term
13248: 	} elsif (($uri !~ m -^(editupload)/-) && 
13249:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13250: 	    my $file=&filelocation('',&clutter($filename));
13251: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13252: 	    $metastring=&getfile($file);
13253: 	}
13254:         my $parser=HTML::LCParser->new(\$metastring);
13255:         my $token;
13256:         undef %metathesekeys;
13257:         while ($token=$parser->get_token) {
13258: 	    if ($token->[0] eq 'S') {
13259: 		if (defined($token->[2]->{'package'})) {
13260: #
13261: # This is a package - get package info
13262: #
13263: 		    my $package=$token->[2]->{'package'};
13264: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13265: 		    if (defined($token->[2]->{'id'})) { 
13266: 			$keyroot.='_'.$token->[2]->{'id'}; 
13267: 		    }
13268: 		    if ($metaentry{':packages'}) {
13269: 			$metaentry{':packages'}.=','.$package.$keyroot;
13270: 		    } else {
13271: 			$metaentry{':packages'}=$package.$keyroot;
13272: 		    }
13273: 		    foreach my $pack_entry (keys(%packagetab)) {
13274: 			my $part=$keyroot;
13275: 			$part=~s/^\_//;
13276: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13277: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13278: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13279: 			    # ignore package.tab specified default values
13280:                             # here &package_tab_default() will fetch those
13281: 			    if ($subp eq 'default') { next; }
13282: 			    my $value=$packagetab{$pack_entry};
13283: 			    my $unikey;
13284: 			    if ($pack =~ /_0$/) {
13285: 				$unikey='parameter_0_'.$name;
13286: 				$part=0;
13287: 			    } else {
13288: 				$unikey='parameter'.$keyroot.'_'.$name;
13289: 			    }
13290: 			    if ($subp eq 'display') {
13291: 				$value.=' [Part: '.$part.']';
13292: 			    }
13293: 			    $metaentry{':'.$unikey.'.part'}=$part;
13294: 			    $metathesekeys{$unikey}=1;
13295: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13296: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13297: 			    }
13298: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13299: 				$metaentry{':'.$unikey}=
13300: 				    $metaentry{':'.$unikey.'.default'};
13301: 			    }
13302: 			}
13303: 		    }
13304: 		} else {
13305: #
13306: # This is not a package - some other kind of start tag
13307: #
13308: 		    my $entry=$token->[1];
13309: 		    my $unikey='';
13310: 
13311: 		    if ($entry eq 'import') {
13312: #
13313: # Importing a library here
13314: #
13315:                         my $location=$parser->get_text('/import');
13316:                         my $dir=$filename;
13317:                         $dir=~s|[^/]*$||;
13318:                         $location=&filelocation($dir,$location);
13319: 
13320:                         my $importid=$token->[2]->{'id'};
13321:                         my $importmode=$token->[2]->{'importmode'};
13322: #
13323: # Check metadata for imported file to
13324: # see if it contained response items
13325: #
13326:                         my ($origfile,@libfilekeys);
13327:                         my %currmetaentry = %metaentry;
13328:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13329:                                                            $depthcount+1));
13330:                         if (grep(/^responseorder$/,@libfilekeys)) {
13331:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13332:                                                              undef,$depthcount+1);
13333:                             if ($libresponseorder ne '') {
13334:                                 if ($#origfiletagids<0) {
13335:                                     undef(%importedrespids);
13336:                                     undef(%importedpartids);
13337:                                 }
13338:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13339:                                 if (@respids) {
13340:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13341:                                 }
13342:                                 if ($importedrespids{$importid} ne '') {
13343:                                     $importedresponses = 1;
13344: # We need to get the original file and the imported file to get the response order correct
13345: # Load and inspect original file
13346:                                     if ($#origfiletagids<0) {
13347:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13348:                                         $origfile=&getfile($origfilelocation);
13349:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13350:                                     }
13351:                                 }
13352:                             }
13353:                         }
13354: # Do not overwrite contents of %metaentry hash for resource itself with 
13355: # hash populated for imported library file
13356:                         %metaentry = %currmetaentry;
13357:                         undef(%currmetaentry);
13358:                         if ($importmode eq 'part') {
13359: # Import as part(s)
13360:                            $importedparts=1;
13361: # We need to get the original file and the imported file to get the part order correct
13362: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13363: # Load and inspect original file if we didn't do that already
13364:                            if ($#origfiletagids<0) {
13365:                                undef(%importedrespids);
13366:                                undef(%importedpartids);
13367:                                if ($origfile eq '') {
13368:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13369:                                    $origfile=&getfile($origfilelocation);
13370:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13371:                                }
13372:                            }
13373:                            my @impfilepartids;
13374: # If <partorder> tag is included in metadata for the imported file
13375: # get the parts in the imported file from that.
13376:                            if (grep(/^partorder$/,@libfilekeys)) {
13377:                                %currmetaentry = %metaentry;
13378:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13379:                                                             $depthcount+1);
13380:                                %metaentry = %currmetaentry;
13381:                                undef(%currmetaentry);
13382:                                if ($libpartorder ne '') {
13383:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13384:                                }
13385:                            } else {
13386: # If no <partorder> tag available, load and inspect imported file
13387:                                my $impfile=&getfile($location);
13388:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13389:                            }
13390:                            if ($#impfilepartids>=0) {
13391: # This problem had parts
13392:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13393:                            } else {
13394: # Importing by turning a single problem into a problem part
13395: # It gets the import-tags ID as part-ID
13396:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13397:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13398:                            }
13399:                         } else {
13400: # Import as problem or as normal import
13401:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13402:                             unless ($importmode eq 'problem') {
13403: # Normal import
13404:                                 if (defined($token->[2]->{'id'})) {
13405:                                     $unikey.='_'.$token->[2]->{'id'};
13406:                                 }
13407:                             }
13408: # Check metadata for imported file to
13409: # see if it contained parts
13410:                             if (grep(/^partorder$/,@libfilekeys)) {
13411:                                 %currmetaentry = %metaentry;
13412:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13413:                                                              $depthcount+1);
13414:                                 %metaentry = %currmetaentry;
13415:                                 undef(%currmetaentry);
13416:                                 if ($libpartorder ne '') {
13417:                                     $importedparts = 1;
13418:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13419:                                 }
13420:                             }
13421:                         }
13422: 			if ($depthcount<20) {
13423: 			    my $metadata = 
13424: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13425: 					  $depthcount+1);
13426: 			    foreach my $meta (split(',',$metadata)) {
13427: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13428: 				$metathesekeys{$meta}=1;
13429: 			    }
13430:                         }
13431: 		    } else {
13432: #
13433: # Not importing, some other kind of non-package, non-library start tag
13434: # 
13435:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13436:                         if (defined($token->[2]->{'id'})) {
13437:                             $unikey.='_'.$token->[2]->{'id'};
13438:                         }
13439: 			if (defined($token->[2]->{'name'})) { 
13440: 			    $unikey.='_'.$token->[2]->{'name'}; 
13441: 			}
13442: 			$metathesekeys{$unikey}=1;
13443: 			foreach my $param (@{$token->[3]}) {
13444: 			    $metaentry{':'.$unikey.'.'.$param} =
13445: 				$token->[2]->{$param};
13446: 			}
13447: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13448: 			my $default=$metaentry{':'.$unikey.'.default'};
13449: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13450: 		 # only ws inside the tag, and not in default, so use default
13451: 		 # as value
13452: 			    $metaentry{':'.$unikey}=$default;
13453: 			} elsif ( $internaltext =~ /\S/ ) {
13454: 		  # something interesting inside the tag
13455: 			    $metaentry{':'.$unikey}=$internaltext;
13456: 			} else {
13457: 		  # no interesting values, don't set a default
13458: 			}
13459: # end of not-a-package not-a-library import
13460: 		    }
13461: # end of not-a-package start tag
13462: 		}
13463: # the next is the end of "start tag"
13464: 	    }
13465: 	}
13466: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13467: 	$extension = lc($extension);
13468: 	if ($extension eq 'htm') { $extension='html'; }
13469: 
13470: 	foreach my $key (keys(%packagetab)) {
13471: 	    #no specific packages #how's our extension
13472: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13473: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13474: 					 \%metathesekeys);
13475: 	}
13476: 
13477: 	if (!exists($metaentry{':packages'})
13478: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13479: 	    foreach my $key (keys(%packagetab)) {
13480: 		#no specific packages well let's get default then
13481: 		if ($key!~/^default&/) { next; }
13482: 		&metadata_create_package_def($uri,$key,'default',
13483: 					     \%metathesekeys);
13484: 	    }
13485: 	}
13486: # are there custom rights to evaluate
13487: 	if ($metaentry{':copyright'} eq 'custom') {
13488: 
13489:     #
13490:     # Importing a rights file here
13491:     #
13492: 	    unless ($depthcount) {
13493: 		my $location=$metaentry{':customdistributionfile'};
13494: 		my $dir=$filename;
13495: 		$dir=~s|[^/]*$||;
13496: 		$location=&filelocation($dir,$location);
13497: 		my $rights_metadata =
13498: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13499: 			      $depthcount+1);
13500: 		foreach my $rights (split(',',$rights_metadata)) {
13501: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13502: 		    $metathesekeys{$rights}=1;
13503: 		}
13504: 	    }
13505: 	}
13506: 	# uniqifiy package listing
13507: 	my %seen;
13508: 	my @uniq_packages =
13509: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13510: 	$metaentry{':packages'} = join(',',@uniq_packages);
13511: 
13512:         if (($importedresponses) || ($importedparts)) {
13513:             if ($importedparts) {
13514: # We had imported parts and need to rebuild partorder
13515:                 $metaentry{':partorder'}='';
13516:                 $metathesekeys{'partorder'}=1;
13517:             }
13518:             if ($importedresponses) {
13519: # We had imported responses and need to rebuil responseorder
13520:                 $metaentry{':responseorder'}='';
13521:                 $metathesekeys{'responseorder'}=1;
13522:             }
13523:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13524:                 my $origid = $origfiletagids[$index+1];
13525:                 if ($origfiletagids[$index] eq 'part') {
13526: # Original part, part of the problem
13527:                     if ($importedparts) {
13528:                         $metaentry{':partorder'}.=','.$origid;
13529:                     }
13530:                 } elsif ($origfiletagids[$index] eq 'import') {
13531:                     if ($importedparts) {
13532: # We have imported parts at this position
13533:                         if ($importedpartids{$origid} ne '') {
13534:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13535:                         }
13536:                     }
13537:                     if ($importedresponses) {
13538: # We have imported responses at this position
13539:                         if ($importedrespids{$origid} ne '') {
13540:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13541:                         }
13542:                     }
13543:                 } else {
13544: # Original response item, part of the problem
13545:                     if ($importedresponses) {
13546:                         $metaentry{':responseorder'}.=','.$origid;
13547:                     }
13548:                 }
13549:             }
13550:             if ($importedparts) {
13551:                 $metaentry{':partorder'}=~s/^\,//;
13552:             }
13553:             if ($importedresponses) {
13554:                 $metaentry{':responseorder'}=~s/^\,//;
13555:             }
13556:         }
13557: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13558: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13559: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13560:         unless ($liburi) {
13561: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13562:         }
13563: # this is the end of "was not already recently cached
13564:     }
13565:     return $metaentry{':'.$what};
13566: }
13567: 
13568: sub metadata_create_package_def {
13569:     my ($uri,$key,$package,$metathesekeys)=@_;
13570:     my ($pack,$name,$subp)=split(/\&/,$key);
13571:     if ($subp eq 'default') { next; }
13572:     
13573:     if (defined($metaentry{':packages'})) {
13574: 	$metaentry{':packages'}.=','.$package;
13575:     } else {
13576: 	$metaentry{':packages'}=$package;
13577:     }
13578:     my $value=$packagetab{$key};
13579:     my $unikey;
13580:     $unikey='parameter_0_'.$name;
13581:     $metaentry{':'.$unikey.'.part'}=0;
13582:     $$metathesekeys{$unikey}=1;
13583:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13584: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13585:     }
13586:     if (defined($metaentry{':'.$unikey.'.default'})) {
13587: 	$metaentry{':'.$unikey}=
13588: 	    $metaentry{':'.$unikey.'.default'};
13589:     }
13590: }
13591: 
13592: sub metadata_generate_part0 {
13593:     my ($metadata,$metacache,$uri) = @_;
13594:     my %allnames;
13595:     foreach my $metakey (keys(%$metadata)) {
13596: 	if ($metakey=~/^parameter\_(.*)/) {
13597: 	  my $part=$$metacache{':'.$metakey.'.part'};
13598: 	  my $name=$$metacache{':'.$metakey.'.name'};
13599: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13600: 	    $allnames{$name}=$part;
13601: 	  }
13602: 	}
13603:     }
13604:     foreach my $name (keys(%allnames)) {
13605:       $$metadata{"parameter_0_$name"}=1;
13606:       my $key=":parameter_0_$name";
13607:       $$metacache{"$key.part"}='0';
13608:       $$metacache{"$key.name"}=$name;
13609:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13610: 					   $allnames{$name}.'_'.$name.
13611: 					   '.type'};
13612:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13613: 			     '.display'};
13614:       my $expr='[Part: '.$allnames{$name}.']';
13615:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13616:       $$metacache{"$key.display"}=$olddis;
13617:     }
13618: }
13619: 
13620: # ------------------------------------------------------ Devalidate title cache
13621: 
13622: sub devalidate_title_cache {
13623:     my ($url)=@_;
13624:     if (!$env{'request.course.id'}) { return; }
13625:     my $symb=&symbread($url);
13626:     if (!$symb) { return; }
13627:     my $key=$env{'request.course.id'}."\0".$symb;
13628:     &devalidate_cache_new('title',$key);
13629: }
13630: 
13631: # ------------------------------------------------- Get the title of a course
13632: 
13633: sub current_course_title {
13634:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13635: }
13636: # ------------------------------------------------- Get the title of a resource
13637: 
13638: sub gettitle {
13639:     my $urlsymb=shift;
13640:     my $symb=&symbread($urlsymb);
13641:     if ($symb) {
13642: 	my $key=$env{'request.course.id'}."\0".$symb;
13643: 	my ($result,$cached)=&is_cached_new('title',$key);
13644: 	if (defined($cached)) { 
13645: 	    return $result;
13646: 	}
13647: 	my ($map,$resid,$url)=&decode_symb($symb);
13648: 	my $title='';
13649: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13650: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13651: 	} else {
13652: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13653: 		    &GDBM_READER(),0640)) {
13654: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13655: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13656: 		untie(%bighash);
13657: 	    }
13658: 	}
13659: 	$title=~s/\&colon\;/\:/gs;
13660: 	if ($title) {
13661: # Remember both $symb and $title for dynamic metadata
13662:             $accesshash{$symb.'___crstitle'}=$title;
13663:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13664: # Cache this title and then return it
13665: 	    return &do_cache_new('title',$key,$title,600);
13666: 	}
13667: 	$urlsymb=$url;
13668:     }
13669:     my $title=&metadata($urlsymb,'title');
13670:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13671:     return $title;
13672: }
13673: 
13674: sub get_slot {
13675:     my ($which,$cnum,$cdom)=@_;
13676:     if (!$cnum || !$cdom) {
13677: 	(undef,my $courseid)=&whichuser();
13678: 	$cdom=$env{'course.'.$courseid.'.domain'};
13679: 	$cnum=$env{'course.'.$courseid.'.num'};
13680:     }
13681:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13682:     my %slotinfo;
13683:     if (exists($remembered{$key})) {
13684: 	$slotinfo{$which} = $remembered{$key};
13685:     } else {
13686: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13687: 	&Apache::lonhomework::showhash(%slotinfo);
13688: 	my ($tmp)=keys(%slotinfo);
13689: 	if ($tmp=~/^error:/) { return (); }
13690: 	$remembered{$key} = $slotinfo{$which};
13691:     }
13692:     if (ref($slotinfo{$which}) eq 'HASH') {
13693: 	return %{$slotinfo{$which}};
13694:     }
13695:     return $slotinfo{$which};
13696: }
13697: 
13698: sub get_reservable_slots {
13699:     my ($cnum,$cdom,$uname,$udom) = @_;
13700:     my $now = time;
13701:     my $reservable_info;
13702:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13703:     if (exists($remembered{$key})) {
13704:         $reservable_info = $remembered{$key};
13705:     } else {
13706:         my %resv;
13707:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13708:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13709:         $reservable_info = \%resv;
13710:         $remembered{$key} = $reservable_info;
13711:     }
13712:     return $reservable_info;
13713: }
13714: 
13715: sub get_course_slots {
13716:     my ($cnum,$cdom) = @_;
13717:     my $hashid=$cnum.':'.$cdom;
13718:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
13719:     if (defined($cached)) {
13720:         if (ref($result) eq 'HASH') {
13721:             return %{$result};
13722:         }
13723:     } else {
13724:         my %slots=&dump('slots',$cdom,$cnum);
13725:         my ($tmp) = keys(%slots);
13726:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13727:             &do_cache_new('allslots',$hashid,\%slots,600);
13728:             return %slots;
13729:         }
13730:     }
13731:     return;
13732: }
13733: 
13734: sub devalidate_slots_cache {
13735:     my ($cnum,$cdom)=@_;
13736:     my $hashid=$cnum.':'.$cdom;
13737:     &devalidate_cache_new('allslots',$hashid);
13738: }
13739: 
13740: sub get_coursechange {
13741:     my ($cdom,$cnum) = @_;
13742:     if ($cdom eq '' || $cnum eq '') {
13743:         return unless ($env{'request.course.id'});
13744:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13745:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13746:     }
13747:     my $hashid=$cdom.'_'.$cnum;
13748:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13749:     if ((defined($cached)) && ($change ne '')) {
13750:         return $change;
13751:     } else {
13752:         my %crshash;
13753:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13754:         if ($crshash{'internal.contentchange'} eq '') {
13755:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13756:             if ($change eq '') {
13757:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13758:                 $change = $crshash{'internal.created'};
13759:             }
13760:         } else {
13761:             $change = $crshash{'internal.contentchange'};
13762:         }
13763:         my $cachetime = 600;
13764:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13765:     }
13766:     return $change;
13767: }
13768: 
13769: sub devalidate_coursechange_cache {
13770:     my ($cdom,$cnum)=@_;
13771:     my $hashid=$cdom.'_'.$cnum;
13772:     &devalidate_cache_new('crschange',$hashid);
13773: }
13774: 
13775: sub get_suppchange {
13776:     my ($cdom,$cnum) = @_;
13777:     if ($cdom eq '' || $cnum eq '') {
13778:         return unless ($env{'request.course.id'});
13779:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13780:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13781:     }
13782:     my $hashid=$cdom.'_'.$cnum;
13783:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13784:     if ((defined($cached)) && ($change ne '')) {
13785:         return $change;
13786:     } else {
13787:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13788:         if ($crshash{'internal.supplementalchange'} eq '') {
13789:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13790:             if ($change eq '') {
13791:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13792:                 $change = $crshash{'internal.created'};
13793:             }
13794:         } else {
13795:             $change = $crshash{'internal.supplementalchange'};
13796:         }
13797:         my $cachetime = 600;
13798:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
13799:     }
13800:     return $change;
13801: }
13802: 
13803: sub devalidate_suppchange_cache {
13804:     my ($cdom,$cnum)=@_;
13805:     my $hashid=$cdom.'_'.$cnum;
13806:     &devalidate_cache_new('suppchange',$hashid);
13807: }
13808: 
13809: sub update_supp_caches {
13810:     my ($cdom,$cnum) = @_;
13811:     my %servers = &internet_dom_servers($cdom);
13812:     my @ids=&current_machine_ids();
13813:     foreach my $server (keys(%servers)) {
13814:         next if (grep(/^\Q$server\E$/,@ids));
13815:         my $hashid=$cnum.':'.$cdom;
13816:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
13817:         &remote_devalidate_cache($server,[$cachekey]);
13818:     }
13819:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
13820:     &count_supptools($cnum,$cdom,1);
13821:     my $now = time;
13822:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13823:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13824:     }
13825:     &put('environment',{'internal.supplementalchange' => $now},
13826:          $cdom,$cnum);
13827:     &Apache::lonnet::appenv(
13828:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13829:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13830: }
13831: 
13832: # ------------------------------------------------- Update symbolic store links
13833: 
13834: sub symblist {
13835:     my ($mapname,%newhash)=@_;
13836:     $mapname=&deversion(&declutter($mapname));
13837:     my %hash;
13838:     if (($env{'request.course.fn'}) && (%newhash)) {
13839:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13840:                       &GDBM_WRCREAT(),0640)) {
13841: 	    foreach my $url (keys(%newhash)) {
13842: 		next if ($url eq 'last_known'
13843: 			 && $env{'form.no_update_last_known'});
13844: 		$hash{declutter($url)}=&encode_symb($mapname,
13845: 						    $newhash{$url}->[1],
13846: 						    $newhash{$url}->[0]);
13847:             }
13848:             if (untie(%hash)) {
13849: 		return 'ok';
13850:             }
13851:         }
13852:     }
13853:     return 'error';
13854: }
13855: 
13856: # --------------------------------------------------------------- Verify a symb
13857: 
13858: sub symbverify {
13859:     my ($symb,$thisurl,$encstate)=@_;
13860:     my $thisfn=$thisurl;
13861:     $thisfn=&declutter($thisfn);
13862: # direct jump to resource in page or to a sequence - will construct own symbs
13863:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13864: # check URL part
13865:     my ($map,$resid,$url)=&decode_symb($symb);
13866: 
13867:     unless ($url eq $thisfn) { return 0; }
13868: 
13869:     $symb=&symbclean($symb);
13870:     $thisurl=&deversion($thisurl);
13871:     $thisfn=&deversion($thisfn);
13872: 
13873:     my %bighash;
13874:     my $okay=0;
13875: 
13876:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13877:                             &GDBM_READER(),0640)) {
13878:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13879:             $thisurl =~ s/\?.+$//;
13880:             if ($map =~ m{^uploaded/.+\.page$}) {
13881:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13882:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13883:             }
13884:         }
13885:         my $ids;
13886:         if ($map =~ m{^uploaded/.+\.page$}) {
13887:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13888:         } else {
13889:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13890:         }
13891:         unless ($ids) {
13892:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13893:             $ids=$bighash{$idkey};
13894:         }
13895:         if ($ids) {
13896: # ------------------------------------------------------------------- Has ID(s)
13897:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13898:                 $symb =~ s/\?.+$//;
13899:             }
13900: 	    foreach my $id (split(/\,/,$ids)) {
13901: 	       my ($mapid,$resid)=split(/\./,$id);
13902:                if (
13903:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13904:    eq $symb) {
13905:                    if (ref($encstate)) {
13906:                        $$encstate = $bighash{'encrypted_'.$id};
13907:                    }
13908: 		   if (($env{'request.role.adv'}) ||
13909: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13910:                        ($thisurl eq '/adm/navmaps')) {
13911: 		       $okay=1;
13912:                        last;
13913: 		   }
13914: 	       }
13915: 	   }
13916:         }
13917: 	untie(%bighash);
13918:     }
13919:     return $okay;
13920: }
13921: 
13922: # --------------------------------------------------------------- Clean-up symb
13923: 
13924: sub symbclean {
13925:     my $symb=shift;
13926:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13927: # remove version from map
13928:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13929: 
13930: # remove version from URL
13931:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13932: 
13933: # remove wrapper
13934: 
13935:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13936:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13937:     return $symb;
13938: }
13939: 
13940: # ---------------------------------------------- Split symb to find map and url
13941: 
13942: sub encode_symb {
13943:     my ($map,$resid,$url)=@_;
13944:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13945: }
13946: 
13947: sub decode_symb {
13948:     my $symb=shift;
13949:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13950:     my ($map,$resid,$url)=split(/___/,$symb);
13951:     return (&fixversion($map),$resid,&fixversion($url));
13952: }
13953: 
13954: sub fixversion {
13955:     my $fn=shift;
13956:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13957:     my %bighash;
13958:     my $uri=&clutter($fn);
13959:     my $key=$env{'request.course.id'}.'_'.$uri;
13960: # is this cached?
13961:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13962:     if (defined($cached)) { return $result; }
13963: # unfortunately not cached, or expired
13964:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13965: 	    &GDBM_READER(),0640)) {
13966:  	if ($bighash{'version_'.$uri}) {
13967:  	    my $version=$bighash{'version_'.$uri};
13968:  	    unless (($version eq 'mostrecent') || 
13969: 		    ($version==&getversion($uri))) {
13970:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13971:  	    }
13972:  	}
13973:  	untie %bighash;
13974:     }
13975:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13976: }
13977: 
13978: sub deversion {
13979:     my $url=shift;
13980:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13981:     return $url;
13982: }
13983: 
13984: # ------------------------------------------------------ Return symb list entry
13985: 
13986: sub symbread {
13987:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13988:         $ignoresymbdb,$noenccheck)=@_;
13989:     my $cache_str='request.symbread.cached.'.$thisfn;
13990:     if (defined($env{$cache_str})) {
13991:         unless (ref($possibles) eq 'HASH') {
13992:             if ($ignorecachednull) {
13993:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13994:             } else {
13995:                 return $env{$cache_str};
13996:             }
13997:         }
13998:     }
13999: # no filename provided? try from environment
14000:     unless ($thisfn) {
14001:         if ($env{'request.symb'}) {
14002:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14003: 	}
14004: 	$thisfn=$env{'request.filename'};
14005:     }
14006:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14007: # is that filename actually a symb? Verify, clean, and return
14008:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14009: 	if (&symbverify($thisfn,$1)) {
14010: 	    return $env{$cache_str}=&symbclean($thisfn);
14011: 	}
14012:     }
14013:     $thisfn=declutter($thisfn);
14014:     my %hash;
14015:     my %bighash;
14016:     my $syval='';
14017:     if (($env{'request.course.fn'}) && ($thisfn)) {
14018:         unless ($ignoresymbdb) {
14019:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14020:                           &GDBM_READER(),0640)) {
14021: 	        $syval=$hash{$thisfn};
14022:                 untie(%hash);
14023:             }
14024:             if ($syval && $checkforblock) {
14025:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14026:                 if (@blockers) {
14027:                     $syval='';
14028:                 }
14029:             }
14030:         }
14031: # ---------------------------------------------------------- There was an entry
14032:         if ($syval) {
14033: 	    #unless ($syval=~/\_\d+$/) {
14034: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14035: 		    #&appenv({'request.ambiguous' => $thisfn});
14036: 		    #return $env{$cache_str}='';
14037: 		#}    
14038: 		#$syval.=$1;
14039: 	    #}
14040:         } else {
14041: # ------------------------------------------------------- Was not in symb table
14042:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14043:                             &GDBM_READER(),0640)) {
14044: # ---------------------------------------------- Get ID(s) for current resource
14045:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14046:               unless ($ids) { 
14047:                  $ids=$bighash{'ids_/'.$thisfn};
14048:               }
14049:               unless ($ids) {
14050: # alias?
14051: 		  $ids=$bighash{'mapalias_'.$thisfn};
14052:               }
14053:               if ($ids) {
14054: # ------------------------------------------------------------------- Has ID(s)
14055:                  my @possibilities=split(/\,/,$ids);
14056:                  if ($#possibilities==0) {
14057: # ----------------------------------------------- There is only one possibility
14058: 		     my ($mapid,$resid)=split(/\./,$ids);
14059: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14060: 						    $resid,$thisfn);
14061:                      if (ref($possibles) eq 'HASH') {
14062:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14063:                              $possibles->{$syval} = 1;
14064:                          }
14065:                      }
14066:                      if ($checkforblock) {
14067:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14068:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14069:                              if (@blockers) {
14070:                                  $syval = '';
14071:                                  untie(%bighash);
14072:                                  return $env{$cache_str}='';
14073:                              }
14074:                          }
14075:                      }
14076:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14077: # ------------------------------------------ There is more than one possibility
14078:                      my $realpossible=0;
14079:                      foreach my $id (@possibilities) {
14080: 			 my $file=$bighash{'src_'.$id};
14081:                          my $canaccess;
14082:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14083:                              $canaccess = 1;
14084:                          } else { 
14085:                              $canaccess = &allowed('bre',$file);
14086:                          }
14087:                          if ($canaccess) {
14088:          		     my ($mapid,$resid)=split(/\./,$id);
14089:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14090:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14091: 						             $resid,$thisfn);
14092:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14093:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14094:                                  if ($checkforblock) {
14095:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14096:                                      if (@blockers > 0) {
14097:                                          $syval = '';
14098:                                      } else {
14099:                                          $syval = $poss_syval;
14100:                                          $realpossible++;
14101:                                      }
14102:                                  } else {
14103:                                      $syval = $poss_syval;
14104:                                      $realpossible++;
14105:                                  }
14106:                                  if ($syval) {
14107:                                      if (ref($possibles) eq 'HASH') {
14108:                                          $possibles->{$syval} = 1;
14109:                                      }
14110:                                  }
14111:                              }
14112: 			 }
14113:                      }
14114: 		     if ($realpossible!=1) { $syval=''; }
14115:                  } else {
14116:                      $syval='';
14117:                  }
14118: 	      }
14119:               untie(%bighash);
14120:            }
14121:         }
14122:         if ($syval) {
14123: 	    return $env{$cache_str}=$syval;
14124:         }
14125:     }
14126:     &appenv({'request.ambiguous' => $thisfn});
14127:     return $env{$cache_str}='';
14128: }
14129: 
14130: # ---------------------------------------------------------- Return random seed
14131: 
14132: sub numval {
14133:     my $txt=shift;
14134:     $txt=~tr/A-J/0-9/;
14135:     $txt=~tr/a-j/0-9/;
14136:     $txt=~tr/K-T/0-9/;
14137:     $txt=~tr/k-t/0-9/;
14138:     $txt=~tr/U-Z/0-5/;
14139:     $txt=~tr/u-z/0-5/;
14140:     $txt=~s/\D//g;
14141:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14142:     return int($txt);
14143: }
14144: 
14145: sub numval2 {
14146:     my $txt=shift;
14147:     $txt=~tr/A-J/0-9/;
14148:     $txt=~tr/a-j/0-9/;
14149:     $txt=~tr/K-T/0-9/;
14150:     $txt=~tr/k-t/0-9/;
14151:     $txt=~tr/U-Z/0-5/;
14152:     $txt=~tr/u-z/0-5/;
14153:     $txt=~s/\D//g;
14154:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14155:     my $total;
14156:     foreach my $val (@txts) { $total+=$val; }
14157:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14158:     return int($total);
14159: }
14160: 
14161: sub numval3 {
14162:     use integer;
14163:     my $txt=shift;
14164:     $txt=~tr/A-J/0-9/;
14165:     $txt=~tr/a-j/0-9/;
14166:     $txt=~tr/K-T/0-9/;
14167:     $txt=~tr/k-t/0-9/;
14168:     $txt=~tr/U-Z/0-5/;
14169:     $txt=~tr/u-z/0-5/;
14170:     $txt=~s/\D//g;
14171:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14172:     my $total;
14173:     foreach my $val (@txts) { $total+=$val; }
14174:     if ($_64bit) { $total=(($total<<32)>>32); }
14175:     return $total;
14176: }
14177: 
14178: sub digest {
14179:     my ($data)=@_;
14180:     my $digest=&Digest::MD5::md5($data);
14181:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14182:     my ($e,$f);
14183:     {
14184:         use integer;
14185:         $e=($a+$b);
14186:         $f=($c+$d);
14187:         if ($_64bit) {
14188:             $e=(($e<<32)>>32);
14189:             $f=(($f<<32)>>32);
14190:         }
14191:     }
14192:     if (wantarray) {
14193: 	return ($e,$f);
14194:     } else {
14195: 	my $g;
14196: 	{
14197: 	    use integer;
14198: 	    $g=($e+$f);
14199: 	    if ($_64bit) {
14200: 		$g=(($g<<32)>>32);
14201: 	    }
14202: 	}
14203: 	return $g;
14204:     }
14205: }
14206: 
14207: sub latest_rnd_algorithm_id {
14208:     return '64bit5';
14209: }
14210: 
14211: sub get_rand_alg {
14212:     my ($courseid)=@_;
14213:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14214:     if ($courseid) {
14215: 	return $env{"course.$courseid.rndseed"};
14216:     }
14217:     return &latest_rnd_algorithm_id();
14218: }
14219: 
14220: sub validCODE {
14221:     my ($CODE)=@_;
14222:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14223:     return 0;
14224: }
14225: 
14226: sub getCODE {
14227:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14228:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14229: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14230: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14231: 	return $Apache::lonhomework::history{'resource.CODE'};
14232:     }
14233:     return undef;
14234: }
14235: #
14236: #  Determines the random seed for a specific context:
14237: #
14238: # parameters:
14239: #   symb      - in course context the symb for the seed.
14240: #   course_id - The course id of the form domain_coursenum.
14241: #   domain    - Domain for the user.
14242: #   course    - Course for the user.
14243: #   cenv      - environment of the course.
14244: #
14245: # NOTE:
14246: #   All parameters are picked out of the environment if missing
14247: #   or not defined.
14248: #   If a symb cannot be determined the current time is used instead.
14249: #
14250: #  For a given well defined symb, courside, domain, username,
14251: #  and course environment, the seed is reproducible.
14252: #
14253: sub rndseed {
14254:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14255:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14256:     if (!defined($symb)) {
14257: 	unless ($symb=$wsymb) { return time; }
14258:     }
14259:     if (!defined $courseid) { 
14260: 	$courseid=$wcourseid; 
14261:     }
14262:     if (!defined $domain) { $domain=$wdomain; }
14263:     if (!defined $username) { $username=$wusername }
14264: 
14265:     my $which;
14266:     if (defined($cenv->{'rndseed'})) {
14267: 	$which = $cenv->{'rndseed'};
14268:     } else {
14269: 	$which =&get_rand_alg($courseid);
14270:     }
14271:     if (defined(&getCODE())) {
14272: 
14273: 	if ($which eq '64bit5') {
14274: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14275: 	} elsif ($which eq '64bit4') {
14276: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14277: 	} else {
14278: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14279: 	}
14280:     } elsif ($which eq '64bit5') {
14281: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14282:     } elsif ($which eq '64bit4') {
14283: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14284:     } elsif ($which eq '64bit3') {
14285: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14286:     } elsif ($which eq '64bit2') {
14287: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14288:     } elsif ($which eq '64bit') {
14289: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14290:     }
14291:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14292: }
14293: 
14294: sub rndseed_32bit {
14295:     my ($symb,$courseid,$domain,$username)=@_;
14296:     {
14297: 	use integer;
14298: 	my $symbchck=unpack("%32C*",$symb) << 27;
14299: 	my $symbseed=numval($symb) << 22;
14300: 	my $namechck=unpack("%32C*",$username) << 17;
14301: 	my $nameseed=numval($username) << 12;
14302: 	my $domainseed=unpack("%32C*",$domain) << 7;
14303: 	my $courseseed=unpack("%32C*",$courseid);
14304: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14305: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14306: 	#&logthis("rndseed :$num:$symb");
14307: 	if ($_64bit) { $num=(($num<<32)>>32); }
14308: 	return $num;
14309:     }
14310: }
14311: 
14312: sub rndseed_64bit {
14313:     my ($symb,$courseid,$domain,$username)=@_;
14314:     {
14315: 	use integer;
14316: 	my $symbchck=unpack("%32S*",$symb) << 21;
14317: 	my $symbseed=numval($symb) << 10;
14318: 	my $namechck=unpack("%32S*",$username);
14319: 	
14320: 	my $nameseed=numval($username) << 21;
14321: 	my $domainseed=unpack("%32S*",$domain) << 10;
14322: 	my $courseseed=unpack("%32S*",$courseid);
14323: 	
14324: 	my $num1=$symbchck+$symbseed+$namechck;
14325: 	my $num2=$nameseed+$domainseed+$courseseed;
14326: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14327: 	#&logthis("rndseed :$num:$symb");
14328: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14329: 	return "$num1,$num2";
14330:     }
14331: }
14332: 
14333: sub rndseed_64bit2 {
14334:     my ($symb,$courseid,$domain,$username)=@_;
14335:     {
14336: 	use integer;
14337: 	# strings need to be an even # of cahracters long, it it is odd the
14338:         # last characters gets thrown away
14339: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14340: 	my $symbseed=numval($symb) << 10;
14341: 	my $namechck=unpack("%32S*",$username.' ');
14342: 	
14343: 	my $nameseed=numval($username) << 21;
14344: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14345: 	my $courseseed=unpack("%32S*",$courseid.' ');
14346: 	
14347: 	my $num1=$symbchck+$symbseed+$namechck;
14348: 	my $num2=$nameseed+$domainseed+$courseseed;
14349: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14350: 	#&logthis("rndseed :$num:$symb");
14351: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14352: 	return "$num1,$num2";
14353:     }
14354: }
14355: 
14356: sub rndseed_64bit3 {
14357:     my ($symb,$courseid,$domain,$username)=@_;
14358:     {
14359: 	use integer;
14360: 	# strings need to be an even # of cahracters long, it it is odd the
14361:         # last characters gets thrown away
14362: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14363: 	my $symbseed=numval2($symb) << 10;
14364: 	my $namechck=unpack("%32S*",$username.' ');
14365: 	
14366: 	my $nameseed=numval2($username) << 21;
14367: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14368: 	my $courseseed=unpack("%32S*",$courseid.' ');
14369: 	
14370: 	my $num1=$symbchck+$symbseed+$namechck;
14371: 	my $num2=$nameseed+$domainseed+$courseseed;
14372: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14373: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14374: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14375: 	
14376: 	return "$num1:$num2";
14377:     }
14378: }
14379: 
14380: sub rndseed_64bit4 {
14381:     my ($symb,$courseid,$domain,$username)=@_;
14382:     {
14383: 	use integer;
14384: 	# strings need to be an even # of cahracters long, it it is odd the
14385:         # last characters gets thrown away
14386: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14387: 	my $symbseed=numval3($symb) << 10;
14388: 	my $namechck=unpack("%32S*",$username.' ');
14389: 	
14390: 	my $nameseed=numval3($username) << 21;
14391: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14392: 	my $courseseed=unpack("%32S*",$courseid.' ');
14393: 	
14394: 	my $num1=$symbchck+$symbseed+$namechck;
14395: 	my $num2=$nameseed+$domainseed+$courseseed;
14396: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14397: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14398: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14399: 	
14400: 	return "$num1:$num2";
14401:     }
14402: }
14403: 
14404: sub rndseed_64bit5 {
14405:     my ($symb,$courseid,$domain,$username)=@_;
14406:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14407:     return "$num1:$num2";
14408: }
14409: 
14410: sub rndseed_CODE_64bit {
14411:     my ($symb,$courseid,$domain,$username)=@_;
14412:     {
14413: 	use integer;
14414: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14415: 	my $symbseed=numval2($symb);
14416: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14417: 	my $CODEseed=numval(&getCODE());
14418: 	my $courseseed=unpack("%32S*",$courseid.' ');
14419: 	my $num1=$symbseed+$CODEchck;
14420: 	my $num2=$CODEseed+$courseseed+$symbchck;
14421: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14422: 	#&logthis("rndseed :$num1:$num2:$symb");
14423: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14424: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14425: 	return "$num1:$num2";
14426:     }
14427: }
14428: 
14429: sub rndseed_CODE_64bit4 {
14430:     my ($symb,$courseid,$domain,$username)=@_;
14431:     {
14432: 	use integer;
14433: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14434: 	my $symbseed=numval3($symb);
14435: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14436: 	my $CODEseed=numval3(&getCODE());
14437: 	my $courseseed=unpack("%32S*",$courseid.' ');
14438: 	my $num1=$symbseed+$CODEchck;
14439: 	my $num2=$CODEseed+$courseseed+$symbchck;
14440: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14441: 	#&logthis("rndseed :$num1:$num2:$symb");
14442: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14443: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14444: 	return "$num1:$num2";
14445:     }
14446: }
14447: 
14448: sub rndseed_CODE_64bit5 {
14449:     my ($symb,$courseid,$domain,$username)=@_;
14450:     my $code = &getCODE();
14451:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14452:     return "$num1:$num2";
14453: }
14454: 
14455: sub setup_random_from_rndseed {
14456:     my ($rndseed)=@_;
14457:     if ($rndseed =~/([,:])/) {
14458:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14459:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14460:             &Math::Random::random_set_seed_from_phrase($rndseed);
14461:         } else {
14462:             &Math::Random::random_set_seed($num1,$num2);
14463:         }
14464:     } else {
14465: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14466:     }
14467: }
14468: 
14469: sub latest_receipt_algorithm_id {
14470:     return 'receipt3';
14471: }
14472: 
14473: sub recunique {
14474:     my $fucourseid=shift;
14475:     my $unique;
14476:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14477: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14478: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14479:     } else {
14480: 	$unique=$perlvar{'lonReceipt'};
14481:     }
14482:     return unpack("%32C*",$unique);
14483: }
14484: 
14485: sub recprefix {
14486:     my $fucourseid=shift;
14487:     my $prefix;
14488:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14489: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14490: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14491:     } else {
14492: 	$prefix=$perlvar{'lonHostID'};
14493:     }
14494:     return unpack("%32C*",$prefix);
14495: }
14496: 
14497: sub ireceipt {
14498:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14499: 
14500:     my $return =&recprefix($fucourseid).'-';
14501: 
14502:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14503: 	$env{'request.state'} eq 'construct') {
14504: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14505: 	return $return;
14506:     }
14507: 
14508:     my $cuname=unpack("%32C*",$funame);
14509:     my $cudom=unpack("%32C*",$fudom);
14510:     my $cucourseid=unpack("%32C*",$fucourseid);
14511:     my $cusymb=unpack("%32C*",$fusymb);
14512:     my $cunique=&recunique($fucourseid);
14513:     my $cpart=unpack("%32S*",$part);
14514:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14515: 
14516: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14517: 			       
14518: 	$return.= ($cunique%$cuname+
14519: 		   $cunique%$cudom+
14520: 		   $cusymb%$cuname+
14521: 		   $cusymb%$cudom+
14522: 		   $cucourseid%$cuname+
14523: 		   $cucourseid%$cudom+
14524: 		   $cpart%$cuname+
14525: 		   $cpart%$cudom);
14526:     } else {
14527: 	$return.= ($cunique%$cuname+
14528: 		   $cunique%$cudom+
14529: 		   $cusymb%$cuname+
14530: 		   $cusymb%$cudom+
14531: 		   $cucourseid%$cuname+
14532: 		   $cucourseid%$cudom);
14533:     }
14534:     return $return;
14535: }
14536: 
14537: sub receipt {
14538:     my ($part)=@_;
14539:     my ($symb,$courseid,$domain,$name) = &whichuser();
14540:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14541: }
14542: 
14543: sub whichuser {
14544:     my ($passedsymb)=@_;
14545:     my ($symb,$courseid,$domain,$name,$publicuser);
14546:     if (defined($env{'form.grade_symb'})) {
14547: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14548: 	my $allowed=&allowed('vgr',$tmp_courseid);
14549: 	if (!$allowed &&
14550: 	    exists($env{'request.course.sec'}) &&
14551: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14552: 	    $allowed=&allowed('vgr',$tmp_courseid.
14553: 			      '/'.$env{'request.course.sec'});
14554: 	}
14555: 	if ($allowed) {
14556: 	    ($symb)=&get_env_multiple('form.grade_symb');
14557: 	    $courseid=$tmp_courseid;
14558: 	    ($domain)=&get_env_multiple('form.grade_domain');
14559: 	    ($name)=&get_env_multiple('form.grade_username');
14560: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14561: 	}
14562:     }
14563:     if (!$passedsymb) {
14564: 	$symb=&symbread();
14565:     } else {
14566: 	$symb=$passedsymb;
14567:     }
14568:     $courseid=$env{'request.course.id'};
14569:     $domain=$env{'user.domain'};
14570:     $name=$env{'user.name'};
14571:     if ($name eq 'public' && $domain eq 'public') {
14572: 	if (!defined($env{'form.username'})) {
14573: 	    $env{'form.username'}.=time.rand(10000000);
14574: 	}
14575: 	$name.=$env{'form.username'};
14576:     }
14577:     return ($symb,$courseid,$domain,$name,$publicuser);
14578: 
14579: }
14580: 
14581: # ------------------------------------------------------------ Serves up a file
14582: # returns either the contents of the file or 
14583: # -1 if the file doesn't exist
14584: #
14585: # if the target is a file that was uploaded via DOCS, 
14586: # a check will be made to see if a current copy exists on the local server,
14587: # if it does this will be served, otherwise a copy will be retrieved from
14588: # the home server for the course and stored in /home/httpd/html/userfiles on
14589: # the local server.   
14590: 
14591: sub getfile {
14592:     my ($file) = @_;
14593:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14594:     &repcopy($file);
14595:     return &readfile($file);
14596: }
14597: 
14598: sub repcopy_userfile {
14599:     my ($file)=@_;
14600:     my $londocroot = $perlvar{'lonDocRoot'};
14601:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14602:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14603:     my ($cdom,$cnum,$filename) = 
14604: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14605:     my $uri="/uploaded/$cdom/$cnum/$filename";
14606:     if (-e "$file") {
14607: # we already have a local copy, check it out
14608: 	my @fileinfo = stat($file);
14609: 	my $rtncode;
14610: 	my $info;
14611: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14612: 	if ($lwpresp ne 'ok') {
14613: # there is no such file anymore, even though we had a local copy
14614: 	    if ($rtncode eq '404') {
14615: 		unlink($file);
14616: 	    }
14617: 	    return -1;
14618: 	}
14619: 	if ($info < $fileinfo[9]) {
14620: # nice, the file we have is up-to-date, just say okay
14621: 	    return 'ok';
14622: 	} else {
14623: # the file is outdated, get rid of it
14624: 	    unlink($file);
14625: 	}
14626:     }
14627: # one way or the other, at this point, we don't have the file
14628: # construct the correct path for the file
14629:     my @parts = ($cdom,$cnum); 
14630:     if ($filename =~ m|^(.+)/[^/]+$|) {
14631: 	push @parts, split(/\//,$1);
14632:     }
14633:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14634:     foreach my $part (@parts) {
14635: 	$path .= '/'.$part;
14636: 	if (!-e $path) {
14637: 	    mkdir($path,0770);
14638: 	}
14639:     }
14640: # now the path exists for sure
14641: # get a user agent
14642:     my $transferfile=$file.'.in.transfer';
14643: # FIXME: this should flock
14644:     if (-e $transferfile) { return 'ok'; }
14645:     my $request;
14646:     $uri=~s/^\///;
14647:     my $homeserver = &homeserver($cnum,$cdom);
14648:     my $hostname = &hostname($homeserver);
14649:     my $protocol = $protocol{$homeserver};
14650:     $protocol = 'http' if ($protocol ne 'https');
14651:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14652:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14653: # did it work?
14654:     if ($response->is_error()) {
14655: 	unlink($transferfile);
14656: 	&logthis("Userfile repcopy failed for $uri");
14657: 	return -1;
14658:     }
14659: # worked, rename the transfer file
14660:     rename($transferfile,$file);
14661:     return 'ok';
14662: }
14663: 
14664: sub tokenwrapper {
14665:     my $uri=shift;
14666:     $uri=~s|^https?\://([^/]+)||;
14667:     $uri=~s|^/||;
14668:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14669:     my $token=$1;
14670:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14671:     if ($udom && $uname && $file) {
14672: 	$file=~s|(\?\.*)*$||;
14673:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14674:         my $homeserver = &homeserver($uname,$udom);
14675:         my $hostname = &hostname($homeserver);
14676:         my $protocol = $protocol{$homeserver};
14677:         $protocol = 'http' if ($protocol ne 'https');
14678:         return $protocol.'://'.$hostname.'/'.$uri.
14679:                (($uri=~/\?/)?'&':'?').'token='.$token.
14680:                                '&tokenissued='.$perlvar{'lonHostID'};
14681:     } else {
14682:         return '/adm/notfound.html';
14683:     }
14684: }
14685: 
14686: # call with reqtype HEAD: get last modification time
14687: # call with reqtype GET: get the file contents
14688: # Do not call this with reqtype GET for large files! It loads everything into memory
14689: #
14690: sub getuploaded {
14691:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14692:     $uri=~s/^\///;
14693:     my $homeserver = &homeserver($cnum,$cdom);
14694:     my $hostname = &hostname($homeserver);
14695:     my $protocol = $protocol{$homeserver};
14696:     $protocol = 'http' if ($protocol ne 'https');
14697:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14698:     my $request=new HTTP::Request($reqtype,$uri);
14699:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14700:     $$rtncode = $response->code;
14701:     if (! $response->is_success()) {
14702: 	return 'failed';
14703:     }      
14704:     if ($reqtype eq 'HEAD') {
14705: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14706:     } elsif ($reqtype eq 'GET') {
14707: 	$$info = $response->content;
14708:     }
14709:     return 'ok';
14710: }
14711: 
14712: sub readfile {
14713:     my $file = shift;
14714:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14715:     my $fh;
14716:     open($fh,"<",$file);
14717:     my $a='';
14718:     while (my $line = <$fh>) { $a .= $line; }
14719:     return $a;
14720: }
14721: 
14722: sub filelocation {
14723:     my ($dir,$file) = @_;
14724:     my $location;
14725:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14726: 
14727:     if ($file =~ m-^/adm/-) {
14728: 	$file=~s-^/adm/wrapper/-/-;
14729: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14730:     }
14731: 
14732:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14733:         $location = $file;
14734:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14735:         my ($udom,$uname,$filename)=
14736:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14737:         my $home=&homeserver($uname,$udom);
14738:         my $is_me=0;
14739:         my @ids=&current_machine_ids();
14740:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14741:         if ($is_me) {
14742:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14743:         } else {
14744:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14745:   	      $udom.'/'.$uname.'/'.$filename;
14746:         }
14747:     } elsif ($file =~ m-^/adm/-) {
14748: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14749:     } else {
14750:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14751:         $file=~s:^/(res|priv)/:/:;
14752:         my $space=$1;
14753:         if ( !( $file =~ m:^/:) ) {
14754:             $location = $dir. '/'.$file;
14755:         } else {
14756:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14757:         }
14758:     }
14759:     $location=~s://+:/:g; # remove duplicate /
14760:     while ($location=~m{/\.\./}) {
14761: 	if ($location =~ m{/[^/]+/\.\./}) {
14762: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14763: 	} else {
14764: 	    $location=~ s{/\.\./}{/}g;
14765: 	}
14766:     } #remove dir/..
14767:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14768:     return $location;
14769: }
14770: 
14771: sub hreflocation {
14772:     my ($dir,$file)=@_;
14773:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14774: 	$file=filelocation($dir,$file);
14775:     } elsif ($file=~m-^/adm/-) {
14776: 	$file=~s-^/adm/wrapper/-/-;
14777: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14778:     }
14779:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14780: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14781:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14782: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14783: 	        {/uploaded/$1/$2/}x;
14784:     }
14785:     if ($file=~ m{^/userfiles/}) {
14786: 	$file =~ s{^/userfiles/}{/uploaded/};
14787:     }
14788:     return $file;
14789: }
14790: 
14791: 
14792: 
14793: 
14794: 
14795: sub current_machine_domains {
14796:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14797: }
14798: 
14799: sub machine_domains {
14800:     my ($hostname) = @_;
14801:     my @domains;
14802:     my %hostname = &all_hostnames();
14803:     while( my($id, $name) = each(%hostname)) {
14804: #	&logthis("-$id-$name-$hostname-");
14805: 	if ($hostname eq $name) {
14806: 	    push(@domains,&host_domain($id));
14807: 	}
14808:     }
14809:     return @domains;
14810: }
14811: 
14812: sub current_machine_ids {
14813:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14814: }
14815: 
14816: sub machine_ids {
14817:     my ($hostname) = @_;
14818:     $hostname ||= &hostname($perlvar{'lonHostID'});
14819:     my @ids;
14820:     my %name_to_host = &all_names();
14821:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14822: 	return @{ $name_to_host{$hostname} };
14823:     }
14824:     return;
14825: }
14826: 
14827: sub additional_machine_domains {
14828:     my @domains;
14829:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14830:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14831:             while (my $line = <$fh>) {
14832:                 chomp($line);           
14833:                 $line =~ s/\s//g;
14834:                 push(@domains,$line);
14835:             }
14836:             close($fh);
14837:         }
14838:     }
14839:     return @domains;
14840: }
14841: 
14842: sub default_login_domain {
14843:     my $domain = $perlvar{'lonDefDomain'};
14844:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14845:     foreach my $posdom (&current_machine_domains(),
14846:                         &additional_machine_domains()) {
14847:         if (lc($posdom) eq lc($testdomain)) {
14848:             $domain=$posdom;
14849:             last;
14850:         }
14851:     }
14852:     return $domain;
14853: }
14854: 
14855: sub shared_institution {
14856:     my ($dom,$lonhost) = @_;
14857:     if ($lonhost eq '') {
14858:         $lonhost = $perlvar{'lonHostID'};
14859:     }
14860:     my $same_intdom;
14861:     my $hostintdom = &internet_dom($lonhost);
14862:     if ($hostintdom ne '') {
14863:         my %iphost = &get_iphost();
14864:         my $primary_id = &domain($dom,'primary');
14865:         my $primary_ip = &get_host_ip($primary_id);
14866:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14867:             foreach my $id (@{$iphost{$primary_ip}}) {
14868:                 my $intdom = &internet_dom($id);
14869:                 if ($intdom eq $hostintdom) {
14870:                     $same_intdom = 1;
14871:                     last;
14872:                 }
14873:             }
14874:         }
14875:     }
14876:     return $same_intdom;
14877: }
14878: 
14879: sub uses_sts {
14880:     my ($ignore_cache) = @_;
14881:     my $lonhost = $perlvar{'lonHostID'};
14882:     my $hostname = &hostname($lonhost);
14883:     my $sts_on;
14884:     if ($protocol{$lonhost} eq 'https') {
14885:         my $cachetime = 12*3600;
14886:         if (!$ignore_cache) {
14887:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14888:             if (defined($cached)) {
14889:                 return $sts_on;
14890:             }
14891:         }
14892:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14893:         my $request=new HTTP::Request('HEAD',$url);
14894:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14895:         if ($response->is_success) {
14896:             my $has_sts = $response->header('Strict-Transport-Security');
14897:             if ($has_sts eq '') {
14898:                 $sts_on = 0;
14899:             } else {
14900:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14901:                     my $maxage = $1;
14902:                     if ($maxage) {
14903:                         $sts_on = 1;
14904:                     } else {
14905:                         $sts_on = 0;
14906:                     }
14907:                 } else {
14908:                     $sts_on = 0;
14909:                 }
14910:             }
14911:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14912:         }
14913:     }
14914:     return;
14915: }
14916: 
14917: sub waf_allssl {
14918:     my ($host_name) = @_;
14919:     my $alias = &get_proxy_alias();
14920:     if ($host_name eq '') {
14921:         $host_name = $ENV{'SERVER_NAME'};
14922:     }
14923:     if (($host_name ne '') && ($alias eq $host_name)) {
14924:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14925:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14926:         if ($defdomdefaults{'waf_sslopt'}) {
14927:             return $defdomdefaults{'waf_sslopt'};
14928:         }
14929:     }
14930:     return;
14931: }
14932: 
14933: sub get_requestor_ip {
14934:     my ($r,$nolookup,$noproxy) = @_;
14935:     my $from_ip;
14936:     if (ref($r)) {
14937:         if ($r->can('useragent_ip')) {
14938:             if ($noproxy && $r->can('client_ip')) {
14939:                 $from_ip = $r->client_ip();
14940:             } else {
14941:                 $from_ip = $r->useragent_ip();
14942:             }
14943:         } elsif ($r->connection->can('remote_ip')) {
14944:             $from_ip = $r->connection->remote_ip();
14945:         } else {
14946:             $from_ip = $r->get_remote_host($nolookup);
14947:         }
14948:     } else {
14949:         $from_ip = $ENV{'REMOTE_ADDR'};
14950:     }
14951:     return $from_ip if ($noproxy); 
14952:     # Who controls proxy settings for server
14953:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14954:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14955:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14956:         if ($proxyinfo->{'vpnint'}) {
14957:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14958:                 return $from_ip;
14959:             }
14960:         }
14961:         if ($proxyinfo->{'trusted'}) {
14962:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14963:                 my $ipheader = $proxyinfo->{'ipheader'};
14964:                 my ($ip,$xfor);
14965:                 if (ref($r)) {
14966:                     if ($ipheader) {
14967:                         $ip = $r->headers_in->{$ipheader};
14968:                     }
14969:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14970:                 } else {
14971:                     if ($ipheader) {
14972:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14973:                     }
14974:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14975:                 }
14976:                 if (($ip eq '') && ($xfor ne '')) {
14977:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14978:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14979:                             $ip = $poss_ip;
14980:                             last;
14981:                         }
14982:                     }
14983:                 }
14984:                 if ($ip ne '') {
14985:                     return $ip;
14986:                 }
14987:             }
14988:         }
14989:     }
14990:     return $from_ip;
14991: }
14992: 
14993: sub get_proxy_settings {
14994:     my ($dom_in_use) = @_;
14995:     my %domdefaults = &get_domain_defaults($dom_in_use);
14996:     my $proxyinfo = {
14997:                        ipheader => $domdefaults{'waf_ipheader'},
14998:                        trusted  => $domdefaults{'waf_trusted'},
14999:                        vpnint   => $domdefaults{'waf_vpnint'},
15000:                        vpnext   => $domdefaults{'waf_vpnext'},
15001:                        sslopt   => $domdefaults{'waf_sslopt'},
15002:                     };
15003:     return $proxyinfo;
15004: }
15005: 
15006: sub ip_match {
15007:     my ($ip,$pattern_str) = @_;
15008:     $ip=Net::CIDR::cidrvalidate($ip);
15009:     if ($ip) {
15010:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15011:     }
15012:     return;
15013: }
15014: 
15015: sub get_proxy_alias {
15016:     my ($lonid) = @_;
15017:     if ($lonid eq '') {
15018:         $lonid = $perlvar{'lonHostID'};
15019:     }
15020:     if (!defined(&hostname($lonid))) {
15021:         return;
15022:     }
15023:     if ($lonid ne '') {
15024:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15025:         if ($cached) {
15026:             return $alias;
15027:         }
15028:         my $dom = &host_domain($lonid);
15029:         if ($dom ne '') {
15030:             my $cachetime = 60*60*24;
15031:             my %domconfig =
15032:                 &get_dom('configuration',['wafproxy'],$dom);
15033:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15034:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15035:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15036:                 }
15037:             }
15038:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15039:         }
15040:     }
15041:     return;
15042: }
15043: 
15044: sub use_proxy_alias {
15045:     my ($r,$lonid) = @_;
15046:     my $alias = &get_proxy_alias($lonid);
15047:     if ($alias) {
15048:         my $dom = &host_domain($lonid);
15049:         if ($dom ne '') {
15050:             my $proxyinfo = &get_proxy_settings($dom);
15051:             my ($vpnint,$remote_ip);
15052:             if (ref($proxyinfo) eq 'HASH') {
15053:                 $vpnint = $proxyinfo->{'vpnint'};
15054:                 if ($vpnint) {
15055:                     $remote_ip = &get_requestor_ip($r,1,1);
15056:                 }
15057:             }
15058:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15059:                 return $alias;
15060:             }
15061:         }
15062:     }
15063:     return;
15064: }
15065: 
15066: sub alias_sso {
15067:     my ($lonid) = @_;
15068:     if ($lonid eq '') {
15069:         $lonid = $perlvar{'lonHostID'};
15070:     }
15071:     if (!defined(&hostname($lonid))) {
15072:         return;
15073:     }
15074:     if ($lonid ne '') {
15075:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15076:         if ($cached) {
15077:             return $use_alias;
15078:         }
15079:         my $dom = &host_domain($lonid);
15080:         if ($dom ne '') {
15081:             my $cachetime = 60*60*24;
15082:             my %domconfig =
15083:                 &get_dom('configuration',['wafproxy'],$dom);
15084:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15085:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15086:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15087:                 }
15088:             }
15089:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15090:         }
15091:     }
15092:     return;
15093: }
15094: 
15095: sub get_saml_landing {
15096:     my ($lonid) = @_;
15097:     if ($lonid eq '') {
15098:         my $defdom = &default_login_domain();
15099:         my @hosts = &current_machine_ids();
15100:         if (@hosts > 1) {
15101:             foreach my $hostid (@hosts) {
15102:                 if (&host_domain($hostid) eq $defdom) {
15103:                     $lonid = $hostid;
15104:                     last;
15105:                 }
15106:             }
15107:         } else {
15108:             $lonid = $perlvar{'lonHostID'};
15109:         }
15110:         if ($lonid) {
15111:             unless (&host_domain($lonid) eq $defdom) {
15112:                 return;
15113:             }
15114:         } else {
15115:             return;
15116:         }
15117:     } elsif (!defined(&hostname($lonid))) {
15118:         return;
15119:     }
15120:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15121:     if ($cached) {
15122:         return $landing;
15123:     }
15124:     my $dom = &host_domain($lonid);
15125:     if ($dom ne '') {
15126:         my $cachetime = 60*60*24;
15127:         my %domconfig =
15128:             &get_dom('configuration',['login'],$dom);
15129:         if (ref($domconfig{'login'}) eq 'HASH') {
15130:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15131:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15132:                     $landing = 1;
15133:                 }
15134:             }
15135:         }
15136:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15137:     }
15138:     return;
15139: }
15140: 
15141: # ------------------------------------------------------------- Declutters URLs
15142: 
15143: sub declutter {
15144:     my $thisfn=shift;
15145:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15146:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15147:         $thisfn=~s{^/home/httpd/html}{};
15148:     }
15149:     $thisfn=~s/^\///;
15150:     $thisfn=~s|^adm/wrapper/||;
15151:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15152:     $thisfn=~s/^res\///;
15153:     $thisfn=~s/^priv\///;
15154:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15155:         $thisfn=~s/\?.+$//;
15156:     }
15157:     return $thisfn;
15158: }
15159: 
15160: # ------------------------------------------------------------- Clutter up URLs
15161: 
15162: sub clutter {
15163:     my $thisfn='/'.&declutter(shift);
15164:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15165: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15166:        $thisfn='/res'.$thisfn; 
15167:     }
15168:     if ($thisfn !~m|^/adm|) {
15169: 	if ($thisfn =~ m|^/ext/|) {
15170: 	    $thisfn='/adm/wrapper'.$thisfn;
15171: 	} else {
15172: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15173: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15174: 	    if ($embstyle eq 'ssi'
15175: 		|| ($embstyle eq 'hdn')
15176: 		|| ($embstyle eq 'rat')
15177: 		|| ($embstyle eq 'prv')
15178: 		|| ($embstyle eq 'ign')) {
15179: 		#do nothing with these
15180: 	    } elsif (($embstyle eq 'img') 
15181: 		|| ($embstyle eq 'emb')
15182: 		|| ($embstyle eq 'wrp')) {
15183: 		$thisfn='/adm/wrapper'.$thisfn;
15184: 	    } elsif ($embstyle eq 'unk'
15185: 		     && $thisfn!~/\.(sequence|page)$/) {
15186: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15187: 	    } else {
15188: #		&logthis("Got a blank emb style");
15189: 	    }
15190: 	}
15191:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15192:         $thisfn='/adm/wrapper'.$thisfn;
15193:     }
15194:     return $thisfn;
15195: }
15196: 
15197: sub clutter_with_no_wrapper {
15198:     my $uri = &clutter(shift);
15199:     if ($uri =~ m-^/adm/-) {
15200: 	$uri =~ s-^/adm/wrapper/-/-;
15201: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15202:     }
15203:     return $uri;
15204: }
15205: 
15206: sub freeze_escape {
15207:     my ($value)=@_;
15208:     if (ref($value)) {
15209: 	$value=&nfreeze($value);
15210: 	return '__FROZEN__'.&escape($value);
15211:     }
15212:     return &escape($value);
15213: }
15214: 
15215: 
15216: sub thaw_unescape {
15217:     my ($value)=@_;
15218:     if ($value =~ /^__FROZEN__/) {
15219: 	substr($value,0,10,undef);
15220: 	$value=&unescape($value);
15221: 	return &thaw($value);
15222:     }
15223:     return &unescape($value);
15224: }
15225: 
15226: sub correct_line_ends {
15227:     my ($result)=@_;
15228:     $$result =~s/\r\n/\n/mg;
15229:     $$result =~s/\r/\n/mg;
15230: }
15231: # ================================================================ Main Program
15232: 
15233: sub goodbye {
15234:    &logthis("Starting Shut down");
15235: #not converted to using infrastruture and probably shouldn't be
15236:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15237: #converted
15238: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15239:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15240: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15241: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15242: #1.1 only
15243: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15244: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15245: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15246: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15247:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15248:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15249:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15250:    &flushcourselogs();
15251:    &logthis("Shutting down");
15252: }
15253: 
15254: sub get_dns {
15255:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15256:     if (!$ignore_cache) {
15257: 	my ($content,$cached)=
15258: 	    &is_cached_new('dns',$url);
15259: 	if ($cached) {
15260: 	    &$func($content,$hashref);
15261: 	    return;
15262: 	}
15263:     }
15264: 
15265:     my %alldns;
15266:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15267:         foreach my $dns (<$config>) {
15268: 	    next if ($dns !~ /^\^(\S*)/x);
15269:             my $line = $1;
15270:             my ($host,$protocol) = split(/:/,$line);
15271:             if ($protocol ne 'https') {
15272:                 $protocol = 'http';
15273:             }
15274: 	    $alldns{$host} = $protocol;
15275:         }
15276:         close($config);
15277:     }
15278:     while (%alldns) {
15279: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15280:         my ($contents,@content);
15281:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15282:             my $command = (split('/',$url))[3];
15283:             my ($dir,$file) = &parse_getdns_url($command,$url);
15284:             delete($alldns{$dns});
15285:             next if (($dir eq '') || ($file eq ''));
15286:             if (open(my $config,'<',"$dir/$file")) {
15287:                 @content = <$config>;
15288:                 close($config);
15289:             }
15290:             if ($url eq '/adm/dns/loncapaCRL') {
15291:                 $contents = join('',@content);
15292:             }
15293:         } else {
15294: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15295:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15296:             delete($alldns{$dns});
15297: 	    next if ($response->is_error());
15298:             if ($url eq '/adm/dns/loncapaCRL') {
15299:                 $contents = $response->content;
15300:             } else {
15301:                 @content = split("\n",$response->content);
15302:             }
15303:         }
15304:         if ($url eq '/adm/dns/loncapaCRL') {
15305:             return &$func($contents);
15306:         } else {
15307: 	    unless ($nocache) {
15308: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15309: 	    }
15310: 	    &$func(\@content,$hashref);
15311:             return;
15312:         }
15313:     }
15314:     my $which = (split('/',$url,4))[3];
15315:     if ($which eq 'loncapaCRL') {
15316:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15317:         if (-e $diskfile) {
15318:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15319:         } else {
15320:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15321:         }
15322:     } else {
15323:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15324:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15325:             my @content = <$config>;
15326:             close($config);
15327:             &$func(\@content,$hashref);
15328:         }
15329:     }
15330:     return;
15331: }
15332: 
15333: # ------------------------------------------------------Get DNS checksums file
15334: sub parse_dns_checksums_tab {
15335:     my ($lines,$hashref) = @_;
15336:     my $lonhost = $perlvar{'lonHostID'};
15337:     my $machine_dom = &host_domain($lonhost);
15338:     my $loncaparev = &get_server_loncaparev($machine_dom);
15339:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15340:     my $webconfdir = '/etc/httpd/conf';
15341:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15342:         $webconfdir = '/etc/apache2';
15343:     } elsif ($distro =~ /^sles(\d+)$/) {
15344:         if ($1 >= 10) {
15345:             $webconfdir = '/etc/apache2';
15346:         }
15347:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15348:         if ($1 >= 10.0) {
15349:             $webconfdir = '/etc/apache2';
15350:         }
15351:     }
15352:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15353:     my (%chksum,%revnum);
15354:     if (ref($lines) eq 'ARRAY') {
15355:         chomp(@{$lines});
15356:         my $version = shift(@{$lines});
15357:         if ($version eq $release) {  
15358:             foreach my $line (@{$lines}) {
15359:                 my ($file,$version,$shasum) = split(/,/,$line);
15360:                 if ($file =~ m{^/etc/httpd/conf}) {
15361:                     if ($webconfdir eq '/etc/apache2') {
15362:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15363:                     }
15364:                 }
15365:                 $chksum{$file} = $shasum;
15366:                 $revnum{$file} = $version;
15367:             }
15368:             if (ref($hashref) eq 'HASH') {
15369:                 %{$hashref} = (
15370:                                 sums     => \%chksum,
15371:                                 versions => \%revnum,
15372:                               );
15373:             }
15374:         }
15375:     }
15376:     return;
15377: }
15378: 
15379: sub fetch_dns_checksums {
15380:     my %checksums;
15381:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15382:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15383:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15384:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15385:              \%checksums);
15386:     return \%checksums;
15387: }
15388: 
15389: sub fetch_crl_pemfile {
15390:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15391: }
15392: 
15393: sub save_crl_pem {
15394:     my ($content) = @_;
15395:     my ($msg,$hadchanges);
15396:     if ($content ne '') {
15397:         my $now = time;
15398:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15399:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15400:         if (open(my $fh,'>',"$tmpcrl")) {
15401:             print $fh $content;
15402:             close($fh);
15403:             if (-e $lonca) {
15404:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15405:                     my $check = <PIPE>;
15406:                     close(PIPE);
15407:                     chomp($check);
15408:                     if ($check eq 'verify OK') {
15409:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15410:                         my $backup;
15411:                         if (-e $dest) {
15412:                             if (&File::Copy::move($dest,"$dest.bak")) {
15413:                                 $backup = 'ok';
15414:                             }
15415:                         }
15416:                         if (&File::Copy::move($tmpcrl,$dest)) {
15417:                             $msg = 'ok';
15418:                             if ($backup) {
15419:                                 my (%oldnums,%newnums);
15420:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15421:                                     while (<PIPE>) {
15422:                                         $oldnums{(split(/:/))[1]} = 1;
15423:                                     }
15424:                                     close(PIPE);
15425:                                 }
15426:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15427:                                     while(<PIPE>) {
15428:                                         $newnums{(split(/:/))[1]} = 1;
15429:                                     }
15430:                                     close(PIPE);
15431:                                 }
15432:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15433:                                     unless (exists($oldnums{$key})) {
15434:                                         $hadchanges = 1;
15435:                                         last;
15436:                                     }
15437:                                 }
15438:                                 unless ($hadchanges) {
15439:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15440:                                         unless (exists($newnums{$key})) {
15441:                                             $hadchanges = 1;
15442:                                             last;
15443:                                         }
15444:                                     }
15445:                                 }
15446:                             }
15447:                         }
15448:                     } else {
15449:                         unlink($tmpcrl);
15450:                     }
15451:                 } else {
15452:                     unlink($tmpcrl);
15453:                 }
15454:             } else {
15455:                 unlink($tmpcrl);
15456:             }
15457:         }
15458:     }
15459:     return ($msg,$hadchanges);
15460: }
15461: 
15462: sub parse_getdns_url {
15463:     my ($command,$url) = @_;
15464:     my $dir = $perlvar{'lonTabDir'};
15465:     my $file;
15466:     if ($command eq 'hosts') {
15467:         $file = 'dns_hosts.tab';
15468:     } elsif ($command eq 'domain') {
15469:         $file = 'dns_domain.tab';
15470:     } elsif ($command eq 'checksums') {
15471:         my $version = (split('/',$url))[4];
15472:         $file = "dns_checksums/$version.tab",
15473:     } elsif ($command eq 'loncapaCRL') {
15474:         $dir = $perlvar{'lonCertificateDirectory'};
15475:         $file = $perlvar{'lonnetCertRevocationList'};
15476:     }
15477:     return ($dir,$file);
15478: }
15479: 
15480: # ------------------------------------------------------------ Read domain file
15481: {
15482:     my $loaded;
15483:     my %domain;
15484: 
15485:     sub parse_domain_tab {
15486: 	my ($lines) = @_;
15487: 	foreach my $line (@$lines) {
15488: 	    next if ($line =~ /^(\#|\s*$ )/x);
15489: 
15490: 	    chomp($line);
15491: 	    my ($name,@elements) = split(/:/,$line,9);
15492: 	    my %this_domain;
15493: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15494: 			       'lang_def', 'city', 'longi', 'lati',
15495: 			       'primary') {
15496: 		$this_domain{$field} = shift(@elements);
15497: 	    }
15498: 	    $domain{$name} = \%this_domain;
15499: 	}
15500:     }
15501: 
15502:     sub reset_domain_info {
15503: 	undef($loaded);
15504: 	undef(%domain);
15505:     }
15506: 
15507:     sub load_domain_tab {
15508: 	my ($ignore_cache,$nocache) = @_;
15509: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15510: 	my $fh;
15511: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15512: 	    my @lines = <$fh>;
15513: 	    &parse_domain_tab(\@lines);
15514: 	}
15515: 	close($fh);
15516: 	$loaded = 1;
15517:     }
15518: 
15519:     sub domain {
15520: 	&load_domain_tab() if (!$loaded);
15521: 
15522: 	my ($name,$what) = @_;
15523: 	return if ( !exists($domain{$name}) );
15524: 
15525: 	if (!$what) {
15526: 	    return $domain{$name}{'description'};
15527: 	}
15528: 	return $domain{$name}{$what};
15529:     }
15530: 
15531:     sub domain_info {
15532:         &load_domain_tab() if (!$loaded);
15533:         return %domain;
15534:     }
15535: 
15536: }
15537: 
15538: 
15539: # ------------------------------------------------------------- Read hosts file
15540: {
15541:     my %hostname;
15542:     my %hostdom;
15543:     my %libserv;
15544:     my $loaded;
15545:     my %name_to_host;
15546:     my %internetdom;
15547:     my %LC_dns_serv;
15548: 
15549:     sub parse_hosts_tab {
15550: 	my ($file) = @_;
15551: 	foreach my $configline (@$file) {
15552: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15553:             chomp($configline);
15554: 	    if ($configline =~ /^\^/) {
15555:                 if ($configline =~ /^\^([\w.\-]+)/) {
15556:                     $LC_dns_serv{$1} = 1;
15557:                 }
15558:                 next;
15559:             }
15560: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15561: 	    $name=~s/\s//g;
15562: 	    if ($id && $domain && $role && $name) {
15563:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15564:                     my $curr = $hostname{$id};
15565:                     my $skip;
15566:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15567:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15568:                             $skip = 1;
15569:                         } else {
15570:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15571:                         }
15572:                     }
15573:                     unless ($skip) {
15574:                         push(@{$name_to_host{$name}},$id);
15575:                     }
15576:                 } else {
15577:                     push(@{$name_to_host{$name}},$id);
15578:                 }
15579: 		$hostname{$id}=$name;
15580: 		$hostdom{$id}=$domain;
15581: 		if ($role eq 'library') { $libserv{$id}=$name; }
15582:                 if (defined($protocol)) {
15583:                     if ($protocol eq 'https') {
15584:                         $protocol{$id} = $protocol;
15585:                     } else {
15586:                         $protocol{$id} = 'http'; 
15587:                     }
15588:                 } else {
15589:                     $protocol{$id} = 'http';
15590:                 }
15591:                 if (defined($intdom)) {
15592:                     $internetdom{$id} = $intdom;
15593:                 }
15594: 	    }
15595: 	}
15596:     }
15597:     
15598:     sub reset_hosts_info {
15599: 	&purge_remembered();
15600: 	&reset_domain_info();
15601: 	&reset_hosts_ip_info();
15602:         undef(%internetdom);
15603: 	undef(%name_to_host);
15604: 	undef(%hostname);
15605: 	undef(%hostdom);
15606: 	undef(%libserv);
15607: 	undef($loaded);
15608:     }
15609: 
15610:     sub load_hosts_tab {
15611: 	my ($ignore_cache,$nocache) = @_;
15612: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15613: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15614: 	my @config = <$config>;
15615: 	&parse_hosts_tab(\@config);
15616: 	close($config);
15617: 	$loaded=1;
15618:     }
15619: 
15620:     sub hostname {
15621: 	&load_hosts_tab() if (!$loaded);
15622: 
15623: 	my ($lonid) = @_;
15624: 	return $hostname{$lonid};
15625:     }
15626: 
15627:     sub all_hostnames {
15628: 	&load_hosts_tab() if (!$loaded);
15629: 
15630: 	return %hostname;
15631:     }
15632: 
15633:     sub all_names {
15634:         my ($ignore_cache,$nocache) = @_;
15635: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15636: 
15637: 	return %name_to_host;
15638:     }
15639: 
15640:     sub all_host_domain {
15641:         &load_hosts_tab() if (!$loaded);
15642:         return %hostdom;
15643:     }
15644: 
15645:     sub all_host_intdom {
15646:         &load_hosts_tab() if (!$loaded);
15647:         return %internetdom;
15648:     }
15649: 
15650:     sub is_library {
15651: 	&load_hosts_tab() if (!$loaded);
15652: 
15653: 	return exists($libserv{$_[0]});
15654:     }
15655: 
15656:     sub all_library {
15657: 	&load_hosts_tab() if (!$loaded);
15658: 
15659: 	return %libserv;
15660:     }
15661: 
15662:     sub unique_library {
15663: 	#2x reverse removes all hostnames that appear more than once
15664:         my %unique = reverse &all_library();
15665:         return reverse %unique;
15666:     }
15667: 
15668:     sub get_servers {
15669: 	&load_hosts_tab() if (!$loaded);
15670: 
15671: 	my ($domain,$type) = @_;
15672: 	my %possible_hosts = ($type eq 'library') ? %libserv
15673: 	                                          : %hostname;
15674: 	my %result;
15675: 	if (ref($domain) eq 'ARRAY') {
15676: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15677: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15678: 		    $result{$host} = $hostname;
15679: 		}
15680: 	    }
15681: 	} else {
15682: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15683: 		if ($hostdom{$host} eq $domain) {
15684: 		    $result{$host} = $hostname;
15685: 		}
15686: 	    }
15687: 	}
15688: 	return %result;
15689:     }
15690: 
15691:     sub get_unique_servers {
15692:         my %unique = reverse &get_servers(@_);
15693: 	return reverse %unique;
15694:     }
15695: 
15696:     sub host_domain {
15697: 	&load_hosts_tab() if (!$loaded);
15698: 
15699: 	my ($lonid) = @_;
15700: 	return $hostdom{$lonid};
15701:     }
15702: 
15703:     sub all_domains {
15704: 	&load_hosts_tab() if (!$loaded);
15705: 
15706: 	my %seen;
15707: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15708: 	return @uniq;
15709:     }
15710: 
15711:     sub internet_dom {
15712:         &load_hosts_tab() if (!$loaded);
15713: 
15714:         my ($lonid) = @_;
15715:         return $internetdom{$lonid};
15716:     }
15717: 
15718:     sub is_LC_dns {
15719:         &load_hosts_tab() if (!$loaded);
15720: 
15721:         my ($hostname) = @_;
15722:         return exists($LC_dns_serv{$hostname});
15723:     }
15724: 
15725: }
15726: 
15727: { 
15728:     my %iphost;
15729:     my %name_to_ip;
15730:     my %lonid_to_ip;
15731: 
15732:     sub get_hosts_from_ip {
15733: 	my ($ip) = @_;
15734: 	my %iphosts = &get_iphost();
15735: 	if (ref($iphosts{$ip})) {
15736: 	    return @{$iphosts{$ip}};
15737: 	}
15738: 	return;
15739:     }
15740:     
15741:     sub reset_hosts_ip_info {
15742: 	undef(%iphost);
15743: 	undef(%name_to_ip);
15744: 	undef(%lonid_to_ip);
15745:     }
15746: 
15747:     sub get_host_ip {
15748: 	my ($lonid) = @_;
15749: 	if (exists($lonid_to_ip{$lonid})) {
15750: 	    return $lonid_to_ip{$lonid};
15751: 	}
15752: 	my $name=&hostname($lonid);
15753:    	my $ip = gethostbyname($name);
15754: 	return if (!$ip || length($ip) ne 4);
15755: 	$ip=inet_ntoa($ip);
15756: 	$name_to_ip{$name}   = $ip;
15757: 	$lonid_to_ip{$lonid} = $ip;
15758: 	return $ip;
15759:     }
15760:     
15761:     sub get_iphost {
15762: 	my ($ignore_cache,$nocache) = @_;
15763: 
15764: 	if (!$ignore_cache) {
15765: 	    if (%iphost) {
15766: 		return %iphost;
15767: 	    }
15768: 	    my ($ip_info,$cached)=
15769: 		&is_cached_new('iphost','iphost');
15770: 	    if ($cached) {
15771: 		%iphost      = %{$ip_info->[0]};
15772: 		%name_to_ip  = %{$ip_info->[1]};
15773: 		%lonid_to_ip = %{$ip_info->[2]};
15774: 		return %iphost;
15775: 	    }
15776: 	}
15777: 
15778: 	# get yesterday's info for fallback
15779: 	my %old_name_to_ip;
15780: 	my ($ip_info,$cached)=
15781: 	    &is_cached_new('iphost','iphost');
15782: 	if ($cached) {
15783: 	    %old_name_to_ip = %{$ip_info->[1]};
15784: 	}
15785: 
15786: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15787: 	foreach my $name (keys(%name_to_host)) {
15788: 	    my $ip;
15789: 	    if (!exists($name_to_ip{$name})) {
15790: 		$ip = gethostbyname($name);
15791: 		if (!$ip || length($ip) ne 4) {
15792: 		    if (defined($old_name_to_ip{$name})) {
15793: 			$ip = $old_name_to_ip{$name};
15794: 			&logthis("Can't find $name defaulting to old $ip");
15795: 		    } else {
15796: 			&logthis("Name $name no IP found");
15797: 			next;
15798: 		    }
15799: 		} else {
15800: 		    $ip=inet_ntoa($ip);
15801: 		}
15802: 		$name_to_ip{$name} = $ip;
15803: 	    } else {
15804: 		$ip = $name_to_ip{$name};
15805: 	    }
15806: 	    foreach my $id (@{ $name_to_host{$name} }) {
15807: 		$lonid_to_ip{$id} = $ip;
15808: 	    }
15809: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15810: 	}
15811:         unless ($nocache) {
15812: 	    &do_cache_new('iphost','iphost',
15813: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15814: 		          48*60*60);
15815:         }
15816: 
15817: 	return %iphost;
15818:     }
15819: 
15820:     #
15821:     #  Given a DNS returns the loncapa host name for that DNS 
15822:     # 
15823:     sub host_from_dns {
15824:         my ($dns) = @_;
15825:         my @hosts;
15826:         my $ip;
15827: 
15828:         if (exists($name_to_ip{$dns})) {
15829:             $ip = $name_to_ip{$dns};
15830:         }
15831:         if (!$ip) {
15832:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15833:             if (length($ip) == 4) { 
15834: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15835:             }
15836:         }
15837:         if ($ip) {
15838: 	    @hosts = get_hosts_from_ip($ip);
15839: 	    return $hosts[0];
15840:         }
15841:         return undef;
15842:     }
15843: 
15844:     sub get_internet_names {
15845:         my ($lonid) = @_;
15846:         return if ($lonid eq '');
15847:         my ($idnref,$cached)=
15848:             &is_cached_new('internetnames',$lonid);
15849:         if ($cached) {
15850:             return $idnref;
15851:         }
15852:         my $ip = &get_host_ip($lonid);
15853:         my @hosts = &get_hosts_from_ip($ip);
15854:         my %iphost = &get_iphost();
15855:         my (@idns,%seen);
15856:         foreach my $id (@hosts) {
15857:             my $dom = &host_domain($id);
15858:             my $prim_id = &domain($dom,'primary');
15859:             my $prim_ip = &get_host_ip($prim_id);
15860:             next if ($seen{$prim_ip});
15861:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15862:                 foreach my $id (@{$iphost{$prim_ip}}) {
15863:                     my $intdom = &internet_dom($id);
15864:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15865:                         push(@idns,$intdom);
15866:                     }
15867:                 }
15868:             }
15869:             $seen{$prim_ip} = 1;
15870:         }
15871:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15872:     }
15873: 
15874: }
15875: 
15876: sub all_loncaparevs {
15877:     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);
15878: }
15879: 
15880: # ---------------------------------------------------------- Read loncaparev table
15881: {
15882:     sub load_loncaparevs { 
15883:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15884:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15885:                 while (my $configline=<$config>) {
15886:                     chomp($configline);
15887:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15888:                     $loncaparevs{$hostid}=$loncaparev;
15889:                 }
15890:                 close($config);
15891:             }
15892:         }
15893:     }
15894: }
15895: 
15896: # ---------------------------------------------------------- Read serverhostID table
15897: {
15898:     sub load_serverhomeIDs {
15899:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15900:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15901:                 while (my $configline=<$config>) {
15902:                     chomp($configline);
15903:                     my ($name,$id)=split(/:/,$configline);
15904:                     $serverhomeIDs{$name}=$id;
15905:                 }
15906:                 close($config);
15907:             }
15908:         }
15909:     }
15910: }
15911: 
15912: 
15913: BEGIN {
15914: 
15915: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15916:     unless ($readit) {
15917: {
15918:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15919:     %perlvar = (%perlvar,%{$configvars});
15920: }
15921: 
15922: 
15923: # ------------------------------------------------------ Read spare server file
15924: {
15925:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15926: 
15927:     while (my $configline=<$config>) {
15928:        chomp($configline);
15929:        if ($configline) {
15930: 	   my ($host,$type) = split(':',$configline,2);
15931: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15932: 	   push(@{ $spareid{$type} }, $host);
15933:        }
15934:     }
15935:     close($config);
15936: }
15937: # ------------------------------------------------------------ Read permissions
15938: {
15939:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15940: 
15941:     while (my $configline=<$config>) {
15942: 	chomp($configline);
15943: 	if ($configline) {
15944: 	    my ($role,$perm)=split(/ /,$configline);
15945: 	    if ($perm ne '') { $pr{$role}=$perm; }
15946: 	}
15947:     }
15948:     close($config);
15949: }
15950: 
15951: # -------------------------------------------- Read plain texts for permissions
15952: {
15953:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15954: 
15955:     while (my $configline=<$config>) {
15956: 	chomp($configline);
15957: 	if ($configline) {
15958: 	    my ($short,@plain)=split(/:/,$configline);
15959:             %{$prp{$short}} = ();
15960: 	    if (@plain > 0) {
15961:                 $prp{$short}{'std'} = $plain[0];
15962:                 for (my $i=1; $i<@plain; $i++) {
15963:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15964:                 }
15965:             }
15966: 	}
15967:     }
15968:     close($config);
15969: }
15970: 
15971: # ---------------------------------------------------------- Read package table
15972: {
15973:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15974: 
15975:     while (my $configline=<$config>) {
15976: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15977: 	chomp($configline);
15978: 	my ($short,$plain)=split(/:/,$configline);
15979: 	my ($pack,$name)=split(/\&/,$short);
15980: 	if ($plain ne '') {
15981: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15982: 	    $packagetab{$short}=$plain; 
15983: 	}
15984:     }
15985:     close($config);
15986: }
15987: 
15988: # ---------------------------------------------------------- Read loncaparev table
15989: 
15990: &load_loncaparevs();
15991: 
15992: # ---------------------------------------------------------- Read serverhostID table
15993: 
15994: &load_serverhomeIDs();
15995: 
15996: # ---------------------------------------------------------- Read releaseslist XML
15997: {
15998:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15999:     if (-e $file) {
16000:         my $parser = HTML::LCParser->new($file);
16001:         while (my $token = $parser->get_token()) {
16002:             if ($token->[0] eq 'S') {
16003:                 my $item = $token->[1];
16004:                 my $name = $token->[2]{'name'};
16005:                 my $value = $token->[2]{'value'};
16006:                 my $valuematch = $token->[2]{'valuematch'};
16007:                 my $namematch = $token->[2]{'namematch'};
16008:                 if ($item eq 'parameter') {
16009:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16010:                         my $release = $parser->get_text();
16011:                         $release =~ s/(^\s*|\s*$ )//gx;
16012:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16013:                     }
16014:                 } elsif ($item ne '' && $name ne '') {
16015:                     my $release = $parser->get_text();
16016:                     $release =~ s/(^\s*|\s*$ )//gx;
16017:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16018:                 }
16019:             }
16020:         }
16021:     }
16022: }
16023: 
16024: # ---------------------------------------------------------- Read managers table
16025: {
16026:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16027:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16028:             while (my $configline=<$config>) {
16029:                 chomp($configline);
16030:                 next if ($configline =~ /^\#/);
16031:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16032:                     $managerstab{$configline} = 1;
16033:                 }
16034:             }
16035:             close($config);
16036:         }
16037:     }
16038: }
16039: 
16040: # ------------- set up temporary directory
16041: {
16042:     $tmpdir = LONCAPA::tempdir();
16043: 
16044: }
16045: 
16046: # ------------- set default texengine (domain default overrides this)
16047: {
16048:     $deftex = LONCAPA::texengine();
16049: }
16050: 
16051: # ------------- set default minimum length for passwords for internal auth users
16052: {
16053:     $passwdmin = LONCAPA::passwd_min();
16054: }
16055: 
16056: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16057: 				'compress_threshold'=> 20_000,
16058:  			        });
16059: 
16060: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16061: $dumpcount=0;
16062: $locknum=0;
16063: 
16064: &logtouch();
16065: &logthis('<font color="yellow">INFO: Read configuration</font>');
16066: $readit=1;
16067:     {
16068: 	use integer;
16069: 	my $test=(2**32)+1;
16070: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16071: 	&logthis(" Detected 64bit platform ($_64bit)");
16072:     }
16073: }
16074: }
16075: 
16076: 1;
16077: __END__
16078: 
16079: =pod
16080: 
16081: =head1 NAME
16082: 
16083: Apache::lonnet - Subroutines to ask questions about things in the network.
16084: 
16085: =head1 SYNOPSIS
16086: 
16087: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16088: 
16089:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16090: 
16091: Common parameters:
16092: 
16093: =over 4
16094: 
16095: =item *
16096: 
16097: $uname : an internal username (if $cname expecting a course Id specifically)
16098: 
16099: =item *
16100: 
16101: $udom : a domain (if $cdom expecting a course's domain specifically)
16102: 
16103: =item *
16104: 
16105: $symb : a resource instance identifier
16106: 
16107: =item *
16108: 
16109: $namespace : the name of a .db file that contains the data needed or
16110: being set.
16111: 
16112: =back
16113: 
16114: =head1 OVERVIEW
16115: 
16116: lonnet provides subroutines which interact with the
16117: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16118: about classes, users, and resources.
16119: 
16120: For many of these objects you can also use this to store data about
16121: them or modify them in various ways.
16122: 
16123: =head2 Symbs
16124: 
16125: To identify a specific instance of a resource, LON-CAPA uses symbols
16126: or "symbs"X<symb>. These identifiers are built from the URL of the
16127: map, the resource number of the resource in the map, and the URL of
16128: the resource itself. The latter is somewhat redundant, but might help
16129: if maps change.
16130: 
16131: An example is
16132: 
16133:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16134: 
16135: The respective map entry is
16136: 
16137:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16138:   title="Problem 2">
16139:  </resource>
16140: 
16141: Symbs are used by the random number generator, as well as to store and
16142: restore data specific to a certain instance of for example a problem.
16143: 
16144: =head2 Storing And Retrieving Data
16145: 
16146: X<store()>X<cstore()>X<restore()>Three of the most important functions
16147: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16148: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16149: is is the non-critical message twin of cstore. These functions are for
16150: handlers to store a perl hash to a user's permanent data space in an
16151: easy manner, and to retrieve it again on another call. It is expected
16152: that a handler would use this once at the beginning to retrieve data,
16153: and then again once at the end to send only the new data back.
16154: 
16155: The data is stored in the user's data directory on the user's
16156: homeserver under the ID of the course.
16157: 
16158: The hash that is returned by restore will have all of the previous
16159: value for all of the elements of the hash.
16160: 
16161: Example:
16162: 
16163:  #creating a hash
16164:  my %hash;
16165:  $hash{'foo'}='bar';
16166: 
16167:  #storing it
16168:  &Apache::lonnet::cstore(\%hash);
16169: 
16170:  #changing a value
16171:  $hash{'foo'}='notbar';
16172: 
16173:  #adding a new value
16174:  $hash{'bar'}='foo';
16175:  &Apache::lonnet::cstore(\%hash);
16176: 
16177:  #retrieving the hash
16178:  my %history=&Apache::lonnet::restore();
16179: 
16180:  #print the hash
16181:  foreach my $key (sort(keys(%history))) {
16182:    print("\%history{$key} = $history{$key}");
16183:  }
16184: 
16185: Will print out:
16186: 
16187:  %history{1:foo} = bar
16188:  %history{1:keys} = foo:timestamp
16189:  %history{1:timestamp} = 990455579
16190:  %history{2:bar} = foo
16191:  %history{2:foo} = notbar
16192:  %history{2:keys} = foo:bar:timestamp
16193:  %history{2:timestamp} = 990455580
16194:  %history{bar} = foo
16195:  %history{foo} = notbar
16196:  %history{timestamp} = 990455580
16197:  %history{version} = 2
16198: 
16199: Note that the special hash entries C<keys>, C<version> and
16200: C<timestamp> were added to the hash. C<version> will be equal to the
16201: total number of versions of the data that have been stored. The
16202: C<timestamp> attribute will be the UNIX time the hash was
16203: stored. C<keys> is available in every historical section to list which
16204: keys were added or changed at a specific historical revision of a
16205: hash.
16206: 
16207: B<Warning>: do not store the hash that restore returns directly. This
16208: will cause a mess since it will restore the historical keys as if the
16209: were new keys. I.E. 1:foo will become 1:1:foo etc.
16210: 
16211: Calling convention:
16212: 
16213:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16214:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16215: 
16216: For more detailed information, see lonnet specific documentation.
16217: 
16218: =head1 RETURN MESSAGES
16219: 
16220: =over 4
16221: 
16222: =item * B<con_lost>: unable to contact remote host
16223: 
16224: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16225: when the connection is brought back up
16226: 
16227: =item * B<con_failed>: unable to contact remote host and unable to save message
16228: for later delivery
16229: 
16230: =item * B<error:>: an error a occurred, a description of the error follows the :
16231: 
16232: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16233: that was requested
16234: 
16235: =back
16236: 
16237: =head1 PUBLIC SUBROUTINES
16238: 
16239: =head2 Session Environment Functions
16240: 
16241: =over 4
16242: 
16243: =item * 
16244: X<appenv()>
16245: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16246: the user envirnoment file, and will be restored for each access this
16247: user makes during this session, also modifies the %env for the current
16248: process. Optional rolesarrayref - if defined contains a reference to an array
16249: of roles which are exempt from the restriction on modifying user.role entries 
16250: in the user's environment.db and in %env.    
16251: 
16252: =item *
16253: X<delenv()>
16254: B<delenv($delthis,$regexp)>: removes all items from the session
16255: environment file that begin with $delthis. If the 
16256: optional second arg - $regexp - is true, $delthis is treated as a 
16257: regular expression, otherwise \Q$delthis\E is used. 
16258: The values are also deleted from the current processes %env.
16259: 
16260: =item * get_env_multiple($name) 
16261: 
16262: gets $name from the %env hash, it seemlessly handles the cases where multiple
16263: values may be defined and end up as an array ref.
16264: 
16265: returns an array of values
16266: 
16267: =back
16268: 
16269: =head2 User Information
16270: 
16271: =over 4
16272: 
16273: =item *
16274: X<queryauthenticate()>
16275: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16276: authentication scheme
16277: 
16278: =item *
16279: X<authenticate()>
16280: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16281: authenticate user from domain's lib servers (first use the current
16282: one). C<$upass> should be the users password.
16283: $checkdefauth is optional (value is 1 if a check should be made to
16284:    authenticate user using default authentication method, and allow
16285:    account creation if username does not have account in the domain).
16286: $clientcancheckhost is optional (value is 1 if checking whether the
16287:    server can host will occur on the client side in lonauth.pm).   
16288: 
16289: =item *
16290: X<homeserver()>
16291: B<homeserver($uname,$udom)>: find the server which has
16292: the user's directory and files (there must be only one), this caches
16293: the answer, and also caches if there is a borken connection.
16294: 
16295: =item *
16296: X<idget()>
16297: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16298: a list of student/employee IDs or clicker IDs
16299: (student/employee IDs are a unique resource in a domain, there must be 
16300: only 1 ID per username, and only 1 username per ID in a specific domain).
16301: clickerIDs are not necessarily unique, as students might share clickers.
16302: (returns hash: id=>name,id=>name)
16303: 
16304: =item *
16305: X<idrget()>
16306: B<idrget($udom,@unames)>: find the IDs behind a list of
16307: usernames (returns hash: name=>id,name=>id)
16308: 
16309: =item *
16310: X<idput()>
16311: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16312: names and associated student/employee IDs or clicker IDs.
16313: 
16314: =item *
16315: X<iddel()>
16316: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16317: student/employee ID or clicker ID username look-ups from domain.
16318: The homeserver ($uhome) and namespace ($namespace) are optional.
16319: If no $uhome is provided, it will be determined usig &homeserver()
16320: for each user.  If no $namespace is provided, the default is ids.
16321: 
16322: =item *
16323: X<updateclickers()>
16324: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16325: clicker ID-to-username look-ups in clickers.db on library server.
16326: Permitted actions are add or del (i.e., add or delete). The 
16327: clickers.db contains clickerID as keys (escaped), and each corresponding
16328: value is an escaped comma-separated list of usernames (for whom the
16329: library server is the homeserver), who registered that particular ID.
16330: If $critical is true, the update will be sent via &critical, otherwise
16331: &reply() will be used.
16332: 
16333: =item *
16334: X<rolesinit()>
16335: B<rolesinit($udom,$username)>: get user privileges.
16336: returns user role, first access and timer interval hashes
16337: 
16338: =item *
16339: X<privileged()>
16340: B<privileged($username,$domain)>: returns a true if user has a
16341: privileged and active role (i.e. su or dc), false otherwise.
16342: 
16343: =item *
16344: X<getsection()>
16345: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16346: course $cname, return section name/number or '' for "not in course"
16347: and '-1' for "no section"
16348: 
16349: =item *
16350: X<userenvironment()>
16351: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16352: passed in @what from the requested user's environment, returns a hash
16353: 
16354: =item * 
16355: X<userlog_query()>
16356: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16357: activity.log file. %filters defines filters applied when parsing the
16358: log file. These can be start or end timestamps, or the type of action
16359: - log to look for Login or Logout events, check for Checkin or
16360: Checkout, role for role selection. The response is in the form
16361: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16362: escaped strings of the action recorded in the activity.log file.
16363: 
16364: =back
16365: 
16366: =head2 User Roles
16367: 
16368: =over 4
16369: 
16370: =item *
16371: 
16372: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16373: returns codes for allowed actions.
16374: 
16375: The first argument is required, all others are optional.
16376: 
16377: $priv is the privilege being checked.
16378: $uri contains additional information about what is being checked for access (e.g.,
16379: URL, course ID etc.). 
16380: $symb is the unique resource instance identifier in a course; if needed,
16381: but not provided, it will be retrieved via a call to &symbread(). 
16382: $role is the role for which a priv is being checked (only used if priv is evb). 
16383: $clientip is the user's IP address (only used when checking for access to portfolio 
16384: files).
16385: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16386: prevents recursive calls to &allowed.
16387: 
16388:  F: full access
16389:  U,I,K: authentication modes (cxx only)
16390:  '': forbidden
16391:  1: user needs to choose course
16392:  2: browse allowed
16393:  A: passphrase authentication needed
16394:  B: access temporarily blocked because of a blocking event in a course.
16395:  D: access blocked because access is required via session initiated via deep-link 
16396: 
16397: =item *
16398: 
16399: constructaccess($url,$setpriv) : check for access to construction space URL
16400: 
16401: See if the owner domain and name in the URL match those in the
16402: expected environment.  If so, return three element list
16403: ($ownername,$ownerdomain,$ownerhome).
16404: 
16405: Otherwise return the null string.
16406: 
16407: If second argument 'setpriv' is true, it assigns the privileges,
16408: and returns the same three element list, unless the owner has
16409: blocked "ad hoc" Domain Coordinator access to the Author Space,
16410: in which case the null string is returned.
16411: 
16412: =item *
16413: 
16414: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16415: define a custom role rolename set privileges in format of lonTabs/roles.tab
16416: for system, domain, and course level. $uname and $udom are optional (current
16417: user's username and domain will be used when either of $uname or $udom are absent.
16418: 
16419: =item *
16420: 
16421: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16422: (rolesplain.tab); plain text explanation of a user role term.
16423: $type is Course (default) or Community.
16424: If $forcedefault evaluates to true, text returned will be default 
16425: text for $type. Otherwise, if this is a course, the text returned 
16426: will be a custom name for the role (if defined in the course's 
16427: environment).  If no custom name is defined the default is returned.
16428:    
16429: =item *
16430: 
16431: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16432: All arguments are optional. Returns a hash of a roles, either for
16433: co-author/assistant author roles for a user's Construction Space
16434: (default), or if $context is 'userroles', roles for the user himself,
16435: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16436: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16437: For each key, value is set to colon-separated start and end times for
16438: the role.  If no username and domain are specified, will default to
16439: current user/domain. Types, roles, and roledoms are references to arrays
16440: of role statuses (active, future or previous), roles 
16441: (e.g., cc,in, st etc.) and domains of the roles which can be used
16442: to restrict the list of roles reported. If no array ref is 
16443: provided for types, will default to return only active roles.
16444: 
16445: =item *
16446: 
16447: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16448: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16449: 
16450: Additional optional arguments are: $type (if role checking is to be restricted 
16451: to certain user status types -- previous (expired roles), active (currently
16452: available roles) or future (roles available in the future), and
16453: $hideprivileged -- if true will not report course roles for users who
16454: have active Domain Coordinator role in course's domain or in additional
16455: domains (specified in 'Domains to check for privileged users' in course
16456: environment -- set via:  Course Settings -> Classlists and staff listing).
16457: 
16458: =item *
16459: 
16460: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16461: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16462: $possdomains and $possroles are optional array refs -- to domains to check and
16463: roles to check.  If $possdomains is not specified, a dump will be done of the
16464: users' roles.db to check for a dc or su role in any domain. This can be
16465: time consuming if &privileged is called repeatedly (e.g., when displaying a
16466: classlist), so in such cases, supplying a $possdomains array is preferred, as
16467: this then allows &privileged_by_domain() to be used, which caches the identity
16468: of privileged users, eliminating the need for repeated calls to &dump().
16469: 
16470: =item *
16471: 
16472: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16473: where the outer hash keys are domains specified in the $possdomains array ref,
16474: next inner hash keys are privileged roles specified in the $roles array ref,
16475: and the innermost hash contains key = value pairs for username:domain = end:start
16476: for active or future "privileged" users with that role in that domain. To avoid
16477: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16478: innerhash are cached using priv_$role and $dom as the identifiers.
16479: 
16480: =back
16481: 
16482: =head2 User Modification
16483: 
16484: =over 4
16485: 
16486: =item *
16487: 
16488: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16489: user for the level given by URL.  Optional start and end dates (leave empty
16490: string or zero for "no date")
16491: 
16492: =item *
16493: 
16494: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16495: change a users, password, possible return values are: ok,
16496: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16497: refused
16498: 
16499: =item *
16500: 
16501: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16502: 
16503: =item *
16504: 
16505: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16506:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16507: 
16508: will update user information (firstname,middlename,lastname,generation,
16509: permanentemail), and if forceid is true, student/employee ID also.
16510: A user's institutional affiliation(s) can also be updated.
16511: User information fields will not be overwritten with empty entries 
16512: unless the field is included in the $candelete array reference.
16513: This array is included when a single user is modified via "Manage Users",
16514: or when Autoupdate.pl is run by cron in a domain.
16515: 
16516: =item *
16517: 
16518: modifystudent
16519: 
16520: modify a student's enrollment and identification information.
16521: The course id is resolved based on the current user's environment.  
16522: This means the invoking user must be a course coordinator or otherwise
16523: associated with a course.
16524: 
16525: This call is essentially a wrapper for lonnet::modifyuser and
16526: lonnet::modify_student_enrollment
16527: 
16528: Inputs: 
16529: 
16530: =over 4
16531: 
16532: =item B<$udom> Student's loncapa domain
16533: 
16534: =item B<$uname> Student's loncapa login name
16535: 
16536: =item B<$uid> Student/Employee ID
16537: 
16538: =item B<$umode> Student's authentication mode
16539: 
16540: =item B<$upass> Student's password
16541: 
16542: =item B<$first> Student's first name
16543: 
16544: =item B<$middle> Student's middle name
16545: 
16546: =item B<$last> Student's last name
16547: 
16548: =item B<$gene> Student's generation
16549: 
16550: =item B<$usec> Student's section in course
16551: 
16552: =item B<$end> Unix time of the roles expiration
16553: 
16554: =item B<$start> Unix time of the roles start date
16555: 
16556: =item B<$forceid> If defined, allow $uid to be changed
16557: 
16558: =item B<$desiredhome> server to use as home server for student
16559: 
16560: =item B<$email> Student's permanent e-mail address
16561: 
16562: =item B<$type> Type of enrollment (auto or manual)
16563: 
16564: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16565: 
16566: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16567: 
16568: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16569: 
16570: =item B<$context> role change context (shown in User Management Logs display in a course)
16571: 
16572: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16573: 
16574: =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.
16575: 
16576: =back
16577: 
16578: =item *
16579: 
16580: modify_student_enrollment
16581: 
16582: Change a student's enrollment status in a class.  The environment variable
16583: 'role.request.course' must be defined for this function to proceed.
16584: 
16585: Inputs:
16586: 
16587: =over 4
16588: 
16589: =item $udom, student's domain
16590: 
16591: =item $uname, student's name
16592: 
16593: =item $uid, student's user id
16594: 
16595: =item $first, student's first name
16596: 
16597: =item $middle
16598: 
16599: =item $last
16600: 
16601: =item $gene
16602: 
16603: =item $usec
16604: 
16605: =item $end
16606: 
16607: =item $start
16608: 
16609: =item $type
16610: 
16611: =item $locktype
16612: 
16613: =item $cid
16614: 
16615: =item $selfenroll
16616: 
16617: =item $context
16618: 
16619: =item $credits, number of credits student will earn from this class
16620: 
16621: =item $instsec, institutional course section code for student
16622: 
16623: =back
16624: 
16625: 
16626: =item *
16627: 
16628: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16629: custom role; give a custom role to a user for the level given by URL.  Specify
16630: name and domain of role author, and role name
16631: 
16632: =item *
16633: 
16634: revokerole($udom,$uname,$url,$role) : revoke a role for url
16635: 
16636: =item *
16637: 
16638: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16639: 
16640: =back
16641: 
16642: =head2 Course Infomation
16643: 
16644: =over 4
16645: 
16646: =item *
16647: 
16648: coursedescription($courseid,$options) : returns a hash of information about the
16649: specified course id, including all environment settings for the
16650: course, the description of the course will be in the hash under the
16651: key 'description'
16652: 
16653: $options is an optional parameter that if supplied is a hash reference that controls
16654: what how this function works.  It has the following key/values:
16655: 
16656: =over 4
16657: 
16658: =item freshen_cache
16659: 
16660: If defined, and the environment cache for the course is valid, it is 
16661: returned in the returned hash.
16662: 
16663: =item one_time
16664: 
16665: If defined, the last cache time is set to _now_
16666: 
16667: =item user
16668: 
16669: If defined, the supplied username is used instead of the current user.
16670: 
16671: 
16672: =back
16673: 
16674: =item *
16675: 
16676: resdata($name,$domain,$type,@which) : request for current parameter
16677: setting for a specific $type, where $type is either 'course' or 'user',
16678: @what should be a list of parameters to ask about. This routine caches
16679: answers for 10 minutes.
16680: 
16681: =item *
16682: 
16683: get_courseresdata($courseid, $domain) : dump the entire course resource
16684: data base, returning a hash that is keyed by the resource name and has
16685: values that are the resource value.  I believe that the timestamps and
16686: versions are also returned.
16687: 
16688: =back
16689: 
16690: =head2 Course Modification
16691: 
16692: =over 4
16693: 
16694: =item *
16695: 
16696: writecoursepref($courseid,%prefs) : write preferences (environment
16697: database) for a course
16698: 
16699: =item *
16700: 
16701: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16702: 
16703: =item *
16704: 
16705: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16706: 
16707: =item *
16708: 
16709: is_course($courseid), is_course($cdom, $cnum)
16710: 
16711: Accepts either a combined $courseid (in the form of domain_courseid) or the
16712: two component version $cdom, $cnum. It checks if the specified course exists.
16713: 
16714: Returns:
16715:     undef if the course doesn't exist, otherwise
16716:     in scalar context the combined courseid.
16717:     in list context the two components of the course identifier, domain and 
16718:     courseid.    
16719: 
16720: =back
16721: 
16722: =head2 Bubblesheet Configuration
16723: 
16724: =over 4
16725: 
16726: =item *
16727: 
16728: get_scantron_config($which)
16729: 
16730: $which - the name of the configuration to parse from the file.
16731: 
16732: Parses and returns the bubblesheet configuration line selected as a
16733: hash of configuration file fields.
16734: 
16735: 
16736: Returns:
16737:     If the named configuration is not in the file, an empty
16738:     hash is returned.
16739: 
16740:     a hash with the fields
16741:       name         - internal name for the this configuration setup
16742:       description  - text to display to operator that describes this config
16743:       CODElocation - if 0 or the string 'none'
16744:                           - no CODE exists for this config
16745:                      if -1 || the string 'letter'
16746:                           - a CODE exists for this config and is
16747:                             a string of letters
16748:                      Unsupported value (but planned for future support)
16749:                           if a positive integer
16750:                                - The CODE exists as the first n items from
16751:                                  the question section of the form
16752:                           if the string 'number'
16753:                                - The CODE exists for this config and is
16754:                                  a string of numbers
16755:       CODEstart   - (only matter if a CODE exists) column in the line where
16756:                      the CODE starts
16757:       CODElength  - length of the CODE
16758:       IDstart     - column where the student/employee ID starts
16759:       IDlength    - length of the student/employee ID info
16760:       Qstart      - column where the information from the bubbled
16761:                     'questions' start
16762:       Qlength     - number of columns comprising a single bubble line from
16763:                     the sheet. (usually either 1 or 10)
16764:       Qon         - either a single character representing the character used
16765:                     to signal a bubble was chosen in the positional setup, or
16766:                     the string 'letter' if the letter of the chosen bubble is
16767:                     in the final, or 'number' if a number representing the
16768:                     chosen bubble is in the file (1->A 0->J)
16769:       Qoff        - the character used to represent that a bubble was
16770:                     left blank
16771:       PaperID     - if the scanning process generates a unique number for each
16772:                     sheet scanned the column that this ID number starts in
16773:       PaperIDlength - number of columns that comprise the unique ID number
16774:                       for the sheet of paper
16775:       FirstName   - column that the first name starts in
16776:       FirstNameLength - number of columns that the first name spans
16777:       LastName    - column that the last name starts in
16778:       LastNameLength - number of columns that the last name spans
16779:       BubblesPerRow - number of bubbles available in each row used to
16780:                       bubble an answer. (If not specified, 10 assumed).
16781: 
16782: 
16783: =item *
16784: 
16785: get_scantronformat_file($cdom)
16786: 
16787: $cdom - the course's domain (optional); if not supplied, uses
16788: domain for current $env{'request.course.id'}.
16789: 
16790: Returns an array containing lines from the scantron format file for
16791: the domain of the course.
16792: 
16793: If a url for a custom.tab file is listed in domain's configuration.db,
16794: lines are from this file.
16795: 
16796: Otherwise, if a default.tab has been published in RES space by the
16797: domainconfig user, lines are from this file.
16798: 
16799: Otherwise, fall back to getting lines from the legacy file on the
16800: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16801: 
16802: =back
16803: 
16804: =head2 Resource Subroutines
16805: 
16806: =over 4
16807: 
16808: =item *
16809: 
16810: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16811: 
16812: =item *
16813: 
16814: repcopy($filename) : subscribes to the requested file, and attempts to
16815: replicate from the owning library server, Might return
16816: 'unavailable', 'not_found', 'forbidden', 'ok', or
16817: 'bad_request', also attempts to grab the metadata for the
16818: resource. Expects the local filesystem pathname
16819: (/home/httpd/html/res/....)
16820: 
16821: =back
16822: 
16823: =head2 Resource Information
16824: 
16825: =over 4
16826: 
16827: =item *
16828: 
16829: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16830: and returns the value of a variety of different possible values,
16831: $varname should be a request string, and the other parameters can be
16832: used to specify who and what one is asking about. Ordinarily, $cid 
16833: does not need to be specified, as it is retrived from 
16834: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16835: within lonuserstate::loadmap() when initializing a course, before
16836: $env{'request.course.id'} has been set, so it needs to be provided
16837: in that one case.
16838: 
16839: Possible values for $varname are environment.lastname (or other item
16840: from the envirnment hash), user.name (or someother aspect about the
16841: user), resource.0.maxtries (or some other part and parameter of a
16842: resource)
16843: 
16844: =item *
16845: 
16846: directcondval($number) : get current value of a condition; reads from a state
16847: string
16848: 
16849: =item *
16850: 
16851: condval($condidx) : value of condition index based on state
16852: 
16853: =item *
16854: 
16855: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16856: resource's metadata, $what should be either a specific key, or either
16857: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16858: packages that this resource currently uses, the last 3 arguments are 
16859: only used internally for recursive metadata.
16860: 
16861: the toolsymb is only used where the uri is for an external tool (for which
16862: the uri as well as the symb are guaranteed to be unique).
16863: 
16864: this function automatically caches all requests except any made recursively
16865: to retrieve a list of metadata keys for an imported library file ($liburi is 
16866: defined).
16867: 
16868: =item *
16869: 
16870: metadata_query($query,$custom,$customshow) : make a metadata query against the
16871: network of library servers; returns file handle of where SQL and regex results
16872: will be stored for query
16873: 
16874: =item *
16875: 
16876: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16877: return symbolic list entry (all arguments optional). 
16878: 
16879: Args: filename is the filename (including path) for the file for which a symb 
16880: is required; donotrecurse, if true will prevent calls to allowed() being made 
16881: to check access status if more than one resource was found in the bighash 
16882: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16883: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16884: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16885: cause possible symbs to be checked to determine if they are subject to content
16886: blocking, if so they will not be included as possible symbs; possibles is a
16887: ref to a hash, which, as a side effect, will be populated with all possible 
16888: symbs (content blocking not tested).
16889:  
16890: returns the data handle
16891: 
16892: =item *
16893: 
16894: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16895: and is a possible symb for the URL in $thisfn, and if is an encrypted
16896: resource that the user accessed using /enc/ returns a 1 on success, 0
16897: on failure, user must be in a course, as it assumes the existence of
16898: the course initial hash, and uses $env('request.course.id'}.  The third
16899: arg is an optional reference to a scalar.  If this arg is passed in the 
16900: call to symbverify, it will be set to 1 if the symb has been set to be 
16901: encrypted; otherwise it will be null.  
16902: 
16903: =item *
16904: 
16905: symbclean($symb) : removes versions numbers from a symb, returns the
16906: cleaned symb
16907: 
16908: =item *
16909: 
16910: is_on_map($uri) : checks if the $uri is somewhere on the current
16911: course map, user must be in a course for it to work.
16912: 
16913: =item *
16914: 
16915: numval($salt) : return random seed value (addend for rndseed)
16916: 
16917: =item *
16918: 
16919: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16920: a random seed, all arguments are optional, if they aren't sent it uses the
16921: environment to derive them. Note: if symb isn't sent and it can't get one
16922: from &symbread it will use the current time as its return value
16923: 
16924: =item *
16925: 
16926: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16927: unfakeable, receipt
16928: 
16929: =item *
16930: 
16931: receipt() : API to ireceipt working off of env values; given out to users
16932: 
16933: =item *
16934: 
16935: countacc($url) : count the number of accesses to a given URL
16936: 
16937: =item *
16938: 
16939: 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
16940: 
16941: =item *
16942: 
16943: 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)
16944: 
16945: =item *
16946: 
16947: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16948: 
16949: =item *
16950: 
16951: devalidate($symb) : devalidate temporary spreadsheet calculations,
16952: forcing spreadsheet to reevaluate the resource scores next time.
16953: 
16954: =item * 
16955: 
16956: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16957: when viewing in course context.
16958: 
16959:  input: six args -- filename (decluttered), course number, course domain,
16960:                     url, symb (if registered) and group (if this is a 
16961:                     group item -- e.g., bulletin board, group page etc.).
16962: 
16963:  output: array of five scalars --
16964:          $cfile -- url for file editing if editable on current server
16965:          $home -- homeserver of resource (i.e., for author if published,
16966:                                           or course if uploaded.).
16967:          $switchserver --  1 if server switch will be needed.
16968:          $forceedit -- 1 if icon/link should be to go to edit mode 
16969:          $forceview -- 1 if icon/link should be to go to view mode
16970: 
16971: =item *
16972: 
16973: is_course_upload($file,$cnum,$cdom)
16974: 
16975: Used in course context to determine if current file was uploaded to 
16976: the course (i.e., would be found in /userfiles/docs on the course's 
16977: homeserver.
16978: 
16979:   input: 3 args -- filename (decluttered), course number and course domain.
16980:   output: boolean -- 1 if file was uploaded.
16981: 
16982: =back
16983: 
16984: =head2 Storing/Retreiving Data
16985: 
16986: =over 4
16987: 
16988: =item *
16989: 
16990: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16991: permanently for this url; hashref needs to be given and should be a \%hashname;
16992: the remaining args aren't required and if they aren't passed or are '' they will
16993: be derived from the env (with the exception of $laststore, which is an 
16994: optional arg used when a user's submission is stored in grading).
16995: $laststore is $version=$timestamp, where $version is the most recent version
16996: number retrieved for the corresponding $symb in the $namespace db file, and
16997: $timestamp is the timestamp for that transaction (UNIX time).
16998: $laststore is currently only passed when cstore() is called by 
16999: structuretags::finalize_storage().
17000: 
17001: =item *
17002: 
17003: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17004: but uses critical subroutine
17005: 
17006: =item *
17007: 
17008: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17009: all args are optional
17010: 
17011: =item *
17012: 
17013: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17014: dumps the complete (or key matching regexp) namespace into a hash
17015: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17016: normally &store()ed into
17017: 
17018: $range should be either an integer '100' (give me the first 100
17019:                                            matching records)
17020:               or be  two integers sperated by a - with no spaces
17021:                  '30-50' (give me the 30th through the 50th matching
17022:                           records)
17023: 
17024: 
17025: =item *
17026: 
17027: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17028: replaces a &store() version of data with a replacement set of data
17029: for a particular resource in a namespace passed in the $storehash hash 
17030: reference. If $tolog is true, the transaction is logged in the courselog
17031: with an action=PUTSTORE.
17032: 
17033: =item *
17034: 
17035: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17036: works very similar to store/cstore, but all data is stored in a
17037: temporary location and can be reset using tmpreset, $storehash should
17038: be a hash reference, returns nothing on success
17039: 
17040: =item *
17041: 
17042: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17043: similar to restore, but all data is stored in a temporary location and
17044: can be reset using tmpreset. Returns a hash of values on success,
17045: error string otherwise.
17046: 
17047: =item *
17048: 
17049: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17050: deltes all keys for $symb form the temporary storage hash.
17051: 
17052: =item *
17053: 
17054: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17055: reference filled in from namesp ($udom and $uname are optional)
17056: 
17057: =item *
17058: 
17059: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17060: namesp ($udom and $uname are optional)
17061: 
17062: =item *
17063: 
17064: dump($namespace,$udom,$uname,$regexp,$range) : 
17065: dumps the complete (or key matching regexp) namespace into a hash
17066: ($udom, $uname, $regexp, $range are optional)
17067: 
17068: $range should be either an integer '100' (give me the first 100
17069:                                            matching records)
17070:               or be  two integers sperated by a - with no spaces
17071:                  '30-50' (give me the 30th through the 50th matching
17072:                           records)
17073: =item *
17074: 
17075: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17076: $store can be a scalar, an array reference, or if the amount to be 
17077: incremented is > 1, a hash reference.
17078: 
17079: ($udom and $uname are optional)
17080: 
17081: =item *
17082: 
17083: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17084: ($udom and $uname are optional)
17085: 
17086: =item *
17087: 
17088: cput($namespace,$storehash,$udom,$uname) : critical put
17089: ($udom and $uname are optional)
17090: 
17091: =item *
17092: 
17093: newput($namespace,$storehash,$udom,$uname) :
17094: 
17095: Attempts to store the items in the $storehash, but only if they don't
17096: currently exist, if this succeeds you can be certain that you have 
17097: successfully created a new key value pair in the $namespace db.
17098: 
17099: 
17100: Args:
17101:  $namespace: name of database to store values to
17102:  $storehash: hashref to store to the db
17103:  $udom: (optional) domain of user containing the db
17104:  $uname: (optional) name of user caontaining the db
17105: 
17106: Returns:
17107:  'ok' -> succeeded in storing all keys of $storehash
17108:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17109:                         least <key> already existed in the db (other
17110:                         requested keys may also already exist)
17111:  'error: <msg>' -> unable to tie the DB or other error occurred
17112:  'con_lost' -> unable to contact request server
17113:  'refused' -> action was not allowed by remote machine
17114: 
17115: 
17116: =item *
17117: 
17118: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17119: reference filled in from namesp (encrypts the return communication)
17120: ($udom and $uname are optional)
17121: 
17122: =item *
17123: 
17124: log($udom,$name,$home,$message) : write to permanent log for user; use
17125: critical subroutine
17126: 
17127: =item *
17128: 
17129: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17130: array reference filled in from namespace found in domain level on either
17131: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17132: 
17133: =item *
17134: 
17135: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17136: domain level either on specified domain server ($uhome) or primary domain 
17137: server ($udom and $uhome are optional)
17138: 
17139: =item * 
17140: 
17141: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17142: for: authentication, language, quotas, timezone, date locale, and portal URL in
17143: the target domain.
17144: 
17145: May also include additional key => value pairs for the following groups:
17146: 
17147: =over
17148: 
17149: =item
17150: disk quotas (MB allocated by default to portfolios and authoring spaces).
17151: 
17152: =over
17153: 
17154: =item defaultquota, authorquota
17155: 
17156: =back
17157: 
17158: =item
17159: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17160: portfolio for users).
17161: 
17162: =over
17163: 
17164: =item
17165: aboutme, blog, webdav, portfolio
17166: 
17167: =back
17168: 
17169: =item
17170: requestcourses: ability to request courses, and how requests are processed.
17171: 
17172: =over
17173: 
17174: =item
17175: official, unofficial, community, textbook, placement
17176: 
17177: =back
17178: 
17179: =item
17180: inststatus: types of institutional affiliation, and order in which they are displayed.
17181: 
17182: =over
17183: 
17184: =item
17185: inststatustypes, inststatusorder, inststatusguest
17186: 
17187: =back
17188: 
17189: =item
17190: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17191: for course's uploaded content.
17192: 
17193: =over
17194: 
17195: =item
17196: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17197: communityquota, textbookquota, placementquota
17198: 
17199: =back
17200: 
17201: =item
17202: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17203: on your servers.
17204: 
17205: =over
17206: 
17207: =item 
17208: remotesessions, hostedsessions
17209: 
17210: =back
17211: 
17212: =back
17213: 
17214: In cases where a domain coordinator has never used the "Set Domain Configuration"
17215: utility to create a configuration.db file on a domain's primary library server 
17216: only the following domain defaults: auth_def, auth_arg_def, lang_def
17217: -- corresponding values are authentication type (internal, krb4, krb5,
17218: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17219: will be available. Values are retrieved from cache (if current), unless the
17220: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17221: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17222: 
17223: Typical usage:
17224: 
17225: %domdefaults = &get_domain_defaults($target_domain);
17226: 
17227: =back
17228: 
17229: =head2 Network Status Functions
17230: 
17231: =over 4
17232: 
17233: =item *
17234: 
17235: dirlist() : return directory list based on URI (first arg).
17236: 
17237: Inputs: 1 required, 5 optional.
17238: 
17239: =over
17240: 
17241: =item 
17242: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17243: 
17244: =item
17245: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17246: 
17247: =item
17248: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17249: 
17250: =item
17251: $getpropath - boolean: 1 if prepend path using &propath(). 
17252: 
17253: =item
17254: $getuserdir - boolean: 1 if prepend path for "userfiles".
17255: 
17256: =item 
17257: $alternateRoot - path to prepend in place of path from $uri.
17258: 
17259: =back
17260: 
17261: Returns: Array of up to two items.
17262: 
17263: =over
17264: 
17265: a reference to an array of files/subdirectories
17266: 
17267: =over
17268: 
17269: Each element in the array of files/subdirectories is a & separated list of
17270: item name and the result of running stat on the item.  If dirlist was requested
17271: for a file instead of a directory, the item name will be ''. For a directory 
17272: listing, if the item is a metadata file, the element will end &N&M 
17273: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17274: default copyright set (1).  
17275: 
17276: =back
17277: 
17278: a scalar containing error condition (if encountered).
17279: 
17280: =over
17281: 
17282: =item 
17283: no_host (no homeserver identified for $username:$domain).
17284: 
17285: =item 
17286: no_such_host (server contacted for listing not identified as valid host).
17287: 
17288: =item 
17289: con_lost (connection to remote server failed).
17290: 
17291: =item 
17292: refused (invalid $username:$domain received on lond side).
17293: 
17294: =item 
17295: no_such_dir (directory at specified path on lond side does not exist). 
17296: 
17297: =item 
17298: empty (directory at specified path on lond side is empty).
17299: 
17300: =over
17301: 
17302: This is currently not encountered because the &ls3, &ls2, 
17303: &ls (_handler) routines on the lond side do not filter out
17304: . and .. from a directory listing. 
17305: 
17306: =back
17307: 
17308: =back
17309: 
17310: =back
17311: 
17312: =item *
17313: 
17314: spareserver() : find server with least workload from spare.tab
17315: 
17316: 
17317: =item *
17318: 
17319: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17320: if there is no corresponding loncapa host.
17321: 
17322: =back
17323: 
17324: 
17325: =head2 Apache Request
17326: 
17327: =over 4
17328: 
17329: =item *
17330: 
17331: ssi($url,%hash) : server side include, does a complete request cycle on url to
17332: localhost, posts hash
17333: 
17334: =back
17335: 
17336: =head2 Data to String to Data
17337: 
17338: =over 4
17339: 
17340: =item *
17341: 
17342: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17343: and '&' separators, supports elements that are arrayrefs and hashrefs
17344: 
17345: =item *
17346: 
17347: hashref2str($hashref) : convert a hashref into a string complete with
17348: escaping and '=' and '&' separators, supports elements that are
17349: arrayrefs and hashrefs
17350: 
17351: =item *
17352: 
17353: arrayref2str($arrayref) : convert an arrayref into a string complete
17354: with escaping and '&' separators, supports elements that are arrayrefs
17355: and hashrefs
17356: 
17357: =item *
17358: 
17359: str2hash($string) : convert string to hash using unescaping and
17360: splitting on '=' and '&', supports elements that are arrayrefs and
17361: hashrefs
17362: 
17363: =item *
17364: 
17365: str2array($string) : convert string to hash using unescaping and
17366: splitting on '&', supports elements that are arrayrefs and hashrefs
17367: 
17368: =back
17369: 
17370: =head2 Logging Routines
17371: 
17372: 
17373: These routines allow one to make log messages in the lonnet.log and
17374: lonnet.perm logfiles.
17375: 
17376: =over 4
17377: 
17378: =item *
17379: 
17380: logtouch() : make sure the logfile, lonnet.log, exists
17381: 
17382: =item *
17383: 
17384: logthis() : append message to the normal lonnet.log file, it gets
17385: preiodically rolled over and deleted.
17386: 
17387: =item *
17388: 
17389: logperm() : append a permanent message to lonnet.perm.log, this log
17390: file never gets deleted by any automated portion of the system, only
17391: messages of critical importance should go in here.
17392: 
17393: 
17394: =back
17395: 
17396: =head2 General File Helper Routines
17397: 
17398: =over 4
17399: 
17400: =item *
17401: 
17402: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17403: (a) files in /uploaded
17404:   (i) If a local copy of the file exists - 
17405:       compares modification date of local copy with last-modified date for 
17406:       definitive version stored on home server for course. If local copy is 
17407:       stale, requests a new version from the home server and stores it. 
17408:       If the original has been removed from the home server, then local copy 
17409:       is unlinked.
17410:   (ii) If local copy does not exist -
17411:       requests the file from the home server and stores it. 
17412:   
17413:   If $caller is 'uploadrep':  
17414:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17415:     for request for files originally uploaded via DOCS. 
17416:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17417:   
17418:   Otherwise:
17419:      This indicates a call from the content generation phase of the request.
17420:      -  returns the entire contents of the file or -1.
17421:      
17422: (b) files in /res
17423:    - returns the entire contents of a file or -1; 
17424:    it properly subscribes to and replicates the file if neccessary.
17425: 
17426: 
17427: =item *
17428: 
17429: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17430:                   reference
17431: 
17432: returns either a stat() list of data about the file or an empty list
17433: if the file doesn't exist or couldn't find out about it (connection
17434: problems or user unknown)
17435: 
17436: =item *
17437: 
17438: filelocation($dir,$file) : returns file system location of a file
17439: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17440: directory that relative $file lookups are to looked in ($dir of /a/dir
17441: and a file of ../bob will become /a/bob)
17442: 
17443: =item *
17444: 
17445: hreflocation($dir,$file) : returns file system location or a URL; same as
17446: filelocation except for hrefs
17447: 
17448: =item *
17449: 
17450: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17451: also removes beginning /home/httpd/html unless /priv/ follows it.
17452: 
17453: =back
17454: 
17455: =head2 Usererfile file routines (/uploaded*)
17456: 
17457: =over 4
17458: 
17459: =item *
17460: 
17461: userfileupload(): main rotine for putting a file in a user or course's
17462:                   filespace, arguments are,
17463: 
17464:  formname - required - this is the name of the element in $env where the
17465:            filename, and the contents of the file to create/modifed exist
17466:            the filename is in $env{'form.'.$formname.'.filename'} and the
17467:            contents of the file is located in $env{'form.'.$formname}
17468:  context - if coursedoc, store the file in the course of the active role
17469:              of the current user; 
17470:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17471:            if 'canceloverwrite': delete file in tmp/overwrites directory
17472:  subdir - required - subdirectory to put the file in under ../userfiles/
17473:          if undefined, it will be placed in "unknown"
17474: 
17475:  (This routine calls clean_filename() to remove any dangerous
17476:  characters from the filename, and then calls finuserfileupload() to
17477:  complete the transaction)
17478: 
17479:  returns either the url of the uploaded file (/uploaded/....) if successful
17480:  and /adm/notfound.html if unsuccessful
17481: 
17482: =item *
17483: 
17484: clean_filename(): routine for cleaing a filename up for storage in
17485:                  userfile space, argument is:
17486: 
17487:  filename - proposed filename
17488: 
17489: returns: the new clean filename
17490: 
17491: =item *
17492: 
17493: finishuserfileupload(): routine that creates and sends the file to
17494: userspace, probably shouldn't be called directly
17495: 
17496:   docuname: username or courseid of destination for the file
17497:   docudom: domain of user/course of destination for the file
17498:   formname: same as for userfileupload()
17499:   fname: filename (including subdirectories) for the file
17500:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17501:           if hashref, and context is scantron, will convert csv format to standard format
17502:   allfiles: reference to hash used to store objects found by parser
17503:   codebase: reference to hash used for codebases of java objects found by parser
17504:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17505:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17506:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17507:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17508:   context: if 'overwrite', will move the uploaded file from its temporary location to
17509:             userfiles to facilitate overwriting a previously uploaded file with same name.
17510:   mimetype: reference to scalar to accommodate mime type determined
17511:             from File::MMagic if $parser = parse.
17512: 
17513:  returns either the url of the uploaded file (/uploaded/....) if successful
17514:  and /adm/notfound.html if unsuccessful (or an error message if context 
17515:  was 'overwrite').
17516:  
17517: 
17518: =item *
17519: 
17520: renameuserfile(): renames an existing userfile to a new name
17521: 
17522:   Args:
17523:    docuname: username or courseid of destination for the file
17524:    docudom: domain of user/course of destination for the file
17525:    old: current file name (including any subdirs under userfiles)
17526:    new: desired file name (including any subdirs under userfiles)
17527: 
17528: =item *
17529: 
17530: mkdiruserfile(): creates a directory is a userfiles dir
17531: 
17532:   Args:
17533:    docuname: username or courseid of destination for the file
17534:    docudom: domain of user/course of destination for the file
17535:    dir: dir to create (including any subdirs under userfiles)
17536: 
17537: =item *
17538: 
17539: removeuserfile(): removes a file that exists in userfiles
17540: 
17541:   Args:
17542:    docuname: username or courseid of destination for the file
17543:    docudom: domain of user/course of destination for the file
17544:    fname: filname to delete (including any subdirs under userfiles)
17545: 
17546: =item *
17547: 
17548: removeuploadedurl(): convience function for removeuserfile()
17549: 
17550:   Args:
17551:    url:  a full /uploaded/... url to delete
17552: 
17553: =item * 
17554: 
17555: get_portfile_permissions():
17556:   Args:
17557:     domain: domain of user or course contain the portfolio files
17558:     user: name of user or num of course contain the portfolio files
17559:   Returns:
17560:     hashref of a dump of the proper file_permissions.db
17561:    
17562: 
17563: =item * 
17564: 
17565: get_access_controls():
17566: 
17567: Args:
17568:   current_permissions: the hash ref returned from get_portfile_permissions()
17569:   group: (optional) the group you want the files associated with
17570:   file: (optional) the file you want access info on
17571: 
17572: Returns:
17573:     a hash (keys are file names) of hashes containing
17574:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17575:         values are XML containing access control settings (see below) 
17576: 
17577: Internal notes:
17578: 
17579:  access controls are stored in file_permissions.db as key=value pairs.
17580:     key -> path to file/file_name\0uniqueID:scope_end_start
17581:         where scope -> public,guest,course,group,domains or users.
17582:               end -> UNIX time for end of access (0 -> no end date)
17583:               start -> UNIX time for start of access
17584: 
17585:     value -> XML description of access control
17586:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17587:             <start></start>
17588:             <end></end>
17589: 
17590:             <password></password>  for scope type = guest
17591: 
17592:             <domain></domain>     for scope type = course or group
17593:             <number></number>
17594:             <roles id="">
17595:              <role></role>
17596:              <access></access>
17597:              <section></section>
17598:              <group></group>
17599:             </roles>
17600: 
17601:             <dom></dom>         for scope type = domains
17602: 
17603:             <users>             for scope type = users
17604:              <user>
17605:               <uname></uname>
17606:               <udom></udom>
17607:              </user>
17608:             </users>
17609:            </scope> 
17610:               
17611:  Access data is also aggregated for each file in an additional key=value pair:
17612:  key -> path to file/file_name\0accesscontrol 
17613:  value -> reference to hash
17614:           hash contains key = value pairs
17615:           where key = uniqueID:scope_end_start
17616:                 value = UNIX time record was last updated
17617: 
17618:           Used to improve speed of look-ups of access controls for each file.  
17619:  
17620:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17621: 
17622: =item *
17623: 
17624: modify_access_controls():
17625: 
17626: Modifies access controls for a portfolio file
17627: Args
17628: 1. file name
17629: 2. reference to hash of required changes,
17630: 3. domain
17631: 4. username
17632:   where domain,username are the domain of the portfolio owner 
17633:   (either a user or a course) 
17634: 
17635: Returns:
17636: 1. result of additions or updates ('ok' or 'error', with error message). 
17637: 2. result of deletions ('ok' or 'error', with error message).
17638: 3. reference to hash of any new or updated access controls.
17639: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17640:    key = integer (inbound ID)
17641:    value = uniqueID
17642: 
17643: =item *
17644: 
17645: get_timebased_id():
17646: 
17647: Attempts to get a unique timestamp-based suffix for use with items added to a 
17648: course via the Course Editor (e.g., folders, composite pages, 
17649: group bulletin boards).
17650: 
17651: Args: (first three required; six others optional)
17652: 
17653: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17654:    docssequence, or name of group
17655: 
17656: 2. keyid (alphanumeric): name of temporary locking key in hash,
17657:    e.g., num, boardids
17658: 
17659: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17660:    file will be named nohist_namespace.db
17661: 
17662: 4. cdom: domain of course; default is current course domain from %env
17663: 
17664: 5. cnum: course number; default is current course number from %env
17665: 
17666: 6. idtype: set to concat if an additional digit is to be appended to the 
17667:    unix timestamp to form the suffix, if the plain timestamp is already
17668:    in use.  Default is to not do this, but simply increment the unix 
17669:    timestamp by 1 until a unique key is obtained.
17670: 
17671: 7. who: holder of locking key; defaults to user:domain for user.
17672: 
17673: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17674:    retrying); default is 3.
17675: 
17676: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17677: 
17678: Returns:
17679: 
17680: 1. suffix obtained (numeric)
17681: 
17682: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17683: 
17684: 3. error: contains (localized) error message if an error occurred.
17685: 
17686: 
17687: =back
17688: 
17689: =head2 HTTP Helper Routines
17690: 
17691: =over 4
17692: 
17693: =item *
17694: 
17695: escape() : unpack non-word characters into CGI-compatible hex codes
17696: 
17697: =item *
17698: 
17699: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17700: 
17701: =back
17702: 
17703: =head1 PRIVATE SUBROUTINES
17704: 
17705: =head2 Underlying communication routines (Shouldn't call)
17706: 
17707: =over 4
17708: 
17709: =item *
17710: 
17711: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17712: 
17713: =item *
17714: 
17715: reply() : uses subreply to send a message to remote machine, logs all failures
17716: 
17717: =item *
17718: 
17719: critical() : passes a critical message to another server; if cannot
17720: get through then place message in connection buffer directory and
17721: returns con_delayed, if incapable of saving message, returns
17722: con_failed
17723: 
17724: =item *
17725: 
17726: reconlonc() : tries to reconnect lonc client processes.
17727: 
17728: =back
17729: 
17730: =head2 Resource Access Logging
17731: 
17732: =over 4
17733: 
17734: =item *
17735: 
17736: flushcourselogs() : flush (save) buffer logs and access logs
17737: 
17738: =item *
17739: 
17740: courselog($what) : save message for course in hash
17741: 
17742: =item *
17743: 
17744: courseacclog($what) : save message for course using &courselog().  Perform
17745: special processing for specific resource types (problems, exams, quizzes, etc).
17746: 
17747: =item *
17748: 
17749: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17750: as a PerlChildExitHandler
17751: 
17752: =back
17753: 
17754: =head2 Other
17755: 
17756: =over 4
17757: 
17758: =item *
17759: 
17760: symblist($mapname,%newhash) : update symbolic storage links
17761: 
17762: =back
17763: 
17764: =cut
17765: 

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