File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1508: download - view: text, annotated - select for diffs
Tue Apr 11 20:35:19 2023 UTC (14 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754
  - Domain configuration to set defaults for which course types can use:
    (a) External Tools defined/configured in domain, and (b) External Tools
    defined/configured in course.
  - Domain defaults can be overridden by DC for specific course(s) via:
    Main Menu > "View or modify a course or community".

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1508 2023/04/11 20:35:19 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','domexttool',
 2703:                                   'exttool',],$domain);
 2704:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2705:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2706:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2707:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2708:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2709:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2710:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2711:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2712:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2713:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2714:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2715:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2716:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2717:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2718:     } else {
 2719:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2720:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2721:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2722:     }
 2723:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2724:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2725:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2726:         } else {
 2727:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2728:         }
 2729:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2730:         foreach my $item (@usertools) {
 2731:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2732:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2733:             }
 2734:         }
 2735:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2736:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2737:         }
 2738:     }
 2739:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2740:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2741:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2742:         }
 2743:     }
 2744:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2745:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2746:     }
 2747:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2748:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2749:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2750:         }
 2751:     }
 2752:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2753:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2754:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2755:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2756:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2757:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2758:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2759:         }
 2760:         foreach my $type (@coursetypes) {
 2761:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2762:                 unless ($type eq 'community') {
 2763:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2764:                 }
 2765:             }
 2766:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2767:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2768:             }
 2769:             if ($domdefaults{'postsubmit'} eq 'on') {
 2770:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2771:                     $domdefaults{$type.'postsubtimeout'} = 
 2772:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2773:                 }
 2774:             }
 2775:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2776:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2777:             } else {
 2778:                 $domdefaults{$type.'domexttool'} = 1;
 2779:             }
 2780:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2781:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2782:             } else {
 2783:                 $domdefaults{$type.'exttool'} = 0;
 2784:             }
 2785:         }
 2786:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2787:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2788:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2789:                 if (@clonecodes) {
 2790:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2791:                 }
 2792:             }
 2793:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2794:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2795:         }
 2796:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2797:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2798:         }
 2799:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2800:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2801:         }
 2802:     }
 2803:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2804:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2805:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2806:         }
 2807:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2808:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2809:         }
 2810:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2811:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2812:         }
 2813:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2814:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2815:         }
 2816:     }
 2817:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2818:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2819:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2820:                             'approval','limit');
 2821:             foreach my $type (@coursetypes) {
 2822:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2823:                     my @mgrdc = ();
 2824:                     foreach my $item (@settings) {
 2825:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2826:                             push(@mgrdc,$item);
 2827:                         }
 2828:                     }
 2829:                     if (@mgrdc) {
 2830:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2831:                     }
 2832:                 }
 2833:             }
 2834:         }
 2835:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2836:             foreach my $type (@coursetypes) {
 2837:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2838:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2839:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2840:                     }
 2841:                 }
 2842:             }
 2843:         }
 2844:     }
 2845:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2846:         $domdefaults{'catauth'} = 'std';
 2847:         $domdefaults{'catunauth'} = 'std';
 2848:         if ($domconfig{'coursecategories'}{'auth'}) {
 2849:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2850:         }
 2851:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2852:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2853:         }
 2854:     }
 2855:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2856:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2857:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2858:         }
 2859:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2860:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2861:         }
 2862:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2863:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2864:         }
 2865:     }
 2866:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2867:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2868:         foreach my $prefix (@prefixes) {
 2869:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2870:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2871:             }
 2872:         }
 2873:     }
 2874:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2875:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2876:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2877:     }
 2878:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2879:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2880:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2881:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2882:         }
 2883:     }
 2884:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2885:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2886:             if ($domconfig{'wafproxy'}{$item}) {
 2887:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2888:             }
 2889:         }
 2890:     }
 2891:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2892:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2893:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2894:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2895:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2896:         }
 2897:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2898:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2899:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2900:             }
 2901:         }
 2902:     }
 2903:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2904:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2905:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2906:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2907:         }
 2908:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2909:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2910:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2911:             }
 2912:         }
 2913:     }
 2914:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2915:     return %domdefaults;
 2916: }
 2917: 
 2918: sub get_dom_cats {
 2919:     my ($dom) = @_;
 2920:     return unless (&domain($dom));
 2921:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2922:     unless (defined($cached)) {
 2923:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2924:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2925:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2926:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2927:             } else {
 2928:                 $cats = {};
 2929:             }
 2930:         } else {
 2931:             $cats = {};
 2932:         }
 2933:         &do_cache_new('cats',$dom,$cats,3600);
 2934:     }
 2935:     return $cats;
 2936: }
 2937: 
 2938: sub get_dom_instcats {
 2939:     my ($dom) = @_;
 2940:     return unless (&domain($dom));
 2941:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2942:     unless (defined($cached)) {
 2943:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2944:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2945:         if ($totcodes > 0) {
 2946:             my $caller = 'global';
 2947:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2948:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2949:                 $instcats = {
 2950:                                 totcodes => $totcodes,
 2951:                                 codes => \%codes,
 2952:                                 codetitles => \@codetitles,
 2953:                                 cat_titles => \%cat_titles,
 2954:                                 cat_order => \%cat_order,
 2955:                             };
 2956:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2957:             }
 2958:         }
 2959:     }
 2960:     return $instcats;
 2961: }
 2962: 
 2963: sub retrieve_instcodes {
 2964:     my ($coursecodes,$dom) = @_;
 2965:     my $totcodes;
 2966:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2967:     foreach my $course (keys(%courses)) {
 2968:         if (ref($courses{$course}) eq 'HASH') {
 2969:             if ($courses{$course}{'inst_code'} ne '') {
 2970:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2971:                 $totcodes ++;
 2972:             }
 2973:         }
 2974:     }
 2975:     return $totcodes;
 2976: }
 2977: 
 2978: sub course_portal_url {
 2979:     my ($cnum,$cdom,$r) = @_;
 2980:     my $chome = &homeserver($cnum,$cdom);
 2981:     my $hostname = &hostname($chome);
 2982:     my $protocol = $protocol{$chome};
 2983:     $protocol = 'http' if ($protocol ne 'https');
 2984:     my %domdefaults = &get_domain_defaults($cdom);
 2985:     my $firsturl;
 2986:     if ($domdefaults{'portal_def'}) {
 2987:         $firsturl = $domdefaults{'portal_def'};
 2988:     } else {
 2989:         my $alias = &use_proxy_alias($r,$chome);
 2990:         $hostname = $alias if ($alias ne '');
 2991:         $firsturl = $protocol.'://'.$hostname;
 2992:     }
 2993:     return $firsturl;
 2994: }
 2995: 
 2996: sub url_prefix {
 2997:     my ($r,$dom,$home,$context) = @_;
 2998:     my $prefix;
 2999:     my %domdefs = &get_domain_defaults($dom);
 3000:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3001:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3002:             $prefix = $1;
 3003:         }
 3004:     }
 3005:     if ($prefix eq '') {
 3006:         my $hostname = &hostname($home);
 3007:         my $protocol = $protocol{$home};
 3008:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3009:         my $alias = &use_proxy_alias($r,$home);
 3010:         $hostname = $alias if ($alias ne '');
 3011:         $prefix = $protocol.'://'.$hostname;
 3012:     }
 3013:     return $prefix;
 3014: }
 3015: 
 3016: # --------------------------------------------- Get domain config for passwords
 3017: 
 3018: sub get_passwdconf {
 3019:     my ($dom) = @_;
 3020:     my (%passwdconf,$gotconf,$lookup);
 3021:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3022:     if (defined($cached)) {
 3023:         if (ref($result) eq 'HASH') {
 3024:             %passwdconf = %{$result};
 3025:             $gotconf = 1;
 3026:         }
 3027:     }
 3028:     unless ($gotconf) {
 3029:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3030:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3031:             %passwdconf = %{$domconfig{'passwords'}};
 3032:         }
 3033:         my $cachetime = 24*60*60;
 3034:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3035:     }
 3036:     return %passwdconf;
 3037: }
 3038: 
 3039: # --------------------------------------------------- Assign a key to a student
 3040: 
 3041: sub assign_access_key {
 3042: #
 3043: # a valid key looks like uname:udom#comments
 3044: # comments are being appended
 3045: #
 3046:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3047:     $kdom=
 3048:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3049:     $knum=
 3050:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3051:     $cdom=
 3052:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3053:     $cnum=
 3054:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3055:     $udom=$env{'user.name'} unless (defined($udom));
 3056:     $uname=$env{'user.domain'} unless (defined($uname));
 3057:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3058:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3059:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3060:                                                   # assigned to this person
 3061:                                                   # - this should not happen,
 3062:                                                   # unless something went wrong
 3063:                                                   # the first time around
 3064: # ready to assign
 3065:         $logentry=$1.'; '.$logentry;
 3066:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3067:                                                  $kdom,$knum) eq 'ok') {
 3068: # key now belongs to user
 3069: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3070:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3071:                 &appenv({'environment.'.$envkey => $ckey});
 3072:                 return 'ok';
 3073:             } else {
 3074:                 return 
 3075:   'error: Count not permanently assign key, will need to be re-entered later.';
 3076: 	    }
 3077:         } else {
 3078:             return 'error: Could not assign key, try again later.';
 3079:         }
 3080:     } elsif (!$existing{$ckey}) {
 3081: # the key does not exist
 3082: 	return 'error: The key does not exist';
 3083:     } else {
 3084: # the key is somebody else's
 3085: 	return 'error: The key is already in use';
 3086:     }
 3087: }
 3088: 
 3089: # ------------------------------------------ put an additional comment on a key
 3090: 
 3091: sub comment_access_key {
 3092: #
 3093: # a valid key looks like uname:udom#comments
 3094: # comments are being appended
 3095: #
 3096:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3097:     $cdom=
 3098:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3099:     $cnum=
 3100:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3101:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3102:     if ($existing{$ckey}) {
 3103:         $existing{$ckey}.='; '.$logentry;
 3104: # ready to assign
 3105:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3106:                                                  $cdom,$cnum) eq 'ok') {
 3107: 	    return 'ok';
 3108:         } else {
 3109: 	    return 'error: Count not store comment.';
 3110:         }
 3111:     } else {
 3112: # the key does not exist
 3113: 	return 'error: The key does not exist';
 3114:     }
 3115: }
 3116: 
 3117: # ------------------------------------------------------ Generate a set of keys
 3118: 
 3119: sub generate_access_keys {
 3120:     my ($number,$cdom,$cnum,$logentry)=@_;
 3121:     $cdom=
 3122:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3123:     $cnum=
 3124:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3125:     unless (&allowed('mky',$cdom)) { return 0; }
 3126:     unless (($cdom) && ($cnum)) { return 0; }
 3127:     if ($number>10000) { return 0; }
 3128:     sleep(2); # make sure don't get same seed twice
 3129:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3130:     my $total=0;
 3131:     for (my $i=1;$i<=$number;$i++) {
 3132:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3133:                   sprintf("%lx",int(100000*rand)).'-'.
 3134:                   sprintf("%lx",int(100000*rand));
 3135:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3136:        $newkey=~s/0/h/g; # and also 0 and O
 3137:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3138:        if ($existing{$newkey}) {
 3139:            $i--;
 3140:        } else {
 3141: 	  if (&put('accesskeys',
 3142:               { $newkey => '# generated '.localtime().
 3143:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3144:                            '; '.$logentry },
 3145: 		   $cdom,$cnum) eq 'ok') {
 3146:               $total++;
 3147: 	  }
 3148:        }
 3149:     }
 3150:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3151:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3152:     return $total;
 3153: }
 3154: 
 3155: # ------------------------------------------------------- Validate an accesskey
 3156: 
 3157: sub validate_access_key {
 3158:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3159:     $cdom=
 3160:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3161:     $cnum=
 3162:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3163:     $udom=$env{'user.domain'} unless (defined($udom));
 3164:     $uname=$env{'user.name'} unless (defined($uname));
 3165:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3166:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3167: }
 3168: 
 3169: # ------------------------------------- Find the section of student in a course
 3170: sub devalidate_getsection_cache {
 3171:     my ($udom,$unam,$courseid)=@_;
 3172:     my $hashid="$udom:$unam:$courseid";
 3173:     &devalidate_cache_new('getsection',$hashid);
 3174: }
 3175: 
 3176: sub courseid_to_courseurl {
 3177:     my ($courseid) = @_;
 3178:     #already url style courseid
 3179:     return $courseid if ($courseid =~ m{^/});
 3180: 
 3181:     if (exists($env{'course.'.$courseid.'.num'})) {
 3182: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3183: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3184: 	return "/$cdom/$cnum";
 3185:     }
 3186: 
 3187:     my %courseinfo=&coursedescription($courseid);
 3188:     if (exists($courseinfo{'num'})) {
 3189: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3190:     }
 3191: 
 3192:     return undef;
 3193: }
 3194: 
 3195: sub getsection {
 3196:     my ($udom,$unam,$courseid)=@_;
 3197:     my $cachetime=1800;
 3198: 
 3199:     my $hashid="$udom:$unam:$courseid";
 3200:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3201:     if (defined($cached)) { return $result; }
 3202: 
 3203:     my %Pending; 
 3204:     my %Expired;
 3205:     #
 3206:     # Each role can either have not started yet (pending), be active, 
 3207:     #    or have expired.
 3208:     #
 3209:     # If there is an active role, we are done.
 3210:     #
 3211:     # If there is more than one role which has not started yet, 
 3212:     #     choose the one which will start sooner
 3213:     # If there is one role which has not started yet, return it.
 3214:     #
 3215:     # If there is more than one expired role, choose the one which ended last.
 3216:     # If there is a role which has expired, return it.
 3217:     #
 3218:     $courseid = &courseid_to_courseurl($courseid);
 3219:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3220:     foreach my $key (keys(%roleshash)) {
 3221:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3222:         my $section=$1;
 3223:         if ($key eq $courseid.'_st') { $section=''; }
 3224:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3225:         my $now=time;
 3226:         if (defined($end) && $end && ($now > $end)) {
 3227:             $Expired{$end}=$section;
 3228:             next;
 3229:         }
 3230:         if (defined($start) && $start && ($now < $start)) {
 3231:             $Pending{$start}=$section;
 3232:             next;
 3233:         }
 3234:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3235:     }
 3236:     #
 3237:     # Presumedly there will be few matching roles from the above
 3238:     # loop and the sorting time will be negligible.
 3239:     if (scalar(keys(%Pending))) {
 3240:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3241:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3242:     } 
 3243:     if (scalar(keys(%Expired))) {
 3244:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3245:         my $time = pop(@sorted);
 3246:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3247:     }
 3248:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3249: }
 3250: 
 3251: sub save_cache {
 3252:     &purge_remembered();
 3253:     #&Apache::loncommon::validate_page();
 3254:     undef(%env);
 3255:     undef($env_loaded);
 3256: }
 3257: 
 3258: my $to_remember=-1;
 3259: my %remembered;
 3260: my %accessed;
 3261: my $kicks=0;
 3262: my $hits=0;
 3263: sub make_key {
 3264:     my ($name,$id) = @_;
 3265:     if (length($id) > 65 
 3266: 	&& length(&escape($id)) > 200) {
 3267: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3268:     }
 3269:     return &escape($name.':'.$id);
 3270: }
 3271: 
 3272: sub devalidate_cache_new {
 3273:     my ($name,$id,$debug) = @_;
 3274:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3275:     my $remembered_id=$name.':'.$id;
 3276:     $id=&make_key($name,$id);
 3277:     $memcache->delete($id);
 3278:     delete($remembered{$remembered_id});
 3279:     delete($accessed{$remembered_id});
 3280: }
 3281: 
 3282: sub is_cached_new {
 3283:     my ($name,$id,$debug) = @_;
 3284:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3285:     if (exists($remembered{$remembered_id})) {
 3286: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3287: 	$accessed{$remembered_id}=[&gettimeofday()];
 3288: 	$hits++;
 3289: 	return ($remembered{$remembered_id},1);
 3290:     }
 3291:     $id=&make_key($name,$id);
 3292:     my $value = $memcache->get($id);
 3293:     if (!(defined($value))) {
 3294: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3295: 	return (undef,undef);
 3296:     }
 3297:     if ($value eq '__undef__') {
 3298: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3299: 	$value=undef;
 3300:     }
 3301:     &make_room($remembered_id,$value,$debug);
 3302:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3303:     return ($value,1);
 3304: }
 3305: 
 3306: sub do_cache_new {
 3307:     my ($name,$id,$value,$time,$debug) = @_;
 3308:     my $remembered_id=$name.':'.$id;
 3309:     $id=&make_key($name,$id);
 3310:     my $setvalue=$value;
 3311:     if (!defined($setvalue)) {
 3312: 	$setvalue='__undef__';
 3313:     }
 3314:     if (!defined($time) ) {
 3315: 	$time=600;
 3316:     }
 3317:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3318:     my $result = $memcache->set($id,$setvalue,$time);
 3319:     if (! $result) {
 3320: 	&logthis("caching of id -> $id  failed");
 3321: 	$memcache->disconnect_all();
 3322:     }
 3323:     # need to make a copy of $value
 3324:     &make_room($remembered_id,$value,$debug);
 3325:     return $value;
 3326: }
 3327: 
 3328: sub make_room {
 3329:     my ($remembered_id,$value,$debug)=@_;
 3330: 
 3331:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3332:                                     : $value;
 3333:     if ($to_remember<0) { return; }
 3334:     $accessed{$remembered_id}=[&gettimeofday()];
 3335:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3336:     my $to_kick;
 3337:     my $max_time=0;
 3338:     foreach my $other (keys(%accessed)) {
 3339: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3340: 	    $to_kick=$other;
 3341: 	    $max_time=&tv_interval($accessed{$other});
 3342: 	}
 3343:     }
 3344:     delete($remembered{$to_kick});
 3345:     delete($accessed{$to_kick});
 3346:     $kicks++;
 3347:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3348:     return;
 3349: }
 3350: 
 3351: sub purge_remembered {
 3352:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3353:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3354:     undef(%remembered);
 3355:     undef(%accessed);
 3356: }
 3357: # ------------------------------------- Read an entry from a user's environment
 3358: 
 3359: sub userenvironment {
 3360:     my ($udom,$unam,@what)=@_;
 3361:     my $items;
 3362:     foreach my $item (@what) {
 3363:         $items.=&escape($item).'&';
 3364:     }
 3365:     $items=~s/\&$//;
 3366:     my %returnhash=();
 3367:     my $uhome = &homeserver($unam,$udom);
 3368:     unless ($uhome eq 'no_host') {
 3369:         my @answer=split(/\&/, 
 3370:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3371:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3372:             return %returnhash;
 3373:         }
 3374:         my $i;
 3375:         for ($i=0;$i<=$#what;$i++) {
 3376: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3377:         }
 3378:     }
 3379:     return %returnhash;
 3380: }
 3381: 
 3382: # ---------------------------------------------------------- Get a studentphoto
 3383: sub studentphoto {
 3384:     my ($udom,$unam,$ext) = @_;
 3385:     my $home=&homeserver($unam,$udom);
 3386:     if (defined($env{'request.course.id'})) {
 3387:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3388:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3389:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3390:             } else {
 3391:                 my ($result,$perm_reqd)=
 3392: 		    &auto_photo_permission($unam,$udom);
 3393:                 if ($result eq 'ok') {
 3394:                     if (!($perm_reqd eq 'yes')) {
 3395:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3396:                     }
 3397:                 }
 3398:             }
 3399:         }
 3400:     } else {
 3401:         my ($result,$perm_reqd) = 
 3402: 	    &auto_photo_permission($unam,$udom);
 3403:         if ($result eq 'ok') {
 3404:             if (!($perm_reqd eq 'yes')) {
 3405:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3406:             }
 3407:         }
 3408:     }
 3409:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3410: }
 3411: 
 3412: sub retrievestudentphoto {
 3413:     my ($udom,$unam,$ext,$type) = @_;
 3414:     my $home=&homeserver($unam,$udom);
 3415:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3416:     if ($ret eq 'ok') {
 3417:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3418:         if ($type eq 'thumbnail') {
 3419:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3420:         }
 3421:         my $tokenurl=&tokenwrapper($url);
 3422:         return $tokenurl;
 3423:     } else {
 3424:         if ($type eq 'thumbnail') {
 3425:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3426:         } else { 
 3427:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3428:         }
 3429:     }
 3430: }
 3431: 
 3432: # -------------------------------------------------------------------- New chat
 3433: 
 3434: sub chatsend {
 3435:     my ($newentry,$anon,$group)=@_;
 3436:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3437:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3438:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3439:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3440: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3441: 		   &escape($newentry)).':'.$group,$chome);
 3442: }
 3443: 
 3444: # ------------------------------------------ Find current version of a resource
 3445: 
 3446: sub getversion {
 3447:     my $fname=&clutter(shift);
 3448:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3449:     return &currentversion(&filelocation('',$fname));
 3450: }
 3451: 
 3452: sub currentversion {
 3453:     my $fname=shift;
 3454:     my $author=$fname;
 3455:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3456:     my ($udom,$uname)=split(/\//,$author);
 3457:     my $home=&homeserver($uname,$udom);
 3458:     if ($home eq 'no_host') { 
 3459:         return -1; 
 3460:     }
 3461:     my $answer=&reply("currentversion:$fname",$home);
 3462:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3463: 	return -1;
 3464:     }
 3465:     return $answer;
 3466: }
 3467: 
 3468: #
 3469: # Return special version number of resource if set by override, empty otherwise
 3470: #
 3471: sub usedversion {
 3472:     my $fname=shift;
 3473:     unless ($fname) { $fname=$env{'request.uri'}; }
 3474:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3475:     if ($urlversion) { return $urlversion; }
 3476:     return '';
 3477: }
 3478: 
 3479: # ----------------------------- Subscribe to a resource, return URL if possible
 3480: 
 3481: sub subscribe {
 3482:     my $fname=shift;
 3483:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3484:     $fname=~s/[\n\r]//g;
 3485:     my $author=$fname;
 3486:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3487:     my ($udom,$uname)=split(/\//,$author);
 3488:     my $home=homeserver($uname,$udom);
 3489:     if ($home eq 'no_host') {
 3490:         return 'not_found';
 3491:     }
 3492:     my $answer=reply("sub:$fname",$home);
 3493:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3494: 	$answer.=' by '.$home;
 3495:     }
 3496:     return $answer;
 3497: }
 3498:     
 3499: # -------------------------------------------------------------- Replicate file
 3500: 
 3501: sub repcopy {
 3502:     my $filename=shift;
 3503:     $filename=~s/\/+/\//g;
 3504:     my $londocroot = $perlvar{'lonDocRoot'};
 3505:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3506:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3507:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3508: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3509: 	return &repcopy_userfile($filename);
 3510:     }
 3511:     $filename=~s/[\n\r]//g;
 3512:     my $transname="$filename.in.transfer";
 3513: # FIXME: this should flock
 3514:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3515:     my $remoteurl=subscribe($filename);
 3516:     if ($remoteurl =~ /^con_lost by/) {
 3517: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3518:            return 'unavailable';
 3519:     } elsif ($remoteurl eq 'not_found') {
 3520: 	   #&logthis("Subscribe returned not_found: $filename");
 3521: 	   return 'not_found';
 3522:     } elsif ($remoteurl =~ /^rejected by/) {
 3523: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3524:            return 'forbidden';
 3525:     } elsif ($remoteurl eq 'directory') {
 3526:            return 'ok';
 3527:     } else {
 3528:         my $author=$filename;
 3529:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3530:         my ($udom,$uname)=split(/\//,$author);
 3531:         my $home=homeserver($uname,$udom);
 3532:         unless ($home eq $perlvar{'lonHostID'}) {
 3533:            my @parts=split(/\//,$filename);
 3534:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3535:            if ($path ne "$londocroot/res") {
 3536:                &logthis("Malconfiguration for replication: $filename");
 3537: 	       return 'bad_request';
 3538:            }
 3539:            my $count;
 3540:            for ($count=5;$count<$#parts;$count++) {
 3541:                $path.="/$parts[$count]";
 3542:                if ((-e $path)!=1) {
 3543: 		   mkdir($path,0777);
 3544:                }
 3545:            }
 3546:            my $request=new HTTP::Request('GET',"$remoteurl");
 3547:            my $response;
 3548:            if ($remoteurl =~ m{/raw/}) {
 3549:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3550:            } else {
 3551:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3552:            }
 3553:            if ($response->is_error()) {
 3554: 	       unlink($transname);
 3555:                my $message=$response->status_line;
 3556:                &logthis("<font color=\"blue\">WARNING:"
 3557:                        ." LWP get: $message: $filename</font>");
 3558:                return 'unavailable';
 3559:            } else {
 3560: 	       if ($remoteurl!~/\.meta$/) {
 3561:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3562:                   my $mresponse;
 3563:                   if ($remoteurl =~ m{/raw/}) {
 3564:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3565:                   } else {
 3566:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3567:                   }
 3568:                   if ($mresponse->is_error()) {
 3569: 		      unlink($filename.'.meta');
 3570:                       &logthis(
 3571:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3572:                   }
 3573: 	       }
 3574:                rename($transname,$filename);
 3575:                return 'ok';
 3576:            }
 3577:        }
 3578:     }
 3579: }
 3580: 
 3581: # ------------------------------------------------- Unsubscribe from a resource
 3582: 
 3583: sub unsubscribe {
 3584:     my ($fname) = @_;
 3585:     my $answer;
 3586:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3587:     $fname=~s/[\n\r]//g;
 3588:     my $author=$fname;
 3589:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3590:     my ($udom,$uname)=split(/\//,$author);
 3591:     my $home=homeserver($uname,$udom);
 3592:     if ($home eq 'no_host') {
 3593:         $answer = 'no_host';
 3594:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3595:         $answer = 'home';
 3596:     } else {
 3597:         my $defdom = $perlvar{'lonDefDomain'};
 3598:         if (&will_trust('content',$defdom,$udom)) {
 3599:             $answer = reply("unsub:$fname",$home);
 3600:         } else {
 3601:             $answer = 'untrusted';
 3602:         }
 3603:     }
 3604:     return $answer;
 3605: }
 3606: 
 3607: # ------------------------------------------------ Get server side include body
 3608: sub ssi_body {
 3609:     my ($filelink,%form)=@_;
 3610:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3611:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3612:     }
 3613:     my $output='';
 3614:     my $response;
 3615:     if ($filelink=~/^https?\:/) {
 3616:        ($output,$response)=&externalssi($filelink);
 3617:     } else {
 3618:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3619:        $filelink .= 'inhibitmenu=yes';
 3620:        ($output,$response)=&ssi($filelink,%form);
 3621:     }
 3622:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3623:     $output=~s/^.*?\<body[^\>]*\>//si;
 3624:     $output=~s/\<\/body\s*\>.*?$//si;
 3625:     if (wantarray) {
 3626:         return ($output, $response);
 3627:     } else {
 3628:         return $output;
 3629:     }
 3630: }
 3631: 
 3632: # --------------------------------------------------------- Server Side Include
 3633: 
 3634: sub absolute_url {
 3635:     my ($host_name,$unalias,$keep_proto) = @_;
 3636:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3637:     if ($host_name eq '') {
 3638: 	$host_name = $ENV{'SERVER_NAME'};
 3639:     }
 3640:     if ($unalias) {
 3641:         my $alias = &get_proxy_alias();
 3642:         if ($alias eq $host_name) {
 3643:             my $lonhost = $perlvar{'lonHostID'};
 3644:             my $hostname = &hostname($lonhost);
 3645:             my $lcproto; 
 3646:             if (($keep_proto) || ($hostname eq '')) {
 3647:                 $lcproto = $protocol;
 3648:             } else {
 3649:                 $lcproto = $protocol{$lonhost};
 3650:                 $lcproto = 'http' if ($lcproto ne 'https');
 3651:                 $lcproto .= '://';
 3652:             }
 3653:             unless ($hostname eq '') {
 3654:                 return $lcproto.$hostname;
 3655:             }
 3656:         }
 3657:     }
 3658:     return $protocol.$host_name;
 3659: }
 3660: 
 3661: #
 3662: #   Server side include.
 3663: # Parameters:
 3664: #  fn     Possibly encrypted resource name/id.
 3665: #  form   Hash that describes how the rendering should be done
 3666: #         and other things.
 3667: # Returns:
 3668: #   Scalar context: The content of the response.
 3669: #   Array context:  2 element list of the content and the full response object.
 3670: #     
 3671: sub ssi {
 3672: 
 3673:     my ($fn,%form)=@_;
 3674:     my ($host,$request,$response);
 3675:     $host = &absolute_url('',1);
 3676: 
 3677:     $form{'no_update_last_known'}=1;
 3678:     &Apache::lonenc::check_encrypt(\$fn);
 3679:     if (%form) {
 3680:       $request=new HTTP::Request('POST',$host.$fn);
 3681:       $request->content(join('&',map { 
 3682:             my $name = escape($_);
 3683:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3684:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3685:             : &escape($form{$_}) );    
 3686:         } keys(%form)));
 3687:     } else {
 3688:       $request=new HTTP::Request('GET',$host.$fn);
 3689:     }
 3690: 
 3691:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3692:     my $lonhost = $perlvar{'lonHostID'};
 3693:     my $islocal;
 3694:     if (($env{'request.course.id'}) &&
 3695:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3696:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3697:         ($form{'grade_symb'} ne '') &&
 3698:         (&allowed('mgr',$env{'request.course.id'}.
 3699:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3700:         $islocal = 1;
 3701:     }
 3702:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3703:                                              '','','',$islocal);
 3704: 
 3705:     if (wantarray) {
 3706: 	return ($response->content, $response);
 3707:     } else {
 3708: 	return $response->content;
 3709:     }
 3710: }
 3711: 
 3712: sub externalssi {
 3713:     my ($url)=@_;
 3714:     my $request=new HTTP::Request('GET',$url);
 3715:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3716:     if (wantarray) {
 3717:         return ($response->content, $response);
 3718:     } else {
 3719:         return $response->content;
 3720:     }
 3721: }
 3722: 
 3723: 
 3724: # If the local copy of a replicated resource is outdated, trigger a  
 3725: # connection from the homeserver to flush the delayed queue. If no update 
 3726: # happens, remove local copies of outdated resource (and corresponding
 3727: # metadata file).
 3728: 
 3729: sub remove_stale_resfile {
 3730:     my ($url) = @_;
 3731:     my $removed;
 3732:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3733:         my $audom = $1;
 3734:         my $auname = $2;
 3735:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3736:             my $homeserver = &homeserver($auname,$audom);
 3737:             unless (($homeserver eq 'no_host') ||
 3738:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3739:                 my $fname = &filelocation('',$url);
 3740:                 if (-e $fname) {
 3741:                     my $hostname = &hostname($homeserver);
 3742:                     if ($hostname) {
 3743:                         my $protocol = $protocol{$homeserver};
 3744:                         $protocol = 'http' if ($protocol ne 'https');
 3745:                         my $uri = &declutter($url);
 3746:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3747:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3748:                         if ($response->is_success()) {
 3749:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3750:                             my $locmodtime = (stat($fname))[9];
 3751:                             if ($locmodtime < $remmodtime) {
 3752:                                 my $stale;
 3753:                                 my $answer = &reply('pong',$homeserver);
 3754:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3755:                                     sleep(0.2);
 3756:                                     $locmodtime = (stat($fname))[9];
 3757:                                     if ($locmodtime < $remmodtime) {
 3758:                                         my $posstransfer = $fname.'.in.transfer';
 3759:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3760:                                             $removed = 1;
 3761:                                         } else {
 3762:                                             $stale = 1;
 3763:                                         }
 3764:                                     } else {
 3765:                                         $removed = 1;
 3766:                                     }
 3767:                                 } else {
 3768:                                     $stale = 1;
 3769:                                 }
 3770:                                 if ($stale) {
 3771:                                     if (unlink($fname)) {
 3772:                                         if ($uri!~/\.meta$/) {
 3773:                                             if (-e $fname.'.meta') {
 3774:                                                 unlink($fname.'.meta');
 3775:                                             }
 3776:                                         }
 3777:                                         my $unsubresult = &unsubscribe($fname);
 3778:                                         unless ($unsubresult eq 'ok') {
 3779:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3780:                                         }
 3781:                                         $removed = 1;
 3782:                                     }
 3783:                                 }
 3784:                             }
 3785:                         }
 3786:                     }
 3787:                 }
 3788:             }
 3789:         }
 3790:     }
 3791:     return $removed;
 3792: }
 3793: 
 3794: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3795: 
 3796: sub allowuploaded {
 3797:     my ($srcurl,$url)=@_;
 3798:     $url=&clutter(&declutter($url));
 3799:     my $dir=$url;
 3800:     $dir=~s/\/[^\/]+$//;
 3801:     my %httpref=();
 3802:     my $httpurl=&hreflocation('',$url);
 3803:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3804:     &Apache::lonnet::appenv(\%httpref);
 3805: }
 3806: 
 3807: #
 3808: # Determine if the current user should be able to edit a particular resource,
 3809: # when viewing in course context.
 3810: # (a) When viewing resource used to determine if "Edit" item is included in 
 3811: #     Functions.
 3812: # (b) When displaying folder contents in course editor, used to determine if
 3813: #     "Edit" link will be displayed alongside resource.
 3814: #
 3815: #  input: six args -- filename (decluttered), course number, course domain,
 3816: #                   url, symb (if registered) and group (if this is a group
 3817: #                   item -- e.g., bulletin board, group page etc.).
 3818: #  output: array of five scalars -- 
 3819: #          $cfile -- url for file editing if editable on current server
 3820: #          $home -- homeserver of resource (i.e., for author if published,
 3821: #                                           or course if uploaded.).
 3822: #          $switchserver --  1 if server switch will be needed.
 3823: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3824: #          $forceview -- 1 if icon/link should be to go to view mode
 3825: #
 3826: 
 3827: sub can_edit_resource {
 3828:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3829:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3830: #
 3831: # For aboutme pages user can only edit his/her own.
 3832: #
 3833:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3834:         my ($sdom,$sname) = ($1,$2);
 3835:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3836:             $home = $env{'user.home'};
 3837:             $cfile = $resurl;
 3838:             if ($env{'form.forceedit'}) {
 3839:                 $forceview = 1;
 3840:             } else {
 3841:                 $forceedit = 1;
 3842:             }
 3843:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3844:         } else {
 3845:             return;
 3846:         }
 3847:     }
 3848: 
 3849:     if ($env{'request.course.id'}) {
 3850:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3851:         if ($group ne '') {
 3852: # if this is a group homepage or group bulletin board, check group privs
 3853:             my $allowed = 0;
 3854:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3855:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3856:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3857:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3858:                     $allowed = 1;
 3859:                 }
 3860:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3861:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3862:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3863:                     $allowed = 1;
 3864:                 }
 3865:             }
 3866:             if ($allowed) {
 3867:                 $home=&homeserver($cnum,$cdom);
 3868:                 if ($env{'form.forceedit'}) {
 3869:                     $forceview = 1;
 3870:                 } else {
 3871:                     $forceedit = 1;
 3872:                 }
 3873:                 $cfile = $resurl;
 3874:             } else {
 3875:                 return;
 3876:             }
 3877:         } else {
 3878:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3879:                 unless (&allowed('opa',$env{'request.course.id'})) {
 3880:                     return;
 3881:                 }
 3882:             } elsif (!$crsedit) {
 3883:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 3884: #
 3885: # No edit allowed where CC has switched to student role.
 3886: #
 3887:                     return;
 3888:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 3889:                          ($resurl =~ m{^/res/lib/templates/})) {
 3890:                     return;
 3891:                 }
 3892:             }
 3893:         }
 3894:     }
 3895: 
 3896:     if ($file ne '') {
 3897:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3898:             if (&is_course_upload($file,$cnum,$cdom)) {
 3899:                 $uploaded = 1;
 3900:                 $incourse = 1;
 3901:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3902:                     $cfile = &hreflocation('',$file);
 3903:                     if ($env{'form.forceedit'}) {
 3904:                         $forceview = 1;
 3905:                     } else {
 3906:                         $forceedit = 1;
 3907:                     }
 3908:                 }
 3909:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3910:                 $incourse = 1;
 3911:                 if ($env{'form.forceedit'}) {
 3912:                     $forceview = 1;
 3913:                 } else {
 3914:                     $forceedit = 1;
 3915:                 }
 3916:                 $cfile = $resurl;
 3917:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3918:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3919:                     $incourse = 1;
 3920:                     if ($env{'form.forceedit'}) {
 3921:                         $forceview = 1;
 3922:                     } else {
 3923:                         $forceedit = 1;
 3924:                     }
 3925:                     $cfile = $resurl;
 3926:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3927:                     $incourse = 1;
 3928:                     $cfile = $resurl.'/smpedit';
 3929:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3930:                     $incourse = 1;
 3931:                     if ($env{'form.forceedit'}) {
 3932:                         $forceview = 1;
 3933:                     } else {
 3934:                         $forceedit = 1;
 3935:                     }
 3936:                     $cfile = $resurl;
 3937:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3938:                     my ($map,$id,$res) = &decode_symb($symb);
 3939:                     if ($map =~ /\.page$/) {
 3940:                         $incourse = 1;
 3941:                         if ($env{'form.forceedit'}) {
 3942:                             $forceview = 1;
 3943:                             $cfile = $map;
 3944:                         } else {
 3945:                             $forceedit = 1;
 3946:                             $cfile =  '/adm/wrapper'.$resurl;
 3947:                         }
 3948:                     }
 3949:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3950:                     $incourse = 1;
 3951:                     if ($env{'form.forceedit'}) {
 3952:                         $forceview = 1;
 3953:                     } else {
 3954:                         $forceedit = 1;
 3955:                     }
 3956:                     $cfile = $resurl;
 3957:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3958:                     $incourse = 1;
 3959:                     if ($env{'form.forceedit'}) {
 3960:                         $forceview = 1;
 3961:                     } else {
 3962:                         $forceedit = 1;
 3963:                     }
 3964:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3965:                 }
 3966:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3967:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3968:                 if (&is_on_map($template)) { 
 3969:                     $incourse = 1;
 3970:                     $forceview = 1;
 3971:                     $cfile = $template;
 3972:                 }
 3973:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3974:                 $incourse = 1;
 3975:                 if ($env{'form.forceedit'}) {
 3976:                     $forceview = 1;
 3977:                 } else {
 3978:                     $forceedit = 1;
 3979:                 }
 3980:                 $cfile = $resurl;
 3981:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3982:                 $incourse = 1;
 3983:                 if ($env{'form.forceedit'}) {
 3984:                     $forceview = 1;
 3985:                 } else {
 3986:                     $forceedit = 1;
 3987:                 }
 3988:                 $cfile = $resurl;
 3989:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3990:                 $incourse = 1;
 3991:                 $forceview = 1;
 3992:                 if ($symb) {
 3993:                     my ($map,$id,$res)=&decode_symb($symb);
 3994:                     $env{'request.symb'} = $symb;
 3995:                     $cfile = &clutter($res);
 3996:                 } else {
 3997:                     $cfile = $env{'form.suppurl'};
 3998:                     my $escfile = &unescape($cfile);
 3999:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4000:                         $cfile = '/adm/wrapper'.$escfile;
 4001:                     } else {
 4002:                         $escfile =~ s{^http://}{};
 4003:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4004:                     }
 4005:                 }
 4006:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4007:                 if ($env{'form.forceedit'}) {
 4008:                     $forceview = 1;
 4009:                 } else {
 4010:                     $forceedit = 1;
 4011:                 }
 4012:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4013:             }
 4014:         }
 4015:         if ($uploaded || $incourse) {
 4016:             $home=&homeserver($cnum,$cdom);
 4017:         } elsif ($file !~ m{/$}) {
 4018:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4019:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4020:             # Check that the user has permission to edit this resource
 4021:             my $setpriv = 1;
 4022:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4023:             if (defined($cfudom)) {
 4024:                 $home=&homeserver($cfuname,$cfudom);
 4025:                 $cfile=$file;
 4026:             }
 4027:         }
 4028:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4029:             (($home ne '') && ($home ne 'no_host'))) {
 4030:             my @ids=&current_machine_ids();
 4031:             unless (grep(/^\Q$home\E$/,@ids)) {
 4032:                 $switchserver=1;
 4033:             }
 4034:         }
 4035:     }
 4036:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4037: }
 4038: 
 4039: sub is_course_upload {
 4040:     my ($file,$cnum,$cdom) = @_;
 4041:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4042:     $uploadpath =~ s{^\/}{};
 4043:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4044:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4045:         return 1;
 4046:     }
 4047:     return;
 4048: }
 4049: 
 4050: sub in_course {
 4051:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4052:     if ($hideprivileged) {
 4053:         my $skipuser;
 4054:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4055:         my @possdoms = ($cdom);  
 4056:         if ($coursehash{'checkforpriv'}) { 
 4057:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4058:         }
 4059:         if (&privileged($uname,$udom,\@possdoms)) {
 4060:             $skipuser = 1;
 4061:             if ($coursehash{'nothideprivileged'}) {
 4062:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4063:                     my $user;
 4064:                     if ($item =~ /:/) {
 4065:                         $user = $item;
 4066:                     } else {
 4067:                         $user = join(':',split(/[\@]/,$item));
 4068:                     }
 4069:                     if ($user eq $uname.':'.$udom) {
 4070:                         undef($skipuser);
 4071:                         last;
 4072:                     }
 4073:                 }
 4074:             }
 4075:             if ($skipuser) {
 4076:                 return 0;
 4077:             }
 4078:         }
 4079:     }
 4080:     $type ||= 'any';
 4081:     if (!defined($cdom) || !defined($cnum)) {
 4082:         my $cid  = $env{'request.course.id'};
 4083:         $cdom = $env{'course.'.$cid.'.domain'};
 4084:         $cnum = $env{'course.'.$cid.'.num'};
 4085:     }
 4086:     my $typesref;
 4087:     if (($type eq 'any') || ($type eq 'all')) {
 4088:         $typesref = ['active','previous','future'];
 4089:     } elsif ($type eq 'previous' || $type eq 'future') {
 4090:         $typesref = [$type];
 4091:     }
 4092:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4093:                               $typesref,undef,[$cdom]);
 4094:     my ($tmp) = keys(%roles);
 4095:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4096:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4097:     if (@course_roles > 0) {
 4098:         return 1;
 4099:     }
 4100:     return 0;
 4101: }
 4102: 
 4103: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4104: # input: action, courseID, current domain, intended
 4105: #        path to file, source of file, instruction to parse file for objects,
 4106: #        ref to hash for embedded objects,
 4107: #        ref to hash for codebase of java objects.
 4108: #        reference to scalar to accommodate mime type determined
 4109: #          from File::MMagic if $parser = parse.
 4110: #
 4111: # output: url to file (if action was uploaddoc), 
 4112: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4113: #
 4114: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4115: # course.
 4116: #
 4117: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4118: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4119: #          course's home server.
 4120: #
 4121: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4122: #          be copied from $source (current location) to 
 4123: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4124: #         and will then be copied to
 4125: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4126: #         course's home server.
 4127: #
 4128: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4129: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4130: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4131: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4132: #         in course's home server.
 4133: #
 4134: 
 4135: sub process_coursefile {
 4136:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4137:         $mimetype)=@_;
 4138:     my $fetchresult;
 4139:     my $home=&homeserver($docuname,$docudom);
 4140:     if ($action eq 'propagate') {
 4141:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4142: 			     $home);
 4143:     } else {
 4144:         my $fpath = '';
 4145:         my $fname = $file;
 4146:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4147:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4148:         my $filepath = &build_filepath($fpath);
 4149:         if ($action eq 'copy') {
 4150:             if ($source eq '') {
 4151:                 $fetchresult = 'no source file';
 4152:                 return $fetchresult;
 4153:             } else {
 4154:                 my $destination = $filepath.'/'.$fname;
 4155:                 rename($source,$destination);
 4156:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4157:                                  $home);
 4158:             }
 4159:         } elsif ($action eq 'uploaddoc') {
 4160:             open(my $fh,'>',$filepath.'/'.$fname);
 4161:             print $fh $env{'form.'.$source};
 4162:             close($fh);
 4163:             if ($parser eq 'parse') {
 4164:                 my $mm = new File::MMagic;
 4165:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4166:                 if ($type eq 'text/html') {
 4167:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4168:                     unless ($parse_result eq 'ok') {
 4169:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4170:                     }
 4171:                 }
 4172:                 if (ref($mimetype)) {
 4173:                     $$mimetype = $type;
 4174:                 } 
 4175:             }
 4176:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4177:                                  $home);
 4178:             if ($fetchresult eq 'ok') {
 4179:                 return '/uploaded/'.$fpath.'/'.$fname;
 4180:             } else {
 4181:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4182:                         ' to host '.$home.': '.$fetchresult);
 4183:                 return '/adm/notfound.html';
 4184:             }
 4185:         }
 4186:     }
 4187:     unless ( $fetchresult eq 'ok') {
 4188:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4189:              ' to host '.$home.': '.$fetchresult);
 4190:     }
 4191:     return $fetchresult;
 4192: }
 4193: 
 4194: sub build_filepath {
 4195:     my ($fpath) = @_;
 4196:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4197:     unless ($fpath eq '') {
 4198:         my @parts=split('/',$fpath);
 4199:         foreach my $part (@parts) {
 4200:             $filepath.= '/'.$part;
 4201:             if ((-e $filepath)!=1) {
 4202:                 mkdir($filepath,0777);
 4203:             }
 4204:         }
 4205:     }
 4206:     return $filepath;
 4207: }
 4208: 
 4209: sub store_edited_file {
 4210:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4211:     my $file = $primary_url;
 4212:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4213:     my $fpath = '';
 4214:     my $fname = $file;
 4215:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4216:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4217:     my $filepath = &build_filepath($fpath);
 4218:     open(my $fh,'>',$filepath.'/'.$fname);
 4219:     print $fh $content;
 4220:     close($fh);
 4221:     my $home=&homeserver($docuname,$docudom);
 4222:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4223: 			  $home);
 4224:     if ($$fetchresult eq 'ok') {
 4225:         return '/uploaded/'.$fpath.'/'.$fname;
 4226:     } else {
 4227:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4228: 		 ' to host '.$home.': '.$$fetchresult);
 4229:         return '/adm/notfound.html';
 4230:     }
 4231: }
 4232: 
 4233: sub clean_filename {
 4234:     my ($fname,$args)=@_;
 4235: # Replace Windows backslashes by forward slashes
 4236:     $fname=~s/\\/\//g;
 4237:     if (!$args->{'keep_path'}) {
 4238:         # Get rid of everything but the actual filename
 4239: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4240:     }
 4241: # Replace spaces by underscores
 4242:     $fname=~s/\s+/\_/g;
 4243: # Transliterate non-ascii text to ascii
 4244:     my $lang = &Apache::lonlocal::current_language();
 4245:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4246: # Replace all other weird characters by nothing
 4247:     $fname=~s{[^/\w\.\-]}{}g;
 4248: # Replace all .\d. sequences with _\d. so they no longer look like version
 4249: # numbers
 4250:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4251: # Replace three or more adjacent underscores with one for consistency 
 4252: # with loncfile::filename_check() so complete url can be extracted by
 4253: # lonnet::decode_symb()
 4254:     $fname=~s/_{3,}/_/g;
 4255:     return $fname;
 4256: }
 4257: 
 4258: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4259: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4260: # image with the same aspect ratio as the original, but with dimensions which do 
 4261: # not exceed $resizewidth and $resizeheight.
 4262:  
 4263: sub resizeImage {
 4264:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4265:     my $ima = Image::Magick->new;
 4266:     my $resized;
 4267:     if (-e $img_path) {
 4268:         $ima->Read($img_path);
 4269:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4270:             my $width = $ima->Get('width');
 4271:             my $height = $ima->Get('height');
 4272:             if ($width > $resizewidth) {
 4273: 	        my $factor = $width/$resizewidth;
 4274:                 my $newheight = $height/$factor;
 4275:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4276:                 $resized = 1;
 4277:             }
 4278:         }
 4279:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4280:             my $width = $ima->Get('width');
 4281:             my $height = $ima->Get('height');
 4282:             if ($height > $resizeheight) {
 4283:                 my $factor = $height/$resizeheight;
 4284:                 my $newwidth = $width/$factor;
 4285:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4286:                 $resized = 1;
 4287:             }
 4288:         }
 4289:         if ($resized) {
 4290:             $ima->Write($img_path);
 4291:         }
 4292:     }
 4293:     return;
 4294: }
 4295: 
 4296: # --------------- Take an uploaded file and put it into the userfiles directory
 4297: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4298: #                    the desired filename is in $env{"form.$formname.filename"}
 4299: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4300: #                                    canceloverwrite, scantron, toollogo  or ''.
 4301: #                   if 'coursedoc': upload to the current course
 4302: #                   if 'existingfile': write file to tmp/overwrites directory 
 4303: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4304: #                   $context is passed as argument to &finishuserfileupload
 4305: #        $subdir - directory in userfile to store the file into
 4306: #        $parser - instruction to parse file for objects ($parser = parse) or
 4307: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4308: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4309: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4310: #        $allfiles - reference to hash for embedded objects
 4311: #        $codebase - reference to hash for codebase of java objects
 4312: #        $destuname - username for permanent storage of uploaded file
 4313: #        $destudom - domain for permanaent storage of uploaded file
 4314: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4315: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4316: #        $resizewidth - width (pixels) to which to resize uploaded image
 4317: #        $resizeheight - height (pixels) to which to resize uploaded image
 4318: #        $mimetype - reference to scalar to accommodate mime type determined
 4319: #                    from File::MMagic.
 4320: # 
 4321: # output: url of file in userspace, or error: <message> 
 4322: #             or /adm/notfound.html if failure to upload occurse
 4323: 
 4324: sub userfileupload {
 4325:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4326:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4327:     if (!defined($subdir)) { $subdir='unknown'; }
 4328:     my $fname=$env{'form.'.$formname.'.filename'};
 4329:     $fname=&clean_filename($fname);
 4330:     # See if there is anything left
 4331:     unless ($fname) { return 'error: no uploaded file'; }
 4332:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4333:     if ($fname =~ /^\./) {
 4334:         my ($s,$usec) = &gettimeofday();
 4335:         while (length($usec) < 6) {
 4336:             $usec = '0'.$usec;
 4337:         }
 4338:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4339:     }
 4340:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4341:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4342:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4343:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4344:         my $now = time;
 4345:         my $filepath;
 4346:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4347:              $filepath = 'tmp/helprequests/'.$now;
 4348:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4349:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4350:                          '_'.$env{'user.domain'}.'/pending';
 4351:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4352:             my ($docuname,$docudom);
 4353:             if ($destudom =~ /^$match_domain$/) {
 4354:                 $docudom = $destudom;
 4355:             } else {
 4356:                 $docudom = $env{'user.domain'};
 4357:             }
 4358:             if ($destuname =~ /^$match_username$/) {
 4359:                 $docuname = $destuname;
 4360:             } else {
 4361:                 $docuname = $env{'user.name'};
 4362:             }
 4363:             if (exists($env{'form.group'})) {
 4364:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4365:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4366:             }
 4367:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4368:             if ($context eq 'canceloverwrite') {
 4369:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4370:                 if (-e  $tempfile) {
 4371:                     my @info = stat($tempfile);
 4372:                     if ($info[9] eq $env{'form.timestamp'}) {
 4373:                         unlink($tempfile);
 4374:                     }
 4375:                 }
 4376:                 return;
 4377:             }
 4378:         }
 4379:         # Create the directory if not present
 4380:         my @parts=split(/\//,$filepath);
 4381:         my $fullpath = $perlvar{'lonDaemons'};
 4382:         for (my $i=0;$i<@parts;$i++) {
 4383:             $fullpath .= '/'.$parts[$i];
 4384:             if ((-e $fullpath)!=1) {
 4385:                 mkdir($fullpath,0777);
 4386:             }
 4387:         }
 4388:         open(my $fh,'>',$fullpath.'/'.$fname);
 4389:         print $fh $env{'form.'.$formname};
 4390:         close($fh);
 4391:         if ($context eq 'existingfile') {
 4392:             my @info = stat($fullpath.'/'.$fname);
 4393:             return ($fullpath.'/'.$fname,$info[9]);
 4394:         } else {
 4395:             return $fullpath.'/'.$fname;
 4396:         }
 4397:     }
 4398:     if ($subdir eq 'scantron') {
 4399:         $fname = 'scantron_orig_'.$fname;
 4400:     } else {
 4401:         $fname="$subdir/$fname";
 4402:     }
 4403:     if ($context eq 'coursedoc') {
 4404: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4405: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4406:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4407:             return &finishuserfileupload($docuname,$docudom,
 4408: 					 $formname,$fname,$parser,$allfiles,
 4409: 					 $codebase,$thumbwidth,$thumbheight,
 4410:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4411:         } else {
 4412:             if ($env{'form.folder'}) {
 4413:                 $fname=$env{'form.folder'}.'/'.$fname;
 4414:             }
 4415:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4416: 				       $fname,$formname,$parser,
 4417: 				       $allfiles,$codebase,$mimetype);
 4418:         }
 4419:     } elsif (defined($destuname)) {
 4420:         my $docuname=$destuname;
 4421:         my $docudom=$destudom;
 4422: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4423: 				     $parser,$allfiles,$codebase,
 4424:                                      $thumbwidth,$thumbheight,
 4425:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4426:     } else {
 4427:         my $docuname=$env{'user.name'};
 4428:         my $docudom=$env{'user.domain'};
 4429:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4430:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4431:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4432:         }
 4433: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4434: 				     $parser,$allfiles,$codebase,
 4435:                                      $thumbwidth,$thumbheight,
 4436:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4437:     }
 4438: }
 4439: 
 4440: sub finishuserfileupload {
 4441:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4442:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4443:     my $path=$docudom.'/'.$docuname.'/';
 4444:     my $filepath=$perlvar{'lonDocRoot'};
 4445:   
 4446:     my ($fnamepath,$file,$fetchthumb);
 4447:     $file=$fname;
 4448:     if ($fname=~m|/|) {
 4449:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4450: 	$path.=$fnamepath.'/';
 4451:     }
 4452:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4453:     my $count;
 4454:     for ($count=4;$count<=$#parts;$count++) {
 4455:         $filepath.="/$parts[$count]";
 4456:         if ((-e $filepath)!=1) {
 4457: 	    mkdir($filepath,0777);
 4458:         }
 4459:     }
 4460: 
 4461: # Save the file
 4462:     {
 4463: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4464: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4465: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4466: 	    return '/adm/notfound.html';
 4467: 	}
 4468:         if ($context eq 'overwrite') {
 4469:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4470:             my $target = $filepath.'/'.$file;
 4471:             if (-e $source) {
 4472:                 my @info = stat($source);
 4473:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4474:                     unless (&File::Copy::move($source,$target)) {
 4475:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4476:                         return "Moving from $source failed";
 4477:                     }
 4478:                 } else {
 4479:                     return "Temporary file: $source had unexpected date/time for last modification";
 4480:                 }
 4481:             } else {
 4482:                 return "Temporary file: $source missing";
 4483:             }
 4484:         } elsif (!print FH ($env{'form.'.$formname})) {
 4485: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4486: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4487: 	    return '/adm/notfound.html';
 4488: 	}
 4489: 	close(FH);
 4490:         if ($resizewidth && $resizeheight) {
 4491:             my $mm = new File::MMagic;
 4492:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4493:             if ($mime_type =~ m{^image/}) {
 4494: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4495:             }  
 4496: 	}
 4497:     }
 4498:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4499:         if (ref($mimetype)) {
 4500:             if ($$mimetype eq '') {
 4501:                 my $mm = new File::MMagic;
 4502:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4503:                 $$mimetype = $type;
 4504:             }
 4505:         }
 4506:     }
 4507:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4508:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4509:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4510:                                                        $allfiles,$codebase);
 4511:             unless ($parse_result eq 'ok') {
 4512:                 &logthis('Failed to parse '.$filepath.$file.
 4513: 	   	         ' for embedded media: '.$parse_result); 
 4514:             }
 4515:         }
 4516:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4517:         my $format = $env{'form.scantron_format'};
 4518:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4519:     }
 4520:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4521:         my $input = $filepath.'/'.$file;
 4522:         my $output = $filepath.'/'.'tn-'.$file;
 4523:         my $makethumb; 
 4524:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4525:         if ($context eq 'toollogo') {
 4526:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4527:             if ($fullwidth ne '' && $fullheight ne '') {
 4528:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4529:                     $makethumb = 1;
 4530:                 }
 4531:             }
 4532:         } else {
 4533:             $makethumb = 1;
 4534:         }
 4535:         if ($makethumb) {
 4536:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4537:             system({$args[0]} @args);
 4538:             if (-e $filepath.'/'.'tn-'.$file) {
 4539:                 $fetchthumb  = 1; 
 4540:             }
 4541:         }
 4542:     }
 4543:  
 4544: # Notify homeserver to grep it
 4545: #
 4546:     my $docuhome=&homeserver($docuname,$docudom);	
 4547:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4548:     if ($fetchresult eq 'ok') {
 4549:         if ($fetchthumb) {
 4550:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4551:             if ($thumbresult ne 'ok') {
 4552:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4553:                          $docuhome.': '.$thumbresult);
 4554:             }
 4555:         }
 4556: #
 4557: # Return the URL to it
 4558:         return '/uploaded/'.$path.$file;
 4559:     } else {
 4560:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4561: 		 ': '.$fetchresult);
 4562:         return '/adm/notfound.html';
 4563:     }
 4564: }
 4565: 
 4566: sub extract_embedded_items {
 4567:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4568:     my @state = ();
 4569:     my (%lastids,%related,%shockwave,%flashvars);
 4570:     my %javafiles = (
 4571:                       codebase => '',
 4572:                       code => '',
 4573:                       archive => ''
 4574:                     );
 4575:     my %mediafiles = (
 4576:                       src => '',
 4577:                       movie => '',
 4578:                      );
 4579:     my $p;
 4580:     if ($content) {
 4581:         $p = HTML::LCParser->new($content);
 4582:     } else {
 4583:         $p = HTML::LCParser->new($fullpath);
 4584:     }
 4585:     while (my $t=$p->get_token()) {
 4586: 	if ($t->[0] eq 'S') {
 4587: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4588: 	    push(@state, $tagname);
 4589:             if (lc($tagname) eq 'allow') {
 4590:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4591:             }
 4592: 	    if (lc($tagname) eq 'img') {
 4593: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4594: 	    }
 4595: 	    if (lc($tagname) eq 'a') {
 4596:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4597:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4598:                 }
 4599: 	    }
 4600:             if (lc($tagname) eq 'script') {
 4601:                 my $src;
 4602:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4603:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4604:                 } else {
 4605:                     if ($attr->{'src'} ne '') {
 4606:                         $src = $attr->{'src'};
 4607:                         &add_filetype($allfiles,$src,'src');
 4608:                     }
 4609:                 }
 4610:                 my $text = $p->get_trimmed_text();
 4611:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4612:                     my @swfargs = split(/,/,$1);
 4613:                     foreach my $item (@swfargs) {
 4614:                         $item =~ s/["']//g;
 4615:                         $item =~ s/^\s+//;
 4616:                         $item =~ s/\s+$//;
 4617:                     }
 4618:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4619:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4620:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4621:                         } else {
 4622:                             $related{$swfargs[0]} = [$swfargs[2]];
 4623:                         }
 4624:                     }
 4625:                 }
 4626:             }
 4627:             if (lc($tagname) eq 'link') {
 4628:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4629:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4630:                 }
 4631:             }
 4632: 	    if (lc($tagname) eq 'object' ||
 4633: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4634: 		foreach my $item (keys(%javafiles)) {
 4635: 		    $javafiles{$item} = '';
 4636: 		}
 4637:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4638:                     $lastids{lc($tagname)} = $attr->{'id'};
 4639:                 }
 4640: 	    }
 4641: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4642: 		my $name = lc($attr->{'name'});
 4643: 		foreach my $item (keys(%javafiles)) {
 4644: 		    if ($name eq $item) {
 4645: 			$javafiles{$item} = $attr->{'value'};
 4646: 			last;
 4647: 		    }
 4648: 		}
 4649:                 my $pathfrom;
 4650: 		foreach my $item (keys(%mediafiles)) {
 4651: 		    if ($name eq $item) {
 4652:                         $pathfrom = $attr->{'value'};
 4653:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4654: 			&add_filetype($allfiles,$pathfrom,$name);
 4655: 			last;
 4656: 		    }
 4657: 		}
 4658:                 if ($name eq 'flashvars') {
 4659:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4660:                 }
 4661:                 if ($pathfrom ne '') {
 4662:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4663:                                          $pathfrom);
 4664:                 }
 4665: 	    }
 4666: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4667: 		foreach my $item (keys(%javafiles)) {
 4668: 		    if ($attr->{$item}) {
 4669: 			$javafiles{$item} = $attr->{$item};
 4670: 			last;
 4671: 		    }
 4672: 		}
 4673: 		foreach my $item (keys(%mediafiles)) {
 4674: 		    if ($attr->{$item}) {
 4675: 			&add_filetype($allfiles,$attr->{$item},$item);
 4676: 			last;
 4677: 		    }
 4678: 		}
 4679:                 if (lc($tagname) eq 'embed') {
 4680:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4681:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4682:                                              $attr->{'src'});
 4683:                     }
 4684:                 }
 4685: 	    }
 4686:             if (lc($tagname) eq 'iframe') {
 4687:                 my $src = $attr->{'src'} ;
 4688:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4689:                     &add_filetype($allfiles,$src,'src');
 4690:                 } elsif ($src =~ m{^/}) {
 4691:                     if ($env{'request.course.id'}) {
 4692:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4693:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4694:                         my $url = &hreflocation('',$fullpath);
 4695:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4696:                             my $relpath = $1;
 4697:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4698:                                 &add_filetype($allfiles,$1,'src');
 4699:                             }
 4700:                         }
 4701:                     }
 4702:                 }
 4703:             }
 4704:             if ($t->[4] =~ m{/>$}) {
 4705:                 pop(@state);
 4706:             }
 4707: 	} elsif ($t->[0] eq 'E') {
 4708: 	    my ($tagname) = ($t->[1]);
 4709: 	    if ($javafiles{'codebase'} ne '') {
 4710: 		$javafiles{'codebase'} .= '/';
 4711: 	    }  
 4712: 	    if (lc($tagname) eq 'applet' ||
 4713: 		lc($tagname) eq 'object' ||
 4714: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4715: 		) {
 4716: 		foreach my $item (keys(%javafiles)) {
 4717: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4718: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4719: 			&add_filetype($allfiles,$file,$item);
 4720: 		    }
 4721: 		}
 4722: 	    } 
 4723: 	    pop @state;
 4724: 	}
 4725:     }
 4726:     foreach my $id (sort(keys(%flashvars))) {
 4727:         if ($shockwave{$id} ne '') {
 4728:             my @pairs = split(/\&/,$flashvars{$id});
 4729:             foreach my $pair (@pairs) {
 4730:                 my ($key,$value) = split(/\=/,$pair);
 4731:                 if ($key eq 'thumb') {
 4732:                     &add_filetype($allfiles,$value,$key);
 4733:                 } elsif ($key eq 'content') {
 4734:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4735:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4736:                     if ($ext ne '') {
 4737:                         &add_filetype($allfiles,$path.$value,$ext);
 4738:                     }
 4739:                 }
 4740:             }
 4741:         }
 4742:     }
 4743:     return 'ok';
 4744: }
 4745: 
 4746: sub add_filetype {
 4747:     my ($allfiles,$file,$type)=@_;
 4748:     if (exists($allfiles->{$file})) {
 4749: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4750: 	    push(@{$allfiles->{$file}}, &escape($type));
 4751: 	}
 4752:     } else {
 4753: 	@{$allfiles->{$file}} = (&escape($type));
 4754:     }
 4755: }
 4756: 
 4757: sub embedded_dependency {
 4758:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4759:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4760:         if (($identifier ne '') &&
 4761:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4762:             ($pathfrom ne '')) {
 4763:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4764:             foreach my $dep (@{$related->{$identifier}}) {
 4765:                 &add_filetype($allfiles,$path.$dep,'object');
 4766:             }
 4767:         }
 4768:     }
 4769:     return;
 4770: }
 4771: 
 4772: sub check_dimensions {
 4773:     my ($inputfile) = @_;
 4774:     my ($fullwidth,$fullheight);
 4775:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4776:         my $mm = new File::MMagic;
 4777:         my $mime_type = $mm->checktype_filename($inputfile);
 4778:         if ($mime_type =~ m{^image/}) {
 4779:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4780:                 my $imageinfo = <PIPE>;
 4781:                 if (!close(PIPE)) {
 4782:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4783:                 }
 4784:                 chomp($imageinfo);
 4785:                 my ($fullsize) =
 4786:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4787:                 if ($fullsize) {
 4788:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4789:                 }
 4790:             }
 4791:         }
 4792:     }
 4793:     return ($fullwidth,$fullheight);
 4794: }
 4795: 
 4796: sub bubblesheet_converter {
 4797:     my ($cdom,$fullpath,$config,$format) = @_;
 4798:     if ((&domain($cdom) ne '') &&
 4799:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4800:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4801:         my (%csvcols,%csvoptions);
 4802:         if (ref($config->{'fields'}) eq 'HASH') {  
 4803:             %csvcols = %{$config->{'fields'}};
 4804:         }
 4805:         if (ref($config->{'options'}) eq 'HASH') {
 4806:             %csvoptions = %{$config->{'options'}};
 4807:         }
 4808:         my %csvbynum = reverse(%csvcols);
 4809:         my %scantronconf = &get_scantron_config($format,$cdom);
 4810:         if (keys(%scantronconf)) {
 4811:             my %bynum = (
 4812:                           $scantronconf{CODEstart} => 'CODEstart',
 4813:                           $scantronconf{IDstart}   => 'IDstart',
 4814:                           $scantronconf{PaperID}   => 'PaperID',
 4815:                           $scantronconf{FirstName} => 'FirstName',
 4816:                           $scantronconf{LastName}  => 'LastName',
 4817:                           $scantronconf{Qstart}    => 'Qstart',
 4818:                         );
 4819:             my @ordered;
 4820:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4821:                 push(@ordered,$bynum{$item});
 4822:             }
 4823:             my %mapstart = (
 4824:                               CODEstart => 'CODE',
 4825:                               IDstart   => 'ID',
 4826:                               PaperID   => 'PaperID',
 4827:                               FirstName => 'FirstName',
 4828:                               LastName  => 'LastName',
 4829:                               Qstart    => 'FirstQuestion',
 4830:                            );
 4831:             my %maplength = (
 4832:                               CODEstart => 'CODElength',
 4833:                               IDstart   => 'IDlength',
 4834:                               PaperID   => 'PaperIDlength',
 4835:                               FirstName => 'FirstNamelength',
 4836:                               LastName  => 'LastNamelength',
 4837:             );
 4838:             if (open(my $fh,'<',$fullpath)) {
 4839:                 my $output;
 4840:                 my %lettdig = &letter_to_digits();
 4841:                 my %diglett = reverse(%lettdig);
 4842:                 my $numletts = scalar(keys(%lettdig));
 4843:                 my $num = 0;
 4844:                 while (my $line=<$fh>) {
 4845:                     $num ++;
 4846:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4847:                     $line =~ s{[\r\n]+$}{};
 4848:                     my %found;
 4849:                     my @values = split(/,/,$line,-1);
 4850:                     my ($qstart,$record);
 4851:                     for (my $i=0; $i<@values; $i++) {
 4852:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4853:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4854:                             if ($values[$i] eq '') {
 4855:                                 $values[$i] = $scantronconf{'Qoff'};
 4856:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4857:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4858:                                     $values[$i] = $lettdig{uc($values[$i])};
 4859:                                 }
 4860:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4861:                                 if ($values[$i] =~ /^[0-9]$/) {
 4862:                                     $values[$i] = $diglett{$values[$i]};
 4863:                                 }
 4864:                             } else {
 4865:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4866:                                     my $digit;
 4867:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4868:                                         $digit = $lettdig{uc($values[$i])}-1;
 4869:                                         if ($values[$i] eq 'J') {
 4870:                                             $digit += $numletts;
 4871:                                         }
 4872:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4873:                                         $digit = $values[$i]-1;
 4874:                                         if ($values[$i] eq '0') {
 4875:                                             $digit += $numletts;
 4876:                                         }
 4877:                                     }
 4878:                                     my $qval='';
 4879:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4880:                                         if ($j == $digit) {
 4881:                                             $qval .= $scantronconf{'Qon'};
 4882:                                         } else {
 4883:                                             $qval .= $scantronconf{'Qoff'};
 4884:                                         }
 4885:                                     }
 4886:                                     $values[$i] = $qval;
 4887:                                 }
 4888:                             }
 4889:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4890:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4891:                             }
 4892:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4893:                             if ($numblank > 0) {
 4894:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4895:                             }
 4896:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4897:                                 $qstart = $i;
 4898:                                 $found{$csvbynum{$i}} = $values[$i];
 4899:                             } else {
 4900:                                 $found{'FirstQuestion'} .= $values[$i];
 4901:                             }
 4902:                         } elsif (exists($csvbynum{$i})) {
 4903:                             if ($csvoptions{'rem'}) {
 4904:                                 $values[$i] =~ s/^\s+//;
 4905:                             }
 4906:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4907:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4908:                                     $values[$i] = '0'.$values[$i];
 4909:                                 }
 4910:                             }
 4911:                             $found{$csvbynum{$i}} = $values[$i];
 4912:                         }
 4913:                     }
 4914:                     foreach my $item (@ordered) {
 4915:                         my $currlength = 1+length($record);
 4916:                         my $numspaces = $scantronconf{$item} - $currlength;
 4917:                         if ($numspaces > 0) {
 4918:                             $record .= (' ' x $numspaces);
 4919:                         }
 4920:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4921:                             unless ($item eq 'Qstart') {
 4922:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4923:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4924:                                 }
 4925:                             }
 4926:                             $record .= $found{$mapstart{$item}};
 4927:                         }
 4928:                     }
 4929:                     $output .= "$record\n";
 4930:                 }
 4931:                 close($fh);
 4932:                 if ($output) {
 4933:                     if (open(my $fh,'>',$fullpath)) {
 4934:                         print $fh $output;
 4935:                         close($fh);
 4936:                     }
 4937:                 }
 4938:             }
 4939:         }
 4940:         return;
 4941:     }
 4942: }
 4943: 
 4944: sub letter_to_digits {
 4945:     my %lettdig = (
 4946:                     A => 1,
 4947:                     B => 2,
 4948:                     C => 3,
 4949:                     D => 4,
 4950:                     E => 5,
 4951:                     F => 6,
 4952:                     G => 7,
 4953:                     H => 8,
 4954:                     I => 9,
 4955:                     J => 0,
 4956:                   );
 4957:     return %lettdig;
 4958: }
 4959: 
 4960: sub get_scantron_config {
 4961:     my ($which,$cdom) = @_;
 4962:     my @lines = &get_scantronformat_file($cdom);
 4963:     my %config;
 4964:     #FIXME probably should move to XML it has already gotten a bit much now
 4965:     foreach my $line (@lines) {
 4966:         my ($name,$descrip)=split(/:/,$line);
 4967:         if ($name ne $which ) { next; }
 4968:         chomp($line);
 4969:         my @config=split(/:/,$line);
 4970:         $config{'name'}=$config[0];
 4971:         $config{'description'}=$config[1];
 4972:         $config{'CODElocation'}=$config[2];
 4973:         $config{'CODEstart'}=$config[3];
 4974:         $config{'CODElength'}=$config[4];
 4975:         $config{'IDstart'}=$config[5];
 4976:         $config{'IDlength'}=$config[6];
 4977:         $config{'Qstart'}=$config[7];
 4978:         $config{'Qlength'}=$config[8];
 4979:         $config{'Qoff'}=$config[9];
 4980:         $config{'Qon'}=$config[10];
 4981:         $config{'PaperID'}=$config[11];
 4982:         $config{'PaperIDlength'}=$config[12];
 4983:         $config{'FirstName'}=$config[13];
 4984:         $config{'FirstNamelength'}=$config[14];
 4985:         $config{'LastName'}=$config[15];
 4986:         $config{'LastNamelength'}=$config[16];
 4987:         $config{'BubblesPerRow'}=$config[17];
 4988:         last;
 4989:     }
 4990:     return %config;
 4991: }
 4992: 
 4993: sub get_scantronformat_file {
 4994:     my ($cdom) = @_;
 4995:     if ($cdom eq '') {
 4996:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4997:     }
 4998:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4999:     my $gottab = 0;
 5000:     my @lines;
 5001:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5002:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5003:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5004:             if ($formatfile ne '-1') {
 5005:                 @lines = split("\n",$formatfile,-1);
 5006:                 $gottab = 1;
 5007:             }
 5008:         }
 5009:     }
 5010:     if (!$gottab) {
 5011:         my $confname = $cdom.'-domainconfig';
 5012:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5013:         my $formatfile = &getfile($default);
 5014:         if ($formatfile ne '-1') {
 5015:             @lines = split("\n",$formatfile,-1);
 5016:             $gottab = 1;
 5017:         }
 5018:     }
 5019:     if (!$gottab) {
 5020:         my @domains = &current_machine_domains();
 5021:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5022:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5023:                 @lines = <$fh>;
 5024:                 close($fh);
 5025:             }
 5026:         } else {
 5027:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5028:                 @lines = <$fh>;
 5029:                 close($fh);
 5030:             }
 5031:         }
 5032:         chomp(@lines);
 5033:     }
 5034:     return @lines;
 5035: }
 5036: 
 5037: sub removeuploadedurl {
 5038:     my ($url)=@_;	
 5039:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5040:     return &removeuserfile($uname,$udom,$fname);
 5041: }
 5042: 
 5043: sub removeuserfile {
 5044:     my ($docuname,$docudom,$fname)=@_;
 5045:     my $home=&homeserver($docuname,$docudom);    
 5046:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5047:     if ($result eq 'ok') {	
 5048:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5049:             my $metafile = $fname.'.meta';
 5050:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5051: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5052:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5053:             my $sqlresult = 
 5054:                 &update_portfolio_table($docuname,$docudom,$file,
 5055:                                         'portfolio_metadata',$group,
 5056:                                         'delete');
 5057:         }
 5058:     }
 5059:     return $result;
 5060: }
 5061: 
 5062: sub mkdiruserfile {
 5063:     my ($docuname,$docudom,$dir)=@_;
 5064:     my $home=&homeserver($docuname,$docudom);
 5065:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5066: }
 5067: 
 5068: sub renameuserfile {
 5069:     my ($docuname,$docudom,$old,$new)=@_;
 5070:     my $home=&homeserver($docuname,$docudom);
 5071:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5072:                         &escape("$old").':'.&escape("$new"),$home);
 5073:     if ($result eq 'ok') {
 5074:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5075:             my $oldmeta = $old.'.meta';
 5076:             my $newmeta = $new.'.meta';
 5077:             my $metaresult = 
 5078:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5079: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5080:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5081:             my $sqlresult = 
 5082:                 &update_portfolio_table($docuname,$docudom,$file,
 5083:                                         'portfolio_metadata',$group,
 5084:                                         'delete');
 5085:         }
 5086:     }
 5087:     return $result;
 5088: }
 5089: 
 5090: # ------------------------------------------------------------------------- Log
 5091: 
 5092: sub log {
 5093:     my ($dom,$nam,$hom,$what)=@_;
 5094:     return critical("log:$dom:$nam:$what",$hom);
 5095: }
 5096: 
 5097: # ------------------------------------------------------------------ Course Log
 5098: #
 5099: # This routine flushes several buffers of non-mission-critical nature
 5100: #
 5101: 
 5102: sub flushcourselogs {
 5103:     &logthis('Flushing log buffers');
 5104: #
 5105: # course logs
 5106: # This is a log of all transactions in a course, which can be used
 5107: # for data mining purposes
 5108: #
 5109: # It also collects the courseid database, which lists last transaction
 5110: # times and course titles for all courseids
 5111: #
 5112:     my %courseidbuffer=();
 5113:     foreach my $crsid (keys(%courselogs)) {
 5114:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5115: 		          &escape($courselogs{$crsid}),
 5116: 		          $coursehombuf{$crsid}) eq 'ok') {
 5117: 	    delete $courselogs{$crsid};
 5118:         } else {
 5119:             &logthis('Failed to flush log buffer for '.$crsid);
 5120:             if (length($courselogs{$crsid})>40000) {
 5121:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5122:                         " exceeded maximum size, deleting.</font>");
 5123:                delete $courselogs{$crsid};
 5124:             }
 5125:         }
 5126:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5127:             'description' => $coursedescrbuf{$crsid},
 5128:             'inst_code'    => $courseinstcodebuf{$crsid},
 5129:             'type'        => $coursetypebuf{$crsid},
 5130:             'owner'       => $courseownerbuf{$crsid},
 5131:         };
 5132:     }
 5133: #
 5134: # Write course id database (reverse lookup) to homeserver of courses 
 5135: # Is used in pickcourse
 5136: #
 5137:     foreach my $crs_home (keys(%courseidbuffer)) {
 5138:         my $response = &courseidput(&host_domain($crs_home),
 5139:                                     $courseidbuffer{$crs_home},
 5140:                                     $crs_home,'timeonly');
 5141:     }
 5142: #
 5143: # File accesses
 5144: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5145: #
 5146:     foreach my $entry (keys(%accesshash)) {
 5147:         if ($entry =~ /___count$/) {
 5148:             my ($dom,$name);
 5149:             ($dom,$name,undef)=
 5150: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5151:             if (! defined($dom) || $dom eq '' || 
 5152:                 ! defined($name) || $name eq '') {
 5153:                 my $cid = $env{'request.course.id'};
 5154: #
 5155: # FIXME 11/29/2021
 5156: # Typo in rev. 1.458 (2003/12/09)??
 5157: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5158: #
 5159: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5160: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5161: # in a nohist_accesscount.db file for the user rather than the course.
 5162: #
 5163: # That said there is a lot of noise in the data being stored.
 5164: # So counts for prtspool/  and adm/ etc. are recorded.
 5165: #
 5166: # A review of which items ending '___count' are written to %accesshash should likely be 
 5167: # made before deciding whether to set these to 'course.' instead of 'request.'
 5168: #
 5169: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5170: # accesses for things which are not published resources, regardless of course, and
 5171: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5172: # anyone in the course for things which are not published resources.
 5173: #
 5174: # For an author, nohist_accesscount.db ends up having records for other items
 5175: # mixed up with the legitimate access counts for the author's published resources.
 5176: #
 5177:                 $dom  = $env{'request.'.$cid.'.domain'};
 5178:                 $name = $env{'request.'.$cid.'.num'};
 5179:             }
 5180:             my $value = $accesshash{$entry};
 5181:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5182:             my %temphash=($url => $value);
 5183:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5184:             if ($result eq 'ok') {
 5185:                 delete $accesshash{$entry};
 5186:             }
 5187:         } else {
 5188:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5189:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5190:             my %temphash=($entry => $accesshash{$entry});
 5191:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5192:                 delete $accesshash{$entry};
 5193:             }
 5194:         }
 5195:     }
 5196: #
 5197: # Roles
 5198: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5199: #
 5200:     foreach my $entry (keys(%userrolehash)) {
 5201:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5202: 	    split(/\:/,$entry);
 5203:         if (&put('nohist_userroles',
 5204:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5205:                 $rudom,$runame) eq 'ok') {
 5206: 	    delete $userrolehash{$entry};
 5207:         }
 5208:     }
 5209: #
 5210: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5211: #
 5212:     my %domrolebuffer = ();
 5213:     foreach my $entry (keys(%domainrolehash)) {
 5214:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5215:         if ($domrolebuffer{$rudom}) {
 5216:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5217:                       '='.&escape($domainrolehash{$entry});
 5218:         } else {
 5219:             $domrolebuffer{$rudom}.=&escape($entry).
 5220:                       '='.&escape($domainrolehash{$entry});
 5221:         }
 5222:         delete $domainrolehash{$entry};
 5223:     }
 5224:     foreach my $dom (keys(%domrolebuffer)) {
 5225: 	my %servers;
 5226: 	if (defined(&domain($dom,'primary'))) {
 5227: 	    my $primary=&domain($dom,'primary');
 5228: 	    my $hostname=&hostname($primary);
 5229: 	    $servers{$primary} = $hostname;
 5230: 	} else { 
 5231: 	    %servers = &get_servers($dom,'library');
 5232: 	}
 5233: 	foreach my $tryserver (keys(%servers)) {
 5234: 	    if (&reply('domroleput:'.$dom.':'.
 5235: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5236: 		last;
 5237: 	    } else {  
 5238: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5239: 	    }
 5240:         }
 5241:     }
 5242:     $dumpcount++;
 5243: }
 5244: 
 5245: sub courselog {
 5246:     my $what=shift;
 5247:     $what=time.':'.$what;
 5248:     unless ($env{'request.course.id'}) { return ''; }
 5249:     $coursedombuf{$env{'request.course.id'}}=
 5250:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5251:     $coursenumbuf{$env{'request.course.id'}}=
 5252:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5253:     $coursehombuf{$env{'request.course.id'}}=
 5254:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5255:     $coursedescrbuf{$env{'request.course.id'}}=
 5256:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5257:     $courseinstcodebuf{$env{'request.course.id'}}=
 5258:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5259:     $courseownerbuf{$env{'request.course.id'}}=
 5260:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5261:     $coursetypebuf{$env{'request.course.id'}}=
 5262:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5263:     if (defined $courselogs{$env{'request.course.id'}}) {
 5264: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5265:     } else {
 5266: 	$courselogs{$env{'request.course.id'}}.=$what;
 5267:     }
 5268:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5269: 	&flushcourselogs();
 5270:     }
 5271: }
 5272: 
 5273: sub courseacclog {
 5274:     my $fnsymb=shift;
 5275:     unless ($env{'request.course.id'}) { return ''; }
 5276:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5277:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5278:         $what.=':POST';
 5279:         # FIXME: Probably ought to escape things....
 5280: 	foreach my $key (keys(%env)) {
 5281:             if ($key=~/^form\.(.*)/) {
 5282:                 my $formitem = $1;
 5283:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5284:                     $what.=':'.$formitem.'='.$env{$key};
 5285:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5286:                     if ($formitem eq 'proctorpassword') {
 5287:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5288:                     } else {
 5289:                         $what.=':'.$formitem.'='.$env{$key};
 5290:                     }
 5291:                 }
 5292:             }
 5293:         }
 5294:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5295:         # FIXME: We should not be depending on a form parameter that someone
 5296:         # editing lonsearchcat.pm might change in the future.
 5297:         if ($env{'form.phase'} eq 'course_search') {
 5298:             $what.= ':POST';
 5299:             # FIXME: Probably ought to escape things....
 5300:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5301:                                  'crsdiscuss') {
 5302:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5303:             }
 5304:         }
 5305:     }
 5306:     &courselog($what);
 5307: }
 5308: 
 5309: sub countacc {
 5310:     my $url=&declutter(shift);
 5311:     return if (! defined($url) || $url eq '');
 5312:     unless ($env{'request.course.id'}) { return ''; }
 5313: #
 5314: # Mark that this url was used in this course
 5315: #
 5316:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5317: #
 5318: # Increase the access count for this resource in this child process
 5319: #
 5320:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5321:     $accesshash{$key}++;
 5322: }
 5323: 
 5324: sub linklog {
 5325:     my ($from,$to)=@_;
 5326:     $from=&declutter($from);
 5327:     $to=&declutter($to);
 5328:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5329:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5330: }
 5331: 
 5332: sub statslog {
 5333:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5334:     if ($users<2) { return; }
 5335:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5336:             'course'       => $env{'request.course.id'},
 5337:             'sections'     => '"all"',
 5338:             'num_students' => $users,
 5339:             'part'         => $part,
 5340:             'symb'         => $symb,
 5341:             'mean_tries'   => $av_attempts,
 5342:             'deg_of_diff'  => $degdiff});
 5343:     foreach my $key (keys(%dynstore)) {
 5344:         $accesshash{$key}=$dynstore{$key};
 5345:     }
 5346: }
 5347:   
 5348: sub userrolelog {
 5349:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5350:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5351:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5352:        $userrolehash
 5353:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5354:                     =$tend.':'.$tstart;
 5355:     }
 5356:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5357:        $userrolehash
 5358:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5359:                     =$tend.':'.$tstart;
 5360:     }
 5361:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5362:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5363:        $domainrolehash
 5364:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5365:                     = $tend.':'.$tstart;
 5366:     }
 5367: }
 5368: 
 5369: sub courserolelog {
 5370:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5371:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5372:         my $cdom = $1;
 5373:         my $cnum = $2;
 5374:         my $sec = $3;
 5375:         my $namespace = 'rolelog';
 5376:         my %storehash = (
 5377:                            role    => $trole,
 5378:                            start   => $tstart,
 5379:                            end     => $tend,
 5380:                            selfenroll => $selfenroll,
 5381:                            context    => $context,
 5382:                         );
 5383:         if ($trole eq 'gr') {
 5384:             $namespace = 'groupslog';
 5385:             $storehash{'group'} = $sec;
 5386:         } else {
 5387:             $storehash{'section'} = $sec;
 5388:         }
 5389:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5390:                    $domain,$cnum,$cdom);
 5391:         if (($trole ne 'st') || ($sec ne '')) {
 5392:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5393:         }
 5394:     }
 5395:     return;
 5396: }
 5397: 
 5398: sub domainrolelog {
 5399:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5400:     if ($area =~ m{^/($match_domain)/$}) {
 5401:         my $cdom = $1;
 5402:         my $domconfiguser = &get_domainconfiguser($cdom);
 5403:         my $namespace = 'rolelog';
 5404:         my %storehash = (
 5405:                            role    => $trole,
 5406:                            start   => $tstart,
 5407:                            end     => $tend,
 5408:                            context => $context,
 5409:                         );
 5410:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5411:                    $domain,$domconfiguser,$cdom);
 5412:     }
 5413:     return;
 5414: 
 5415: }
 5416: 
 5417: sub coauthorrolelog {
 5418:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5419:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5420:         my $audom = $1;
 5421:         my $auname = $2;
 5422:         my $namespace = 'rolelog';
 5423:         my %storehash = (
 5424:                            role    => $trole,
 5425:                            start   => $tstart,
 5426:                            end     => $tend,
 5427:                            context => $context,
 5428:                         );
 5429:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5430:                    $domain,$auname,$audom);
 5431:     }
 5432:     return;
 5433: }
 5434: 
 5435: sub get_course_adv_roles {
 5436:     my ($cid,$codes) = @_;
 5437:     $cid=$env{'request.course.id'} unless (defined($cid));
 5438:     my %coursehash=&coursedescription($cid);
 5439:     my $crstype = &Apache::loncommon::course_type($cid);
 5440:     my %nothide=();
 5441:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5442:         if ($user !~ /:/) {
 5443: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5444:         } else {
 5445:             $nothide{$user}=1;
 5446:         }
 5447:     }
 5448:     my @possdoms = ($coursehash{'domain'});
 5449:     if ($coursehash{'checkforpriv'}) {
 5450:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5451:     }
 5452:     my %returnhash=();
 5453:     my %dumphash=
 5454:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5455:     my $now=time;
 5456:     my %privileged;
 5457:     foreach my $entry (keys(%dumphash)) {
 5458: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5459:         if (($tstart) && ($tstart<0)) { next; }
 5460:         if (($tend) && ($tend<$now)) { next; }
 5461:         if (($tstart) && ($now<$tstart)) { next; }
 5462:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5463: 	if ($username eq '' || $domain eq '') { next; }
 5464:         if ((&privileged($username,$domain,\@possdoms)) &&
 5465:             (!$nothide{$username.':'.$domain})) { next; }
 5466: 	if ($role eq 'cr') { next; }
 5467:         if ($codes) {
 5468:             if ($section) { $role .= ':'.$section; }
 5469:             if ($returnhash{$role}) {
 5470:                 $returnhash{$role}.=','.$username.':'.$domain;
 5471:             } else {
 5472:                 $returnhash{$role}=$username.':'.$domain;
 5473:             }
 5474:         } else {
 5475:             my $key=&plaintext($role,$crstype);
 5476:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5477:             if ($returnhash{$key}) {
 5478: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5479:             } else {
 5480:                 $returnhash{$key}=$username.':'.$domain;
 5481:             }
 5482:         }
 5483:     }
 5484:     return %returnhash;
 5485: }
 5486: 
 5487: sub get_my_roles {
 5488:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5489:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5490:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5491:     my (%dumphash,%nothide);
 5492:     if ($context eq 'userroles') {
 5493:         %dumphash = &dump('roles',$udom,$uname);
 5494:     } else {
 5495:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5496:         if ($hidepriv) {
 5497:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5498:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5499:                 if ($user !~ /:/) {
 5500:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5501:                 } else {
 5502:                     $nothide{$user} = 1;
 5503:                 }
 5504:             }
 5505:         }
 5506:     }
 5507:     my %returnhash=();
 5508:     my $now=time;
 5509:     my %privileged;
 5510:     foreach my $entry (keys(%dumphash)) {
 5511:         my ($role,$tend,$tstart);
 5512:         if ($context eq 'userroles') {
 5513:             next if ($entry =~ /^rolesdef/);
 5514: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5515:         } else {
 5516:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5517:         }
 5518:         if (($tstart) && ($tstart<0)) { next; }
 5519:         my $status = 'active';
 5520:         if (($tend) && ($tend<=$now)) {
 5521:             $status = 'previous';
 5522:         } 
 5523:         if (($tstart) && ($now<$tstart)) {
 5524:             $status = 'future';
 5525:         }
 5526:         if (ref($types) eq 'ARRAY') {
 5527:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5528:                 next;
 5529:             } 
 5530:         } else {
 5531:             if ($status ne 'active') {
 5532:                 next;
 5533:             }
 5534:         }
 5535:         my ($rolecode,$username,$domain,$section,$area);
 5536:         if ($context eq 'userroles') {
 5537:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5538:             (undef,$domain,$username,$section) = split(/\//,$area);
 5539:         } else {
 5540:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5541:         }
 5542:         if (ref($roledoms) eq 'ARRAY') {
 5543:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5544:                 next;
 5545:             }
 5546:         }
 5547:         if (ref($roles) eq 'ARRAY') {
 5548:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5549:                 if ($role =~ /^cr\//) {
 5550:                     if (!grep(/^cr$/,@{$roles})) {
 5551:                         next;
 5552:                     }
 5553:                 } elsif ($role =~ /^gr\//) {
 5554:                     if (!grep(/^gr$/,@{$roles})) {
 5555:                         next;
 5556:                     }
 5557:                 } else {
 5558:                     next;
 5559:                 }
 5560:             }
 5561:         }
 5562:         if ($hidepriv) {
 5563:             my @privroles = ('dc','su');
 5564:             if ($context eq 'userroles') {
 5565:                 next if (grep(/^\Q$role\E$/,@privroles));
 5566:             } else {
 5567:                 my $possdoms = [$domain];
 5568:                 if (ref($roledoms) eq 'ARRAY') {
 5569:                    push(@{$possdoms},@{$roledoms}); 
 5570:                 }
 5571:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5572:                     if (!$nothide{$username.':'.$domain}) {
 5573:                         next;
 5574:                     }
 5575:                 }
 5576:             }
 5577:         }
 5578:         if ($withsec) {
 5579:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5580:                 $tstart.':'.$tend;
 5581:         } else {
 5582:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5583:         }
 5584:     }
 5585:     return %returnhash;
 5586: }
 5587: 
 5588: sub get_all_adhocroles {
 5589:     my ($dom) = @_;
 5590:     my @roles_by_num = ();
 5591:     my %domdefaults = &get_domain_defaults($dom);
 5592:     my (%description,%access_in_dom,%access_info);
 5593:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5594:         my $count = 0;
 5595:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5596:         my %ordered;
 5597:         foreach my $role (sort(keys(%domcurrent))) {
 5598:             my ($order,$desc,$access_in_dom);
 5599:             if (ref($domcurrent{$role}) eq 'HASH') {
 5600:                 $order = $domcurrent{$role}{'order'};
 5601:                 $desc = $domcurrent{$role}{'desc'};
 5602:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5603:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5604:             }
 5605:             if ($order eq '') {
 5606:                 $order = $count;
 5607:             }
 5608:             $ordered{$order} = $role;
 5609:             if ($desc ne '') {
 5610:                 $description{$role} = $desc;
 5611:             } else {
 5612:                 $description{$role}= $role;
 5613:             }
 5614:             $count++;
 5615:         }
 5616:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5617:             push(@roles_by_num,$ordered{$item});
 5618:         }
 5619:     }
 5620:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5621: }
 5622: 
 5623: sub get_my_adhocroles {
 5624:     my ($cid,$checkreg) = @_;
 5625:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5626:     if ($env{'request.course.id'} eq $cid) {
 5627:         $cdom = $env{'course.'.$cid.'.domain'};
 5628:         $cnum = $env{'course.'.$cid.'.num'};
 5629:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5630:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5631:         $cdom = $1;
 5632:         $cnum = $2;
 5633:         %info = &get('environment',['internal.coursecode'],
 5634:                      $cdom,$cnum);
 5635:     }
 5636:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5637:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5638:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5639:         if ($rosterhash{$user} ne '') {
 5640:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5641:             return ([],{}) if ($type eq 'auto');
 5642:         }
 5643:     }
 5644:     if (($cdom ne '') && ($cnum ne ''))  {
 5645:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5646:             my $then=$env{'user.login.time'};
 5647:             my $update=$env{'user.update.time'};
 5648:             if (!$update) {
 5649:                 $update = $then;
 5650:             }
 5651:             my @liveroles;
 5652:             foreach my $role ('dh','da') {
 5653:                 if ($env{"user.role.$role./$cdom/"}) {
 5654:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5655:                     my $limit = $update;
 5656:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5657:                         $limit = $then;
 5658:                     }
 5659:                     my $activerole = 1;
 5660:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5661:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5662:                     if ($activerole) {
 5663:                         push(@liveroles,$role);
 5664:                     }
 5665:                 }
 5666:             }
 5667:             if (@liveroles) {
 5668:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5669:                     my ($accessref,$accessinfo,%access_in_dom);
 5670:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5671:                     if (ref($roles_by_num) eq 'ARRAY') {
 5672:                         if (@{$roles_by_num}) {
 5673:                             my %settings;
 5674:                             if ($env{'request.course.id'} eq $cid) {
 5675:                                 foreach my $envkey (keys(%env)) {
 5676:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5677:                                         $settings{$1} = $env{$envkey};
 5678:                                     }
 5679:                                 }
 5680:                             } else {
 5681:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5682:                             }
 5683:                             my %setincrs;
 5684:                             if ($settings{'internal.adhocaccess'}) {
 5685:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5686:                             }
 5687:                             my @statuses;
 5688:                             if ($env{'environment.inststatus'}) {
 5689:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5690:                             }
 5691:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5692:                             if (ref($accessref) eq 'HASH') {
 5693:                                 %access_in_dom = %{$accessref};
 5694:                             }
 5695:                             foreach my $role (@{$roles_by_num}) {
 5696:                                 my ($curraccess,@okstatus,@personnel);
 5697:                                 if ($setincrs{$role}) {
 5698:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5699:                                     if ($curraccess eq 'status') {
 5700:                                         @okstatus = split(/\&/,$rest);
 5701:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5702:                                         @personnel = split(/\&/,$rest);
 5703:                                     }
 5704:                                 } else {
 5705:                                     $curraccess = $access_in_dom{$role};
 5706:                                     if (ref($accessinfo) eq 'HASH') {
 5707:                                         if ($curraccess eq 'status') {
 5708:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5709:                                                 @okstatus = @{$accessinfo->{$role}};
 5710:                                             }
 5711:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5712:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5713:                                                 @personnel = @{$accessinfo->{$role}};
 5714:                                             }
 5715:                                         }
 5716:                                     }
 5717:                                 }
 5718:                                 if ($curraccess eq 'none') {
 5719:                                     next;
 5720:                                 } elsif ($curraccess eq 'all') {
 5721:                                     push(@possroles,$role);
 5722:                                 } elsif ($curraccess eq 'dh') {
 5723:                                     if (grep(/^dh$/,@liveroles)) {
 5724:                                         push(@possroles,$role);
 5725:                                     } else {
 5726:                                         next;
 5727:                                     }
 5728:                                 } elsif ($curraccess eq 'da') {
 5729:                                     if (grep(/^da$/,@liveroles)) {
 5730:                                         push(@possroles,$role);
 5731:                                     } else {
 5732:                                         next;
 5733:                                     }
 5734:                                 } elsif ($curraccess eq 'status') {
 5735:                                     if (@okstatus) {
 5736:                                         if (!@statuses) {
 5737:                                             if (grep(/^default$/,@okstatus)) {
 5738:                                                 push(@possroles,$role);
 5739:                                             }
 5740:                                         } else {
 5741:                                             foreach my $status (@okstatus) {
 5742:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5743:                                                     push(@possroles,$role);
 5744:                                                     last;
 5745:                                                 }
 5746:                                             }
 5747:                                         }
 5748:                                     }
 5749:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5750:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5751:                                         if ($curraccess eq 'exc') {
 5752:                                             push(@possroles,$role);
 5753:                                         }
 5754:                                     } elsif ($curraccess eq 'inc') {
 5755:                                         push(@possroles,$role);
 5756:                                     }
 5757:                                 }
 5758:                             }
 5759:                         }
 5760:                     }
 5761:                 }
 5762:             }
 5763:         }
 5764:     }
 5765:     unless (ref($description) eq 'HASH') {
 5766:         if (ref($roles_by_num) eq 'ARRAY') {
 5767:             my %desc;
 5768:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5769:             $description = \%desc;
 5770:         } else {
 5771:             $description = {};
 5772:         }
 5773:     }
 5774:     return (\@possroles,$description);
 5775: }
 5776: 
 5777: # ----------------------------------------------------- Frontpage Announcements
 5778: #
 5779: #
 5780: 
 5781: sub postannounce {
 5782:     my ($server,$text)=@_;
 5783:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5784:     unless ($text=~/\w/) { $text=''; }
 5785:     return &reply('setannounce:'.&escape($text),$server);
 5786: }
 5787: 
 5788: sub getannounce {
 5789: 
 5790:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5791: 	my $announcement='';
 5792: 	while (my $line = <$fh>) { $announcement .= $line; }
 5793: 	close($fh);
 5794: 	if ($announcement=~/\w/) { 
 5795: 	    return 
 5796:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5797:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5798: 	} else {
 5799: 	    return '';
 5800: 	}
 5801:     } else {
 5802: 	return '';
 5803:     }
 5804: }
 5805: 
 5806: # ---------------------------------------------------------- Course ID routines
 5807: # Deal with domain's nohist_courseid.db files
 5808: #
 5809: 
 5810: sub courseidput {
 5811:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5812:     return unless (ref($storehash) eq 'HASH');
 5813:     my $outcome;
 5814:     if ($caller eq 'timeonly') {
 5815:         my $cids = '';
 5816:         foreach my $item (keys(%$storehash)) {
 5817:             $cids.=&escape($item).'&';
 5818:         }
 5819:         $cids=~s/\&$//;
 5820:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5821:                           $coursehome);       
 5822:     } else {
 5823:         my $items = '';
 5824:         foreach my $item (keys(%$storehash)) {
 5825:             $items.= &escape($item).'='.
 5826:                      &freeze_escape($$storehash{$item}).'&';
 5827:         }
 5828:         $items=~s/\&$//;
 5829:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5830:                           $coursehome);
 5831:     }
 5832:     if ($outcome eq 'unknown_cmd') {
 5833:         my $what;
 5834:         foreach my $cid (keys(%$storehash)) {
 5835:             $what .= &escape($cid).'=';
 5836:             foreach my $item ('description','inst_code','owner','type') {
 5837:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5838:             }
 5839:             $what =~ s/\:$/&/;
 5840:         }
 5841:         $what =~ s/\&$//;  
 5842:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5843:     } else {
 5844:         return $outcome;
 5845:     }
 5846: }
 5847: 
 5848: sub courseiddump {
 5849:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5850:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5851:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5852:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5853:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5854:     my $as_hash = 1;
 5855:     my %returnhash;
 5856:     if (!$domfilter) { $domfilter=''; }
 5857:     my %libserv = &all_library();
 5858:     foreach my $tryserver (keys(%libserv)) {
 5859:         if ( (  $hostidflag == 1 
 5860: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5861: 	     || (!defined($hostidflag)) ) {
 5862: 
 5863: 	    if (($domfilter eq '') ||
 5864: 		(&host_domain($tryserver) eq $domfilter)) {
 5865:                 my $rep;
 5866:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5867:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5868:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5869:                                 &escape($descfilter), &escape($instcodefilter), 
 5870:                                 &escape($ownerfilter), &escape($coursefilter),
 5871:                                 &escape($typefilter), &escape($regexp_ok), 
 5872:                                 $as_hash, &escape($selfenrollonly), 
 5873:                                 &escape($catfilter), $showhidden, $caller, 
 5874:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5875:                                 &escape($createdbefore), &escape($createdafter), 
 5876:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5877:                                 $reqcrsdom,&escape($reqinstcode))));
 5878:                 } else {
 5879:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5880:                              $sincefilter.':'.&escape($descfilter).':'.
 5881:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5882:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5883:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5884:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5885:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5886:                              &escape($cc_clone).':'.$cloneonly.':'.
 5887:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5888:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5889:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5890:                 }
 5891:                      
 5892:                 my @pairs=split(/\&/,$rep);
 5893:                 foreach my $item (@pairs) {
 5894:                     my ($key,$value)=split(/\=/,$item,2);
 5895:                     $key = &unescape($key);
 5896:                     next if ($key =~ /^error: 2 /);
 5897:                     my $result = &thaw_unescape($value);
 5898:                     if (ref($result) eq 'HASH') {
 5899:                         $returnhash{$key}=$result;
 5900:                     } else {
 5901:                         my @responses = split(/:/,$value);
 5902:                         my @items = ('description','inst_code','owner','type');
 5903:                         for (my $i=0; $i<@responses; $i++) {
 5904:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5905:                         }
 5906:                     }
 5907:                 }
 5908:             }
 5909:         }
 5910:     }
 5911:     return %returnhash;
 5912: }
 5913: 
 5914: sub courselastaccess {
 5915:     my ($cdom,$cnum,$hostidref) = @_;
 5916:     my %returnhash;
 5917:     if ($cdom && $cnum) {
 5918:         my $chome = &homeserver($cnum,$cdom);
 5919:         if ($chome ne 'no_host') {
 5920:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5921:             &extract_lastaccess(\%returnhash,$rep);
 5922:         }
 5923:     } else {
 5924:         if (!$cdom) { $cdom=''; }
 5925:         my %libserv = &all_library();
 5926:         foreach my $tryserver (keys(%libserv)) {
 5927:             if (ref($hostidref) eq 'ARRAY') {
 5928:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5929:             } 
 5930:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5931:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5932:                 &extract_lastaccess(\%returnhash,$rep);
 5933:             }
 5934:         }
 5935:     }
 5936:     return %returnhash;
 5937: }
 5938: 
 5939: sub extract_lastaccess {
 5940:     my ($returnhash,$rep) = @_;
 5941:     if (ref($returnhash) eq 'HASH') {
 5942:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5943:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5944:                  $rep eq '') {
 5945:             my @pairs=split(/\&/,$rep);
 5946:             foreach my $item (@pairs) {
 5947:                 my ($key,$value)=split(/\=/,$item,2);
 5948:                 $key = &unescape($key);
 5949:                 next if ($key =~ /^error: 2 /);
 5950:                 $returnhash->{$key} = &thaw_unescape($value);
 5951:             }
 5952:         }
 5953:     }
 5954:     return;
 5955: }
 5956: 
 5957: # ---------------------------------------------------------- DC e-mail
 5958: 
 5959: sub dcmailput {
 5960:     my ($domain,$msgid,$message,$server)=@_;
 5961:     my $status = &critical(
 5962:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5963:        &escape($message),$server);
 5964:     return $status;
 5965: }
 5966: 
 5967: sub dcmaildump {
 5968:     my ($dom,$startdate,$enddate,$senders) = @_;
 5969:     my %returnhash=();
 5970: 
 5971:     if (defined(&domain($dom,'primary'))) {
 5972:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5973:                                                          &escape($enddate).':';
 5974: 	my @esc_senders=map { &escape($_)} @$senders;
 5975: 	$cmd.=&escape(join('&',@esc_senders));
 5976: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5977:             my ($key,$value) = split(/\=/,$line,2);
 5978:             if (($key) && ($value)) {
 5979:                 $returnhash{&unescape($key)} = &unescape($value);
 5980:             }
 5981:         }
 5982:     }
 5983:     return %returnhash;
 5984: }
 5985: # ---------------------------------------------------------- Domain roles
 5986: 
 5987: sub get_domain_roles {
 5988:     my ($dom,$roles,$startdate,$enddate)=@_;
 5989:     if ((!defined($startdate)) || ($startdate eq '')) {
 5990:         $startdate = '.';
 5991:     }
 5992:     if ((!defined($enddate)) || ($enddate eq '')) {
 5993:         $enddate = '.';
 5994:     }
 5995:     my $rolelist;
 5996:     if (ref($roles) eq 'ARRAY') {
 5997:         $rolelist = join('&',@{$roles});
 5998:     }
 5999:     my %personnel = ();
 6000: 
 6001:     my %servers = &get_servers($dom,'library');
 6002:     foreach my $tryserver (keys(%servers)) {
 6003: 	%{$personnel{$tryserver}}=();
 6004: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6005: 					    &escape($startdate).':'.
 6006: 					    &escape($enddate).':'.
 6007: 					    &escape($rolelist), $tryserver))) {
 6008: 	    my ($key,$value) = split(/\=/,$line,2);
 6009: 	    if (($key) && ($value)) {
 6010: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6011: 	    }
 6012: 	}
 6013:     }
 6014:     return %personnel;
 6015: }
 6016: 
 6017: sub get_active_domroles {
 6018:     my ($dom,$roles) = @_;
 6019:     return () unless (ref($roles) eq 'ARRAY');
 6020:     my $now = time;
 6021:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6022:     my %domroles;
 6023:     foreach my $server (keys(%dompersonnel)) {
 6024:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6025:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6026:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6027:         }
 6028:     }
 6029:     return %domroles;
 6030: }
 6031: 
 6032: # ----------------------------------------------------------- Interval timing 
 6033: 
 6034: {
 6035: # Caches needed for speedup of navmaps
 6036: # We don't want to cache this for very long at all (5 seconds at most)
 6037: # 
 6038: # The user for whom we cache
 6039: my $cachedkey='';
 6040: # The cached times for this user
 6041: my %cachedtimes=();
 6042: # When this was last done
 6043: my $cachedtime='';
 6044: 
 6045: sub load_all_first_access {
 6046:     my ($uname,$udom,$ignorecache)=@_;
 6047:     if (($cachedkey eq $uname.':'.$udom) &&
 6048:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6049:         (!$ignorecache)) {
 6050:         return;
 6051:     }
 6052:     $cachedtime=time;
 6053:     $cachedkey=$uname.':'.$udom;
 6054:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6055: }
 6056: 
 6057: sub get_first_access {
 6058:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6059:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6060:     if ($argsymb) { $symb=$argsymb; }
 6061:     my ($map,$id,$res)=&decode_symb($symb);
 6062:     if ($argmap) { $map = $argmap; }
 6063:     if ($type eq 'course') {
 6064: 	$res='course';
 6065:     } elsif ($type eq 'map') {
 6066: 	$res=&symbread($map);
 6067:     } else {
 6068: 	$res=$symb;
 6069:     }
 6070:     &load_all_first_access($uname,$udom,$ignorecache);
 6071:     return $cachedtimes{"$courseid\0$res"};
 6072: }
 6073: 
 6074: sub set_first_access {
 6075:     my ($type,$interval)=@_;
 6076:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6077:     my ($map,$id,$res)=&decode_symb($symb);
 6078:     if ($type eq 'course') {
 6079: 	$res='course';
 6080:     } elsif ($type eq 'map') {
 6081: 	$res=&symbread($map);
 6082:     } else {
 6083: 	$res=$symb;
 6084:     }
 6085:     $cachedkey='';
 6086:     my $firstaccess=&get_first_access($type,$symb,$map);
 6087:     if ($firstaccess) {
 6088:         &logthis("First access time already set ($firstaccess) when attempting ".
 6089:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6090:                  "in $courseid");
 6091:         return 'already_set';
 6092:     } else {
 6093:         my $start = time;
 6094: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6095:                           $udom,$uname);
 6096:         if ($putres eq 'ok') {
 6097:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6098:                  $udom,$uname); 
 6099:             &appenv(
 6100:                      {
 6101:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6102:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6103:                      }
 6104:                   );
 6105:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6106:                 $cachedtimes{"$courseid\0$res"} = $start;
 6107:             }
 6108:         } elsif ($putres ne 'refused') {
 6109:             &logthis("Result: $putres when attempting to set first access time ".
 6110:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6111:         }
 6112:         return $putres;
 6113:     }
 6114:     return 'already_set';
 6115: }
 6116: }
 6117: 
 6118: # --------------------------------------------- Set Expire Date for Spreadsheet
 6119: 
 6120: sub expirespread {
 6121:     my ($uname,$udom,$stype,$usymb)=@_;
 6122:     my $cid=$env{'request.course.id'}; 
 6123:     if ($cid) {
 6124:        my $now=time;
 6125:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6126:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6127:                             $env{'course.'.$cid.'.num'}.
 6128: 	        	    ':nohist_expirationdates:'.
 6129:                             &escape($key).'='.$now,
 6130:                             $env{'course.'.$cid.'.home'})
 6131:     }
 6132:     return 'ok';
 6133: }
 6134: 
 6135: # ----------------------------------------------------- Devalidate Spreadsheets
 6136: 
 6137: sub devalidate {
 6138:     my ($symb,$uname,$udom)=@_;
 6139:     my $cid=$env{'request.course.id'}; 
 6140:     if ($cid) {
 6141:         # delete the stored spreadsheets for
 6142:         # - the student level sheet of this user in course's homespace
 6143:         # - the assessment level sheet for this resource 
 6144:         #   for this user in user's homespace
 6145: 	# - current conditional state info
 6146: 	my $key=$uname.':'.$udom.':';
 6147:         my $status=
 6148: 	    &del('nohist_calculatedsheets',
 6149: 		 [$key.'studentcalc:'],
 6150: 		 $env{'course.'.$cid.'.domain'},
 6151: 		 $env{'course.'.$cid.'.num'})
 6152: 		.' '.
 6153: 	    &del('nohist_calculatedsheets_'.$cid,
 6154: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6155:         unless ($status eq 'ok ok') {
 6156:            &logthis('Could not devalidate spreadsheet '.
 6157:                     $uname.' at '.$udom.' for '.
 6158: 		    $symb.': '.$status);
 6159:         }
 6160: 	&delenv('user.state.'.$cid);
 6161:     }
 6162: }
 6163: 
 6164: sub get_scalar {
 6165:     my ($string,$end) = @_;
 6166:     my $value;
 6167:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6168: 	$value = $1;
 6169:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6170: 	$value = $1;
 6171:     }
 6172:     return &unescape($value);
 6173: }
 6174: 
 6175: sub array2str {
 6176:   my (@array) = @_;
 6177:   my $result=&arrayref2str(\@array);
 6178:   $result=~s/^__ARRAY_REF__//;
 6179:   $result=~s/__END_ARRAY_REF__$//;
 6180:   return $result;
 6181: }
 6182: 
 6183: sub arrayref2str {
 6184:   my ($arrayref) = @_;
 6185:   my $result='__ARRAY_REF__';
 6186:   foreach my $elem (@$arrayref) {
 6187:     if(ref($elem) eq 'ARRAY') {
 6188:       $result.=&arrayref2str($elem).'&';
 6189:     } elsif(ref($elem) eq 'HASH') {
 6190:       $result.=&hashref2str($elem).'&';
 6191:     } elsif(ref($elem)) {
 6192:       #print("Got a ref of ".(ref($elem))." skipping.");
 6193:     } else {
 6194:       $result.=&escape($elem).'&';
 6195:     }
 6196:   }
 6197:   $result=~s/\&$//;
 6198:   $result .= '__END_ARRAY_REF__';
 6199:   return $result;
 6200: }
 6201: 
 6202: sub hash2str {
 6203:   my (%hash) = @_;
 6204:   my $result=&hashref2str(\%hash);
 6205:   $result=~s/^__HASH_REF__//;
 6206:   $result=~s/__END_HASH_REF__$//;
 6207:   return $result;
 6208: }
 6209: 
 6210: sub hashref2str {
 6211:   my ($hashref)=@_;
 6212:   my $result='__HASH_REF__';
 6213:   foreach my $key (sort(keys(%$hashref))) {
 6214:     if (ref($key) eq 'ARRAY') {
 6215:       $result.=&arrayref2str($key).'=';
 6216:     } elsif (ref($key) eq 'HASH') {
 6217:       $result.=&hashref2str($key).'=';
 6218:     } elsif (ref($key)) {
 6219:       $result.='=';
 6220:       #print("Got a ref of ".(ref($key))." skipping.");
 6221:     } else {
 6222: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6223:     }
 6224: 
 6225:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6226:       $result.=&arrayref2str($hashref->{$key}).'&';
 6227:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6228:       $result.=&hashref2str($hashref->{$key}).'&';
 6229:     } elsif(ref($hashref->{$key})) {
 6230:        $result.='&';
 6231:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6232:     } else {
 6233:       $result.=&escape($hashref->{$key}).'&';
 6234:     }
 6235:   }
 6236:   $result=~s/\&$//;
 6237:   $result .= '__END_HASH_REF__';
 6238:   return $result;
 6239: }
 6240: 
 6241: sub str2hash {
 6242:     my ($string)=@_;
 6243:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6244:     return %$hash;
 6245: }
 6246: 
 6247: sub str2hashref {
 6248:   my ($string) = @_;
 6249: 
 6250:   my %hash;
 6251: 
 6252:   if($string !~ /^__HASH_REF__/) {
 6253:       if (! ($string eq '' || !defined($string))) {
 6254: 	  $hash{'error'}='Not hash reference';
 6255:       }
 6256:       return (\%hash, $string);
 6257:   }
 6258: 
 6259:   $string =~ s/^__HASH_REF__//;
 6260: 
 6261:   while($string !~ /^__END_HASH_REF__/) {
 6262:       #key
 6263:       my $key='';
 6264:       if($string =~ /^__HASH_REF__/) {
 6265:           ($key, $string)=&str2hashref($string);
 6266:           if(defined($key->{'error'})) {
 6267:               $hash{'error'}='Bad data';
 6268:               return (\%hash, $string);
 6269:           }
 6270:       } elsif($string =~ /^__ARRAY_REF__/) {
 6271:           ($key, $string)=&str2arrayref($string);
 6272:           if($key->[0] eq 'Array reference error') {
 6273:               $hash{'error'}='Bad data';
 6274:               return (\%hash, $string);
 6275:           }
 6276:       } else {
 6277:           $string =~ s/^(.*?)=//;
 6278: 	  $key=&unescape($1);
 6279:       }
 6280:       $string =~ s/^=//;
 6281: 
 6282:       #value
 6283:       my $value='';
 6284:       if($string =~ /^__HASH_REF__/) {
 6285:           ($value, $string)=&str2hashref($string);
 6286:           if(defined($value->{'error'})) {
 6287:               $hash{'error'}='Bad data';
 6288:               return (\%hash, $string);
 6289:           }
 6290:       } elsif($string =~ /^__ARRAY_REF__/) {
 6291:           ($value, $string)=&str2arrayref($string);
 6292:           if($value->[0] eq 'Array reference error') {
 6293:               $hash{'error'}='Bad data';
 6294:               return (\%hash, $string);
 6295:           }
 6296:       } else {
 6297: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6298:       }
 6299:       $string =~ s/^&//;
 6300: 
 6301:       $hash{$key}=$value;
 6302:   }
 6303: 
 6304:   $string =~ s/^__END_HASH_REF__//;
 6305: 
 6306:   return (\%hash, $string);
 6307: }
 6308: 
 6309: sub str2array {
 6310:     my ($string)=@_;
 6311:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6312:     return @$array;
 6313: }
 6314: 
 6315: sub str2arrayref {
 6316:   my ($string) = @_;
 6317:   my @array;
 6318: 
 6319:   if($string !~ /^__ARRAY_REF__/) {
 6320:       if (! ($string eq '' || !defined($string))) {
 6321: 	  $array[0]='Array reference error';
 6322:       }
 6323:       return (\@array, $string);
 6324:   }
 6325: 
 6326:   $string =~ s/^__ARRAY_REF__//;
 6327: 
 6328:   while($string !~ /^__END_ARRAY_REF__/) {
 6329:       my $value='';
 6330:       if($string =~ /^__HASH_REF__/) {
 6331:           ($value, $string)=&str2hashref($string);
 6332:           if(defined($value->{'error'})) {
 6333:               $array[0] ='Array reference error';
 6334:               return (\@array, $string);
 6335:           }
 6336:       } elsif($string =~ /^__ARRAY_REF__/) {
 6337:           ($value, $string)=&str2arrayref($string);
 6338:           if($value->[0] eq 'Array reference error') {
 6339:               $array[0] ='Array reference error';
 6340:               return (\@array, $string);
 6341:           }
 6342:       } else {
 6343: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6344:       }
 6345:       $string =~ s/^&//;
 6346: 
 6347:       push(@array, $value);
 6348:   }
 6349: 
 6350:   $string =~ s/^__END_ARRAY_REF__//;
 6351: 
 6352:   return (\@array, $string);
 6353: }
 6354: 
 6355: # -------------------------------------------------------------------Temp Store
 6356: 
 6357: sub tmpreset {
 6358:   my ($symb,$namespace,$domain,$stuname) = @_;
 6359:   if (!$symb) {
 6360:     $symb=&symbread();
 6361:     if (!$symb) { $symb= $env{'request.url'}; }
 6362:   }
 6363:   $symb=escape($symb);
 6364: 
 6365:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6366:   $namespace=~s/\//\_/g;
 6367:   $namespace=~s/\W//g;
 6368: 
 6369:   if (!$domain) { $domain=$env{'user.domain'}; }
 6370:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6371:   if ($domain eq 'public' && $stuname eq 'public') {
 6372:       $stuname=&get_requestor_ip();
 6373:   }
 6374:   my $path=LONCAPA::tempdir();
 6375:   my %hash;
 6376:   if (tie(%hash,'GDBM_File',
 6377: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6378: 	  &GDBM_WRCREAT(),0640)) {
 6379:     foreach my $key (keys(%hash)) {
 6380:       if ($key=~ /:$symb/) {
 6381: 	delete($hash{$key});
 6382:       }
 6383:     }
 6384:   }
 6385: }
 6386: 
 6387: sub tmpstore {
 6388:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6389: 
 6390:   if (!$symb) {
 6391:     $symb=&symbread();
 6392:     if (!$symb) { $symb= $env{'request.url'}; }
 6393:   }
 6394:   $symb=escape($symb);
 6395: 
 6396:   if (!$namespace) {
 6397:     # I don't think we would ever want to store this for a course.
 6398:     # it seems this will only be used if we don't have a course.
 6399:     #$namespace=$env{'request.course.id'};
 6400:     #if (!$namespace) {
 6401:       $namespace=$env{'request.state'};
 6402:     #}
 6403:   }
 6404:   $namespace=~s/\//\_/g;
 6405:   $namespace=~s/\W//g;
 6406:   if (!$domain) { $domain=$env{'user.domain'}; }
 6407:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6408:   if ($domain eq 'public' && $stuname eq 'public') {
 6409:       $stuname=&get_requestor_ip();
 6410:   }
 6411:   my $now=time;
 6412:   my %hash;
 6413:   my $path=LONCAPA::tempdir();
 6414:   if (tie(%hash,'GDBM_File',
 6415: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6416: 	  &GDBM_WRCREAT(),0640)) {
 6417:     $hash{"version:$symb"}++;
 6418:     my $version=$hash{"version:$symb"};
 6419:     my $allkeys=''; 
 6420:     foreach my $key (keys(%$storehash)) {
 6421:       $allkeys.=$key.':';
 6422:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6423:     }
 6424:     $hash{"$version:$symb:timestamp"}=$now;
 6425:     $allkeys.='timestamp';
 6426:     $hash{"$version:keys:$symb"}=$allkeys;
 6427:     if (untie(%hash)) {
 6428:       return 'ok';
 6429:     } else {
 6430:       return "error:$!";
 6431:     }
 6432:   } else {
 6433:     return "error:$!";
 6434:   }
 6435: }
 6436: 
 6437: # -----------------------------------------------------------------Temp Restore
 6438: 
 6439: sub tmprestore {
 6440:   my ($symb,$namespace,$domain,$stuname) = @_;
 6441: 
 6442:   if (!$symb) {
 6443:     $symb=&symbread();
 6444:     if (!$symb) { $symb= $env{'request.url'}; }
 6445:   }
 6446:   $symb=escape($symb);
 6447: 
 6448:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6449: 
 6450:   if (!$domain) { $domain=$env{'user.domain'}; }
 6451:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6452:   if ($domain eq 'public' && $stuname eq 'public') {
 6453:       $stuname=&get_requestor_ip();
 6454:   }
 6455:   my %returnhash;
 6456:   $namespace=~s/\//\_/g;
 6457:   $namespace=~s/\W//g;
 6458:   my %hash;
 6459:   my $path=LONCAPA::tempdir();
 6460:   if (tie(%hash,'GDBM_File',
 6461: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6462: 	  &GDBM_READER(),0640)) {
 6463:     my $version=$hash{"version:$symb"};
 6464:     $returnhash{'version'}=$version;
 6465:     my $scope;
 6466:     for ($scope=1;$scope<=$version;$scope++) {
 6467:       my $vkeys=$hash{"$scope:keys:$symb"};
 6468:       my @keys=split(/:/,$vkeys);
 6469:       my $key;
 6470:       $returnhash{"$scope:keys"}=$vkeys;
 6471:       foreach $key (@keys) {
 6472: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6473: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6474:       }
 6475:     }
 6476:     if (!(untie(%hash))) {
 6477:       return "error:$!";
 6478:     }
 6479:   } else {
 6480:     return "error:$!";
 6481:   }
 6482:   return %returnhash;
 6483: }
 6484: 
 6485: # ----------------------------------------------------------------------- Store
 6486: 
 6487: sub store {
 6488:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6489:     my $home='';
 6490: 
 6491:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6492: 
 6493:     $symb=&symbclean($symb);
 6494:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6495: 
 6496:     if (!$domain) { $domain=$env{'user.domain'}; }
 6497:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6498: 
 6499:     &devalidate($symb,$stuname,$domain);
 6500: 
 6501:     $symb=escape($symb);
 6502:     if (!$namespace) { 
 6503:        unless ($namespace=$env{'request.course.id'}) { 
 6504:           return ''; 
 6505:        } 
 6506:     }
 6507:     if (!$home) { $home=$env{'user.home'}; }
 6508: 
 6509:     $$storehash{'ip'}=&get_requestor_ip();
 6510:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6511: 
 6512:     my $namevalue='';
 6513:     foreach my $key (keys(%$storehash)) {
 6514:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6515:     }
 6516:     $namevalue=~s/\&$//;
 6517:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6518:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6519: }
 6520: 
 6521: # -------------------------------------------------------------- Critical Store
 6522: 
 6523: sub cstore {
 6524:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6525:     my $home='';
 6526: 
 6527:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6528: 
 6529:     $symb=&symbclean($symb);
 6530:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6531: 
 6532:     if (!$domain) { $domain=$env{'user.domain'}; }
 6533:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6534: 
 6535:     &devalidate($symb,$stuname,$domain);
 6536: 
 6537:     $symb=escape($symb);
 6538:     if (!$namespace) { 
 6539:        unless ($namespace=$env{'request.course.id'}) { 
 6540:           return ''; 
 6541:        } 
 6542:     }
 6543:     if (!$home) { $home=$env{'user.home'}; }
 6544: 
 6545:     $$storehash{'ip'}=&get_requestor_ip();
 6546:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6547: 
 6548:     my $namevalue='';
 6549:     foreach my $key (keys(%$storehash)) {
 6550:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6551:     }
 6552:     $namevalue=~s/\&$//;
 6553:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6554:     return critical
 6555:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6556: }
 6557: 
 6558: # --------------------------------------------------------------------- Restore
 6559: 
 6560: sub restore {
 6561:     my ($symb,$namespace,$domain,$stuname) = @_;
 6562:     my $home='';
 6563: 
 6564:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6565: 
 6566:     if (!$symb) {
 6567:         return if ($namespace eq 'courserequests');
 6568:         unless ($symb=escape(&symbread())) { return ''; }
 6569:     } else {
 6570:         unless ($namespace eq 'courserequests') {
 6571:             $symb=&escape(&symbclean($symb));
 6572:         }
 6573:     }
 6574:     if (!$namespace) { 
 6575:        unless ($namespace=$env{'request.course.id'}) { 
 6576:           return ''; 
 6577:        } 
 6578:     }
 6579:     if (!$domain) { $domain=$env{'user.domain'}; }
 6580:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6581:     if (!$home) { $home=$env{'user.home'}; }
 6582:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6583: 
 6584:     my %returnhash=();
 6585:     foreach my $line (split(/\&/,$answer)) {
 6586: 	my ($name,$value)=split(/\=/,$line);
 6587:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6588:     }
 6589:     my $version;
 6590:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6591:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6592:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6593:        }
 6594:     }
 6595:     return %returnhash;
 6596: }
 6597: 
 6598: # ---------------------------------------------------------- Course Description
 6599: #
 6600: #  
 6601: 
 6602: sub coursedescription {
 6603:     my ($courseid,$args)=@_;
 6604:     $courseid=~s/^\///;
 6605:     $courseid=~s/\_/\//g;
 6606:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6607:     my $chome=&homeserver($cnum,$cdomain);
 6608:     my $normalid=$cdomain.'_'.$cnum;
 6609:     # need to always cache even if we get errors otherwise we keep 
 6610:     # trying and trying and trying to get the course description.
 6611:     my %envhash=();
 6612:     my %returnhash=();
 6613:     
 6614:     my $expiretime=600;
 6615:     if ($env{'request.course.id'} eq $normalid) {
 6616: 	$expiretime=120;
 6617:     }
 6618: 
 6619:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6620:     if (!$args->{'freshen_cache'}
 6621: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6622: 	foreach my $key (keys(%env)) {
 6623: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6624: 	    my ($setting) = $1;
 6625: 	    $returnhash{$setting} = $env{$key};
 6626: 	}
 6627: 	return %returnhash;
 6628:     }
 6629: 
 6630:     # get the data again
 6631: 
 6632:     if (!$args->{'one_time'}) {
 6633: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6634:     }
 6635: 
 6636:     if ($chome ne 'no_host') {
 6637:        %returnhash=&dump('environment',$cdomain,$cnum);
 6638:        if (!exists($returnhash{'con_lost'})) {
 6639: 	   my $username = $env{'user.name'}; # Defult username
 6640: 	   if(defined $args->{'user'}) {
 6641: 	       $username = $args->{'user'};
 6642: 	   }
 6643:            $returnhash{'home'}= $chome;
 6644: 	   $returnhash{'domain'} = $cdomain;
 6645: 	   $returnhash{'num'} = $cnum;
 6646:            if (!defined($returnhash{'type'})) {
 6647:                $returnhash{'type'} = 'Course';
 6648:            }
 6649:            while (my ($name,$value) = each %returnhash) {
 6650:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6651:            }
 6652:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6653:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6654: 	       $username.'_'.$cdomain.'_'.$cnum;
 6655:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6656:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6657:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6658:        }
 6659:     }
 6660:     if (!$args->{'one_time'}) {
 6661: 	&appenv(\%envhash);
 6662:     }
 6663:     return %returnhash;
 6664: }
 6665: 
 6666: sub update_released_required {
 6667:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6668:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6669:         $cid = $env{'request.course.id'};
 6670:         $cdom = $env{'course.'.$cid.'.domain'};
 6671:         $cnum = $env{'course.'.$cid.'.num'};
 6672:         $chome = $env{'course.'.$cid.'.home'};
 6673:     }
 6674:     if ($needsrelease) {
 6675:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6676:         my $needsupdate;
 6677:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6678:             $needsupdate = 1;
 6679:         } else {
 6680:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6681:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6682:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6683:                 $needsupdate = 1;
 6684:             }
 6685:         }
 6686:         if ($needsupdate) {
 6687:             my %needshash = (
 6688:                              'internal.releaserequired' => $needsrelease,
 6689:                             );
 6690:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6691:             if ($putresult eq 'ok') {
 6692:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6693:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6694:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6695:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6696:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6697:                 }
 6698:             }
 6699:         }
 6700:     }
 6701:     return;
 6702: }
 6703: 
 6704: # -------------------------------------------------See if a user is privileged
 6705: 
 6706: sub privileged {
 6707:     my ($username,$domain,$possdomains,$possroles)=@_;
 6708:     my $now = time;
 6709:     my $roles;
 6710:     if (ref($possroles) eq 'ARRAY') {
 6711:         $roles = $possroles; 
 6712:     } else {
 6713:         $roles = ['dc','su'];
 6714:     }
 6715:     if (ref($possdomains) eq 'ARRAY') {
 6716:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6717:         foreach my $dom (@{$possdomains}) {
 6718:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6719:                 (ref($privileged{$dom}) eq 'HASH')) {
 6720:                 foreach my $role (@{$roles}) {
 6721:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6722:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6723:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6724:                             return 1 unless (($end && $end < $now) ||
 6725:                                              ($start && $start > $now));
 6726:                         }
 6727:                     }
 6728:                 }
 6729:             }
 6730:         }
 6731:     } else {
 6732:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6733:         my $now = time;
 6734: 
 6735:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6736:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6737:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6738:                 return 1 unless ($tend && $tend < $now) 
 6739:                         or ($tstart && $tstart > $now);
 6740:             }
 6741:         }
 6742:     }
 6743:     return 0;
 6744: }
 6745: 
 6746: sub privileged_by_domain {
 6747:     my ($domains,$roles) = @_;
 6748:     my %privileged = ();
 6749:     my $cachetime = 60*60*24;
 6750:     my $now = time;
 6751:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6752:         return %privileged;
 6753:     }
 6754:     foreach my $dom (@{$domains}) {
 6755:         next if (ref($privileged{$dom}) eq 'HASH');
 6756:         my $needroles;
 6757:         foreach my $role (@{$roles}) {
 6758:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6759:             if (defined($cached)) {
 6760:                 if (ref($result) eq 'HASH') {
 6761:                     $privileged{$dom}{$role} = $result;
 6762:                 }
 6763:             } else {
 6764:                 $needroles = 1;
 6765:             }
 6766:         }
 6767:         if ($needroles) {
 6768:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6769:             $privileged{$dom} = {};
 6770:             foreach my $server (keys(%dompersonnel)) {
 6771:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6772:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6773:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6774:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6775:                         next if ($end && $end < $now);
 6776:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6777:                             $dompersonnel{$server}{$item};
 6778:                     }
 6779:                 }
 6780:             }
 6781:             if (ref($privileged{$dom}) eq 'HASH') {
 6782:                 foreach my $role (@{$roles}) {
 6783:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6784:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6785:                     } else {
 6786:                         my %hash = ();
 6787:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6788:                     }
 6789:                 }
 6790:             }
 6791:         }
 6792:     }
 6793:     return %privileged;
 6794: }
 6795: 
 6796: # -------------------------------------------------------- Get user privileges
 6797: 
 6798: sub rolesinit {
 6799:     my ($domain, $username) = @_;
 6800:     my %userroles = ('user.login.time' => time);
 6801:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6802: 
 6803:     # firstaccess and timerinterval are related to timed maps/resources. 
 6804:     # also, blocking can be triggered by an activating timer
 6805:     # it's saved in the user's %env.
 6806:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6807:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6808:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6809:         %timerintchk, %timerintenv);
 6810: 
 6811:     foreach my $key (keys(%firstaccess)) {
 6812:         my ($cid, $rest) = split(/\0/, $key);
 6813:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6814:     }
 6815: 
 6816:     foreach my $key (keys(%timerinterval)) {
 6817:         my ($cid,$rest) = split(/\0/,$key);
 6818:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6819:     }
 6820: 
 6821:     my %allroles=();
 6822:     my %allgroups=();
 6823: 
 6824:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6825:         my $role = $rolesdump{$area};
 6826:         $area =~ s/\_\w\w$//;
 6827: 
 6828:         my ($trole, $tend, $tstart, $group_privs);
 6829: 
 6830:         if ($role =~ /^cr/) {
 6831:         # Custom role, defined by a user 
 6832:         # e.g., user.role.cr/msu/smith/mynewrole
 6833:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6834:                 $trole = $1;
 6835:                 ($tend, $tstart) = split('_', $2);
 6836:             } else {
 6837:                 $trole = $role;
 6838:             }
 6839:         } elsif ($role =~ m|^gr/|) {
 6840:         # Role of member in a group, defined within a course/community
 6841:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6842:             ($trole, $tend, $tstart) = split(/_/, $role);
 6843:             next if $tstart eq '-1';
 6844:             ($trole, $group_privs) = split(/\//, $trole);
 6845:             $group_privs = &unescape($group_privs);
 6846:         } else {
 6847:         # Just a normal role, defined in roles.tab
 6848:             ($trole, $tend, $tstart) = split(/_/,$role);
 6849:         }
 6850: 
 6851:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6852:                  $username);
 6853:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6854: 
 6855:         # role expired or not available yet?
 6856:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6857:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6858: 
 6859:         next if $area eq '' or $trole eq '';
 6860: 
 6861:         my $spec = "$trole.$area";
 6862:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6863: 
 6864:         if ($trole =~ /^cr\//) {
 6865:         # Custom role, defined by a user
 6866:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6867:         } elsif ($trole eq 'gr') {
 6868:         # Role of a member in a group, defined within a course/community
 6869:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6870:             next;
 6871:         } else {
 6872:         # Normal role, defined in roles.tab
 6873:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6874:         }
 6875: 
 6876:         my $cid = $tdomain.'_'.$trest;
 6877:         unless ($firstaccchk{$cid}) {
 6878:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6879:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6880:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6881:                         $coursetimerstarts{$cid}{$item}; 
 6882:                 }
 6883:             }
 6884:             $firstaccchk{$cid} = 1;
 6885:         }
 6886:         unless ($timerintchk{$cid}) {
 6887:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6888:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6889:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6890:                        $coursetimerintervals{$cid}{$item};
 6891:                 }
 6892:             }
 6893:             $timerintchk{$cid} = 1;
 6894:         }
 6895:     }
 6896: 
 6897:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6898:                                                           \%allroles, \%allgroups);
 6899:     $env{'user.adv'} = $userroles{'user.adv'};
 6900:     $env{'user.rar'} = $userroles{'user.rar'};
 6901: 
 6902:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6903: }
 6904: 
 6905: sub set_arearole {
 6906:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6907:     unless ($nolog) {
 6908: # log the associated role with the area
 6909:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6910:     }
 6911:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6912: }
 6913: 
 6914: sub custom_roleprivs {
 6915:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6916:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6917:     my $homsvr = &homeserver($rauthor,$rdomain);
 6918:     if (&hostname($homsvr) ne '') {
 6919:         my ($rdummy,$roledef)=
 6920:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6921:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6922:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6923:             if (defined($syspriv)) {
 6924:                 if ($trest =~ /^$match_community$/) {
 6925:                     $syspriv =~ s/bre\&S//; 
 6926:                 }
 6927:                 $$allroles{'cm./'}.=':'.$syspriv;
 6928:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6929:             }
 6930:             if ($tdomain ne '') {
 6931:                 if (defined($dompriv)) {
 6932:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6933:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6934:                 }
 6935:                 if (($trest ne '') && (defined($coursepriv))) {
 6936:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6937:                         my $rolename = $1;
 6938:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6939:                     }
 6940:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6941:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6942:                 }
 6943:             }
 6944:         }
 6945:     }
 6946: }
 6947: 
 6948: sub course_adhocrole_privs {
 6949:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6950:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6951:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6952:         my (%currprivs,%storeprivs);
 6953:         foreach my $item (split(/:/,$coursepriv)) {
 6954:             my ($priv,$restrict) = split(/\&/,$item);
 6955:             $currprivs{$priv} = $restrict;
 6956:         }
 6957:         my (%possadd,%possremove,%full);
 6958:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6959:             my ($priv,$restrict)=split(/\&/,$item);
 6960:             $full{$priv} = $restrict;
 6961:         }
 6962:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6963:             next if ($item eq '');
 6964:             my ($rule,$rest) = split(/=/,$item);
 6965:             next unless (($rule eq 'off') || ($rule eq 'on'));
 6966:             foreach my $priv (split(/:/,$rest)) {
 6967:                 if ($priv ne '') {
 6968:                     if ($rule eq 'off') {
 6969:                         $possremove{$priv} = 1;
 6970:                     } else {
 6971:                         $possadd{$priv} = 1;
 6972:                     }
 6973:                 }
 6974:             }
 6975:         }
 6976:         foreach my $priv (sort(keys(%full))) {
 6977:             if (exists($currprivs{$priv})) {
 6978:                 unless (exists($possremove{$priv})) {
 6979:                     $storeprivs{$priv} = $currprivs{$priv};
 6980:                 }
 6981:             } elsif (exists($possadd{$priv})) {
 6982:                 $storeprivs{$priv} = $full{$priv};
 6983:             }
 6984:         }
 6985:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6986:     }
 6987:     return $coursepriv;
 6988: }
 6989: 
 6990: sub group_roleprivs {
 6991:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6992:     my $access = 1;
 6993:     my $now = time;
 6994:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6995:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6996:     if ($access) {
 6997:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6998:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6999:     }
 7000: }
 7001: 
 7002: sub standard_roleprivs {
 7003:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7004:     if (defined($pr{$trole.':s'})) {
 7005:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7006:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7007:     }
 7008:     if ($tdomain ne '') {
 7009:         if (defined($pr{$trole.':d'})) {
 7010:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7011:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7012:         }
 7013:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7014:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7015:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7016:         }
 7017:     }
 7018: }
 7019: 
 7020: sub set_userprivs {
 7021:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7022:     my $author=0;
 7023:     my $adv=0;
 7024:     my $rar=0;
 7025:     my %grouproles = ();
 7026:     if (keys(%{$allgroups}) > 0) {
 7027:         my @groupkeys; 
 7028:         foreach my $role (keys(%{$allroles})) {
 7029:             push(@groupkeys,$role);
 7030:         }
 7031:         if (ref($groups_roles) eq 'HASH') {
 7032:             foreach my $key (keys(%{$groups_roles})) {
 7033:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7034:                     push(@groupkeys,$key);
 7035:                 }
 7036:             }
 7037:         }
 7038:         if (@groupkeys > 0) {
 7039:             foreach my $role (@groupkeys) {
 7040:                 my ($trole,$area,$sec,$extendedarea);
 7041:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7042:                     $trole = $1;
 7043:                     $area = $2;
 7044:                     $sec = $3;
 7045:                     $extendedarea = $area.$sec;
 7046:                     if (exists($$allgroups{$area})) {
 7047:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7048:                             my $spec = $trole.'.'.$extendedarea;
 7049:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7050:                                                 $$allgroups{$area}{$group};
 7051:                         }
 7052:                     }
 7053:                 }
 7054:             }
 7055:         }
 7056:     }
 7057:     foreach my $group (keys(%grouproles)) {
 7058:         $$allroles{$group} = $grouproles{$group};
 7059:     }
 7060:     foreach my $role (keys(%{$allroles})) {
 7061:         my %thesepriv;
 7062:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7063:         foreach my $item (split(/:/,$$allroles{$role})) {
 7064:             if ($item ne '') {
 7065:                 my ($privilege,$restrictions)=split(/&/,$item);
 7066:                 if ($restrictions eq '') {
 7067:                     $thesepriv{$privilege}='F';
 7068:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7069:                     $thesepriv{$privilege}.=$restrictions;
 7070:                 }
 7071:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7072:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7073:             }
 7074:         }
 7075:         my $thesestr='';
 7076:         foreach my $priv (sort(keys(%thesepriv))) {
 7077: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7078: 	}
 7079:         $userroles->{'user.priv.'.$role} = $thesestr;
 7080:     }
 7081:     return ($author,$adv,$rar);
 7082: }
 7083: 
 7084: sub role_status {
 7085:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7086:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7087:         my ($one,$two) = split(m{\./},$rolekey,2);
 7088:         (undef,undef,$$role) = split(/\./,$one,3);
 7089:         unless (!defined($$role) || $$role eq '') {
 7090:             $$where = '/'.$two;
 7091:             $$trolecode=$$role.'.'.$$where;
 7092:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7093:             $$tstatus='is';
 7094:             if ($$tstart && $$tstart>$update) {
 7095:                 $$tstatus='future';
 7096:                 if ($$tstart<$now) {
 7097:                     if ($$tstart && $$tstart>$refresh) {
 7098:                         if (($$where ne '') && ($$role ne '')) {
 7099:                             my (%allroles,%allgroups,$group_privs,
 7100:                                 %groups_roles,@rolecodes);
 7101:                             my %userroles = (
 7102:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7103:                             );
 7104:                             @rolecodes = ('cm'); 
 7105:                             my $spec=$$role.'.'.$$where;
 7106:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7107:                             if ($$role =~ /^cr\//) {
 7108:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7109:                                 push(@rolecodes,'cr');
 7110:                             } elsif ($$role eq 'gr') {
 7111:                                 push(@rolecodes,$$role);
 7112:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7113:                                                     $env{'user.name'});
 7114:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7115:                                 (undef,my $group_privs) = split(/\//,$trole);
 7116:                                 $group_privs = &unescape($group_privs);
 7117:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7118:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7119:                                 &get_groups_roles($tdomain,$trest,
 7120:                                                   \%course_roles,\@rolecodes,
 7121:                                                   \%groups_roles);
 7122:                             } else {
 7123:                                 push(@rolecodes,$$role);
 7124:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7125:                             }
 7126:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7127:                                                                    \%groups_roles);
 7128:                             &appenv(\%userroles,\@rolecodes);
 7129:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7130:                         }
 7131:                     }
 7132:                     $$tstatus = 'is';
 7133:                 }
 7134:             }
 7135:             if ($$tend) {
 7136:                 if ($$tend<$update) {
 7137:                     $$tstatus='expired';
 7138:                 } elsif ($$tend<$now) {
 7139:                     $$tstatus='will_not';
 7140:                 }
 7141:             }
 7142:         }
 7143:     }
 7144: }
 7145: 
 7146: sub get_groups_roles {
 7147:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7148:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7149:                   (ref($rolecodes) eq 'ARRAY') && 
 7150:                   (ref($groups_roles) eq 'HASH')); 
 7151:     if (keys(%{$cdom_courseroles}) > 0) {
 7152:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7153:         if ($cdom ne '' && $cnum ne '') {
 7154:             foreach my $key (keys(%{$cdom_courseroles})) {
 7155:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7156:                     my $crsrole = $1;
 7157:                     my $crssec = $2;
 7158:                     if ($crsrole =~ /^cr/) {
 7159:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7160:                             push(@{$rolecodes},'cr');
 7161:                         }
 7162:                     } else {
 7163:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7164:                             push(@{$rolecodes},$crsrole);
 7165:                         }
 7166:                     }
 7167:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7168:                     if ($crssec ne '') {
 7169:                         $rolekey .= "/$crssec";
 7170:                     }
 7171:                     $rolekey .= './';
 7172:                     $groups_roles->{$rolekey} = $rolecodes;
 7173:                 }
 7174:             }
 7175:         }
 7176:     }
 7177:     return;
 7178: }
 7179: 
 7180: sub delete_env_groupprivs {
 7181:     my ($where,$courseroles,$possroles) = @_;
 7182:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7183:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7184:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7185:         %{$courseroles->{$udom}} =
 7186:             &get_my_roles('','','userroles',['active'],
 7187:                           $possroles,[$udom],1);
 7188:     }
 7189:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7190:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7191:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7192:             my $area = '/'.$cdom.'/'.$cnum;
 7193:             my $privkey = "user.priv.$crsrole.$area";
 7194:             if ($crssec ne '') {
 7195:                 $privkey .= '/'.$crssec;
 7196:             }
 7197:             $privkey .= ".$area/$group";
 7198:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7199:         }
 7200:     }
 7201:     return;
 7202: }
 7203: 
 7204: sub check_adhoc_privs {
 7205:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7206:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7207:     if ($sec) {
 7208:         $cckey .= '/'.$sec;
 7209:     } 
 7210:     my $setprivs;
 7211:     if ($env{$cckey}) {
 7212:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7213:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7214:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7215:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7216:             $setprivs = 1;
 7217:         }
 7218:     } else {
 7219:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7220:         $setprivs = 1;
 7221:     }
 7222:     return $setprivs;
 7223: }
 7224: 
 7225: sub set_adhoc_privileges {
 7226: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7227:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7228:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7229:     if ($sec ne '') {
 7230:         $area .= '/'.$sec;
 7231:     }
 7232:     my $spec = $role.'.'.$area;
 7233:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7234:                                   $env{'user.name'},1);
 7235:     my %rolehash = ();
 7236:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7237:         my $rolename = $1;
 7238:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7239:         my %domdef = &get_domain_defaults($dcdom);
 7240:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7241:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7242:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7243:             }
 7244:         }
 7245:     } else {
 7246:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7247:     }
 7248:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7249:     &appenv(\%userroles,[$role,'cm']);
 7250:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7251:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7252:             ($caller eq 'tiny')) {
 7253:         &appenv( {'request.role'        => $spec,
 7254:                   'request.role.domain' => $dcdom,
 7255:                   'request.course.sec'  => $sec,
 7256:                  }
 7257:                );
 7258:         my $tadv=0;
 7259:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7260:         &appenv({'request.role.adv'    => $tadv});
 7261:     }
 7262: }
 7263: 
 7264: # --------------------------------------------------------------- get interface
 7265: 
 7266: sub get {
 7267:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7268:    my $items='';
 7269:    foreach my $item (@$storearr) {
 7270:        $items.=&escape($item).'&';
 7271:    }
 7272:    $items=~s/\&$//;
 7273:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7274:    if (!$uname) { $uname=$env{'user.name'}; }
 7275:    my $uhome=&homeserver($uname,$udomain);
 7276: 
 7277:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7278:    my @pairs=split(/\&/,$rep);
 7279:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7280:      return @pairs;
 7281:    }
 7282:    my %returnhash=();
 7283:    my $i=0;
 7284:    foreach my $item (@$storearr) {
 7285:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7286:       $i++;
 7287:    }
 7288:    return %returnhash;
 7289: }
 7290: 
 7291: # --------------------------------------------------------------- del interface
 7292: 
 7293: sub del {
 7294:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7295:    my $items='';
 7296:    foreach my $item (@$storearr) {
 7297:        $items.=&escape($item).'&';
 7298:    }
 7299: 
 7300:    $items=~s/\&$//;
 7301:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7302:    if (!$uname) { $uname=$env{'user.name'}; }
 7303:    my $uhome=&homeserver($uname,$udomain);
 7304:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7305: }
 7306: 
 7307: # -------------------------------------------------------------- dump interface
 7308: 
 7309: sub unserialize {
 7310:     my ($rep, $escapedkeys) = @_;
 7311: 
 7312:     return {} if $rep =~ /^error/;
 7313: 
 7314:     my %returnhash=();
 7315: 	foreach my $item (split(/\&/,$rep)) {
 7316: 	    my ($key, $value) = split(/=/, $item, 2);
 7317: 	    $key = unescape($key) unless $escapedkeys;
 7318: 	    next if $key =~ /^error: 2 /;
 7319: 	    $returnhash{$key} = &thaw_unescape($value);
 7320: 	}
 7321:     #return %returnhash;
 7322:     return \%returnhash;
 7323: }        
 7324: 
 7325: # see Lond::dump_with_regexp
 7326: # if $escapedkeys hash keys won't get unescaped.
 7327: sub dump {
 7328:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7329:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7330:     if (!$uname) { $uname=$env{'user.name'}; }
 7331:     my $uhome=&homeserver($uname,$udomain);
 7332: 
 7333:     if ($regexp) {
 7334:         $regexp=&escape($regexp);
 7335:     } else {
 7336:         $regexp='.';
 7337:     }
 7338:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7339:         # user is hosted on this machine
 7340:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7341:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7342:         return %{unserialize($reply, $escapedkeys)};
 7343:     }
 7344:     my $rep;
 7345:     if ($encrypt) {
 7346:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7347:     } else {
 7348:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7349:     }
 7350:     my @pairs=split(/\&/,$rep);
 7351:     my %returnhash=();
 7352:     if (!($rep =~ /^error/ )) {
 7353: 	foreach my $item (@pairs) {
 7354: 	    my ($key,$value)=split(/=/,$item,2);
 7355:         $key = unescape($key) unless $escapedkeys;
 7356:         #$key = &unescape($key);
 7357: 	    next if ($key =~ /^error: 2 /);
 7358: 	    $returnhash{$key}=&thaw_unescape($value);
 7359: 	}
 7360:     }
 7361:     return %returnhash;
 7362: }
 7363: 
 7364: 
 7365: # --------------------------------------------------------- dumpstore interface
 7366: 
 7367: sub dumpstore {
 7368:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7369:    # same as dump but keys must be escaped. They may contain colon separated
 7370:    # lists of values that may themself contain colons (e.g. symbs).
 7371:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7372: }
 7373: 
 7374: # -------------------------------------------------------------- keys interface
 7375: 
 7376: sub getkeys {
 7377:    my ($namespace,$udomain,$uname)=@_;
 7378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7379:    if (!$uname) { $uname=$env{'user.name'}; }
 7380:    my $uhome=&homeserver($uname,$udomain);
 7381:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7382:    my @keyarray=();
 7383:    foreach my $key (split(/\&/,$rep)) {
 7384:       next if ($key =~ /^error: 2 /);
 7385:       push(@keyarray,&unescape($key));
 7386:    }
 7387:    return @keyarray;
 7388: }
 7389: 
 7390: # --------------------------------------------------------------- currentdump
 7391: sub currentdump {
 7392:    my ($courseid,$sdom,$sname)=@_;
 7393:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7394:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7395:    $sname    = $env{'user.name'}         if (! defined($sname));
 7396:    my $uhome = &homeserver($sname,$sdom);
 7397:    my $rep;
 7398: 
 7399:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7400:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7401:                    $courseid)));
 7402:    } else {
 7403:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7404:    }
 7405: 
 7406:    return if ($rep =~ /^(error:|no_such_host)/);
 7407:    #
 7408:    my %returnhash=();
 7409:    #
 7410:    if ($rep eq 'unknown_cmd') {
 7411:        # an old lond will not know currentdump
 7412:        # Do a dump and make it look like a currentdump
 7413:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7414:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7415:        my %hash = @tmp;
 7416:        @tmp=();
 7417:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7418:    } else {
 7419:        my @pairs=split(/\&/,$rep);
 7420:        foreach my $pair (@pairs) {
 7421:            my ($key,$value)=split(/=/,$pair,2);
 7422:            my ($symb,$param) = split(/:/,$key);
 7423:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7424:                                                         &thaw_unescape($value);
 7425:        }
 7426:    }
 7427:    return %returnhash;
 7428: }
 7429: 
 7430: sub convert_dump_to_currentdump{
 7431:     my %hash = %{shift()};
 7432:     my %returnhash;
 7433:     # Code ripped from lond, essentially.  The only difference
 7434:     # here is the unescaping done by lonnet::dump().  Conceivably
 7435:     # we might run in to problems with parameter names =~ /^v\./
 7436:     while (my ($key,$value) = each(%hash)) {
 7437:         my ($v,$symb,$param) = split(/:/,$key);
 7438: 	$symb  = &unescape($symb);
 7439: 	$param = &unescape($param);
 7440:         next if ($v eq 'version' || $symb eq 'keys');
 7441:         next if (exists($returnhash{$symb}) &&
 7442:                  exists($returnhash{$symb}->{$param}) &&
 7443:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7444:         $returnhash{$symb}->{$param}=$value;
 7445:         $returnhash{$symb}->{'v.'.$param}=$v;
 7446:     }
 7447:     #
 7448:     # Remove all of the keys in the hashes which keep track of
 7449:     # the version of the parameter.
 7450:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7451:         # use a foreach because we are going to delete from the hash.
 7452:         foreach my $key (keys(%$param_hash)) {
 7453:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7454:         }
 7455:     }
 7456:     return \%returnhash;
 7457: }
 7458: 
 7459: # ------------------------------------------------------ critical inc interface
 7460: 
 7461: sub cinc {
 7462:     return &inc(@_,'critical');
 7463: }
 7464: 
 7465: # --------------------------------------------------------------- inc interface
 7466: 
 7467: sub inc {
 7468:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7469:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7470:     if (!$uname) { $uname=$env{'user.name'}; }
 7471:     my $uhome=&homeserver($uname,$udomain);
 7472:     my $items='';
 7473:     if (! ref($store)) {
 7474:         # got a single value, so use that instead
 7475:         $items = &escape($store).'=&';
 7476:     } elsif (ref($store) eq 'SCALAR') {
 7477:         $items = &escape($$store).'=&';        
 7478:     } elsif (ref($store) eq 'ARRAY') {
 7479:         $items = join('=&',map {&escape($_);} @{$store});
 7480:     } elsif (ref($store) eq 'HASH') {
 7481:         while (my($key,$value) = each(%{$store})) {
 7482:             $items.= &escape($key).'='.&escape($value).'&';
 7483:         }
 7484:     }
 7485:     $items=~s/\&$//;
 7486:     if ($critical) {
 7487: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7488:     } else {
 7489: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7490:     }
 7491: }
 7492: 
 7493: # --------------------------------------------------------------- put interface
 7494: 
 7495: sub put {
 7496:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7497:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7498:    if (!$uname) { $uname=$env{'user.name'}; }
 7499:    my $uhome=&homeserver($uname,$udomain);
 7500:    my $items='';
 7501:    foreach my $item (keys(%$storehash)) {
 7502:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7503:    }
 7504:    $items=~s/\&$//;
 7505:    if ($encrypt) {
 7506:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7507:    } else {
 7508:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7509:    }
 7510: }
 7511: 
 7512: # ------------------------------------------------------------ newput interface
 7513: 
 7514: sub newput {
 7515:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7516:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7517:    if (!$uname) { $uname=$env{'user.name'}; }
 7518:    my $uhome=&homeserver($uname,$udomain);
 7519:    my $items='';
 7520:    foreach my $key (keys(%$storehash)) {
 7521:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7522:    }
 7523:    $items=~s/\&$//;
 7524:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7525: }
 7526: 
 7527: # ---------------------------------------------------------  putstore interface
 7528: 
 7529: sub putstore {
 7530:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7532:    if (!$uname) { $uname=$env{'user.name'}; }
 7533:    my $uhome=&homeserver($uname,$udomain);
 7534:    my $items='';
 7535:    foreach my $key (keys(%$storehash)) {
 7536:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7537:    }
 7538:    $items=~s/\&$//;
 7539:    my $esc_symb=&escape($symb);
 7540:    my $esc_v=&escape($version);
 7541:    my $reply =
 7542:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7543: 	      $uhome);
 7544:    if (($tolog) && ($reply eq 'ok')) {
 7545:        my $namevalue='';
 7546:        foreach my $key (keys(%{$storehash})) {
 7547:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7548:        }
 7549:        my $ip = &get_requestor_ip();
 7550:        $namevalue .= 'ip='.&escape($ip).
 7551:                      '&host='.&escape($perlvar{'lonHostID'}).
 7552:                      '&version='.$esc_v.
 7553:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7554:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7555:    }
 7556:    if ($reply eq 'unknown_cmd') {
 7557:        # gfall back to way things use to be done
 7558:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7559: 			    $uname);
 7560:    }
 7561:    return $reply;
 7562: }
 7563: 
 7564: sub old_putstore {
 7565:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7566:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7567:     if (!$uname) { $uname=$env{'user.name'}; }
 7568:     my $uhome=&homeserver($uname,$udomain);
 7569:     my %newstorehash;
 7570:     foreach my $item (keys(%$storehash)) {
 7571: 	my $key = $version.':'.&escape($symb).':'.$item;
 7572: 	$newstorehash{$key} = $storehash->{$item};
 7573:     }
 7574:     my $items='';
 7575:     my %allitems = ();
 7576:     foreach my $item (keys(%newstorehash)) {
 7577: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7578: 	    my $key = $1.':keys:'.$2;
 7579: 	    $allitems{$key} .= $3.':';
 7580: 	}
 7581: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7582:     }
 7583:     foreach my $item (keys(%allitems)) {
 7584: 	$allitems{$item} =~ s/\:$//;
 7585: 	$items.= $item.'='.$allitems{$item}.'&';
 7586:     }
 7587:     $items=~s/\&$//;
 7588:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7589: }
 7590: 
 7591: # ------------------------------------------------------ critical put interface
 7592: 
 7593: sub cput {
 7594:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7595:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7596:    if (!$uname) { $uname=$env{'user.name'}; }
 7597:    my $uhome=&homeserver($uname,$udomain);
 7598:    my $items='';
 7599:    foreach my $item (keys(%$storehash)) {
 7600:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7601:    }
 7602:    $items=~s/\&$//;
 7603:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7604: }
 7605: 
 7606: # -------------------------------------------------------------- eget interface
 7607: 
 7608: sub eget {
 7609:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7610:    my $items='';
 7611:    foreach my $item (@$storearr) {
 7612:        $items.=&escape($item).'&';
 7613:    }
 7614:    $items=~s/\&$//;
 7615:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7616:    if (!$uname) { $uname=$env{'user.name'}; }
 7617:    my $uhome=&homeserver($uname,$udomain);
 7618:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7619:    my @pairs=split(/\&/,$rep);
 7620:    my %returnhash=();
 7621:    my $i=0;
 7622:    foreach my $item (@$storearr) {
 7623:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7624:       $i++;
 7625:    }
 7626:    return %returnhash;
 7627: }
 7628: 
 7629: # ------------------------------------------------------------ tmpput interface
 7630: sub tmpput {
 7631:     my ($storehash,$server,$context)=@_;
 7632:     my $items='';
 7633:     foreach my $item (keys(%$storehash)) {
 7634: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7635:     }
 7636:     $items=~s/\&$//;
 7637:     if (defined($context)) {
 7638:         $items .= ':'.&escape($context);
 7639:     }
 7640:     return &reply("tmpput:$items",$server);
 7641: }
 7642: 
 7643: # ------------------------------------------------------------ tmpget interface
 7644: sub tmpget {
 7645:     my ($token,$server)=@_;
 7646:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7647:     my $rep=&reply("tmpget:$token",$server);
 7648:     my %returnhash;
 7649:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7650:         return %returnhash;
 7651:     }
 7652:     foreach my $item (split(/\&/,$rep)) {
 7653: 	my ($key,$value)=split(/=/,$item);
 7654: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7655:     }
 7656:     return %returnhash;
 7657: }
 7658: 
 7659: # ------------------------------------------------------------ tmpdel interface
 7660: sub tmpdel {
 7661:     my ($token,$server)=@_;
 7662:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7663:     return &reply("tmpdel:$token",$server);
 7664: }
 7665: 
 7666: # ------------------------------------------------------------ get_timebased_id 
 7667: 
 7668: sub get_timebased_id {
 7669:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7670:         $maxtries) = @_;
 7671:     my ($newid,$error,$dellock);
 7672:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7673:         return ('','ok','invalid call to get suffix');
 7674:     }
 7675: 
 7676: # set defaults for any optional args for which values were not supplied
 7677:     if ($who eq '') {
 7678:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7679:     }
 7680:     if (!$locktries) {
 7681:         $locktries = 3;
 7682:     }
 7683:     if (!$maxtries) {
 7684:         $maxtries = 10;
 7685:     }
 7686:     
 7687:     if (($cdom eq '') || ($cnum eq '')) {
 7688:         if ($env{'request.course.id'}) {
 7689:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7690:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7691:         }
 7692:         if (($cdom eq '') || ($cnum eq '')) {
 7693:             return ('','ok','call to get suffix not in course context');
 7694:         }
 7695:     }
 7696: 
 7697: # construct locking item
 7698:     my $lockhash = {
 7699:                       $prefix."\0".'locked_'.$keyid => $who,
 7700:                    };
 7701:     my $tries = 0;
 7702: 
 7703: # attempt to get lock on nohist_$namespace file
 7704:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7705:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7706:         $tries ++;
 7707:         sleep 1;
 7708:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7709:     }
 7710: 
 7711: # attempt to get unique identifier, based on current timestamp
 7712:     if ($gotlock eq 'ok') {
 7713:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7714:         my $id = time;
 7715:         $newid = $id;
 7716:         if ($idtype eq 'addcode') {
 7717:             $newid .= &sixnum_code();
 7718:         }
 7719:         my $idtries = 0;
 7720:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7721:             if ($idtype eq 'concat') {
 7722:                 $newid = $id.$idtries;
 7723:             } elsif ($idtype eq 'addcode') {
 7724:                 $newid = $newid.&sixnum_code();
 7725:             } else {
 7726:                 $newid ++;
 7727:             }
 7728:             $idtries ++;
 7729:         }
 7730:         if (!exists($inuse{$prefix."\0".$newid})) {
 7731:             my %new_item =  (
 7732:                               $prefix."\0".$newid => $who,
 7733:                             );
 7734:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7735:                                                  $cdom,$cnum);
 7736:             if ($putresult ne 'ok') {
 7737:                 undef($newid);
 7738:                 $error = 'error saving new item: '.$putresult;
 7739:             }
 7740:         } else {
 7741:              undef($newid);
 7742:              $error = ('error: no unique suffix available for the new item ');
 7743:         }
 7744: #  remove lock
 7745:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7746:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7747:     } else {
 7748:         $error = "error: could not obtain lockfile\n";
 7749:         $dellock = 'ok';
 7750:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7751:             $dellock = 'nolock';
 7752:         }
 7753:     }
 7754:     return ($newid,$dellock,$error);
 7755: }
 7756: 
 7757: sub sixnum_code {
 7758:     my $code;
 7759:     for (0..6) {
 7760:         $code .= int( rand(9) );
 7761:     }
 7762:     return $code;
 7763: }
 7764: 
 7765: # -------------------------------------------------- portfolio access checking
 7766: 
 7767: sub portfolio_access {
 7768:     my ($requrl,$clientip) = @_;
 7769:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7770:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7771:     if ($result) {
 7772:         my %setters;
 7773:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7774:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7775:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7776:             if (($startblock && $endblock) || ($by_ip)) {
 7777:                 return 'B';
 7778:             }
 7779:         } else {
 7780:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7781:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7782:             if (($startblock && $endblock) || ($by_ip)) {
 7783:                 return 'B';
 7784:             }
 7785:         }
 7786:     }
 7787:     if ($result eq 'ok') {
 7788:        return 'F';
 7789:     } elsif ($result =~ /^[^:]+:guest_/) {
 7790:        return 'A';
 7791:     }
 7792:     return '';
 7793: }
 7794: 
 7795: sub get_portfolio_access {
 7796:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7797: 
 7798:     if (!ref($access_hash)) {
 7799: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7800: 	my %access_controls = &get_access_controls($current_perms,$group,
 7801: 						   $file_name);
 7802: 	$access_hash = $access_controls{$file_name};
 7803:     }
 7804: 
 7805:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7806:     my $now = time;
 7807:     if (ref($access_hash) eq 'HASH') {
 7808:         foreach my $key (keys(%{$access_hash})) {
 7809:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7810:             if ($start > $now) {
 7811:                 next;
 7812:             }
 7813:             if ($end && $end<$now) {
 7814:                 next;
 7815:             }
 7816:             if ($scope eq 'public') {
 7817:                 $public = $key;
 7818:                 last;
 7819:             } elsif ($scope eq 'guest') {
 7820:                 $guest = $key;
 7821:             } elsif ($scope eq 'domains') {
 7822:                 push(@domains,$key);
 7823:             } elsif ($scope eq 'users') {
 7824:                 push(@users,$key);
 7825:             } elsif ($scope eq 'course') {
 7826:                 push(@courses,$key);
 7827:             } elsif ($scope eq 'group') {
 7828:                 push(@groups,$key);
 7829:             } elsif ($scope eq 'ip') {
 7830:                 push(@ips,$key);
 7831:             }
 7832:         }
 7833:         if ($public) {
 7834:             return 'ok';
 7835:         } elsif (@ips > 0) {
 7836:             my $allowed;
 7837:             foreach my $ipkey (@ips) {
 7838:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7839:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7840:                         $allowed = 1;
 7841:                         last; 
 7842:                     }
 7843:                 }
 7844:             }
 7845:             if ($allowed) {
 7846:                 return 'ok';
 7847:             }
 7848:         }
 7849:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7850:             if ($guest) {
 7851:                 return $guest;
 7852:             }
 7853:         } else {
 7854:             if (@domains > 0) {
 7855:                 foreach my $domkey (@domains) {
 7856:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7857:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7858:                             return 'ok';
 7859:                         }
 7860:                     }
 7861:                 }
 7862:             }
 7863:             if (@users > 0) {
 7864:                 foreach my $userkey (@users) {
 7865:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7866:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7867:                             if (ref($item) eq 'HASH') {
 7868:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7869:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7870:                                     return 'ok';
 7871:                                 }
 7872:                             }
 7873:                         }
 7874:                     } 
 7875:                 }
 7876:             }
 7877:             my %roleshash;
 7878:             my @courses_and_groups = @courses;
 7879:             push(@courses_and_groups,@groups); 
 7880:             if (@courses_and_groups > 0) {
 7881:                 my (%allgroups,%allroles); 
 7882:                 my ($start,$end,$role,$sec,$group);
 7883:                 foreach my $envkey (%env) {
 7884:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7885:                         my $cid = $2.'_'.$3; 
 7886:                         if ($1 eq 'gr') {
 7887:                             $group = $4;
 7888:                             $allgroups{$cid}{$group} = $env{$envkey};
 7889:                         } else {
 7890:                             if ($4 eq '') {
 7891:                                 $sec = 'none';
 7892:                             } else {
 7893:                                 $sec = $4;
 7894:                             }
 7895:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7896:                         }
 7897:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7898:                         my $cid = $2.'_'.$3;
 7899:                         if ($4 eq '') {
 7900:                             $sec = 'none';
 7901:                         } else {
 7902:                             $sec = $4;
 7903:                         }
 7904:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7905:                     }
 7906:                 }
 7907:                 if (keys(%allroles) == 0) {
 7908:                     return;
 7909:                 }
 7910:                 foreach my $key (@courses_and_groups) {
 7911:                     my %content = %{$$access_hash{$key}};
 7912:                     my $cnum = $content{'number'};
 7913:                     my $cdom = $content{'domain'};
 7914:                     my $cid = $cdom.'_'.$cnum;
 7915:                     if (!exists($allroles{$cid})) {
 7916:                         next;
 7917:                     }    
 7918:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7919:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7920:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7921:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7922:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7923:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7924:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7925:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7926:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7927:                                         if (grep/^all$/,@sections) {
 7928:                                             return 'ok';
 7929:                                         } else {
 7930:                                             if (grep/^$sec$/,@sections) {
 7931:                                                 return 'ok';
 7932:                                             }
 7933:                                         }
 7934:                                     }
 7935:                                 }
 7936:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7937:                                     if (grep/^none$/,@groups) {
 7938:                                         return 'ok';
 7939:                                     }
 7940:                                 } else {
 7941:                                     if (grep/^all$/,@groups) {
 7942:                                         return 'ok';
 7943:                                     } 
 7944:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7945:                                         if (grep/^$group$/,@groups) {
 7946:                                             return 'ok';
 7947:                                         }
 7948:                                     }
 7949:                                 } 
 7950:                             }
 7951:                         }
 7952:                     }
 7953:                 }
 7954:             }
 7955:             if ($guest) {
 7956:                 return $guest;
 7957:             }
 7958:         }
 7959:     }
 7960:     return;
 7961: }
 7962: 
 7963: sub course_group_datechecker {
 7964:     my ($dates,$now,$status) = @_;
 7965:     my ($start,$end) = split(/\./,$dates);
 7966:     if (!$start && !$end) {
 7967:         return 'ok';
 7968:     }
 7969:     if (grep/^active$/,@{$status}) {
 7970:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7971:             return 'ok';
 7972:         }
 7973:     }
 7974:     if (grep/^previous$/,@{$status}) {
 7975:         if ($end > $now ) {
 7976:             return 'ok';
 7977:         }
 7978:     }
 7979:     if (grep/^future$/,@{$status}) {
 7980:         if ($start > $now) {
 7981:             return 'ok';
 7982:         }
 7983:     }
 7984:     return; 
 7985: }
 7986: 
 7987: sub parse_portfolio_url {
 7988:     my ($url) = @_;
 7989: 
 7990:     my ($type,$udom,$unum,$group,$file_name);
 7991:     
 7992:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7993: 	$type = 1;
 7994:         $udom = $1;
 7995:         $unum = $2;
 7996:         $file_name = $3;
 7997:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7998: 	$type = 2;
 7999:         $udom = $1;
 8000:         $unum = $2;
 8001:         $group = $3;
 8002:         $file_name = $3.'/'.$4;
 8003:     }
 8004:     if (wantarray) {
 8005: 	return ($type,$udom,$unum,$file_name,$group);
 8006:     }
 8007:     return $type;
 8008: }
 8009: 
 8010: sub is_portfolio_url {
 8011:     my ($url) = @_;
 8012:     return scalar(&parse_portfolio_url($url));
 8013: }
 8014: 
 8015: sub is_portfolio_file {
 8016:     my ($file) = @_;
 8017:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8018:         return 1;
 8019:     }
 8020:     return;
 8021: }
 8022: 
 8023: sub is_coursetool_logo {
 8024:     my ($uri) = @_;
 8025:     if ($env{'request.course.id'}) {
 8026:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8027:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8028:             return 1;
 8029:         }
 8030:     }
 8031:     return;
 8032: }
 8033: 
 8034: sub usertools_access {
 8035:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8036:     my ($access,%tools);
 8037:     if ($context eq '') {
 8038:         $context = 'tools';
 8039:     }
 8040:     if ($context eq 'requestcourses') {
 8041:         %tools = (
 8042:                       official   => 1,
 8043:                       unofficial => 1,
 8044:                       community  => 1,
 8045:                       textbook   => 1,
 8046:                       placement  => 1,
 8047:                       lti        => 1,
 8048:                  );
 8049:     } elsif ($context eq 'requestauthor') {
 8050:         %tools = (
 8051:                       requestauthor => 1,
 8052:                  );
 8053:     } else {
 8054:         %tools = (
 8055:                       aboutme   => 1,
 8056:                       blog      => 1,
 8057:                       webdav    => 1,
 8058:                       portfolio => 1,
 8059:                       timezone  => 1,
 8060:                  );
 8061:     }
 8062:     return if (!defined($tools{$tool}));
 8063: 
 8064:     if (($udom eq '') || ($uname eq '')) {
 8065:         $udom = $env{'user.domain'};
 8066:         $uname = $env{'user.name'};
 8067:     }
 8068: 
 8069:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8070:         if ($action ne 'reload') {
 8071:             if ($context eq 'requestcourses') {
 8072:                 return $env{'environment.canrequest.'.$tool};
 8073:             } elsif ($context eq 'requestauthor') {
 8074:                 return $env{'environment.canrequest.author'};
 8075:             } else {
 8076:                 return $env{'environment.availabletools.'.$tool};
 8077:             }
 8078:         }
 8079:     }
 8080: 
 8081:     my ($toolstatus,$inststatus,$envkey);
 8082:     if ($context eq 'requestauthor') {
 8083:         $envkey = $context; 
 8084:     } else {
 8085:         $envkey = $context.'.'.$tool;
 8086:     }
 8087: 
 8088:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8089:          ($action ne 'reload')) {
 8090:         $toolstatus = $env{'environment.'.$envkey};
 8091:         $inststatus = $env{'environment.inststatus'};
 8092:     } else {
 8093:         if (ref($userenvref) eq 'HASH') {
 8094:             $toolstatus = $userenvref->{$envkey};
 8095:             $inststatus = $userenvref->{'inststatus'};
 8096:         } else {
 8097:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8098:             $toolstatus = $userenv{$envkey};
 8099:             $inststatus = $userenv{'inststatus'};
 8100:         }
 8101:     }
 8102: 
 8103:     if ($toolstatus ne '') {
 8104:         if ($toolstatus) {
 8105:             $access = 1;
 8106:         } else {
 8107:             $access = 0;
 8108:         }
 8109:         return $access;
 8110:     }
 8111: 
 8112:     my ($is_adv,%domdef);
 8113:     if (ref($is_advref) eq 'HASH') {
 8114:         $is_adv = $is_advref->{'is_adv'};
 8115:     } else {
 8116:         $is_adv = &is_advanced_user($udom,$uname);
 8117:     }
 8118:     if (ref($domdefref) eq 'HASH') {
 8119:         %domdef = %{$domdefref};
 8120:     } else {
 8121:         %domdef = &get_domain_defaults($udom);
 8122:     }
 8123:     if (ref($domdef{$tool}) eq 'HASH') {
 8124:         if ($is_adv) {
 8125:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8126:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8127:                     $access = 1;
 8128:                 } else {
 8129:                     $access = 0;
 8130:                 }
 8131:                 return $access;
 8132:             }
 8133:         }
 8134:         if ($inststatus ne '') {
 8135:             my ($hasaccess,$hasnoaccess);
 8136:             foreach my $affiliation (split(/:/,$inststatus)) {
 8137:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8138:                     if ($domdef{$tool}{$affiliation}) {
 8139:                         $hasaccess = 1;
 8140:                     } else {
 8141:                         $hasnoaccess = 1;
 8142:                     }
 8143:                 }
 8144:             }
 8145:             if ($hasaccess || $hasnoaccess) {
 8146:                 if ($hasaccess) {
 8147:                     $access = 1;
 8148:                 } elsif ($hasnoaccess) {
 8149:                     $access = 0; 
 8150:                 }
 8151:                 return $access;
 8152:             }
 8153:         } else {
 8154:             if ($domdef{$tool}{'default'} ne '') {
 8155:                 if ($domdef{$tool}{'default'}) {
 8156:                     $access = 1;
 8157:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8158:                     $access = 0;
 8159:                 }
 8160:                 return $access;
 8161:             }
 8162:         }
 8163:     } else {
 8164:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8165:             $access = 1;
 8166:         } else {
 8167:             $access = 0;
 8168:         }
 8169:         return $access;
 8170:     }
 8171: }
 8172: 
 8173: sub is_course_owner {
 8174:     my ($cdom,$cnum,$udom,$uname) = @_;
 8175:     if (($udom eq '') || ($uname eq '')) {
 8176:         $udom = $env{'user.domain'};
 8177:         $uname = $env{'user.name'};
 8178:     }
 8179:     unless (($udom eq '') || ($uname eq '')) {
 8180:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8181:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8182:                 return 1;
 8183:             } else {
 8184:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8185:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8186:                     return 1;
 8187:                 }
 8188:             }
 8189:         }
 8190:     }
 8191:     return;
 8192: }
 8193: 
 8194: sub is_advanced_user {
 8195:     my ($udom,$uname) = @_;
 8196:     if ($udom ne '' && $uname ne '') {
 8197:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8198:             if (wantarray) {
 8199:                 return ($env{'user.adv'},$env{'user.author'});
 8200:             } else {
 8201:                 return $env{'user.adv'};
 8202:             }
 8203:         }
 8204:     }
 8205:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8206:     my %allroles;
 8207:     my ($is_adv,$is_author);
 8208:     foreach my $role (keys(%roleshash)) {
 8209:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8210:         my $area = '/'.$tdomain.'/'.$trest;
 8211:         if ($sec ne '') {
 8212:             $area .= '/'.$sec;
 8213:         }
 8214:         if (($area ne '') && ($trole ne '')) {
 8215:             my $spec=$trole.'.'.$area;
 8216:             if ($trole =~ /^cr\//) {
 8217:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8218:             } elsif ($trole ne 'gr') {
 8219:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8220:             }
 8221:             if ($trole eq 'au') {
 8222:                 $is_author = 1;
 8223:             }
 8224:         }
 8225:     }
 8226:     foreach my $role (keys(%allroles)) {
 8227:         last if ($is_adv);
 8228:         foreach my $item (split(/:/,$allroles{$role})) {
 8229:             if ($item ne '') {
 8230:                 my ($privilege,$restrictions)=split(/&/,$item);
 8231:                 if ($privilege eq 'adv') {
 8232:                     $is_adv = 1;
 8233:                     last;
 8234:                 }
 8235:             }
 8236:         }
 8237:     }
 8238:     if (wantarray) {
 8239:         return ($is_adv,$is_author);
 8240:     }
 8241:     return $is_adv;
 8242: }
 8243: 
 8244: sub check_can_request {
 8245:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8246:     my $canreq = 0;
 8247:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8248:         $uname = $env{'user.name'};
 8249:         $udom = $env{'user.domain'};
 8250:     }
 8251:     my ($types,$typename) = &Apache::loncommon::course_types();
 8252:     my @options = ('approval','validate','autolimit');
 8253:     my $optregex = join('|',@options);
 8254:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8255:         my %willtrust;
 8256:         foreach my $type (@{$types}) {
 8257:             if (&usertools_access($uname,$udom,$type,undef,
 8258:                                   'requestcourses')) {
 8259:                 $canreq ++;
 8260:                 if (ref($request_domains) eq 'HASH') {
 8261:                     push(@{$request_domains->{$type}},$udom);
 8262:                 }
 8263:                 if ($dom eq $udom) {
 8264:                     $can_request->{$type} = 1;
 8265:                 }
 8266:             }
 8267:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8268:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8269:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8270:                 if (@curr > 0) {
 8271:                     foreach my $item (@curr) {
 8272:                         if (ref($request_domains) eq 'HASH') {
 8273:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8274:                             if ($otherdom ne '') {
 8275:                                 unless (exists($willtrust{$otherdom})) {
 8276:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8277:                                 }
 8278:                                 if ($willtrust{$otherdom}) {
 8279:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8280:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8281:                                             push(@{$request_domains->{$type}},$otherdom);
 8282:                                         }
 8283:                                     } else {
 8284:                                         push(@{$request_domains->{$type}},$otherdom);
 8285:                                     }
 8286:                                 }
 8287:                             }
 8288:                         }
 8289:                     }
 8290:                     unless ($dom eq $env{'user.domain'}) {
 8291:                         $canreq ++;
 8292:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8293:                             $can_request->{$type} = 1;
 8294:                         }
 8295:                     }
 8296:                 }
 8297:             }
 8298:         }
 8299:     }
 8300:     return $canreq;
 8301: }
 8302: 
 8303: # ---------------------------------------------- Custom access rule evaluation
 8304: 
 8305: sub customaccess {
 8306:     my ($priv,$uri)=@_;
 8307:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8308:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8309:     $udom = &LONCAPA::clean_domain($udom);
 8310:     $ucrs = &LONCAPA::clean_username($ucrs);
 8311:     my $access=0;
 8312:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8313: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8314: 	if ($type eq 'user') {
 8315: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8316: 		my ($tdom,$tuname)=split(m{/},$scope);
 8317: 		if ($tdom) {
 8318: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8319: 		}
 8320: 		if ($tuname) {
 8321: 		    if ($tuname ne $env{'user.name'}) { next; }
 8322: 		}
 8323: 		$access=($effect eq 'allow');
 8324: 		last;
 8325: 	    }
 8326: 	} else {
 8327: 	    if ($role) {
 8328: 		if ($role ne $urole) { next; }
 8329: 	    }
 8330: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8331: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8332: 		if ($tdom) {
 8333: 		    if ($tdom ne $udom) { next; }
 8334: 		}
 8335: 		if ($tcrs) {
 8336: 		    if ($tcrs ne $ucrs) { next; }
 8337: 		}
 8338: 		if ($tsec) {
 8339: 		    if ($tsec ne $usec) { next; }
 8340: 		}
 8341: 		$access=($effect eq 'allow');
 8342: 		last;
 8343: 	    }
 8344: 	    if ($realm eq '' && $role eq '') {
 8345: 		$access=($effect eq 'allow');
 8346: 	    }
 8347: 	}
 8348:     }
 8349:     return $access;
 8350: }
 8351: 
 8352: # ------------------------------------------------- Check for a user privilege
 8353: 
 8354: sub allowed {
 8355:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8356:     my $ver_orguri=$uri;
 8357:     $uri=&deversion($uri);
 8358:     my $orguri=$uri;
 8359:     $uri=&declutter($uri);
 8360: 
 8361:     if ($priv eq 'evb') {
 8362: # Evade communication block restrictions for specified role in a course or domain
 8363:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8364:             return $1;
 8365:         } else {
 8366:             return;
 8367:         }
 8368:     }
 8369: 
 8370:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8371: # Free bre access to adm and meta resources
 8372:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8373: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8374: 	&& ($priv eq 'bre')) {
 8375: 	return 'F';
 8376:     }
 8377: 
 8378: # Free bre access to user's own portfolio contents
 8379:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8380:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8381: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8382:         my %setters;
 8383:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8384:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8385:         if (($startblock && $endblock) || ($by_ip)) {
 8386:             return 'B';
 8387:         } else {
 8388:             return 'F';
 8389:         }
 8390:     }
 8391: 
 8392: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8393:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8394:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8395:         if (exists($env{'request.course.id'})) {
 8396:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8397:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8398:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8399:                 my $courseprivid=$env{'request.course.id'};
 8400:                 $courseprivid=~s/\_/\//;
 8401:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8402:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8403:                     return $1; 
 8404:                 } else {
 8405:                     if ($env{'request.course.sec'}) {
 8406:                         $courseprivid.='/'.$env{'request.course.sec'};
 8407:                     }
 8408:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8409:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8410:                         return $2;
 8411:                     }
 8412:                 }
 8413:             }
 8414:         }
 8415:     }
 8416: 
 8417: # Free bre to public access
 8418: 
 8419:     if ($priv eq 'bre') {
 8420:         my $copyright;
 8421:         unless ($uri =~ /ext\.tool/) {
 8422:             $copyright=&metadata($uri,'copyright');
 8423:         }
 8424: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8425:            return 'F'; 
 8426:         }
 8427:         if ($copyright eq 'priv') {
 8428:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8429: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8430: 		return '';
 8431:             }
 8432:         }
 8433:         if ($copyright eq 'domain') {
 8434:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8435: 	    unless (($env{'user.domain'} eq $1) ||
 8436:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8437: 		return '';
 8438:             }
 8439:         }
 8440:         if ($env{'request.role'}=~ /li\.\//) {
 8441:             # Library role, so allow browsing of resources in this domain.
 8442:             return 'F';
 8443:         }
 8444:         if ($copyright eq 'custom') {
 8445: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8446:         }
 8447:     }
 8448:     # Domain coordinator is trying to create a course
 8449:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8450:         # uri is the requested domain in this case.
 8451:         # comparison to 'request.role.domain' shows if the user has selected
 8452:         # a role of dc for the domain in question.
 8453:         return 'F' if ($uri eq $env{'request.role.domain'});
 8454:     }
 8455: 
 8456:     my $thisallowed='';
 8457:     my $statecond=0;
 8458:     my $courseprivid='';
 8459: 
 8460:     my $ownaccess;
 8461:     # Community Coordinator or Assistant Co-author browsing resource space.
 8462:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8463:         if ($uri eq '') {
 8464:             $ownaccess = 1;
 8465:         } else {
 8466:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8467:                 my $udom = $env{'user.domain'};
 8468:                 my $uname = $env{'user.name'};
 8469:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8470:                     $ownaccess = 1;
 8471:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8472:                     unless ($uri =~ m{\.\./}) {
 8473:                         $ownaccess = 1;
 8474:                     }
 8475:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8476:                     my $now = time;
 8477:                     if ($uri =~ m{^([^/]+)/?$}) {
 8478:                         my $adom = $1;
 8479:                         foreach my $key (keys(%env)) {
 8480:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8481:                                 my ($start,$end) = split(/\./,$env{$key});
 8482:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8483:                                     $ownaccess = 1;
 8484:                                     last;
 8485:                                 }
 8486:                             }
 8487:                         }
 8488:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8489:                         my $adom = $1;
 8490:                         my $aname = $2;
 8491:                         foreach my $role ('ca','aa') { 
 8492:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8493:                                 my ($start,$end) =
 8494:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8495:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8496:                                     $ownaccess = 1;
 8497:                                     last;
 8498:                                 }
 8499:                             }
 8500:                         }
 8501:                     }
 8502:                 }
 8503:             }
 8504:         }
 8505:     }
 8506: 
 8507: # Course
 8508: 
 8509:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8510:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8511:             $thisallowed.=$1;
 8512:         }
 8513:     }
 8514: 
 8515: # Domain
 8516: 
 8517:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8518:        =~/\Q$priv\E\&([^\:]*)/) {
 8519:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8520:             $thisallowed.=$1;
 8521:         }
 8522:     }
 8523: 
 8524: # User who is not author or co-author might still be able to edit
 8525: # resource of an author in the domain (e.g., if Domain Coordinator).
 8526:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8527:         (&allowed('mdc',$env{'request.course.id'}))) {
 8528:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8529:             $thisallowed.=$1;
 8530:         }
 8531:     }
 8532: 
 8533: # Course: uri itself is a course
 8534:     my $courseuri=$uri;
 8535:     $courseuri=~s/\_(\d)/\/$1/;
 8536:     $courseuri=~s/^([^\/])/\/$1/;
 8537: 
 8538:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8539:        =~/\Q$priv\E\&([^\:]*)/) {
 8540:         if ($priv eq 'mip') {
 8541:             my $rem = $1;
 8542:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8543:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8544:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8545:                 if ($cdom ne '') {
 8546:                     my %passwdconf = &get_passwdconf($cdom);
 8547:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8548:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8549:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8550:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8551:                                 unless (@inststatuses) {
 8552:                                     @inststatuses = ('default');
 8553:                                 }
 8554:                                 foreach my $status (@inststatuses) {
 8555:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8556:                                         $thisallowed.=$rem;
 8557:                                     }
 8558:                                 }
 8559:                             }
 8560:                         }
 8561:                     }
 8562:                 }
 8563:             }
 8564:         } else {
 8565:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8566:                 $thisallowed.=$1;
 8567:             }
 8568:         }
 8569:     }
 8570: 
 8571: # URI is an uploaded document for this course, default permissions don't matter
 8572: # not allowing 'edit' access (editupload) to uploaded course docs
 8573:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8574: 	$thisallowed='';
 8575:         my ($match)=&is_on_map($uri);
 8576:         if ($match) {
 8577:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8578:                   =~/\Q$priv\E\&([^\:]*)/) {
 8579:                 my $value = $1;
 8580:                 my $deeplinkblock;
 8581:                 unless ($nodeeplinkcheck) {
 8582:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8583:                 }
 8584:                 if ($deeplinkblock) {
 8585:                     $thisallowed='D';
 8586:                 } elsif ($noblockcheck) {
 8587:                     $thisallowed.=$value;
 8588:                 } else {
 8589:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8590:                     if (@blockers > 0) {
 8591:                         $thisallowed = 'B';
 8592:                     } else {
 8593:                         $thisallowed.=$value;
 8594:                     }
 8595:                 }
 8596:             }
 8597:         } else {
 8598:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8599:             if ($refuri) {
 8600:                 if ($refuri =~ m|^/adm/|) {
 8601:                     $thisallowed='F';
 8602:                 } else {
 8603:                     $refuri=&declutter($refuri);
 8604:                     my ($match) = &is_on_map($refuri);
 8605:                     if ($match) {
 8606:                         my $deeplinkblock;
 8607:                         unless ($nodeeplinkcheck) {
 8608:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8609:                         }
 8610:                         if ($deeplinkblock) {
 8611:                             $thisallowed='D';
 8612:                         } elsif ($noblockcheck) {
 8613:                             $thisallowed='F';
 8614:                         } else {
 8615:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8616:                             if (@blockers > 0) {
 8617:                                 $thisallowed = 'B';
 8618:                             } else {
 8619:                                 $thisallowed='F';
 8620:                             }
 8621:                         }
 8622:                     }
 8623:                 }
 8624:             }
 8625:         }
 8626:     }
 8627: 
 8628:     if ($priv eq 'bre'
 8629: 	&& $thisallowed ne 'F' 
 8630: 	&& $thisallowed ne '2'
 8631: 	&& &is_portfolio_url($uri)) {
 8632: 	$thisallowed = &portfolio_access($uri,$clientip);
 8633:     }
 8634: 
 8635: # Full access at system, domain or course-wide level? Exit.
 8636:     if ($thisallowed=~/F/) {
 8637: 	return 'F';
 8638:     }
 8639: 
 8640: # If this is generating or modifying users, exit with special codes
 8641: 
 8642:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8643: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8644: 	    my ($audom,$auname)=split('/',$uri);
 8645: # no author name given, so this just checks on the general right to make a co-author in this domain
 8646: 	    unless ($auname) { return $thisallowed; }
 8647: # an author name is given, so we are about to actually make a co-author for a certain account
 8648: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8649: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8650: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8651: 	}
 8652: 	return $thisallowed;
 8653:     }
 8654: #
 8655: # Gathered so far: system, domain and course wide privileges
 8656: #
 8657: # Course: See if uri or referer is an individual resource that is part of 
 8658: # the course
 8659: 
 8660:     if ($env{'request.course.id'}) {
 8661: 
 8662:         if ($priv eq 'bre') {
 8663:             if (&is_coursetool_logo($uri)) {
 8664:                 return 'F';
 8665:             }
 8666:         }
 8667: 
 8668: # If this is modifying password (internal auth) domains must match for user and user's role.
 8669: 
 8670:         if ($priv eq 'mip') {
 8671:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8672:                 return $thisallowed;
 8673:             } else {
 8674:                 return '';
 8675:             }
 8676:         }
 8677: 
 8678:        $courseprivid=$env{'request.course.id'};
 8679:        if ($env{'request.course.sec'}) {
 8680:           $courseprivid.='/'.$env{'request.course.sec'};
 8681:        }
 8682:        $courseprivid=~s/\_/\//;
 8683:        my $checkreferer=1;
 8684:        my ($match,$cond)=&is_on_map($uri);
 8685:        if ($match) {
 8686:            $statecond=$cond;
 8687:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8688:                =~/\Q$priv\E\&([^\:]*)/) {
 8689:                my $value = $1;
 8690:                if ($priv eq 'bre') {
 8691:                    my $deeplinkblock;
 8692:                    unless ($nodeeplinkcheck) {
 8693:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8694:                    }
 8695:                    if ($deeplinkblock) {
 8696:                        $thisallowed = 'D';
 8697:                    } elsif ($noblockcheck) {
 8698:                        $thisallowed.=$value;
 8699:                    } else {
 8700:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8701:                        if (@blockers > 0) {
 8702:                            $thisallowed = 'B';
 8703:                        } else {
 8704:                            $thisallowed.=$value;
 8705:                        }
 8706:                    }
 8707:                } else {
 8708:                    $thisallowed.=$value;
 8709:                }
 8710:                $checkreferer=0;
 8711:            }
 8712:        }
 8713: 
 8714:        if ($checkreferer) {
 8715: 	  my $refuri=$env{'httpref.'.$orguri};
 8716:             unless ($refuri) {
 8717:                 foreach my $key (keys(%env)) {
 8718: 		    if ($key=~/^httpref\..*\*/) {
 8719: 			my $pattern=$key;
 8720:                         $pattern=~s/^httpref\.\/res\///;
 8721:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8722:                         $pattern=~s/\//\\\//g;
 8723:                         if ($orguri=~/$pattern/) {
 8724: 			    $refuri=$env{$key};
 8725:                         }
 8726:                     }
 8727:                 }
 8728:             }
 8729: 
 8730:          if ($refuri) { 
 8731: 	  $refuri=&declutter($refuri);
 8732:           my ($match,$cond)=&is_on_map($refuri);
 8733:             if ($match) {
 8734:               my $refstatecond=$cond;
 8735:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8736:                   =~/\Q$priv\E\&([^\:]*)/) {
 8737:                   my $value = $1;
 8738:                   if ($priv eq 'bre') {
 8739:                       my $deeplinkblock;
 8740:                       unless ($nodeeplinkcheck) {
 8741:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8742:                       }
 8743:                       if ($deeplinkblock) {
 8744:                           $thisallowed = 'D';
 8745:                       } elsif ($noblockcheck) {
 8746:                           $thisallowed.=$value;
 8747:                       } else {
 8748:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8749:                           if (@blockers > 0) {
 8750:                               $thisallowed = 'B';
 8751:                           } else {
 8752:                               $thisallowed.=$value;
 8753:                           }
 8754:                       }
 8755:                   } else {
 8756:                       $thisallowed.=$value;
 8757:                   }
 8758:                   $uri=$refuri;
 8759:                   $statecond=$refstatecond;
 8760:               }
 8761:           }
 8762:         }
 8763:        }
 8764:    }
 8765: 
 8766: #
 8767: # Gathered now: all privileges that could apply, and condition number
 8768: # 
 8769: #
 8770: # Full or no access?
 8771: #
 8772: 
 8773:     if ($thisallowed=~/F/) {
 8774: 	return 'F';
 8775:     }
 8776: 
 8777:     unless ($thisallowed) {
 8778:         return '';
 8779:     }
 8780: 
 8781: # Restrictions exist, deal with them
 8782: #
 8783: #   C:according to course preferences
 8784: #   R:according to resource settings
 8785: #   L:unless locked
 8786: #   X:according to user session state
 8787: #
 8788: 
 8789: # Possibly locked functionality, check all courses
 8790: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8791: # Locks might take effect only after 10 minutes cache expiration for other
 8792: # courses, and 2 minutes for current course, in which user has st or ta role
 8793: # which is neither expired nor a future role (unless current course).
 8794: 
 8795:     my ($needlockcheck,$now,$crsonly);
 8796:     if ($thisallowed=~/L/) {
 8797:         $now = time;
 8798:         if ($priv eq 'bre') {
 8799:             if ($uri ne '') {
 8800:                 if ($orguri =~ m{^/+res/}) {
 8801:                     if ($uri =~ m{^lib/templates/}) {
 8802:                         if ($env{'request.course.id'}) {
 8803:                             $crsonly = 1;
 8804:                             $needlockcheck = 1;
 8805:                         }
 8806:                     } else {
 8807:                         $needlockcheck = 1;
 8808:                     }
 8809:                 } elsif ($env{'request.course.id'}) {
 8810:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8811:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8812:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8813:                         $crsonly = 1;
 8814:                     }
 8815:                     $needlockcheck = 1;
 8816:                 }
 8817:             }
 8818:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8819:             $needlockcheck = 1;
 8820:         }
 8821:     }
 8822:     if ($needlockcheck) {
 8823:         foreach my $envkey (keys(%env)) {
 8824:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8825:                my $courseid=$2;
 8826:                my $roleid=$1.'.'.$2;
 8827:                $courseid=~s/^\///;
 8828:                unless ($env{'request.role'} eq $roleid) {
 8829:                    my ($start,$end) = split(/\./,$env{$envkey});
 8830:                    next unless (($now >= $start) && (!$end || $end > $now));
 8831:                }
 8832:                my $expiretime=600;
 8833:                if ($env{'request.role'} eq $roleid) {
 8834: 		  $expiretime=120;
 8835:                }
 8836: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8837:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8838:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8839: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8840:                }
 8841:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8842:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8843: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8844:                        &log($env{'user.domain'},$env{'user.name'},
 8845:                             $env{'user.home'},
 8846:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8847:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8848:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8849: 		       return '';
 8850:                    }
 8851:                }
 8852:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8853:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8854: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8855:                        &log($env{'user.domain'},$env{'user.name'},
 8856:                             $env{'user.home'},
 8857:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8858:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8859:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8860: 		       return '';
 8861:                    }
 8862:                }
 8863: 	   }
 8864:        }
 8865:     }
 8866: 
 8867: #
 8868: # Rest of the restrictions depend on selected course
 8869: #
 8870: 
 8871:     unless ($env{'request.course.id'}) {
 8872: 	if ($thisallowed eq 'A') {
 8873: 	    return 'A';
 8874:         } elsif ($thisallowed eq 'B') {
 8875:             return 'B';
 8876: 	} else {
 8877: 	    return '1';
 8878: 	}
 8879:     }
 8880: 
 8881: #
 8882: # Now user is definitely in a course
 8883: #
 8884: 
 8885: 
 8886: # Course preferences
 8887: 
 8888:    if ($thisallowed=~/C/) {
 8889:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8890:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8891:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8892: 	   =~/\Q$rolecode\E/) {
 8893: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8894: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8895: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8896: 			$env{'request.course.id'});
 8897: 	   }
 8898:            return '';
 8899:        }
 8900: 
 8901:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8902: 	   =~/\Q$unamedom\E/) {
 8903: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8904: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8905: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8906: 			$env{'request.course.id'});
 8907: 	   }
 8908:            return '';
 8909:        }
 8910:    }
 8911: 
 8912: # Resource preferences
 8913: 
 8914:    if ($thisallowed=~/R/) {
 8915:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8916:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8917: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8918: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8919: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8920: 	   }
 8921: 	   return '';
 8922:        }
 8923:    }
 8924: 
 8925: # Restricted for deeplinked session?
 8926: 
 8927:     if ($env{'request.deeplink.login'}) {
 8928:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8929:             if (!$symb) { $symb=&symbread($uri,1); }
 8930:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8931:                 return '';
 8932:             }
 8933:         }
 8934:     }
 8935: 
 8936: # Restricted by state or randomout?
 8937: 
 8938:    if ($thisallowed=~/X/) {
 8939:       if ($env{'acc.randomout'}) {
 8940: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8941:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8942:             return ''; 
 8943:          }
 8944:       }
 8945:       if (&condval($statecond)) {
 8946: 	 return '2';
 8947:       } else {
 8948:          return '';
 8949:       }
 8950:    }
 8951: 
 8952:     if ($thisallowed eq 'A') {
 8953: 	return 'A';
 8954:     } elsif ($thisallowed eq 'B') {
 8955:         return 'B';
 8956:     } elsif ($thisallowed eq 'D') {
 8957:         return 'D';
 8958:     }
 8959:    return 'F';
 8960: }
 8961: 
 8962: # ------------------------------------------- Check construction space access
 8963: 
 8964: sub constructaccess {
 8965:     my ($url,$setpriv)=@_;
 8966: 
 8967: # We do not allow editing of previous versions of files
 8968:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8969: 
 8970: # Get username and domain from URL
 8971:     my ($ownername,$ownerdomain,$ownerhome);
 8972: 
 8973:     ($ownerdomain,$ownername) =
 8974:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8975: 
 8976: # The URL does not really point to any authorspace, forget it
 8977:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8978: 
 8979: # Now we need to see if the user has access to the authorspace of
 8980: # $ownername at $ownerdomain
 8981: 
 8982:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8983: # Real author for this?
 8984:        $ownerhome = $env{'user.home'};
 8985:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8986:           return ($ownername,$ownerdomain,$ownerhome);
 8987:        }
 8988:     } elsif (&is_course($ownerdomain,$ownername)) {
 8989: # Course Authoring Space?
 8990:         if ($env{'request.course.id'}) {
 8991:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8992:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8993:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8994:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8995:                     return ($ownername,$ownerdomain,$ownerhome);
 8996:                 }
 8997:             }
 8998:         }
 8999:         return '';
 9000:     } else {
 9001: # Co-author for this?
 9002:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9003:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9004:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9005:             return ($ownername,$ownerdomain,$ownerhome);
 9006:         }
 9007:     }
 9008: 
 9009: # We don't have any access right now. If we are not possibly going to do anything about this,
 9010: # we might as well leave
 9011:    unless ($setpriv) { return ''; }
 9012: 
 9013: # Backdoor access?
 9014:     my $allowed=&allowed('eco',$ownerdomain);
 9015: # Nope
 9016:     unless ($allowed) { return ''; }
 9017: # Looks like we may have access, but could be locked by the owner of the construction space
 9018:     if ($allowed eq 'U') {
 9019:         my %blocked=&get('environment',['domcoord.author'],
 9020:                          $ownerdomain,$ownername);
 9021: # Is blocked by owner
 9022:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9023:     }
 9024:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9025: # Grant temporary access
 9026:         my $then=$env{'user.login.time'};
 9027:         my $update=$env{'user.update.time'};
 9028:         if (!$update) { $update = $then; }
 9029:         my $refresh=$env{'user.refresh.time'};
 9030:         if (!$refresh) { $refresh = $update; }
 9031:         my $now = time;
 9032:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9033:                            $now,'ca','constructaccess');
 9034:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9035:         return($ownername,$ownerdomain,$ownerhome);
 9036:     }
 9037: # No business here
 9038:     return '';
 9039: }
 9040: 
 9041: # ----------------------------------------------------------- Content Blocking
 9042: 
 9043: {
 9044: # Caches for faster Course Contents display where content blocking
 9045: # is in operation (i.e., interval param set) for timed quiz.
 9046: #
 9047: # User for whom data are being temporarily cached.
 9048: my $cacheduser='';
 9049: # Course for which data are being temporarily cached.
 9050: my $cachedcid='';
 9051: # Cached blockers for this user (a hash of blocking items). 
 9052: my %cachedblockers=();
 9053: # When the data were last cached.
 9054: my $cachedlast='';
 9055: 
 9056: sub load_all_blockers {
 9057:     my ($uname,$udom)=@_;
 9058:     if (($uname ne '') && ($udom ne '')) { 
 9059:         if (($cacheduser eq $uname.':'.$udom) &&
 9060:             ($cachedcid eq $env{'request.course.id'}) &&
 9061:             (abs($cachedlast-time)<5)) {
 9062:             return;
 9063:         }
 9064:     }
 9065:     $cachedlast=time;
 9066:     $cacheduser=$uname.':'.$udom;
 9067:     $cachedcid=$env{'request.course.id'};
 9068:     %cachedblockers = &get_commblock_resources();
 9069:     return;
 9070: }
 9071: 
 9072: sub get_comm_blocks {
 9073:     my ($cdom,$cnum) = @_;
 9074:     if ($cdom eq '' || $cnum eq '') {
 9075:         return unless ($env{'request.course.id'});
 9076:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9077:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9078:     }
 9079:     my %commblocks;
 9080:     my $hashid=$cdom.'_'.$cnum;
 9081:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9082:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9083:         %commblocks = %{$blocksref};
 9084:     } else {
 9085:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9086:         my $cachetime = 600;
 9087:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9088:     }
 9089:     return %commblocks;
 9090: }
 9091: 
 9092: sub get_commblock_resources {
 9093:     my ($blocks) = @_;
 9094:     my %blockers = ();
 9095:     return %blockers unless ($env{'request.course.id'});
 9096:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9097:     if ($env{'request.course.sec'}) {
 9098:         $courseurl .= '/'.$env{'request.course.sec'};
 9099:     }
 9100:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9101:     my %commblocks;
 9102:     if (ref($blocks) eq 'HASH') {
 9103:         %commblocks = %{$blocks};
 9104:     } else {
 9105:         %commblocks = &get_comm_blocks();
 9106:     }
 9107:     return %blockers unless (keys(%commblocks) > 0); 
 9108:     my $navmap = Apache::lonnavmaps::navmap->new();
 9109:     return %blockers unless (ref($navmap));
 9110:     my $now = time;
 9111:     foreach my $block (keys(%commblocks)) {
 9112:         if ($block =~ /^(\d+)____(\d+)$/) {
 9113:             my ($start,$end) = ($1,$2);
 9114:             if ($start <= $now && $end >= $now) {
 9115:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9116:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9117:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9118:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9119:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9120:                             }
 9121:                         }
 9122:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9123:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9124:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9125:                             }
 9126:                         }
 9127:                     }
 9128:                 }
 9129:             }
 9130:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9131:             my $item = $1;
 9132:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9133:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9134:                     my (@interval,$mapname);
 9135:                     my $type = 'map';
 9136:                     if ($item eq 'course') {
 9137:                         $type = 'course';
 9138:                         @interval=&EXT("resource.0.interval");
 9139:                     } else {
 9140:                         if ($item =~ /___\d+___/) {
 9141:                             $type = 'resource';
 9142:                             @interval=&EXT("resource.0.interval",$item);
 9143:                         } else {
 9144:                             $mapname = &deversion($item);
 9145:                             if (ref($navmap)) {
 9146:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9147:                                 @interval = ($timelimit,'map');
 9148:                             }
 9149:                         }
 9150:                     }
 9151:                     if ($interval[0] =~ /^(\d+)/) {
 9152:                         my $timelimit = $1; 
 9153:                         my $first_access;
 9154:                         if ($type eq 'resource') {
 9155:                             $first_access=&get_first_access($interval[1],$item);
 9156:                         } elsif ($type eq 'map') {
 9157:                             $first_access=&get_first_access($interval[1],undef,$item);
 9158:                         } else {
 9159:                             $first_access=&get_first_access($interval[1]);
 9160:                         }
 9161:                         if ($first_access) {
 9162:                             my $timesup = $first_access+$timelimit;
 9163:                             if ($timesup > $now) {
 9164:                                 my $activeblock;
 9165:                                 if ($type eq 'resource') {
 9166:                                     if (ref($navmap)) {
 9167:                                         my $res = $navmap->getBySymb($item);
 9168:                                         if ($res->answerable()) {
 9169:                                             $activeblock = 1;
 9170:                                         }
 9171:                                     }
 9172:                                 } elsif ($type eq 'map') {
 9173:                                     my $mapsymb = &symbread($mapname,1);
 9174:                                     if (($mapsymb) && (ref($navmap))) {
 9175:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9176:                                         if (ref($mapres)) {
 9177:                                             my $first = $mapres->map_start();
 9178:                                             my $finish = $mapres->map_finish();
 9179:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9180:                                             if (ref($it)) {
 9181:                                                 my $res;
 9182:                                                 while ($res = $it->next(undef,1)) {
 9183:                                                     next unless (ref($res));
 9184:                                                     my $symb = $res->symb();
 9185:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9186:                                                     @interval=&EXT("resource.0.interval",$symb);
 9187:                                                     if ($interval[1] eq 'map') {
 9188:                                                         if ($res->answerable()) {
 9189:                                                             $activeblock = 1;
 9190:                                                             last;
 9191:                                                         }
 9192:                                                     }
 9193:                                                 }
 9194:                                             }
 9195:                                         }
 9196:                                     }
 9197:                                 }
 9198:                                 if ($activeblock) {
 9199:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9200:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9201:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9202:                                          }
 9203:                                     }
 9204:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9205:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9206:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9207:                                         }
 9208:                                     }
 9209:                                 }
 9210:                             }
 9211:                         }
 9212:                     }
 9213:                 }
 9214:             }
 9215:         }
 9216:     }
 9217:     return %blockers;
 9218: }
 9219: 
 9220: sub has_comm_blocking {
 9221:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9222:     my @blockers;
 9223:     return unless ($env{'request.course.id'});
 9224:     return unless ($priv eq 'bre');
 9225:     return if ($env{'request.state'} eq 'construct');
 9226:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9227:     if ($env{'request.course.sec'}) {
 9228:         $courseurl .= '/'.$env{'request.course.sec'};
 9229:     }
 9230:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9231:     my %blockinfo;
 9232:     if (ref($blocks) eq 'HASH') {
 9233:         %blockinfo = &get_commblock_resources($blocks);
 9234:     } else {
 9235:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9236:         %blockinfo = %cachedblockers;
 9237:     }
 9238:     return unless (keys(%blockinfo) > 0);
 9239:     my (%possibles,@symbs);
 9240:     if (!$symb) {
 9241:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9242:     }
 9243:     if ($symb) {
 9244:         @symbs = ($symb);
 9245:     } elsif (keys(%possibles)) { 
 9246:         @symbs = keys(%possibles);
 9247:     }
 9248:     my $noblock;
 9249:     foreach my $symb (@symbs) {
 9250:         last if ($noblock);
 9251:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9252:         foreach my $block (keys(%blockinfo)) {
 9253:             if ($block =~ /^firstaccess____(.+)$/) {
 9254:                 my $item = $1;
 9255:                 unless ($blocked) {
 9256:                     if (($item eq $map) || ($item eq $symb)) {
 9257:                         $noblock = 1;
 9258:                         last;
 9259:                     }
 9260:                 }
 9261:             }
 9262:             if (ref($blockinfo{$block}) eq 'HASH') {
 9263:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9264:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9265:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9266:                             push(@blockers,$block);
 9267:                         }
 9268:                     }
 9269:                 }
 9270:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9271:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9272:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9273:                             push(@blockers,$block);
 9274:                         }
 9275:                     }
 9276:                 }
 9277:             }
 9278:         }
 9279:     }
 9280:     unless ($noblock) { 
 9281:         return @blockers;
 9282:     }
 9283:     return;
 9284: }
 9285: }
 9286: 
 9287: sub deeplink_check {
 9288:     my ($priv,$symb,$uri) = @_;
 9289:     return unless ($env{'request.course.id'});
 9290:     return unless ($priv eq 'bre');
 9291:     return if ($env{'request.state'} eq 'construct');
 9292:     return if ($env{'request.role.adv'});
 9293:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9294:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9295:     my (%possibles,@symbs);
 9296:     if (!$symb) {
 9297:         $symb = &symbread($uri,1,1,1,\%possibles);
 9298:     }
 9299:     if ($symb) {
 9300:         @symbs = ($symb);
 9301:     } elsif (keys(%possibles)) {
 9302:         @symbs = keys(%possibles);
 9303:     }
 9304: 
 9305:     my ($deeplink_symb,$allow);
 9306:     if ($env{'request.deeplink.login'}) {
 9307:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9308:     }
 9309:     foreach my $symb (@symbs) {
 9310:         last if ($allow);
 9311:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9312:         if ($deeplink eq '') {
 9313:             $allow = 1;
 9314:         } else {
 9315:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9316:             if ($state ne 'only') {
 9317:                 $allow = 1;
 9318:             } else {
 9319:                 my $check_deeplink_entry;
 9320:                 if ($protect ne 'none') {
 9321:                     my ($acctype,$item) = split(/:/,$protect);
 9322:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9323:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9324:                             $check_deeplink_entry = 1
 9325:                         }
 9326:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9327:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9328:                             $check_deeplink_entry = 1;
 9329:                         }
 9330:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9331:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9332:                             $check_deeplink_entry = 1;
 9333:                         }
 9334:                     }
 9335:                 }
 9336:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9337:                     if ($scope eq 'res') {
 9338:                         if ($symb eq $deeplink_symb) {
 9339:                             $allow = 1;
 9340:                         }
 9341:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9342:                         my ($map_from_symb,$map_from_login);
 9343:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9344:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9345:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9346:                         } else {
 9347:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9348:                         }
 9349:                         if (($map_from_symb) && ($map_from_login)) {
 9350:                             if ($map_from_symb eq $map_from_login) {
 9351:                                 $allow = 1;
 9352:                             } elsif ($scope eq 'rec') {
 9353:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9354:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9355:                                     $allow = 1;
 9356:                                 }
 9357:                             }
 9358:                         }
 9359:                     }
 9360:                 }
 9361:             }
 9362:         }
 9363:     }
 9364:     return if ($allow);
 9365:     return 1;
 9366: }
 9367: 
 9368: # -------------------------------- Deversion and split uri into path an filename   
 9369: 
 9370: #
 9371: #   Removes the version from a URI and
 9372: #   splits it in to its filename and path to the filename.
 9373: #   Seems like File::Basename could have done this more clearly.
 9374: #   Parameters:
 9375: #      $uri   - input URI
 9376: #   Returns:
 9377: #     Two element list consisting of 
 9378: #     $pathname  - the URI up to and excluding the trailing /
 9379: #     $filename  - The part of the URI following the last /
 9380: #  NOTE:
 9381: #    Another realization of this is simply:
 9382: #    use File::Basename;
 9383: #    ...
 9384: #    $uri = shift;
 9385: #    $filename = basename($uri);
 9386: #    $path     = dirname($uri);
 9387: #    return ($filename, $path);
 9388: #
 9389: #     The implementation below is probably faster however.
 9390: #
 9391: sub split_uri_for_cond {
 9392:     my $uri=&deversion(&declutter(shift));
 9393:     my @uriparts=split(/\//,$uri);
 9394:     my $filename=pop(@uriparts);
 9395:     my $pathname=join('/',@uriparts);
 9396:     return ($pathname,$filename);
 9397: }
 9398: # --------------------------------------------------- Is a resource on the map?
 9399: 
 9400: sub is_on_map {
 9401:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9402:     #Trying to find the conditional for the file
 9403:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9404: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9405:     if ($match) {
 9406: 	return (1,$1);
 9407:     } else {
 9408: 	return (0,0);
 9409:     }
 9410: }
 9411: 
 9412: # --------------------------------------------------------- Get symb from alias
 9413: 
 9414: sub get_symb_from_alias {
 9415:     my $symb=shift;
 9416:     my ($map,$resid,$url)=&decode_symb($symb);
 9417: # Already is a symb
 9418:     if ($url) { return $symb; }
 9419: # Must be an alias
 9420:     my $aliassymb='';
 9421:     my %bighash;
 9422:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9423:                             &GDBM_READER(),0640)) {
 9424:         my $rid=$bighash{'mapalias_'.$symb};
 9425: 	if ($rid) {
 9426: 	    my ($mapid,$resid)=split(/\./,$rid);
 9427: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9428: 				    $resid,$bighash{'src_'.$rid});
 9429: 	}
 9430:         untie %bighash;
 9431:     }
 9432:     return $aliassymb;
 9433: }
 9434: 
 9435: # ----------------------------------------------------------------- Define Role
 9436: 
 9437: sub definerole {
 9438:   if (allowed('mcr','/')) {
 9439:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9440:     foreach my $role (split(':',$sysrole)) {
 9441: 	my ($crole,$cqual)=split(/\&/,$role);
 9442:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9443:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9444: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9445:                return "refused:s:$crole&$cqual"; 
 9446:             }
 9447:         }
 9448:     }
 9449:     foreach my $role (split(':',$domrole)) {
 9450: 	my ($crole,$cqual)=split(/\&/,$role);
 9451:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9452:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9453: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9454:                return "refused:d:$crole&$cqual"; 
 9455:             }
 9456:         }
 9457:     }
 9458:     foreach my $role (split(':',$courole)) {
 9459: 	my ($crole,$cqual)=split(/\&/,$role);
 9460:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9461:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9462: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9463:                return "refused:c:$crole&$cqual"; 
 9464:             }
 9465:         }
 9466:     }
 9467:     my $uhome;
 9468:     if (($uname ne '') && ($udom ne '')) {
 9469:         $uhome = &homeserver($uname,$udom);
 9470:         return $uhome if ($uhome eq 'no_host');
 9471:     } else {
 9472:         $uname = $env{'user.name'};
 9473:         $udom = $env{'user.domain'};
 9474:         $uhome = $env{'user.home'};
 9475:     }
 9476:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9477:                 "$udom:$uname:rolesdef_$rolename=".
 9478:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9479:     return reply($command,$uhome);
 9480:   } else {
 9481:     return 'refused';
 9482:   }
 9483: }
 9484: 
 9485: # ---------------- Make a metadata query against the network of library servers
 9486: 
 9487: sub metadata_query {
 9488:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9489:     my %rhash;
 9490:     my %libserv = &all_library();
 9491:     my @server_list = (defined($server_array) ? @$server_array
 9492:                                               : keys(%libserv) );
 9493:     for my $server (@server_list) {
 9494:         my $domains = ''; 
 9495:         if (ref($domains_hash) eq 'HASH') {
 9496:             $domains = $domains_hash->{$server}; 
 9497:         }
 9498: 	unless ($custom or $customshow) {
 9499: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9500: 	    $rhash{$server}=$reply;
 9501: 	}
 9502: 	else {
 9503: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9504: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9505: 			     $server);
 9506: 	    $rhash{$server}=$reply;
 9507: 	}
 9508:     }
 9509:     return \%rhash;
 9510: }
 9511: 
 9512: # ----------------------------------------- Send log queries and wait for reply
 9513: 
 9514: sub log_query {
 9515:     my ($uname,$udom,$query,%filters)=@_;
 9516:     my $uhome=&homeserver($uname,$udom);
 9517:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9518:     my $uhost=&hostname($uhome);
 9519:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9520:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9521:                        $uhome);
 9522:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9523:     return get_query_reply($queryid);
 9524: }
 9525: 
 9526: # -------------------------- Update MySQL table for portfolio file
 9527: 
 9528: sub update_portfolio_table {
 9529:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9530:     if ($group ne '') {
 9531:         $file_name =~s /^\Q$group\E//;
 9532:     }
 9533:     my $homeserver = &homeserver($uname,$udom);
 9534:     my $queryid=
 9535:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9536:                ':'.&escape($file_name).':'.$action,$homeserver);
 9537:     my $reply = &get_query_reply($queryid);
 9538:     return $reply;
 9539: }
 9540: 
 9541: # -------------------------- Update MySQL allusers table
 9542: 
 9543: sub update_allusers_table {
 9544:     my ($uname,$udom,$names) = @_;
 9545:     my $homeserver = &homeserver($uname,$udom);
 9546:     my $queryid=
 9547:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9548:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9549:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9550:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9551:                'generation='.&escape($names->{'generation'}).'%%'.
 9552:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9553:                'id='.&escape($names->{'id'}),$homeserver);
 9554:     return;
 9555: }
 9556: 
 9557: # ------- Request retrieval of institutional classlists for course(s)
 9558: 
 9559: sub fetch_enrollment_query {
 9560:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9561:     my ($homeserver,$sleep,$loopmax);
 9562:     my $maxtries = 1;
 9563:     if ($context eq 'automated') {
 9564:         $homeserver = $perlvar{'lonHostID'};
 9565:         $sleep = 2;
 9566:         $loopmax = 100;
 9567:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9568:     } else {
 9569:         $homeserver = &homeserver($cnum,$dom);
 9570:     }
 9571:     my $host=&hostname($homeserver);
 9572:     my $cmd = '';
 9573:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9574:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9575:     }
 9576:     $cmd =~ s/%%$//;
 9577:     $cmd = &escape($cmd);
 9578:     my $query = 'fetchenrollment';
 9579:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9580:     unless ($queryid=~/^\Q$host\E\_/) { 
 9581:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9582:         return 'error: '.$queryid;
 9583:     }
 9584:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9585:     my $tries = 1;
 9586:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9587:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9588:         $tries ++;
 9589:     }
 9590:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9591:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9592:     } else {
 9593:         my @responses = split(/:/,$reply);
 9594:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9595:             foreach my $line (@responses) {
 9596:                 my ($key,$value) = split(/=/,$line,2);
 9597:                 $$replyref{$key} = $value;
 9598:             }
 9599:         } else {
 9600:             my $pathname = LONCAPA::tempdir();
 9601:             foreach my $line (@responses) {
 9602:                 my ($key,$value) = split(/=/,$line);
 9603:                 $$replyref{$key} = $value;
 9604:                 if ($value > 0) {
 9605:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9606:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9607:                         my $destname = $pathname.'/'.$filename;
 9608:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9609:                         if ($xml_classlist =~ /^error/) {
 9610:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9611:                         } else {
 9612:                             if ( open(FILE,">",$destname) ) {
 9613:                                 print FILE &unescape($xml_classlist);
 9614:                                 close(FILE);
 9615:                             } else {
 9616:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9617:                             }
 9618:                         }
 9619:                     }
 9620:                 }
 9621:             }
 9622:         }
 9623:         return 'ok';
 9624:     }
 9625:     return 'error';
 9626: }
 9627: 
 9628: sub get_query_reply {
 9629:     my ($queryid,$sleep,$loopmax) = @_;
 9630:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9631:         $sleep = 0.2;
 9632:     }
 9633:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9634:         $loopmax = 100;
 9635:     }
 9636:     my $replyfile=LONCAPA::tempdir().$queryid;
 9637:     my $reply='';
 9638:     for (1..$loopmax) {
 9639: 	sleep($sleep);
 9640:         if (-e $replyfile.'.end') {
 9641: 	    if (open(my $fh,"<",$replyfile)) {
 9642: 		$reply = join('',<$fh>);
 9643: 		close($fh);
 9644: 	   } else { return 'error: reply_file_error'; }
 9645:            return &unescape($reply);
 9646: 	}
 9647:     }
 9648:     return 'timeout:'.$queryid;
 9649: }
 9650: 
 9651: sub courselog_query {
 9652: #
 9653: # possible filters:
 9654: # url: url or symb
 9655: # username
 9656: # domain
 9657: # action: view, submit, grade
 9658: # start: timestamp
 9659: # end: timestamp
 9660: #
 9661:     my (%filters)=@_;
 9662:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9663:     if ($filters{'url'}) {
 9664: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9665:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9666:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9667:     }
 9668:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9669:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9670:     return &log_query($cname,$cdom,'courselog',%filters);
 9671: }
 9672: 
 9673: sub userlog_query {
 9674: #
 9675: # possible filters:
 9676: # action: log check role
 9677: # start: timestamp
 9678: # end: timestamp
 9679: #
 9680:     my ($uname,$udom,%filters)=@_;
 9681:     return &log_query($uname,$udom,'userlog',%filters);
 9682: }
 9683: 
 9684: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9685: 
 9686: sub auto_run {
 9687:     my ($cnum,$cdom) = @_;
 9688:     my $response = 0;
 9689:     my $settings;
 9690:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9691:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9692:         $settings = $domconfig{'autoenroll'};
 9693:         if ($settings->{'run'} eq '1') {
 9694:             $response = 1;
 9695:         }
 9696:     } else {
 9697:         my $homeserver;
 9698:         if (&is_course($cdom,$cnum)) {
 9699:             $homeserver = &homeserver($cnum,$cdom);
 9700:         } else {
 9701:             $homeserver = &domain($cdom,'primary');
 9702:         }
 9703:         if ($homeserver ne 'no_host') {
 9704:             $response = &reply('autorun:'.$cdom,$homeserver);
 9705:         }
 9706:     }
 9707:     return $response;
 9708: }
 9709: 
 9710: sub auto_get_sections {
 9711:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9712:     my $homeserver;
 9713:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9714:         $homeserver = &homeserver($cnum,$cdom);
 9715:     }
 9716:     if (!defined($homeserver)) { 
 9717:         if ($cdom =~ /^$match_domain$/) {
 9718:             $homeserver = &domain($cdom,'primary');
 9719:         }
 9720:     }
 9721:     my @secs;
 9722:     if (defined($homeserver)) {
 9723:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9724:         unless ($response eq 'refused') {
 9725:             @secs = split(/:/,$response);
 9726:         }
 9727:     }
 9728:     return @secs;
 9729: }
 9730: 
 9731: sub auto_new_course {
 9732:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9733:     my $homeserver = &homeserver($cnum,$cdom);
 9734:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9735:     return $response;
 9736: }
 9737: 
 9738: sub auto_validate_courseID {
 9739:     my ($cnum,$cdom,$inst_course_id) = @_;
 9740:     my $homeserver = &homeserver($cnum,$cdom);
 9741:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9742:     return $response;
 9743: }
 9744: 
 9745: sub auto_validate_instcode {
 9746:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9747:     my ($homeserver,$response);
 9748:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9749:         $homeserver = &homeserver($cnum,$cdom);
 9750:     }
 9751:     if (!defined($homeserver)) {
 9752:         if ($cdom =~ /^$match_domain$/) {
 9753:             $homeserver = &domain($cdom,'primary');
 9754:         }
 9755:     }
 9756:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9757:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9758:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9759:     return ($outcome,$description,$defaultcredits);
 9760: }
 9761: 
 9762: sub auto_validate_inst_crosslist {
 9763:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9764:     my ($homeserver,$response);
 9765:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9766:         $homeserver = &homeserver($cnum,$cdom);
 9767:     }
 9768:     if (!defined($homeserver)) {
 9769:         if ($cdom =~ /^$match_domain$/) {
 9770:             $homeserver = &domain($cdom,'primary');
 9771:         }
 9772:     }
 9773:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9774:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9775:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9776:                          &escape($coowner),$homeserver);
 9777:     }
 9778:     return $response;
 9779: }
 9780: 
 9781: sub auto_create_password {
 9782:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9783:     my ($homeserver,$response);
 9784:     my $create_passwd = 0;
 9785:     my $authchk = '';
 9786:     if ($udom =~ /^$match_domain$/) {
 9787:         $homeserver = &domain($udom,'primary');
 9788:     }
 9789:     if ($homeserver eq '') {
 9790:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9791:             $homeserver = &homeserver($cnum,$cdom);
 9792:         }
 9793:     }
 9794:     if ($homeserver eq '') {
 9795:         $authchk = 'nodomain';
 9796:     } else {
 9797:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9798:         if ($response eq 'refused') {
 9799:             $authchk = 'refused';
 9800:         } else {
 9801:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9802:         }
 9803:     }
 9804:     return ($authparam,$create_passwd,$authchk);
 9805: }
 9806: 
 9807: sub auto_photo_permission {
 9808:     my ($cnum,$cdom,$students) = @_;
 9809:     my $homeserver = &homeserver($cnum,$cdom);
 9810:     my ($outcome,$perm_reqd,$conditions) = 
 9811: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9812:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9813: 	return (undef,undef);
 9814:     }
 9815:     return ($outcome,$perm_reqd,$conditions);
 9816: }
 9817: 
 9818: sub auto_checkphotos {
 9819:     my ($uname,$udom,$pid) = @_;
 9820:     my $homeserver = &homeserver($uname,$udom);
 9821:     my ($result,$resulttype);
 9822:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9823: 				   &escape($uname).':'.&escape($pid),
 9824: 				   $homeserver));
 9825:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9826: 	return (undef,undef);
 9827:     }
 9828:     if ($outcome) {
 9829:         ($result,$resulttype) = split(/:/,$outcome);
 9830:     } 
 9831:     return ($result,$resulttype);
 9832: }
 9833: 
 9834: sub auto_photochoice {
 9835:     my ($cnum,$cdom) = @_;
 9836:     my $homeserver = &homeserver($cnum,$cdom);
 9837:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9838: 						       &escape($cdom),
 9839: 						       $homeserver)));
 9840:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9841: 	return (undef,undef);
 9842:     }
 9843:     return ($update,$comment);
 9844: }
 9845: 
 9846: sub auto_photoupdate {
 9847:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9848:     my $homeserver = &homeserver($cnum,$dom);
 9849:     my $host=&hostname($homeserver);
 9850:     my $cmd = '';
 9851:     my $maxtries = 1;
 9852:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9853:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9854:     }
 9855:     $cmd =~ s/%%$//;
 9856:     $cmd = &escape($cmd);
 9857:     my $query = 'institutionalphotos';
 9858:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9859:     unless ($queryid=~/^\Q$host\E\_/) {
 9860:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9861:         return 'error: '.$queryid;
 9862:     }
 9863:     my $reply = &get_query_reply($queryid);
 9864:     my $tries = 1;
 9865:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9866:         $reply = &get_query_reply($queryid);
 9867:         $tries ++;
 9868:     }
 9869:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9870:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9871:     } else {
 9872:         my @responses = split(/:/,$reply);
 9873:         my $outcome = shift(@responses); 
 9874:         foreach my $item (@responses) {
 9875:             my ($key,$value) = split(/=/,$item);
 9876:             $$photo{$key} = $value;
 9877:         }
 9878:         return $outcome;
 9879:     }
 9880:     return 'error';
 9881: }
 9882: 
 9883: sub auto_instcode_format {
 9884:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9885: 	$cat_order) = @_;
 9886:     my $courses = '';
 9887:     my @homeservers;
 9888:     if ($caller eq 'global') {
 9889: 	my %servers = &get_servers($codedom,'library');
 9890: 	foreach my $tryserver (keys(%servers)) {
 9891: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9892: 		push(@homeservers,$tryserver);
 9893: 	    }
 9894:         }
 9895:     } elsif ($caller eq 'requests') {
 9896:         if ($codedom =~ /^$match_domain$/) {
 9897:             my $chome = &domain($codedom,'primary');
 9898:             unless ($chome eq 'no_host') {
 9899:                 push(@homeservers,$chome);
 9900:             }
 9901:         }
 9902:     } else {
 9903:         push(@homeservers,&homeserver($caller,$codedom));
 9904:     }
 9905:     foreach my $code (keys(%{$instcodes})) {
 9906:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9907:     }
 9908:     chop($courses);
 9909:     my $ok_response = 0;
 9910:     my $response;
 9911:     while (@homeservers > 0 && $ok_response == 0) {
 9912:         my $server = shift(@homeservers); 
 9913:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9914:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9915:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9916: 		split(/:/,$response);
 9917:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9918:             push(@{$codetitles},&str2array($codetitles_str));
 9919:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9920:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9921:             $ok_response = 1;
 9922:         }
 9923:     }
 9924:     if ($ok_response) {
 9925:         return 'ok';
 9926:     } else {
 9927:         return $response;
 9928:     }
 9929: }
 9930: 
 9931: sub auto_instcode_defaults {
 9932:     my ($domain,$returnhash,$code_order) = @_;
 9933:     my @homeservers;
 9934: 
 9935:     my %servers = &get_servers($domain,'library');
 9936:     foreach my $tryserver (keys(%servers)) {
 9937: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9938: 	    push(@homeservers,$tryserver);
 9939: 	}
 9940:     }
 9941: 
 9942:     my $response;
 9943:     foreach my $server (@homeservers) {
 9944:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9945:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9946: 	
 9947: 	foreach my $pair (split(/\&/,$response)) {
 9948: 	    my ($name,$value)=split(/\=/,$pair);
 9949: 	    if ($name eq 'code_order') {
 9950: 		@{$code_order} = split(/\&/,&unescape($value));
 9951: 	    } else {
 9952: 		$returnhash->{&unescape($name)}=&unescape($value);
 9953: 	    }
 9954: 	}
 9955: 	return 'ok';
 9956:     }
 9957: 
 9958:     return $response;
 9959: }
 9960: 
 9961: sub auto_possible_instcodes {
 9962:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9963:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9964:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9965:         return;
 9966:     }
 9967:     my (@homeservers,$uhome);
 9968:     if (defined(&domain($domain,'primary'))) {
 9969:         $uhome=&domain($domain,'primary');
 9970:         push(@homeservers,&domain($domain,'primary'));
 9971:     } else {
 9972:         my %servers = &get_servers($domain,'library');
 9973:         foreach my $tryserver (keys(%servers)) {
 9974:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9975:                 push(@homeservers,$tryserver);
 9976:             }
 9977:         }
 9978:     }
 9979:     my $response;
 9980:     foreach my $server (@homeservers) {
 9981:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9982:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9983:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9984:             split(':',$response);
 9985:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9986:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9987:         foreach my $item (split('&',$cat_title)) {   
 9988:             my ($name,$value)=split('=',$item);
 9989:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9990:         }
 9991:         foreach my $item (split('&',$cat_order)) {
 9992:             my ($name,$value)=split('=',$item);
 9993:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9994:         }
 9995:         return 'ok';
 9996:     }
 9997:     return $response;
 9998: }
 9999: 
10000: sub auto_courserequest_checks {
10001:     my ($dom) = @_;
10002:     my ($homeserver,%validations);
10003:     if ($dom =~ /^$match_domain$/) {
10004:         $homeserver = &domain($dom,'primary');
10005:     }
10006:     unless ($homeserver eq 'no_host') {
10007:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10008:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10009:             my @items = split(/&/,$response);
10010:             foreach my $item (@items) {
10011:                 my ($key,$value) = split('=',$item);
10012:                 $validations{&unescape($key)} = &thaw_unescape($value);
10013:             }
10014:         }
10015:     }
10016:     return %validations; 
10017: }
10018: 
10019: sub auto_courserequest_validation {
10020:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10021:     my ($homeserver,$response);
10022:     if ($dom =~ /^$match_domain$/) {
10023:         $homeserver = &domain($dom,'primary');
10024:     }
10025:     unless ($homeserver eq 'no_host') {
10026:         my $customdata;
10027:         if (ref($custominfo) eq 'HASH') {
10028:             $customdata = &freeze_escape($custominfo);
10029:         }
10030:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10031:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10032:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10033:                                     $customdata,$homeserver));
10034:     }
10035:     return $response;
10036: }
10037: 
10038: sub auto_validate_class_sec {
10039:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10040:     my $homeserver = &homeserver($cnum,$cdom);
10041:     my $ownerlist;
10042:     if (ref($owners) eq 'ARRAY') {
10043:         $ownerlist = join(',',@{$owners});
10044:     } else {
10045:         $ownerlist = $owners;
10046:     }
10047:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10048:                         &escape($ownerlist).':'.$cdom,$homeserver);
10049:     return $response;
10050: }
10051: 
10052: sub auto_instsec_reformat {
10053:     my ($cdom,$action,$instsecref) = @_;
10054:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10055:     my @homeservers;
10056:     if (defined(&domain($cdom,'primary'))) {
10057:         push(@homeservers,&domain($cdom,'primary'));
10058:     } else {
10059:         my %servers = &get_servers($cdom,'library');
10060:         foreach my $tryserver (keys(%servers)) {
10061:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10062:                 push(@homeservers,$tryserver);
10063:             }
10064:         }
10065:     }
10066:     my $response;
10067:     my %reformatted = %{$instsecref};
10068:     foreach my $server (@homeservers) {
10069:         if (ref($instsecref) eq 'HASH') {
10070:             my $info = &freeze_escape($instsecref);
10071:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10072:                                 $action.':'.$info,$server);
10073:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10074:             my @items = split(/&/,$response);
10075:             foreach my $item (@items) {
10076:                 my ($key,$value) = split(/=/,$item);
10077:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10078:             }
10079:         }
10080:     }
10081:     return %reformatted;
10082: }
10083: 
10084: sub auto_validate_instclasses {
10085:     my ($cdom,$cnum,$owners,$classesref) = @_;
10086:     my ($homeserver,%validations);
10087:     $homeserver = &homeserver($cnum,$cdom);
10088:     unless ($homeserver eq 'no_host') {
10089:         my $ownerlist;
10090:         if (ref($owners) eq 'ARRAY') {
10091:             $ownerlist = join(',',@{$owners});
10092:         } else {
10093:             $ownerlist = $owners;
10094:         }
10095:         if (ref($classesref) eq 'HASH') {
10096:             my $classes = &freeze_escape($classesref);
10097:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10098:                                 ':'.$cdom.':'.$classes,$homeserver);
10099:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10100:                 my @items = split(/&/,$response);
10101:                 foreach my $item (@items) {
10102:                     my ($key,$value) = split('=',$item);
10103:                     $validations{&unescape($key)} = &thaw_unescape($value);
10104:                 }
10105:             }
10106:         }
10107:     }
10108:     return %validations;
10109: }
10110: 
10111: sub auto_crsreq_update {
10112:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10113:         $code,$accessstart,$accessend,$inbound) = @_;
10114:     my ($homeserver,%crsreqresponse);
10115:     if ($cdom =~ /^$match_domain$/) {
10116:         $homeserver = &domain($cdom,'primary');
10117:     }
10118:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10119:         my $info;
10120:         if (ref($inbound) eq 'HASH') {
10121:             $info = &freeze_escape($inbound);
10122:         }
10123:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10124:                             ':'.&escape($action).':'.&escape($ownername).':'.
10125:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10126:                             &escape($title).':'.&escape($code).':'.
10127:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10128:                             $homeserver);
10129:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10130:             my @items = split(/&/,$response);
10131:             foreach my $item (@items) {
10132:                 my ($key,$value) = split('=',$item);
10133:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10134:             }
10135:         }
10136:     }
10137:     return \%crsreqresponse;
10138: }
10139: 
10140: sub auto_export_grades {
10141:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10142:     my ($homeserver,%exportresponse);
10143:     if ($cdom =~ /^$match_domain$/) {
10144:         $homeserver = &domain($cdom,'primary');
10145:     }
10146:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10147:         my $info;
10148:         if (ref($inforef) eq 'HASH') {
10149:             $info = &freeze_escape($inforef);
10150:         }
10151:         if (ref($gradesref) eq 'HASH') {
10152:             my $grades = &freeze_escape($gradesref);
10153:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10154:                                 $info.':'.$grades,$homeserver);
10155:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10156:                 my @items = split(/&/,$response);
10157:                 foreach my $item (@items) {
10158:                     my ($key,$value) = split('=',$item);
10159:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10160:                 }
10161:             }
10162:         }
10163:     }
10164:     return \%exportresponse;
10165: }
10166: 
10167: sub check_instcode_cloning {
10168:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10169:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10170:         return;
10171:     }
10172:     my $canclone;
10173:     if (@{$code_order} > 0) {
10174:         my $instcoderegexp ='^';
10175:         my @clonecodes = split(/\&/,$cloner);
10176:         foreach my $item (@{$code_order}) {
10177:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10178:                 foreach my $pair (@clonecodes) {
10179:                     my ($key,$val) = split(/\=/,$pair,2);
10180:                     $val = &unescape($val);
10181:                     if ($key eq $item) {
10182:                         $instcoderegexp .= '('.$val.')';
10183:                         last;
10184:                     }
10185:                 }
10186:             } else {
10187:                 $instcoderegexp .= $codedefaults->{$item};
10188:             }
10189:         }
10190:         $instcoderegexp .= '$';
10191:         my (@from,@to);
10192:         eval {
10193:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10194:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10195:         };
10196:         if ((@from > 0) && (@to > 0)) {
10197:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10198:             if (!@diffs) {
10199:                 $canclone = 1;
10200:             }
10201:         }
10202:     }
10203:     return $canclone;
10204: }
10205: 
10206: sub default_instcode_cloning {
10207:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10208:     my (%codedefaults,@code_order,$canclone);
10209:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10210:         %codedefaults = %{$codedefaultsref};
10211:         @code_order = @{$codeorderref};
10212:     } elsif ($clonedom) {
10213:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10214:     }
10215:     if (($domdefclone) && (@code_order)) {
10216:         my @clonecodes = split(/\+/,$domdefclone);
10217:         my $instcoderegexp ='^';
10218:         foreach my $item (@code_order) {
10219:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10220:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10221:             } else {
10222:                 $instcoderegexp .= $codedefaults{$item};
10223:             }
10224:         }
10225:         $instcoderegexp .= '$';
10226:         my (@from,@to);
10227:         eval {
10228:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10229:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10230:         };
10231:         if ((@from > 0) && (@to > 0)) {
10232:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10233:             if (!@diffs) {
10234:                 $canclone = 1;
10235:             }
10236:         }
10237:     }
10238:     return $canclone;
10239: }
10240: 
10241: # ------------------------------------------------------- Course Group routines
10242: 
10243: sub get_coursegroups {
10244:     my ($cdom,$cnum,$group,$namespace) = @_;
10245:     return(&dump($namespace,$cdom,$cnum,$group));
10246: }
10247: 
10248: sub modify_coursegroup {
10249:     my ($cdom,$cnum,$groupsettings) = @_;
10250:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10251: }
10252: 
10253: sub toggle_coursegroup_status {
10254:     my ($cdom,$cnum,$group,$action) = @_;
10255:     my ($from_namespace,$to_namespace);
10256:     if ($action eq 'delete') {
10257:         $from_namespace = 'coursegroups';
10258:         $to_namespace = 'deleted_groups';
10259:     } else {
10260:         $from_namespace = 'deleted_groups';
10261:         $to_namespace = 'coursegroups';
10262:     }
10263:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10264:     if (my $tmp = &error(%curr_group)) {
10265:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10266:         return ('read error',$tmp);
10267:     } else {
10268:         my %savedsettings = %curr_group; 
10269:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10270:         my $deloutcome;
10271:         if ($result eq 'ok') {
10272:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10273:         } else {
10274:             return ('write error',$result);
10275:         }
10276:         if ($deloutcome eq 'ok') {
10277:             return 'ok';
10278:         } else {
10279:             return ('delete error',$deloutcome);
10280:         }
10281:     }
10282: }
10283: 
10284: sub modify_group_roles {
10285:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10286:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10287:     my $role = 'gr/'.&escape($userprivs);
10288:     my ($uname,$udom) = split(/:/,$user);
10289:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10290:     if ($result eq 'ok') {
10291:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10292:     }
10293:     return $result;
10294: }
10295: 
10296: sub modify_coursegroup_membership {
10297:     my ($cdom,$cnum,$membership) = @_;
10298:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10299:     return $result;
10300: }
10301: 
10302: sub get_active_groups {
10303:     my ($udom,$uname,$cdom,$cnum) = @_;
10304:     my $now = time;
10305:     my %groups = ();
10306:     foreach my $key (keys(%env)) {
10307:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10308:             my ($start,$end) = split(/\./,$env{$key});
10309:             if (($end!=0) && ($end<$now)) { next; }
10310:             if (($start!=0) && ($start>$now)) { next; }
10311:             if ($1 eq $cdom && $2 eq $cnum) {
10312:                 $groups{$3} = $env{$key} ;
10313:             }
10314:         }
10315:     }
10316:     return %groups;
10317: }
10318: 
10319: sub get_group_membership {
10320:     my ($cdom,$cnum,$group) = @_;
10321:     return(&dump('groupmembership',$cdom,$cnum,$group));
10322: }
10323: 
10324: sub get_users_groups {
10325:     my ($udom,$uname,$courseid) = @_;
10326:     my @usersgroups;
10327:     my $cachetime=1800;
10328: 
10329:     my $hashid="$udom:$uname:$courseid";
10330:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10331:     if (defined($cached)) {
10332:         @usersgroups = split(/:/,$grouplist);
10333:     } else {  
10334:         $grouplist = '';
10335:         my $courseurl = &courseid_to_courseurl($courseid);
10336:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10337:         my $access_end = $env{'course.'.$courseid.
10338:                               '.default_enrollment_end_date'};
10339:         my $now = time;
10340:         foreach my $key (keys(%roleshash)) {
10341:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10342:                 my $group = $1;
10343:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10344:                     my $start = $2;
10345:                     my $end = $1;
10346:                     if ($start == -1) { next; } # deleted from group
10347:                     if (($start!=0) && ($start>$now)) { next; }
10348:                     if (($end!=0) && ($end<$now)) {
10349:                         if ($access_end && $access_end < $now) {
10350:                             if ($access_end - $end < 86400) {
10351:                                 push(@usersgroups,$group);
10352:                             }
10353:                         }
10354:                         next;
10355:                     }
10356:                     push(@usersgroups,$group);
10357:                 }
10358:             }
10359:         }
10360:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10361:         $grouplist = join(':',@usersgroups);
10362:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10363:     }
10364:     return @usersgroups;
10365: }
10366: 
10367: sub devalidate_getgroups_cache {
10368:     my ($udom,$uname,$cdom,$cnum)=@_;
10369:     my $courseid = $cdom.'_'.$cnum;
10370: 
10371:     my $hashid="$udom:$uname:$courseid";
10372:     &devalidate_cache_new('getgroups',$hashid);
10373: }
10374: 
10375: # ------------------------------------------------------------------ Plain Text
10376: 
10377: sub plaintext {
10378:     my ($short,$type,$cid,$forcedefault) = @_;
10379:     if ($short =~ m{^cr/}) {
10380: 	return (split('/',$short))[-1];
10381:     }
10382:     if (!defined($cid)) {
10383:         $cid = $env{'request.course.id'};
10384:     }
10385:     my %rolenames = (
10386:                       Course    => 'std',
10387:                       Community => 'alt1',
10388:                       Placement => 'std',
10389:                     );
10390:     if ($cid ne '') {
10391:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10392:             unless ($forcedefault) {
10393:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10394:                 &Apache::lonlocal::mt_escape(\$roletext);
10395:                 return &Apache::lonlocal::mt($roletext);
10396:             }
10397:         }
10398:     }
10399:     if ((defined($type)) && (defined($rolenames{$type})) &&
10400:         (defined($rolenames{$type})) && 
10401:         (defined($prp{$short}{$rolenames{$type}}))) {
10402:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10403:     } elsif ($cid ne '') {
10404:         my $crstype = $env{'course.'.$cid.'.type'};
10405:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10406:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10407:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10408:         }
10409:     }
10410:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10411: }
10412: 
10413: # ----------------------------------------------------------------- Assign Role
10414: 
10415: sub assignrole {
10416:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10417:         $context)=@_;
10418:     my $mrole;
10419:     if ($role =~ /^cr\//) {
10420:         my $cwosec=$url;
10421:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10422:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10423:            my $refused = 1;
10424:            if ($context eq 'requestcourses') {
10425:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10426:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10427:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10428:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10429:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10430:                            if ($crsenv{'internal.courseowner'} eq
10431:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10432:                                $refused = '';
10433:                            }
10434:                        }
10435:                    }
10436:                }
10437:            }
10438:            if ($refused) {
10439:                &logthis('Refused custom assignrole: '.
10440:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10441:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10442:                return 'refused';
10443:            }
10444:         }
10445:         $mrole='cr';
10446:     } elsif ($role =~ /^gr\//) {
10447:         my $cwogrp=$url;
10448:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10449:         unless (&allowed('mdg',$cwogrp)) {
10450:             &logthis('Refused group assignrole: '.
10451:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10452:                     $env{'user.name'}.' at '.$env{'user.domain'});
10453:             return 'refused';
10454:         }
10455:         $mrole='gr';
10456:     } else {
10457:         my $cwosec=$url;
10458:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10459:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10460:             my $refused;
10461:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10462:                 if (!(&allowed('c'.$role,$url))) {
10463:                     $refused = 1;
10464:                 }
10465:             } else {
10466:                 $refused = 1;
10467:             }
10468:             if ($refused) {
10469:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10470:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10471:                     my %crsenv;
10472:                     if ($role eq 'cc' || $role eq 'co') {
10473:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10474:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10475:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10476:                                 if ($crsenv{'internal.courseowner'} eq 
10477:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10478:                                     $refused = '';
10479:                                 }
10480:                             }
10481:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10482:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10483:                                 if ($crsenv{'internal.courseowner'} eq 
10484:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10485:                                     $refused = '';
10486:                                 }
10487:                             }
10488:                         }
10489:                     }
10490:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10491:                     if ($role eq 'st') {
10492:                         $refused = '';
10493:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10494:                         $refused = '';
10495:                     }
10496:                 } elsif ($context eq 'requestcourses') {
10497:                     my @possroles = ('st','ta','ep','in','cc','co');
10498:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10499:                         my $wrongcc;
10500:                         if ($cnum =~ /^$match_community$/) {
10501:                             $wrongcc = 1 if ($role eq 'cc');
10502:                         } else {
10503:                             $wrongcc = 1 if ($role eq 'co');
10504:                         }
10505:                         unless ($wrongcc) {
10506:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10507:                             if ($crsenv{'internal.courseowner'} eq 
10508:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10509:                                 $refused = '';
10510:                             }
10511:                         }
10512:                     }
10513:                 } elsif ($context eq 'requestauthor') {
10514:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10515:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10516:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10517:                             $refused = '';
10518:                         } else {
10519:                             my %domdefaults = &get_domain_defaults($udom);
10520:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10521:                                 my $checkbystatus;
10522:                                 if ($env{'user.adv'}) { 
10523:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10524:                                     if ($disposition eq 'automatic') {
10525:                                         $refused = '';
10526:                                     } elsif ($disposition eq '') {
10527:                                         $checkbystatus = 1;
10528:                                     } 
10529:                                 } else {
10530:                                     $checkbystatus = 1;
10531:                                 }
10532:                                 if ($checkbystatus) {
10533:                                     if ($env{'environment.inststatus'}) {
10534:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10535:                                         foreach my $type (@inststatuses) {
10536:                                             if (($type ne '') &&
10537:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10538:                                                 $refused = '';
10539:                                             }
10540:                                         }
10541:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10542:                                         $refused = '';
10543:                                     }
10544:                                 }
10545:                             }
10546:                         }
10547:                     }
10548:                 }
10549:                 if ($refused) {
10550:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10551:                              ' '.$role.' '.$end.' '.$start.' by '.
10552: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10553:                     return 'refused';
10554:                 }
10555:             }
10556:         } elsif ($role eq 'au') {
10557:             if ($url ne '/'.$udom.'/') {
10558:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10559:                          ' to assign author role for '.$uname.':'.$udom.
10560:                          ' in domain: '.$url.' refused (wrong domain).');
10561:                 return 'refused';
10562:             }
10563:         }
10564:         $mrole=$role;
10565:     }
10566:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10567:                 "$udom:$uname:$url".'_'."$mrole=$role";
10568:     if ($end) { $command.='_'.$end; }
10569:     if ($start) {
10570: 	if ($end) { 
10571:            $command.='_'.$start; 
10572:         } else {
10573:            $command.='_0_'.$start;
10574:         }
10575:     }
10576:     my $origstart = $start;
10577:     my $origend = $end;
10578:     my $delflag;
10579: # actually delete
10580:     if ($deleteflag) {
10581: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10582: # modify command to delete the role
10583:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10584:                 "$udom:$uname:$url".'_'."$mrole";
10585: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10586: # set start and finish to negative values for userrolelog
10587:            $start=-1;
10588:            $end=-1;
10589:            $delflag = 1;
10590:         }
10591:     }
10592: # send command
10593:     my $answer=&reply($command,&homeserver($uname,$udom));
10594: # log new user role if status is ok
10595:     if ($answer eq 'ok') {
10596: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10597:         if (($role eq 'cc') || ($role eq 'in') ||
10598:             ($role eq 'ep') || ($role eq 'ad') ||
10599:             ($role eq 'ta') || ($role eq 'st') ||
10600:             ($role=~/^cr/) || ($role eq 'gr') ||
10601:             ($role eq 'co')) {
10602: # for course roles, perform group memberships changes triggered by role change.
10603:             unless ($role =~ /^gr/) {
10604:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10605:                                                  $origstart,$selfenroll,$context);
10606:             }
10607:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10608:                            $selfenroll,$context);
10609:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10610:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10611:                  ($role eq 'da')) {
10612:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10613:                            $context);
10614:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10615:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10616:                              $context); 
10617:         }
10618:         if ($role eq 'cc') {
10619:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10620:         }
10621:     }
10622:     return $answer;
10623: }
10624: 
10625: sub autoupdate_coowners {
10626:     my ($url,$end,$start,$uname,$udom) = @_;
10627:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10628:     if (($cdom ne '') && ($cnum ne '')) {
10629:         my $now = time;
10630:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10631:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10632:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10633:             my $instcode = $coursehash{'internal.coursecode'};
10634:             my $xlists = $coursehash{'internal.crosslistings'};
10635:             if ($instcode ne '') {
10636:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10637:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10638:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10639:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10640:                         unless ($result eq 'valid') {
10641:                             if ($xlists ne '') {
10642:                                 foreach my $xlist (split(',',$xlists)) {
10643:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10644:                                     $result =
10645:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10646:                                                                       $inst_crosslist,$uname.':'.$udom);
10647:                                     last if ($result eq 'valid');
10648:                                 }
10649:                             }
10650:                         }
10651:                         if ($result eq 'valid') {
10652:                             if ($coursehash{'internal.co-owners'}) {
10653:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10654:                                     push(@newcoowners,$coowner);
10655:                                 }
10656:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10657:                                     push(@newcoowners,$uname.':'.$udom);
10658:                                 }
10659:                                 @newcoowners = sort(@newcoowners);
10660:                             } else {
10661:                                 push(@newcoowners,$uname.':'.$udom);
10662:                             }
10663:                         } elsif ($coursehash{'internal.co-owners'}) {
10664:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10665:                                 unless ($coowner eq $uname.':'.$udom) {
10666:                                     push(@newcoowners,$coowner);
10667:                                 }
10668:                             }
10669:                             unless (@newcoowners > 0) {
10670:                                 $delcoowners = 1;
10671:                                 $coowners = '';
10672:                             }
10673:                         }
10674:                         if (@newcoowners || $delcoowners) {
10675:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10676:                                             $delcoowners,@newcoowners);
10677:                         }
10678:                     }
10679:                 }
10680:             }
10681:         }
10682:     }
10683: }
10684: 
10685: sub store_coowners {
10686:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10687:     my $cid = $cdom.'_'.$cnum;
10688:     my ($coowners,$delresult,$putresult);
10689:     if (@newcoowners) {
10690:         $coowners = join(',',@newcoowners);
10691:         my %coownershash = (
10692:                             'internal.co-owners' => $coowners,
10693:                            );
10694:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10695:         if ($putresult eq 'ok') {
10696:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10697:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10698:             }
10699:         }
10700:     }
10701:     if ($delcoowners) {
10702:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10703:         if ($delresult eq 'ok') {
10704:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10705:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10706:             }
10707:         }
10708:     }
10709:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10710:         my %crsinfo =
10711:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10712:         if (ref($crsinfo{$cid}) eq 'HASH') {
10713:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10714:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
10715:         }
10716:     }
10717: }
10718: 
10719: # -------------------------------------------------- Modify user authentication
10720: # Overrides without validation
10721: 
10722: sub modifyuserauth {
10723:     my ($udom,$uname,$umode,$upass)=@_;
10724:     my $uhome=&homeserver($uname,$udom);
10725:     my $allowed;
10726:     if (&allowed('mau',$udom)) {
10727:         $allowed = 1;
10728:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10729:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10730:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10731:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10732:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10733:         if (($cdom ne '') && ($cnum ne '')) {
10734:             my $is_owner = &is_course_owner($cdom,$cnum);
10735:             if ($is_owner) {
10736:                 $allowed = 1;
10737:             }
10738:         }
10739:     }
10740:     unless ($allowed) { return 'refused'; }
10741:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10742:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10743:              ' in domain '.$env{'request.role.domain'});  
10744:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10745: 		     &escape($upass),$uhome);
10746:     my $ip = &get_requestor_ip();
10747:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10748:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10749:          '(Remote '.$ip.'): '.$reply);
10750:     &log($udom,,$uname,$uhome,
10751:         'Authentication changed by '.$env{'user.domain'}.', '.
10752:                                      $env{'user.name'}.', '.$umode.
10753:          '(Remote '.$ip.'): '.$reply);
10754:     unless ($reply eq 'ok') {
10755:         &logthis('Authentication mode error: '.$reply);
10756: 	return 'error: '.$reply;
10757:     }   
10758:     return 'ok';
10759: }
10760: 
10761: # --------------------------------------------------------------- Modify a user
10762: 
10763: sub modifyuser {
10764:     my ($udom,    $uname, $uid,
10765:         $umode,   $upass, $first,
10766:         $middle,  $last,  $gene,
10767:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10768:     $udom= &LONCAPA::clean_domain($udom);
10769:     $uname=&LONCAPA::clean_username($uname);
10770:     my $showcandelete = 'none';
10771:     if (ref($candelete) eq 'ARRAY') {
10772:         if (@{$candelete} > 0) {
10773:             $showcandelete = join(', ',@{$candelete});
10774:         }
10775:     }
10776:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10777:              $umode.', '.$first.', '.$middle.', '.
10778: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10779:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10780:                                      ' desiredhome not specified'). 
10781:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10782:              ' in domain '.$env{'request.role.domain'});
10783:     my $uhome=&homeserver($uname,$udom,'true');
10784:     my $newuser;
10785:     if ($uhome eq 'no_host') {
10786:         $newuser = 1;
10787:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10788:                 ($umode eq 'lti')) {
10789:             return 'error: more information needed to create new user';
10790:         }
10791:     }
10792: # ----------------------------------------------------------------- Create User
10793:     if (($uhome eq 'no_host') && 
10794: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10795:         my $unhome='';
10796:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10797:             $unhome = $desiredhome;
10798: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10799: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10800:         } else { # load balancing routine for determining $unhome
10801:             my $loadm=10000000;
10802: 	    my %servers = &get_servers($udom,'library');
10803: 	    foreach my $tryserver (keys(%servers)) {
10804: 		my $answer=reply('load',$tryserver);
10805: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10806: 		    $loadm=$answer;
10807: 		    $unhome=$tryserver;
10808: 		}
10809: 	    }
10810:         }
10811:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10812: 	    return 'error: unable to find a home server for '.$uname.
10813:                    ' in domain '.$udom;
10814:         }
10815:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10816:                          &escape($upass),$unhome);
10817: 	unless ($reply eq 'ok') {
10818:             return 'error: '.$reply;
10819:         }   
10820:         $uhome=&homeserver($uname,$udom,'true');
10821:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10822: 	    return 'error: unable verify users home machine.';
10823:         }
10824:     }   # End of creation of new user
10825: # ---------------------------------------------------------------------- Add ID
10826:     if ($uid) {
10827:        $uid=~tr/A-Z/a-z/;
10828:        my %uidhash=&idrget($udom,$uname);
10829:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10830:          && (!$forceid)) {
10831: 	  unless ($uid eq $uidhash{$uname}) {
10832: 	      return 'error: user id "'.$uid.'" does not match '.
10833:                   'current user id "'.$uidhash{$uname}.'".';
10834:           }
10835:        } else {
10836: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10837:        }
10838:     }
10839: # -------------------------------------------------------------- Add names, etc
10840:     my @tmp=&get('environment',
10841: 		   ['firstname','middlename','lastname','generation','id',
10842:                     'permanentemail','inststatus'],
10843: 		   $udom,$uname);
10844:     my (%names,%oldnames);
10845:     if ($tmp[0] =~ m/^error:.*/) { 
10846:         %names=(); 
10847:     } else {
10848:         %names = @tmp;
10849:         %oldnames = %names;
10850:     }
10851: #
10852: # If name, email and/or uid are blank (e.g., because an uploaded file
10853: # of users did not contain them), do not overwrite existing values
10854: # unless field is in $candelete array ref.  
10855: #
10856: 
10857:     my @fields = ('firstname','middlename','lastname','generation',
10858:                   'permanentemail','id');
10859:     my %newvalues;
10860:     if (ref($candelete) eq 'ARRAY') {
10861:         foreach my $field (@fields) {
10862:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10863:                 if ($field eq 'firstname') {
10864:                     $names{$field} = $first;
10865:                 } elsif ($field eq 'middlename') {
10866:                     $names{$field} = $middle;
10867:                 } elsif ($field eq 'lastname') {
10868:                     $names{$field} = $last;
10869:                 } elsif ($field eq 'generation') { 
10870:                     $names{$field} = $gene;
10871:                 } elsif ($field eq 'permanentemail') {
10872:                     $names{$field} = $email;
10873:                 } elsif ($field eq 'id') {
10874:                     $names{$field}  = $uid;
10875:                 }
10876:             }
10877:         }
10878:     }
10879:     if ($first)  { $names{'firstname'}  = $first; }
10880:     if (defined($middle)) { $names{'middlename'} = $middle; }
10881:     if ($last)   { $names{'lastname'}   = $last; }
10882:     if (defined($gene))   { $names{'generation'} = $gene; }
10883:     if ($email) {
10884:        $email=~s/[^\w\@\.\-\,]//gs;
10885:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10886:     }
10887:     if ($uid) { $names{'id'}  = $uid; }
10888:     if (defined($inststatus)) {
10889:         $names{'inststatus'} = '';
10890:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10891:         if (ref($usertypes) eq 'HASH') {
10892:             my @okstatuses; 
10893:             foreach my $item (split(/:/,$inststatus)) {
10894:                 if (defined($usertypes->{$item})) {
10895:                     push(@okstatuses,$item);  
10896:                 }
10897:             }
10898:             if (@okstatuses) {
10899:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10900:             }
10901:         }
10902:     }
10903:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10904:                  $umode.', '.$first.', '.$middle.', '.
10905:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10906:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10907:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10908:     } else {
10909:         $logmsg .= ' during self creation';
10910:     }
10911:     my $changed;
10912:     if ($newuser) {
10913:         $changed = 1;
10914:     } else {
10915:         foreach my $field (@fields) {
10916:             if ($names{$field} ne $oldnames{$field}) {
10917:                 $changed = 1;
10918:                 last;
10919:             }
10920:         }
10921:     }
10922:     unless ($changed) {
10923:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10924:         &logthis($logmsg);
10925:         return 'ok';
10926:     }
10927:     my $reply = &put('environment', \%names, $udom,$uname);
10928:     if ($reply ne 'ok') { 
10929:         return 'error: '.$reply;
10930:     }
10931:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10932:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
10933:     }
10934:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10935:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10936:     $logmsg = 'Success modifying user '.$logmsg;
10937:     &logthis($logmsg);
10938:     return 'ok';
10939: }
10940: 
10941: # -------------------------------------------------------------- Modify student
10942: 
10943: sub modifystudent {
10944:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10945:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10946:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10947:     if (!$cid) {
10948: 	unless ($cid=$env{'request.course.id'}) {
10949: 	    return 'not_in_class';
10950: 	}
10951:     }
10952: # --------------------------------------------------------------- Make the user
10953:     my $reply=&modifyuser
10954: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10955:          $desiredhome,$email,$inststatus);
10956:     unless ($reply eq 'ok') { return $reply; }
10957:     # This will cause &modify_student_enrollment to get the uid from the
10958:     # student's environment
10959:     $uid = undef if (!$forceid);
10960:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10961:                                         $gene,$usec,$end,$start,$type,$locktype,
10962:                                         $cid,$selfenroll,$context,$credits,$instsec);
10963:     return $reply;
10964: }
10965: 
10966: sub modify_student_enrollment {
10967:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10968:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10969:     my ($cdom,$cnum,$chome);
10970:     if (!$cid) {
10971: 	unless ($cid=$env{'request.course.id'}) {
10972: 	    return 'not_in_class';
10973: 	}
10974: 	$cdom=$env{'course.'.$cid.'.domain'};
10975: 	$cnum=$env{'course.'.$cid.'.num'};
10976:     } else {
10977: 	($cdom,$cnum)=split(/_/,$cid);
10978:     }
10979:     $chome=$env{'course.'.$cid.'.home'};
10980:     if (!$chome) {
10981: 	$chome=&homeserver($cnum,$cdom);
10982:     }
10983:     if (!$chome) { return 'unknown_course'; }
10984:     # Make sure the user exists
10985:     my $uhome=&homeserver($uname,$udom);
10986:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10987: 	return 'error: no such user';
10988:     }
10989:     # Get student data if we were not given enough information
10990:     if (!defined($first)  || $first  eq '' || 
10991:         !defined($last)   || $last   eq '' || 
10992:         !defined($uid)    || $uid    eq '' || 
10993:         !defined($middle) || $middle eq '' || 
10994:         !defined($gene)   || $gene   eq '') {
10995:         # They did not supply us with enough data to enroll the student, so
10996:         # we need to pick up more information.
10997:         my %tmp = &get('environment',
10998:                        ['firstname','middlename','lastname', 'generation','id']
10999:                        ,$udom,$uname);
11000: 
11001:         #foreach my $key (keys(%tmp)) {
11002:         #    &logthis("key $key = ".$tmp{$key});
11003:         #}
11004:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11005:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11006:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11007:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11008:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11009:     }
11010:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11011:     my $user = "$uname:$udom";
11012:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11013:     my $reply=cput('classlist',
11014: 		   {$user => 
11015: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11016: 		   $cdom,$cnum);
11017:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11018:         &devalidate_getsection_cache($udom,$uname,$cid);
11019:     } else { 
11020: 	return 'error: '.$reply;
11021:     }
11022:     # Add student role to user
11023:     my $uurl='/'.$cid;
11024:     $uurl=~s/\_/\//g;
11025:     if ($usec) {
11026: 	$uurl.='/'.$usec;
11027:     }
11028:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11029:                              $selfenroll,$context);
11030:     if ($result ne 'ok') {
11031:         if ($old_entry{$user} ne '') {
11032:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11033:         } else {
11034:             $reply = &del('classlist',[$user],$cdom,$cnum);
11035:         }
11036:     }
11037:     return $result; 
11038: }
11039: 
11040: sub format_name {
11041:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11042:     my $name;
11043:     if ($first ne 'lastname') {
11044: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11045:     } else {
11046: 	if ($lastname=~/\S/) {
11047: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11048: 	    $name=~s/\s+,/,/;
11049: 	} else {
11050: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11051: 	}
11052:     }
11053:     $name=~s/^\s+//;
11054:     $name=~s/\s+$//;
11055:     $name=~s/\s+/ /g;
11056:     return $name;
11057: }
11058: 
11059: # ------------------------------------------------- Write to course preferences
11060: 
11061: sub writecoursepref {
11062:     my ($courseid,%prefs)=@_;
11063:     $courseid=~s/^\///;
11064:     $courseid=~s/\_/\//g;
11065:     my ($cdomain,$cnum)=split(/\//,$courseid);
11066:     my $chome=homeserver($cnum,$cdomain);
11067:     if (($chome eq '') || ($chome eq 'no_host')) { 
11068: 	return 'error: no such course';
11069:     }
11070:     my $cstring='';
11071:     foreach my $pref (keys(%prefs)) {
11072: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11073:     }
11074:     $cstring=~s/\&$//;
11075:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11076: }
11077: 
11078: # ---------------------------------------------------------- Make/modify course
11079: 
11080: sub createcourse {
11081:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11082:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11083:     $url=&declutter($url);
11084:     my $cid='';
11085:     if ($context eq 'requestcourses') {
11086:         my $can_create = 0;
11087:         my ($ownername,$ownerdom) = split(':',$course_owner);
11088:         if ($udom eq $ownerdom) {
11089:             my $reload;
11090:             if (($callercontext eq 'auto') &&
11091:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11092:                 $reload = 'reload';
11093:             }
11094:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11095:                                   $context)) {
11096:                 $can_create = 1;
11097:             }
11098:         } else {
11099:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11100:                                            $category);
11101:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11102:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11103:                 if (@curr > 0) {
11104:                     my @options = qw(approval validate autolimit);
11105:                     my $optregex = join('|',@options);
11106:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11107:                         $can_create = 1;
11108:                     }
11109:                 }
11110:             }
11111:         }
11112:         if ($can_create) {
11113:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11114:                 unless (&allowed('ccc',$udom)) {
11115:                     return 'refused'; 
11116:                 }
11117:             }
11118:         } else {
11119:             return 'refused';
11120:         }
11121:     } elsif (!&allowed('ccc',$udom)) {
11122:         return 'refused';
11123:     }
11124: # --------------------------------------------------------------- Get Unique ID
11125:     my $uname;
11126:     if ($cnum =~ /^$match_courseid$/) {
11127:         my $chome=&homeserver($cnum,$udom,'true');
11128:         if (($chome eq '') || ($chome eq 'no_host')) {
11129:             $uname = $cnum;
11130:         } else {
11131:             $uname = &generate_coursenum($udom,$crstype);
11132:         }
11133:     } else {
11134:         $uname = &generate_coursenum($udom,$crstype);
11135:     }
11136:     return $uname if ($uname =~ /^error/);
11137: # -------------------------------------------------- Check supplied server name
11138:     if (!defined($course_server)) {
11139:         if (defined(&domain($udom,'primary'))) {
11140:             $course_server = &domain($udom,'primary');
11141:         } else {
11142:             $course_server = $env{'user.home'}; 
11143:         }
11144:     }
11145:     my %host_servers =
11146:         &get_servers($udom,'library');
11147:     unless ($host_servers{$course_server}) {
11148:         return 'error: invalid home server for course: '.$course_server;
11149:     }
11150: # ------------------------------------------------------------- Make the course
11151:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11152:                       $course_server);
11153:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11154:     my $uhome=&homeserver($uname,$udom,'true');
11155:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11156: 	return 'error: no such course';
11157:     }
11158: # ----------------------------------------------------------------- Course made
11159: # log existence
11160:     my $now = time;
11161:     my $newcourse = {
11162:                     $udom.'_'.$uname => {
11163:                                      description => $description,
11164:                                      inst_code   => $inst_code,
11165:                                      owner       => $course_owner,
11166:                                      type        => $crstype,
11167:                                      creator     => $env{'user.name'}.':'.
11168:                                                     $env{'user.domain'},
11169:                                      created     => $now,
11170:                                      context     => $context,
11171:                                                 },
11172:                     };
11173:     &courseidput($udom,$newcourse,$uhome,'notime');
11174: # set toplevel url
11175:     my $topurl=$url;
11176:     unless ($nonstandard) {
11177: # ------------------------------------------ For standard courses, make top url
11178:         my $mapurl=&clutter($url);
11179:         if ($mapurl eq '/res/') { $mapurl=''; }
11180:         $env{'form.initmap'}=(<<ENDINITMAP);
11181: <map>
11182: <resource id="1" type="start"></resource>
11183: <resource id="2" src="$mapurl"></resource>
11184: <resource id="3" type="finish"></resource>
11185: <link index="1" from="1" to="2"></link>
11186: <link index="2" from="2" to="3"></link>
11187: </map>
11188: ENDINITMAP
11189:         $topurl=&declutter(
11190:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11191:                           );
11192:     }
11193: # ----------------------------------------------------------- Write preferences
11194:     &writecoursepref($udom.'_'.$uname,
11195:                      ('description'              => $description,
11196:                       'url'                      => $topurl,
11197:                       'internal.creator'         => $env{'user.name'}.':'.
11198:                                                     $env{'user.domain'},
11199:                       'internal.created'         => $now,
11200:                       'internal.creationcontext' => $context)
11201:                     );
11202:     return '/'.$udom.'/'.$uname;
11203: }
11204: 
11205: # ------------------------------------------------------------------- Create ID
11206: sub generate_coursenum {
11207:     my ($udom,$crstype) = @_;
11208:     my $domdesc = &domain($udom);
11209:     return 'error: invalid domain' if ($domdesc eq '');
11210:     my $first;
11211:     if ($crstype eq 'Community') {
11212:         $first = '0';
11213:     } else {
11214:         $first = int(1+rand(9)); 
11215:     } 
11216:     my $uname=$first.
11217:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11218:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11219:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11220: # ----------------------------------------------- Make sure that does not exist
11221:     my $uhome=&homeserver($uname,$udom,'true');
11222:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11223:         if ($crstype eq 'Community') {
11224:             $first = '0';
11225:         } else {
11226:             $first = int(1+rand(9));
11227:         }
11228:         $uname=$first.
11229:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11230:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11231:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11232:         $uhome=&homeserver($uname,$udom,'true');
11233:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11234:             return 'error: unable to generate unique course-ID';
11235:         }
11236:     }
11237:     return $uname;
11238: }
11239: 
11240: sub is_course {
11241:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11242:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11243: 
11244:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11245:     my $uhome=&homeserver($cnum,$cdom);
11246:     my $iscourse;
11247:     if (grep { $_ eq $uhome } current_machine_ids()) {
11248:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11249:     } else {
11250:         my $hashid = $cdom.':'.$cnum;
11251:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11252:         unless (defined($cached)) {
11253:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11254:                                         $cnum,undef,undef,'.');
11255:             $iscourse = 0;
11256:             if (exists($courses{$cdom.'_'.$cnum})) {
11257:                 $iscourse = 1;
11258:             }
11259:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11260:         }
11261:     }
11262:     return unless ($iscourse);
11263:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11264: }
11265: 
11266: sub store_userdata {
11267:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11268:     my $result;
11269:     if ($datakey ne '') {
11270:         if (ref($storehash) eq 'HASH') {
11271:             if ($udom eq '' || $uname eq '') {
11272:                 $udom = $env{'user.domain'};
11273:                 $uname = $env{'user.name'};
11274:             }
11275:             my $uhome=&homeserver($uname,$udom);
11276:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11277:                 $result = 'error: no_host';
11278:             } else {
11279:                 $storehash->{'ip'} = &get_requestor_ip();
11280:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11281: 
11282:                 my $namevalue='';
11283:                 foreach my $key (keys(%{$storehash})) {
11284:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11285:                 }
11286:                 $namevalue=~s/\&$//;
11287:                 unless ($namespace eq 'courserequests') {
11288:                     $datakey = &escape($datakey);
11289:                 }
11290:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11291:                                   $namevalue,$uhome);
11292:             }
11293:         } else {
11294:             $result = 'error: data to store was not a hash reference'; 
11295:         }
11296:     } else {
11297:         $result= 'error: invalid requestkey'; 
11298:     }
11299:     return $result;
11300: }
11301: 
11302: # ---------------------------------------------------------- Assign Custom Role
11303: 
11304: sub assigncustomrole {
11305:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11306:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11307:                        $end,$start,$deleteflag,$selfenroll,$context);
11308: }
11309: 
11310: # ----------------------------------------------------------------- Revoke Role
11311: 
11312: sub revokerole {
11313:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11314:     my $now=time;
11315:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11316: }
11317: 
11318: # ---------------------------------------------------------- Revoke Custom Role
11319: 
11320: sub revokecustomrole {
11321:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11322:     my $now=time;
11323:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11324:            $deleteflag,$selfenroll,$context);
11325: }
11326: 
11327: # ------------------------------------------------------------ Disk usage
11328: sub diskusage {
11329:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11330:     $directorypath =~ s/\/$//;
11331:     my $listing=&reply('du2:'.&escape($directorypath).':'
11332:                        .&escape($getpropath).':'.&escape($uname).':'
11333:                        .&escape($udom),homeserver($uname,$udom));
11334:     if ($listing eq 'unknown_cmd') {
11335:         if ($getpropath) {
11336:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11337:         }
11338:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11339:     }
11340:     return $listing;
11341: }
11342: 
11343: sub is_locked {
11344:     my ($file_name, $domain, $user, $which) = @_;
11345:     my @check;
11346:     my $is_locked;
11347:     push (@check,$file_name);
11348:     my %locked = &get('file_permissions',\@check,
11349: 		      $env{'user.domain'},$env{'user.name'});
11350:     my ($tmp)=keys(%locked);
11351:     if ($tmp=~/^error:/) { undef(%locked); }
11352:     
11353:     if (ref($locked{$file_name}) eq 'ARRAY') {
11354:         $is_locked = 'false';
11355:         foreach my $entry (@{$locked{$file_name}}) {
11356:            if (ref($entry) eq 'ARRAY') {
11357:                $is_locked = 'true';
11358:                if (ref($which) eq 'ARRAY') {
11359:                    push(@{$which},$entry);
11360:                } else {
11361:                    last;
11362:                }
11363:            }
11364:        }
11365:     } else {
11366:         $is_locked = 'false';
11367:     }
11368:     return $is_locked;
11369: }
11370: 
11371: sub declutter_portfile {
11372:     my ($file) = @_;
11373:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11374:     return $file;
11375: }
11376: 
11377: # ------------------------------------------------------------- Mark as Read Only
11378: 
11379: sub mark_as_readonly {
11380:     my ($domain,$user,$files,$what) = @_;
11381:     my %current_permissions = &dump('file_permissions',$domain,$user);
11382:     my ($tmp)=keys(%current_permissions);
11383:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11384:     foreach my $file (@{$files}) {
11385: 	$file = &declutter_portfile($file);
11386:         push(@{$current_permissions{$file}},$what);
11387:     }
11388:     &put('file_permissions',\%current_permissions,$domain,$user);
11389:     return;
11390: }
11391: 
11392: # ------------------------------------------------------------Save Selected Files
11393: 
11394: sub save_selected_files {
11395:     my ($user, $path, @files) = @_;
11396:     my $filename = $user."savedfiles";
11397:     my @other_files = &files_not_in_path($user, $path);
11398:     open (OUT,'>',LONCAPA::tempdir().$filename);
11399:     foreach my $file (@files) {
11400:         print (OUT $env{'form.currentpath'}.$file."\n");
11401:     }
11402:     foreach my $file (@other_files) {
11403:         print (OUT $file."\n");
11404:     }
11405:     close (OUT);
11406:     return 'ok';
11407: }
11408: 
11409: sub clear_selected_files {
11410:     my ($user) = @_;
11411:     my $filename = $user."savedfiles";
11412:     open (OUT,'>',LONCAPA::tempdir().$filename);
11413:     print (OUT undef);
11414:     close (OUT);
11415:     return ("ok");    
11416: }
11417: 
11418: sub files_in_path {
11419:     my ($user, $path) = @_;
11420:     my $filename = $user."savedfiles";
11421:     my %return_files;
11422:     open (IN,'<',LONCAPA::tempdir().$filename);
11423:     while (my $line_in = <IN>) {
11424:         chomp ($line_in);
11425:         my @paths_and_file = split (m!/!, $line_in);
11426:         my $file_part = pop (@paths_and_file);
11427:         my $path_part = join ('/', @paths_and_file);
11428:         $path_part.='/';
11429:         my $path_and_file = $path_part.$file_part;
11430:         if ($path_part eq $path) {
11431:             $return_files{$file_part}= 'selected';
11432:         }
11433:     }
11434:     close (IN);
11435:     return (\%return_files);
11436: }
11437: 
11438: # called in portfolio select mode, to show files selected NOT in current directory
11439: sub files_not_in_path {
11440:     my ($user, $path) = @_;
11441:     my $filename = $user."savedfiles";
11442:     my @return_files;
11443:     my $path_part;
11444:     open(IN, '<',LONCAPA::tempdir().$filename);
11445:     while (my $line = <IN>) {
11446:         #ok, I know it's clunky, but I want it to work
11447:         my @paths_and_file = split(m|/|, $line);
11448:         my $file_part = pop(@paths_and_file);
11449:         chomp($file_part);
11450:         my $path_part = join('/', @paths_and_file);
11451:         $path_part .= '/';
11452:         my $path_and_file = $path_part.$file_part;
11453:         if ($path_part ne $path) {
11454:             push(@return_files, ($path_and_file));
11455:         }
11456:     }
11457:     close(OUT);
11458:     return (@return_files);
11459: }
11460: 
11461: #------------------------------Submitted/Handedback Portfolio Files Versioning
11462:  
11463: sub portfiles_versioning {
11464:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11465:     my $portfolio_root = '/userfiles/portfolio';
11466:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11467:     foreach my $file (@{$portfiles}) {
11468:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11469:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11470:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11471:         my $getpropath = 1;
11472:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11473:                                              $stu_name,$getpropath);
11474:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11475:         my $new_answer = 
11476:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11477:         if ($new_answer ne 'problem getting file') {
11478:             push(@{$versioned_portfiles}, $directory.$new_answer);
11479:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11480:                               [$symb,$env{'request.course.id'},'graded']);
11481:         }
11482:     }
11483: }
11484: 
11485: sub get_next_version {
11486:     my ($answer_name, $answer_ext, $dir_list) = @_;
11487:     my $version;
11488:     if (ref($dir_list) eq 'ARRAY') {
11489:         foreach my $row (@{$dir_list}) {
11490:             my ($file) = split(/\&/,$row,2);
11491:             my ($file_name,$file_version,$file_ext) =
11492:                 &file_name_version_ext($file);
11493:             if (($file_name eq $answer_name) &&
11494:                 ($file_ext eq $answer_ext)) {
11495:                      # gets here if filename and extension match,
11496:                      # regardless of version
11497:                 if ($file_version ne '') {
11498:                     # a versioned file is found  so save it for later
11499:                     if ($file_version > $version) {
11500:                         $version = $file_version;
11501:                     }
11502:                 }
11503:             }
11504:         }
11505:     }
11506:     $version ++;
11507:     return($version);
11508: }
11509: 
11510: sub version_selected_portfile {
11511:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11512:     my ($answer_name,$answer_ver,$answer_ext) =
11513:         &file_name_version_ext($file_name);
11514:     my $new_answer;
11515:     $env{'form.copy'} =
11516:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11517:     if($env{'form.copy'} eq '-1') {
11518:         $new_answer = 'problem getting file';
11519:     } else {
11520:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11521:         my $copy_result = 
11522:             &finishuserfileupload($stu_name,$domain,'copy',
11523:                                   '/portfolio'.$directory.$new_answer);
11524:     }
11525:     undef($env{'form.copy'});
11526:     return ($new_answer);
11527: }
11528: 
11529: sub file_name_version_ext {
11530:     my ($file)=@_;
11531:     my @file_parts = split(/\./, $file);
11532:     my ($name,$version,$ext);
11533:     if (@file_parts > 1) {
11534:         $ext=pop(@file_parts);
11535:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11536:             $version=pop(@file_parts);
11537:         }
11538:         $name=join('.',@file_parts);
11539:     } else {
11540:         $name=join('.',@file_parts);
11541:     }
11542:     return($name,$version,$ext);
11543: }
11544: 
11545: #----------------------------------------------Get portfolio file permissions
11546: 
11547: sub get_portfile_permissions {
11548:     my ($domain,$user) = @_;
11549:     my %current_permissions = &dump('file_permissions',$domain,$user);
11550:     my ($tmp)=keys(%current_permissions);
11551:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11552:     return \%current_permissions;
11553: }
11554: 
11555: #---------------------------------------------Get portfolio file access controls
11556: 
11557: sub get_access_controls {
11558:     my ($current_permissions,$group,$file) = @_;
11559:     my %access;
11560:     my $real_file = $file;
11561:     $file =~ s/\.meta$//;
11562:     if (defined($file)) {
11563:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11564:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11565:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11566:             }
11567:         }
11568:     } else {
11569:         foreach my $key (keys(%{$current_permissions})) {
11570:             if ($key =~ /\0accesscontrol$/) {
11571:                 if (defined($group)) {
11572:                     if ($key !~ m-^\Q$group\E/-) {
11573:                         next;
11574:                     }
11575:                 }
11576:                 my ($fullpath) = split(/\0/,$key);
11577:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11578:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11579:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11580:                     }
11581:                 }
11582:             }
11583:         }
11584:     }
11585:     return %access;
11586: }
11587: 
11588: sub modify_access_controls {
11589:     my ($file_name,$changes,$domain,$user)=@_;
11590:     my ($outcome,$deloutcome);
11591:     my %store_permissions;
11592:     my %new_values;
11593:     my %new_control;
11594:     my %translation;
11595:     my @deletions = ();
11596:     my $now = time;
11597:     if (exists($$changes{'activate'})) {
11598:         if (ref($$changes{'activate'}) eq 'HASH') {
11599:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11600:             my $numnew = scalar(@newitems);
11601:             for (my $i=0; $i<$numnew; $i++) {
11602:                 my $newkey = $newitems[$i];
11603:                 my $newid = &Apache::loncommon::get_cgi_id();
11604:                 if ($newkey =~ /^\d+:/) { 
11605:                     $newkey =~ s/^(\d+)/$newid/;
11606:                     $translation{$1} = $newid;
11607:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11608:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11609:                     $translation{$1} = $newid;
11610:                 }
11611:                 $new_values{$file_name."\0".$newkey} = 
11612:                                           $$changes{'activate'}{$newitems[$i]};
11613:                 $new_control{$newkey} = $now;
11614:             }
11615:         }
11616:     }
11617:     my %todelete;
11618:     my %changed_items;
11619:     foreach my $action ('delete','update') {
11620:         if (exists($$changes{$action})) {
11621:             if (ref($$changes{$action}) eq 'HASH') {
11622:                 foreach my $key (keys(%{$$changes{$action}})) {
11623:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11624:                     if ($action eq 'delete') { 
11625:                         $todelete{$itemnum} = 1;
11626:                     } else {
11627:                         $changed_items{$itemnum} = $key;
11628:                     }
11629:                 }
11630:             }
11631:         }
11632:     }
11633:     # get lock on access controls for file.
11634:     my $lockhash = {
11635:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11636:                                                        ':'.$env{'user.domain'},
11637:                    }; 
11638:     my $tries = 0;
11639:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11640:    
11641:     while (($gotlock ne 'ok') && $tries < 10) {
11642:         $tries ++;
11643:         sleep(0.1);
11644:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11645:     }
11646:     if ($gotlock eq 'ok') {
11647:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11648:         my ($tmp)=keys(%curr_permissions);
11649:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11650:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11651:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11652:             if (ref($curr_controls) eq 'HASH') {
11653:                 foreach my $control_item (keys(%{$curr_controls})) {
11654:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11655:                     if (defined($todelete{$itemnum})) {
11656:                         push(@deletions,$file_name."\0".$control_item);
11657:                     } else {
11658:                         if (defined($changed_items{$itemnum})) {
11659:                             $new_control{$changed_items{$itemnum}} = $now;
11660:                             push(@deletions,$file_name."\0".$control_item);
11661:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11662:                         } else {
11663:                             $new_control{$control_item} = $$curr_controls{$control_item};
11664:                         }
11665:                     }
11666:                 }
11667:             }
11668:         }
11669:         my ($group);
11670:         if (&is_course($domain,$user)) {
11671:             ($group,my $file) = split(/\//,$file_name,2);
11672:         }
11673:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11674:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11675:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11676:         #  remove lock
11677:         my @del_lock = ($file_name."\0".'locked_access_records');
11678:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11679:         my $sqlresult =
11680:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11681:                                     $group);
11682:     } else {
11683:         $outcome = "error: could not obtain lockfile\n";  
11684:     }
11685:     return ($outcome,$deloutcome,\%new_values,\%translation);
11686: }
11687: 
11688: sub make_public_indefinitely {
11689:     my (@requrl) = @_;
11690:     return &automated_portfile_access('public',\@requrl);
11691: }
11692: 
11693: sub automated_portfile_access {
11694:     my ($accesstype,$addsref,$delsref,$info) = @_;
11695:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11696:         return 'invalid';
11697:     }
11698:     my %urls;
11699:     if (ref($addsref) eq 'ARRAY') {
11700:         foreach my $requrl (@{$addsref}) {
11701:             if (&is_portfolio_url($requrl)) {
11702:                 unless (exists($urls{$requrl})) {
11703:                     $urls{$requrl} = 'add';
11704:                 }
11705:             }
11706:         }
11707:     }
11708:     if (ref($delsref) eq 'ARRAY') {
11709:         foreach my $requrl (@{$delsref}) { 
11710:             if (&is_portfolio_url($requrl)) {
11711:                 unless (exists($urls{$requrl})) {
11712:                     $urls{$requrl} = 'delete'; 
11713:                 }
11714:             }
11715:         }
11716:     }
11717:     unless (keys(%urls)) {
11718:         return 'invalid';
11719:     }
11720:     my $ip;
11721:     if ($accesstype eq 'ip') {
11722:         if (ref($info) eq 'HASH') {
11723:             if ($info->{'ip'} ne '') {
11724:                 $ip = $info->{'ip'};
11725:             }
11726:         }
11727:         if ($ip eq '') {
11728:             return 'invalid';
11729:         }
11730:     }
11731:     my $errors;
11732:     my $now = time;
11733:     my %current_perms;
11734:     foreach my $requrl (sort(keys(%urls))) {
11735:         my $action;
11736:         if ($urls{$requrl} eq 'add') {
11737:             $action = 'activate';
11738:         } else {
11739:             $action = 'none';
11740:         }
11741:         my $aclnum = 0;
11742:         my (undef,$udom,$unum,$file_name,$group) =
11743:             &parse_portfolio_url($requrl);
11744:         unless (exists($current_perms{$unum.':'.$udom})) {
11745:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11746:         }
11747:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11748:                                                    $group,$file_name);
11749:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11750:             my ($num,$scope,$end,$start) = 
11751:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11752:             if ($scope eq $accesstype) {
11753:                 if (($start <= $now) && ($end == 0)) {
11754:                     if ($accesstype eq 'ip') {
11755:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11756:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11757:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11758:                                     if ($urls{$requrl} eq 'add') {
11759:                                         $action = 'none';
11760:                                         last;
11761:                                     } else {
11762:                                         $action = 'delete';
11763:                                         $aclnum = $num;
11764:                                         last;
11765:                                     }
11766:                                 }
11767:                             }
11768:                         }
11769:                     } elsif ($accesstype eq 'public') {
11770:                         if ($urls{$requrl} eq 'add') {
11771:                             $action = 'none';
11772:                             last;
11773:                         } else {
11774:                             $action = 'delete';
11775:                             $aclnum = $num;
11776:                             last;
11777:                         }
11778:                     }
11779:                 } elsif ($accesstype eq 'public') {
11780:                     $action = 'update';
11781:                     $aclnum = $num;
11782:                     last;
11783:                 }
11784:             }
11785:         }
11786:         if ($action eq 'none') {
11787:             next;
11788:         } else {
11789:             my %changes;
11790:             my $newend = 0;
11791:             my $newstart = $now;
11792:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11793:             $changes{$action}{$newkey} = {
11794:                 type => $accesstype,
11795:                 time => {
11796:                     start => $newstart,
11797:                     end   => $newend,
11798:                 },
11799:             };
11800:             if ($accesstype eq 'ip') {
11801:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11802:             }
11803:             my ($outcome,$deloutcome,$new_values,$translation) =
11804:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11805:             unless ($outcome eq 'ok') {
11806:                 $errors .= $outcome.' ';
11807:             }
11808:         }
11809:     }
11810:     if ($errors) {
11811:         $errors =~ s/\s$//;
11812:         return $errors;
11813:     } else {
11814:         return 'ok';
11815:     }
11816: }
11817: 
11818: #------------------------------------------------------Get Marked as Read Only
11819: 
11820: sub get_marked_as_readonly {
11821:     my ($domain,$user,$what,$group) = @_;
11822:     my $current_permissions = &get_portfile_permissions($domain,$user);
11823:     my @readonly_files;
11824:     my $cmp1=$what;
11825:     if (ref($what)) { $cmp1=join('',@{$what}) };
11826:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11827:         if (defined($group)) {
11828:             if ($file_name !~ m-^\Q$group\E/-) {
11829:                 next;
11830:             }
11831:         }
11832:         if (ref($value) eq "ARRAY"){
11833:             foreach my $stored_what (@{$value}) {
11834:                 my $cmp2=$stored_what;
11835:                 if (ref($stored_what) eq 'ARRAY') {
11836:                     $cmp2=join('',@{$stored_what});
11837:                 }
11838:                 if ($cmp1 eq $cmp2) {
11839:                     push(@readonly_files, $file_name);
11840:                     last;
11841:                 } elsif (!defined($what)) {
11842:                     push(@readonly_files, $file_name);
11843:                     last;
11844:                 }
11845:             }
11846:         }
11847:     }
11848:     return @readonly_files;
11849: }
11850: #-----------------------------------------------------------Get Marked as Read Only Hash
11851: 
11852: sub get_marked_as_readonly_hash {
11853:     my ($current_permissions,$group,$what) = @_;
11854:     my %readonly_files;
11855:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11856:         if (defined($group)) {
11857:             if ($file_name !~ m-^\Q$group\E/-) {
11858:                 next;
11859:             }
11860:         }
11861:         if (ref($value) eq "ARRAY"){
11862:             foreach my $stored_what (@{$value}) {
11863:                 if (ref($stored_what) eq 'ARRAY') {
11864:                     foreach my $lock_descriptor(@{$stored_what}) {
11865:                         if ($lock_descriptor eq 'graded') {
11866:                             $readonly_files{$file_name} = 'graded';
11867:                         } elsif ($lock_descriptor eq 'handback') {
11868:                             $readonly_files{$file_name} = 'handback';
11869:                         } else {
11870:                             if (!exists($readonly_files{$file_name})) {
11871:                                 $readonly_files{$file_name} = 'locked';
11872:                             }
11873:                         }
11874:                     }
11875:                 } 
11876:             }
11877:         } 
11878:     }
11879:     return %readonly_files;
11880: }
11881: # ------------------------------------------------------------ Unmark as Read Only
11882: 
11883: sub unmark_as_readonly {
11884:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11885:     # for portfolio submissions, $what contains [$symb,$crsid] 
11886:     my ($domain,$user,$what,$file_name,$group) = @_;
11887:     $file_name = &declutter_portfile($file_name);
11888:     my $symb_crs = $what;
11889:     if (ref($what)) { $symb_crs=join('',@$what); }
11890:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11891:     my ($tmp)=keys(%current_permissions);
11892:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11893:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11894:     foreach my $file (@readonly_files) {
11895: 	my $clean_file = &declutter_portfile($file);
11896: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11897: 	my $current_locks = $current_permissions{$file};
11898:         my @new_locks;
11899:         my @del_keys;
11900:         if (ref($current_locks) eq "ARRAY"){
11901:             foreach my $locker (@{$current_locks}) {
11902:                 my $compare=$locker;
11903:                 if (ref($locker) eq 'ARRAY') {
11904:                     $compare=join('',@{$locker});
11905:                     if ($compare ne $symb_crs) {
11906:                         push(@new_locks, $locker);
11907:                     }
11908:                 }
11909:             }
11910:             if (scalar(@new_locks) > 0) {
11911:                 $current_permissions{$file} = \@new_locks;
11912:             } else {
11913:                 push(@del_keys, $file);
11914:                 &del('file_permissions',\@del_keys, $domain, $user);
11915:                 delete($current_permissions{$file});
11916:             }
11917:         }
11918:     }
11919:     &put('file_permissions',\%current_permissions,$domain,$user);
11920:     return;
11921: }
11922: 
11923: # ------------------------------------------------------------ Directory lister
11924: 
11925: sub dirlist {
11926:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11927:     $uri=~s/^\///;
11928:     $uri=~s/\/$//;
11929:     my ($udom, $uname);
11930:     if ($getuserdir) {
11931:         $udom = $userdomain;
11932:         $uname = $username;
11933:     } else {
11934:         (undef,$udom,$uname)=split(/\//,$uri);
11935:         if(defined($userdomain)) {
11936:             $udom = $userdomain;
11937:         }
11938:         if(defined($username)) {
11939:             $uname = $username;
11940:         }
11941:     }
11942:     my ($dirRoot,$listing,@listing_results);
11943: 
11944:     $dirRoot = $perlvar{'lonDocRoot'};
11945:     if (defined($getpropath)) {
11946:         $dirRoot = &propath($udom,$uname);
11947:         $dirRoot =~ s/\/$//;
11948:     } elsif (defined($getuserdir)) {
11949:         my $subdir=$uname.'__';
11950:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11951:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11952:                    ."/$udom/$subdir/$uname";
11953:     } elsif (defined($alternateRoot)) {
11954:         $dirRoot = $alternateRoot;
11955:     }
11956: 
11957:     if($udom) {
11958:         if($uname) {
11959:             my $uhome = &homeserver($uname,$udom);
11960:             if ($uhome eq 'no_host') {
11961:                 return ([],'no_host');
11962:             }
11963:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11964:                               .$getuserdir.':'.&escape($dirRoot)
11965:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11966:             if ($listing eq 'unknown_cmd') {
11967:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11968:             } else {
11969:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11970:             }
11971:             if ($listing eq 'unknown_cmd') {
11972:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11973:                 @listing_results = split(/:/,$listing);
11974:             } else {
11975:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11976:             }
11977:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11978:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11979:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11980:                 return ([],$listing);
11981:             } else {
11982:                 return (\@listing_results);
11983:             }
11984:         } elsif(!$alternateRoot) {
11985:             my (%allusers,%listerror);
11986: 	    my %servers = &get_servers($udom,'library');
11987:  	    foreach my $tryserver (keys(%servers)) {
11988:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11989:                                   &escape($udom),$tryserver);
11990:                 if ($listing eq 'unknown_cmd') {
11991: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11992: 				      $udom, $tryserver);
11993:                 } else {
11994:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11995:                 }
11996: 		if ($listing eq 'unknown_cmd') {
11997: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11998: 				      $udom, $tryserver);
11999: 		    @listing_results = split(/:/,$listing);
12000: 		} else {
12001: 		    @listing_results =
12002: 			map { &unescape($_); } split(/:/,$listing);
12003: 		}
12004:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12005:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12006:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12007:                     $listerror{$tryserver} = $listing;
12008:                 } else {
12009: 		    foreach my $line (@listing_results) {
12010: 			my ($entry) = split(/&/,$line,2);
12011: 			$allusers{$entry} = 1;
12012: 		    }
12013: 		}
12014:             }
12015:             my @alluserslist=();
12016:             foreach my $user (sort(keys(%allusers))) {
12017:                 push(@alluserslist,$user.'&user');
12018:             }
12019: 
12020:             if (!%listerror) {
12021:                 # no errors
12022:                 return (\@alluserslist);
12023:             } elsif (scalar(keys(%servers)) == 1) {
12024:                 # one library server, one error 
12025:                 my ($key) = keys(%listerror);
12026:                 return (\@alluserslist, $listerror{$key});
12027:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12028:                 # con_lost indicates that we might miss data from at least one
12029:                 # library server
12030:                 return (\@alluserslist, 'con_lost');
12031:             } else {
12032:                 # multiple library servers and no con_lost -> data should be
12033:                 # complete. 
12034:                 return (\@alluserslist);
12035:             }
12036: 
12037:         } else {
12038:             return ([],'missing username');
12039:         }
12040:     } elsif(!defined($getpropath)) {
12041:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12042:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12043:         return (\@all_domains);
12044:     } else {
12045:         return ([],'missing domain');
12046:     }
12047: }
12048: 
12049: # --------------------------------------------- GetFileTimestamp
12050: # This function utilizes dirlist and returns the date stamp for
12051: # when it was last modified.  It will also return an error of -1
12052: # if an error occurs
12053: 
12054: sub GetFileTimestamp {
12055:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12056:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12057:     $studentName   = &LONCAPA::clean_username($studentName);
12058:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12059:                                     undef,$getuserdir);
12060:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12061:         return -1;
12062:     }
12063:     if (ref($fileref) eq 'ARRAY') {
12064:         my @stats = split('&',$fileref->[0]);
12065:         # @stats contains first the filename, then the stat output
12066:         return $stats[10]; # so this is 10 instead of 9.
12067:     } else {
12068:         return -1;
12069:     }
12070: }
12071: 
12072: sub stat_file {
12073:     my ($uri) = @_;
12074:     $uri = &clutter_with_no_wrapper($uri);
12075: 
12076:     my ($udom,$uname,$file);
12077:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12078: 	($udom,$uname,$file) =
12079: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12080: 	$file = 'userfiles/'.$file;
12081:     }
12082:     if ($uri =~ m-^/res/-) {
12083: 	($udom,$uname) = 
12084: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12085: 	$file = $uri;
12086:     }
12087: 
12088:     if (!$udom || !$uname || !$file) {
12089: 	# unable to handle the uri
12090: 	return ();
12091:     }
12092:     my $getpropath;
12093:     if ($file =~ /^userfiles\//) {
12094:         $getpropath = 1;
12095:     }
12096:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12097:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12098:         return ();
12099:     } else {
12100:         if (ref($listref) eq 'ARRAY') {
12101:             my @stats = split('&',$listref->[0]);
12102: 	    shift(@stats); #filename is first
12103: 	    return @stats;
12104:         }
12105:     }
12106:     return ();
12107: }
12108: 
12109: # --------------------------------------------------------- recursedirs
12110: # Recursive function to traverse either a specific user's Authoring Space
12111: # or corresponding Published Resource Space, and populate the hash ref:
12112: # $dirhashref with URLs of all directories, and if $filehashref hash
12113: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12114: # or .rights files in resource space, and .meta, .save, .log, .bak and
12115: # .rights files in Authoring Space.
12116: #
12117: # Inputs:
12118: #
12119: # $is_home - true if current server is home server for user's space
12120: # $recurse - if true will also traverse subdirectories recursively
12121: # $include - reference to hash containing allowed file extensions.  If provided,
12122: #             files which do not have a matching extension will be ignored.
12123: # $exclude - reference to hash containing excluded file extensions.  If provided,
12124: #             files which have a matching extension will be ignored.
12125: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12126: #             directory with first file found (with acceptable extension).
12127: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12128: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12129: # $relpath - Current path (relative to top level).
12130: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12131: # $filehashref - reference to hash to populate with URLs of files (Optional)
12132: #
12133: # Returns: nothing
12134: #
12135: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12136: #
12137: # Currently used by interface/londocs.pm to create linked select boxes for
12138: # directory and filename to import a Course "Author" resource into a course, and
12139: # also to create linked select boxes for Authoring Space and Directory to choose
12140: # save location for creation of a new "standard" problem from the Course Editor.
12141: #
12142: 
12143: sub recursedirs {
12144:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12145:     return unless (ref($dirhashref) eq 'HASH');
12146:     my $docroot = $perlvar{'lonDocRoot'};
12147:     my $currpath = $docroot.$toppath;
12148:     if ($relpath ne '') {
12149:         $currpath .= "/$relpath";
12150:     }
12151:     my ($savefile,$checkinc,$checkexc);
12152:     if (ref($filehashref)) {
12153:         $savefile = 1;
12154:     }
12155:     if (ref($include) eq 'HASH') {
12156:         $checkinc = 1;
12157:     }
12158:     if (ref($exclude) eq 'HASH') {
12159:         $checkexc = 1;
12160:     }
12161:     if ($is_home) {
12162:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12163:             my $filecount = 0;
12164:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12165:                 next if ($item eq '');
12166:                 if (-d "$currpath/$item") {
12167:                     my $newpath;
12168:                     if ($relpath ne '') {
12169:                         $newpath = "$relpath/$item";
12170:                     } else {
12171:                         $newpath = $item;
12172:                     }
12173:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12174:                     if ($recurse) {
12175:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12176:                     }
12177:                 } elsif (($savefile) || ($relpath eq '')) {
12178:                     next if ($nonemptydir && $filecount);
12179:                     if ($checkinc || $checkexc) {
12180:                         my ($extension) = ($item =~ /\.(\w+)$/);
12181:                         if ($checkinc) {
12182:                             next unless ($extension && $include->{$extension});
12183:                         }
12184:                         if ($checkexc) {
12185:                             next if ($extension && $exclude->{$extension});
12186:                         }
12187:                     }
12188:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12189:                         $dirhashref->{'/'} = 1;
12190:                     }
12191:                     if ($savefile) {
12192:                         if ($relpath eq '') {
12193:                             $filehashref->{'/'}{$item} = 1;
12194:                         } else {
12195:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12196:                         }
12197:                     }
12198:                     $filecount ++;
12199:                 }
12200:             }
12201:             closedir($dirh);
12202:         }
12203:     } else {
12204:         my ($dirlistref,$listerror) =
12205:             &dirlist($toppath.$relpath);
12206:         my @dir_lines;
12207:         my $dirptr=16384;
12208:         if (ref($dirlistref) eq 'ARRAY') {
12209:             my $filecount = 0;
12210:             foreach my $dir_line (sort
12211:                               {
12212:                                   my ($afile)=split('&',$a,2);
12213:                                   my ($bfile)=split('&',$b,2);
12214:                                   return (lc($afile) cmp lc($bfile));
12215:                               } (@{$dirlistref})) {
12216:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12217:                     split(/\&/,$dir_line,16);
12218:                 $item =~ s/\s+$//;
12219:                 next if (($item =~ /^\.\.?$/) || ($obs));
12220:                 if ($dirptr&$testdir) {
12221:                     my $newpath;
12222:                     if ($relpath) {
12223:                         $newpath = "$relpath/$item";
12224:                     } else {
12225:                         $newpath = $item;
12226:                     }
12227:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12228:                     if ($recurse) {
12229:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12230:                     }
12231:                 } elsif (($savefile) || ($relpath eq '')) {
12232:                     next if ($nonemptydir && $filecount);
12233:                     if ($checkinc || $checkexc) {
12234:                         my $extension;
12235:                         if ($checkinc) {
12236:                             next unless ($extension && $include->{$extension});
12237:                         }
12238:                         if ($checkexc) {
12239:                             next if ($extension && $exclude->{$extension});
12240:                         }
12241:                     }
12242:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12243:                         $dirhashref->{'/'} = 1;
12244:                     }
12245:                     if ($savefile) {
12246:                         if ($relpath eq '') {
12247:                             $filehashref->{'/'}{$item} = 1;
12248:                         } else {
12249:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12250:                         }
12251:                     }
12252:                     $filecount ++; 
12253:                 }
12254:             }
12255:         }
12256:     }
12257:     if ($addtopdir) {
12258:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12259:             $dirhashref->{'/'} = 1;
12260:         }
12261:     }
12262:     return;
12263: }
12264: 
12265: sub priv_exclude {
12266:     return {
12267:              meta => 1,
12268:              save => 1,
12269:              log => 1,
12270:              bak => 1,
12271:              rights => 1,
12272:              DS_Store => 1,
12273:            };
12274: }
12275: 
12276: # -------------------------------------------------------- Value of a Condition
12277: 
12278: # gets the value of a specific preevaluated condition
12279: #    stored in the string  $env{user.state.<cid>}
12280: # or looks up a condition reference in the bighash and if if hasn't
12281: # already been evaluated recurses into docondval to get the value of
12282: # the condition, then memoizing it to 
12283: #   $env{user.state.<cid>.<condition>}
12284: sub directcondval {
12285:     my $number=shift;
12286:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12287: 	&Apache::lonuserstate::evalstate();
12288:     }
12289:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12290: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12291:     } elsif ($number =~ /^_/) {
12292: 	my $sub_condition;
12293: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12294: 		&GDBM_READER(),0640)) {
12295: 	    $sub_condition=$bighash{'conditions'.$number};
12296: 	    untie(%bighash);
12297: 	}
12298: 	my $value = &docondval($sub_condition);
12299: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12300: 	return $value;
12301:     }
12302:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12303:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12304:     } else {
12305:        return 2;
12306:     }
12307: }
12308: 
12309: # get the collection of conditions for this resource
12310: sub condval {
12311:     my $condidx=shift;
12312:     my $allpathcond='';
12313:     foreach my $cond (split(/\|/,$condidx)) {
12314: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12315: 	    $allpathcond.=
12316: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12317: 	}
12318:     }
12319:     $allpathcond=~s/\|$//;
12320:     return &docondval($allpathcond);
12321: }
12322: 
12323: #evaluates an expression of conditions
12324: sub docondval {
12325:     my ($allpathcond) = @_;
12326:     my $result=0;
12327:     if ($env{'request.course.id'}
12328: 	&& defined($allpathcond)) {
12329: 	my $operand='|';
12330: 	my @stack;
12331: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12332: 	    if ($chunk eq '(') {
12333: 		push @stack,($operand,$result);
12334: 	    } elsif ($chunk eq ')') {
12335: 		my $before=pop @stack;
12336: 		if (pop @stack eq '&') {
12337: 		    $result=$result>$before?$before:$result;
12338: 		} else {
12339: 		    $result=$result>$before?$result:$before;
12340: 		}
12341: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12342: 		$operand=$chunk;
12343: 	    } else {
12344: 		my $new=directcondval($chunk);
12345: 		if ($operand eq '&') {
12346: 		    $result=$result>$new?$new:$result;
12347: 		} else {
12348: 		    $result=$result>$new?$result:$new;
12349: 		}
12350: 	    }
12351: 	}
12352:     }
12353:     return $result;
12354: }
12355: 
12356: # ---------------------------------------------------- Devalidate courseresdata
12357: 
12358: sub devalidatecourseresdata {
12359:     my ($coursenum,$coursedomain)=@_;
12360:     my $hashid=$coursenum.':'.$coursedomain;
12361:     &devalidate_cache_new('courseres',$hashid);
12362: }
12363: 
12364: 
12365: # --------------------------------------------------- Course Resourcedata Query
12366: #
12367: #  Parameters:
12368: #      $coursenum    - Number of the course.
12369: #      $coursedomain - Domain at which the course was created.
12370: #  Returns:
12371: #     A hash of the course parameters along (I think) with timestamps
12372: #     and version info.
12373: 
12374: sub get_courseresdata {
12375:     my ($coursenum,$coursedomain)=@_;
12376:     my $coursehom=&homeserver($coursenum,$coursedomain);
12377:     my $hashid=$coursenum.':'.$coursedomain;
12378:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12379:     my %dumpreply;
12380:     unless (defined($cached)) {
12381: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12382: 	$result=\%dumpreply;
12383: 	my ($tmp) = keys(%dumpreply);
12384: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12385: 	    &do_cache_new('courseres',$hashid,$result,600);
12386: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12387: 	    return $tmp;
12388: 	} elsif ($tmp =~ /^(error)/) {
12389: 	    $result=undef;
12390: 	    &do_cache_new('courseres',$hashid,$result,600);
12391: 	}
12392:     }
12393:     return $result;
12394: }
12395: 
12396: sub devalidateuserresdata {
12397:     my ($uname,$udom)=@_;
12398:     my $hashid="$udom:$uname";
12399:     &devalidate_cache_new('userres',$hashid);
12400: }
12401: 
12402: sub get_userresdata {
12403:     my ($uname,$udom)=@_;
12404:     #most student don\'t have any data set, check if there is some data
12405:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12406: 
12407:     my $hashid="$udom:$uname";
12408:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12409:     if (!defined($cached)) {
12410: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12411: 	$result=\%resourcedata;
12412: 	&do_cache_new('userres',$hashid,$result,600);
12413:     }
12414:     my ($tmp)=keys(%$result);
12415:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12416: 	return $result;
12417:     }
12418:     #error 2 occurs when the .db doesn't exist
12419:     if ($tmp!~/error: 2 /) {
12420:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12421: 	    &logthis("<font color=\"blue\">WARNING:".
12422: 		     " Trying to get resource data for ".
12423: 		     $uname." at ".$udom.": ".
12424: 		     $tmp."</font>");
12425:         }
12426:     } elsif ($tmp=~/error: 2 /) {
12427: 	#&EXT_cache_set($udom,$uname);
12428: 	&do_cache_new('userres',$hashid,undef,600);
12429: 	undef($tmp); # not really an error so don't send it back
12430:     }
12431:     return $tmp;
12432: }
12433: #----------------------------------------------- resdata - return resource data
12434: #  Purpose:
12435: #    Return resource data for either users or for a course.
12436: #  Parameters:
12437: #     $name      - Course/user name.
12438: #     $domain    - Name of the domain the user/course is registered on.
12439: #     $type      - Type of thing $name is (must be 'course' or 'user')
12440: #     $mapp      - decluttered URL of enclosing map  
12441: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12442: #     $recurseup - Ref to array of map URLs, starting with map containing
12443: #                  $mapp up through hierarchy of nested maps to top level map.  
12444: #     $courseid  - CourseID (first part of param identifier).
12445: #     $modifier  - Middle part of param identifier.
12446: #     $what      - Last part of param identifier.
12447: #     @which     - Array of names of resources desired.
12448: #  Returns:
12449: #     The value of the first reasource in @which that is found in the
12450: #     resource hash.
12451: #  Exceptional Conditions:
12452: #     If the $type passed in is not valid (not the string 'course' or 
12453: #     'user', an undefined  reference is returned.
12454: #     If none of the resources are found, an undef is returned
12455: sub resdata {
12456:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12457:         $modifier,$what,@which)=@_;
12458:     my $result;
12459:     if ($type eq 'course') {
12460: 	$result=&get_courseresdata($name,$domain);
12461:     } elsif ($type eq 'user') {
12462: 	$result=&get_userresdata($name,$domain);
12463:     }
12464:     if (!ref($result)) { return $result; }    
12465:     foreach my $item (@which) {
12466:         if ($item->[1] eq 'course') {
12467:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12468:                 unless ($$recursed) {
12469:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12470:                     $$recursed = 1;
12471:                 }
12472:                 foreach my $item (@${recurseup}) {
12473:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12474:                     last if (defined($result->{$norecursechk}));
12475:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12476:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12477:                 }
12478:             }
12479:         }
12480:         if (defined($result->{$item->[0]})) {
12481: 	    return [$result->{$item->[0]},$item->[1]];
12482: 	}
12483:     }
12484:     return undef;
12485: }
12486: 
12487: sub get_domain_lti {
12488:     my ($cdom,$context) = @_;
12489:     my ($name,$cachename,%lti);
12490:     if ($context eq 'consumer') {
12491:         $name = 'ltitools';
12492:     } elsif ($context eq 'provider') {
12493:         $name = 'lti';
12494:     } elsif ($context eq 'linkprot') {
12495:         $name = 'ltisec';
12496:     } else {
12497:         return %lti;
12498:     }
12499: 
12500:     if ($context eq 'linkprot') {
12501:         $cachename = $context;
12502:     } else {
12503:         $cachename = $name;
12504:     }
12505:     
12506:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12507:     if (defined($cached)) {
12508:         if (ref($result) eq 'HASH') {
12509:             %lti = %{$result};
12510:         }
12511:     } else {
12512:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12513:         if (ref($domconfig{$name}) eq 'HASH') {
12514:             if ($context eq 'linkprot') {
12515:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12516:                     %lti = %{$domconfig{$name}{'linkprot'}};
12517:                 }
12518:             } else {
12519:                 %lti = %{$domconfig{$name}};
12520:             }
12521:             if (($context eq 'consumer') && (keys(%lti))) {
12522:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12523:                 if (ref($encdomconfig{$name}) eq 'HASH') {
12524:                     foreach my $id (keys(%lti)) {
12525:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12526:                             foreach my $item ('key','secret') {
12527:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12528:                             }
12529:                         }
12530:                     }
12531:                 }
12532:             }
12533:         }
12534:         my $cachetime = 24*60*60;
12535:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12536:     }
12537:     return %lti;
12538: }
12539: 
12540: sub get_course_lti {
12541:     my ($cnum,$cdom) = @_;
12542:     my $hashid=$cdom.'_'.$cnum;
12543:     my %courselti;
12544:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12545:     if (defined($cached)) {
12546:         if (ref($result) eq 'HASH') {
12547:             %courselti = %{$result};
12548:         }
12549:     } else {
12550:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12551:         my $cachetime = 24*60*60;
12552:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12553:     }
12554:     return %courselti;
12555: }
12556: 
12557: sub courselti_itemid {
12558:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12559:     my ($chome,$itemid);
12560:     $chome = &homeserver($cnum,$cdom);
12561:     return if ($chome eq 'no_host');
12562:     if (ref($params) eq 'HASH') {
12563:         my $rep;
12564:         if (grep { $_ eq $chome } current_machine_ids()) {
12565:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12566:         } else {
12567:             my $escurl = &escape($url);
12568:             my $escmethod = &escape($method);
12569:             my $items = &freeze_escape($params);
12570:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12571:         }
12572:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12573:                 ($rep eq 'unknown_cmd')) {
12574:             $itemid = $rep;
12575:         }
12576:     }
12577:     return $itemid;
12578: }
12579: 
12580: sub domainlti_itemid {
12581:     my ($cdom,$url,$method,$params,$context) = @_;
12582:     my ($primary_id,$itemid);
12583:     $primary_id = &domain($cdom,'primary');
12584:     return if ($primary_id eq '');
12585:     if (ref($params) eq 'HASH') {
12586:         my $rep;
12587:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12588:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12589:         } else {
12590:             my $cnum = '';
12591:             my $escurl = &escape($url);
12592:             my $escmethod = &escape($method);
12593:             my $items = &freeze_escape($params);
12594:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12595:         }
12596:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12597:                 ($rep eq 'unknown_cmd')) {
12598:             $itemid = $rep;
12599:         }
12600:     }
12601:     return $itemid;
12602: }
12603: 
12604: sub count_supptools {
12605:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
12606:     my $hashid=$cnum.':'.$cdom;
12607:     my ($numexttools,$cached);
12608:     unless ($ignorecache) {
12609:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12610:     }
12611:     unless (defined($cached)) {
12612:         my $chome=&homeserver($cnum,$cdom);
12613:         $numexttools = 0;
12614:         unless ($chome eq 'no_host') {
12615:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12616:             if (ref($supplemental) eq 'HASH') {
12617:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12618:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12619:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12620:                             $numexttools ++;
12621:                         }
12622:                     }
12623:                 }
12624:             }
12625:         }
12626:         &do_cache_new('supptools',$hashid,$numexttools,600);
12627:     }
12628:     return $numexttools;
12629: }
12630: 
12631: sub has_unhidden_suppfiles {
12632:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12633:     my $hashid=$cnum.':'.$cdom;
12634:     my ($showsupp,$cached);
12635:     unless ($ignorecache) {
12636:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
12637:     }
12638:     unless (defined($cached)) {
12639:         my $chome=&homeserver($cnum,$cdom);
12640:         unless ($chome eq 'no_host') {
12641:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
12642:             if (ref($supplemental) eq 'HASH') {
12643:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12644:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12645:                         next if ($key =~ /\.sequence$/);
12646:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12647:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12648:                                 unless ($supplemental->{'hidden'}->{$id}) {
12649:                                     $showsupp = 1;
12650:                                     last;
12651:                                 }
12652:                             }
12653:                         }
12654:                         last if ($showsupp);
12655:                     }
12656:                 }
12657:             }
12658:         }
12659:         &do_cache_new('showsupp',$hashid,$showsupp,600);
12660:     }
12661:     return $showsupp;
12662: }
12663: 
12664: #
12665: # EXT resource caching routines
12666: #
12667: 
12668: {
12669: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12670: #
12671: # The course for which we cache
12672: my $cachedmapkey='';
12673: # The cached recursive maps for this course
12674: my %cachedmaps=();
12675: # When this was last done
12676: my $cachedmaptime='';
12677: 
12678: sub clear_EXT_cache_status {
12679:     &delenv('cache.EXT.');
12680: }
12681: 
12682: sub EXT_cache_status {
12683:     my ($target_domain,$target_user) = @_;
12684:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12685:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12686:         # We know already the user has no data
12687:         return 1;
12688:     } else {
12689:         return 0;
12690:     }
12691: }
12692: 
12693: sub EXT_cache_set {
12694:     my ($target_domain,$target_user) = @_;
12695:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12696:     #&appenv({$cachename => time});
12697: }
12698: 
12699: # --------------------------------------------------------- Value of a Variable
12700: sub EXT {
12701: 
12702:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12703:     unless ($varname) { return ''; }
12704:     #get real user name/domain, courseid and symb
12705:     my $courseid;
12706:     my $publicuser;
12707:     if ($symbparm) {
12708: 	$symbparm=&get_symb_from_alias($symbparm);
12709:     }
12710:     if (!($uname && $udom)) {
12711:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12712:       if (!$symbparm) {	$symbparm=$cursymb; }
12713:     } else {
12714: 	$courseid=$env{'request.course.id'};
12715:     }
12716:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12717:     my $rest;
12718:     if (defined($therest[0])) {
12719:        $rest=join('.',@therest);
12720:     } else {
12721:        $rest='';
12722:     }
12723: 
12724:     my $qualifierrest=$qualifier;
12725:     if ($rest) { $qualifierrest.='.'.$rest; }
12726:     my $spacequalifierrest=$space;
12727:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12728:     if ($realm eq 'user') {
12729: # --------------------------------------------------------------- user.resource
12730: 	if ($space eq 'resource') {
12731: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12732: 		  || defined($Apache::lonhomework::parsing_a_task))
12733: 		 &&
12734: 		 ($symbparm eq &symbread()) ) {
12735: 		# if we are in the middle of processing the resource the
12736: 		# get the value we are planning on committing
12737:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12738:                     return $Apache::lonhomework::results{$qualifierrest};
12739:                 } else {
12740:                     return $Apache::lonhomework::history{$qualifierrest};
12741:                 }
12742: 	    } else {
12743: 		my %restored;
12744: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12745: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12746: 		} else {
12747: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12748: 		}
12749: 		return $restored{$qualifierrest};
12750: 	    }
12751: # ----------------------------------------------------------------- user.access
12752:         } elsif ($space eq 'access') {
12753: 	    # FIXME - not supporting calls for a specific user
12754:             return &allowed($qualifier,$rest);
12755: # ------------------------------------------ user.preferences, user.environment
12756:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12757: 	    if (($uname eq $env{'user.name'}) &&
12758: 		($udom eq $env{'user.domain'})) {
12759: 		return $env{join('.',('environment',$qualifierrest))};
12760: 	    } else {
12761: 		my %returnhash;
12762: 		if (!$publicuser) {
12763: 		    %returnhash=&userenvironment($udom,$uname,
12764: 						 $qualifierrest);
12765: 		}
12766: 		return $returnhash{$qualifierrest};
12767: 	    }
12768: # ----------------------------------------------------------------- user.course
12769:         } elsif ($space eq 'course') {
12770: 	    # FIXME - not supporting calls for a specific user
12771:             return $env{join('.',('request.course',$qualifier))};
12772: # ------------------------------------------------------------------- user.role
12773:         } elsif ($space eq 'role') {
12774: 	    # FIXME - not supporting calls for a specific user
12775:             my ($role,$where)=split(/\./,$env{'request.role'});
12776:             if ($qualifier eq 'value') {
12777: 		return $role;
12778:             } elsif ($qualifier eq 'extent') {
12779:                 return $where;
12780:             }
12781: # ----------------------------------------------------------------- user.domain
12782:         } elsif ($space eq 'domain') {
12783:             return $udom;
12784: # ------------------------------------------------------------------- user.name
12785:         } elsif ($space eq 'name') {
12786:             return $uname;
12787: # ---------------------------------------------------- Any other user namespace
12788:         } else {
12789: 	    my %reply;
12790: 	    if (!$publicuser) {
12791: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12792: 	    }
12793: 	    return $reply{$qualifierrest};
12794:         }
12795:     } elsif ($realm eq 'query') {
12796: # ---------------------------------------------- pull stuff out of query string
12797:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12798: 						[$spacequalifierrest]);
12799: 	return $env{'form.'.$spacequalifierrest}; 
12800:    } elsif ($realm eq 'request') {
12801: # ------------------------------------------------------------- request.browser
12802:         if ($space eq 'browser') {
12803:             return $env{'browser.'.$qualifier};
12804: # ------------------------------------------------------------ request.filename
12805:         } else {
12806:             return $env{'request.'.$spacequalifierrest};
12807:         }
12808:     } elsif ($realm eq 'course') {
12809: # ---------------------------------------------------------- course.description
12810:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12811:     } elsif ($realm eq 'resource') {
12812: 
12813: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12814: 	    if (!$symbparm) { $symbparm=&symbread(); }
12815: 	}
12816: 
12817:         if ($qualifier eq '') {
12818: 	    if ($space eq 'title') {
12819: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12820: 	        return &gettitle($symbparm);
12821: 	    }
12822: 	
12823: 	    if ($space eq 'map') {
12824: 	        my ($map) = &decode_symb($symbparm);
12825: 	        return &symbread($map);
12826: 	    }
12827:             if ($space eq 'maptitle') {
12828:                 my ($map) = &decode_symb($symbparm);
12829:                 return &gettitle($map);
12830:             }
12831: 	    if ($space eq 'filename') {
12832: 	        if ($symbparm) {
12833: 		    return &clutter((&decode_symb($symbparm))[2]);
12834: 	        }
12835: 	        return &hreflocation('',$env{'request.filename'});
12836: 	    }
12837: 
12838:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12839:                 if ($space eq 'visibleparts') {
12840:                     my $navmap = Apache::lonnavmaps::navmap->new();
12841:                     my $item;
12842:                     if (ref($navmap)) {
12843:                         my $res = $navmap->getBySymb($symbparm);
12844:                         my $parts = $res->parts();
12845:                         if (ref($parts) eq 'ARRAY') {
12846:                             $item = join(',',@{$parts});
12847:                         }
12848:                         undef($navmap);
12849:                     }
12850:                     return $item;
12851:                 }
12852:             }
12853:         }
12854: 
12855: 	my ($section, $group, @groups, @recurseup, $recursed);
12856:         if (ref($recurseupref) eq 'ARRAY') {
12857:             @recurseup = @{$recurseupref};
12858:             $recursed = 1;
12859:         }
12860: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12861:         if (($courseid eq '') && ($cid)) {
12862:             $courseid = $cid;
12863:         }
12864: 	if (($symbparm && $courseid) && 
12865: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12866: 
12867: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12868: 
12869: # ----------------------------------------------------- Cascading lookup scheme
12870: 	    my $symbp=$symbparm;
12871: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12872: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12873:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12874: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12875: 	    if (($env{'user.name'} eq $uname) &&
12876: 		($env{'user.domain'} eq $udom)) {
12877: 		$section=$env{'request.course.sec'};
12878:                 @groups = split(/:/,$env{'request.course.groups'});  
12879:                 @groups=&sort_course_groups($courseid,@groups); 
12880: 	    } else {
12881: 		if (! defined($usection)) {
12882: 		    $section=&getsection($udom,$uname,$courseid);
12883: 		} else {
12884: 		    $section = $usection;
12885: 		}
12886:                 @groups = &get_users_groups($udom,$uname,$courseid);
12887: 	    }
12888: 
12889: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12890: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12891:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12892: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12893: 
12894: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12895: 	    my $courselevelr=$courseid.'.'.$symbparm;
12896:             $courseleveli=$courseid.'.'.$recurseparm;
12897: 	    $courselevelm=$courseid.'.'.$mapparm;
12898: 
12899: # ----------------------------------------------------------- first, check user
12900: 
12901: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12902:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12903: 				       ([$courselevelr,'resource'],
12904: 					[$courselevelm,'map'     ],
12905:                                         [$courseleveli,'map'     ],
12906: 					[$courselevel, 'course'  ]));
12907: 	    if (defined($userreply)) { return &get_reply($userreply); }
12908: 
12909: # ------------------------------------------------ second, check some of course
12910:             my $coursereply;
12911:             if (@groups > 0) {
12912:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12913:                                        $recurseparm,$mapparm,$spacequalifierrest,
12914:                                        $mapp,\$recursed,\@recurseup);
12915:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12916:             }
12917: 
12918: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12919: 				  $env{'course.'.$courseid.'.domain'},
12920: 				  'course',$mapp,\$recursed,\@recurseup,
12921:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12922: 				  ([$seclevelr,   'resource'],
12923: 				   [$seclevelm,   'map'     ],
12924:                                    [$secleveli,   'map'     ],
12925: 				   [$seclevel,    'course'  ],
12926: 				   [$courselevelr,'resource']));
12927: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12928: 
12929: # ------------------------------------------------------ third, check map parms
12930: 	    my %parmhash=();
12931: 	    my $thisparm='';
12932: 	    if (tie(%parmhash,'GDBM_File',
12933: 		    $env{'request.course.fn'}.'_parms.db',
12934: 		    &GDBM_READER(),0640)) {
12935: 		$thisparm=$parmhash{$symbparm};
12936: 		untie(%parmhash);
12937: 	    }
12938: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12939: 	}
12940: # ------------------------------------------ fourth, look in resource metadata
12941:  
12942:         my $what = $spacequalifierrest;
12943: 	$what=~s/\./\_/;
12944: 	my $filename;
12945: 	if (!$symbparm) { $symbparm=&symbread(); }
12946: 	if ($symbparm) {
12947: 	    $filename=(&decode_symb($symbparm))[2];
12948: 	} else {
12949: 	    $filename=$env{'request.filename'};
12950: 	}
12951:         my $toolsymb;
12952:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12953:             $toolsymb = $symbparm;
12954:         }
12955: 	my $metadata=&metadata($filename,$what,$toolsymb);
12956: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12957: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12958: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12959: 
12960: # ----------------------------------------------- fifth, look in rest of course
12961: 	if ($symbparm && defined($courseid) && 
12962: 	    $courseid eq $env{'request.course.id'}) {
12963: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12964: 				     $env{'course.'.$courseid.'.domain'},
12965: 				     'course',$mapp,\$recursed,\@recurseup,
12966:                                      $courseid,'.',$spacequalifierrest,
12967: 				     ([$courselevelm,'map'   ],
12968:                                       [$courseleveli,'map'   ],
12969: 				      [$courselevel, 'course']));
12970: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12971: 	}
12972: # ------------------------------------------------------------------ Cascade up
12973: 	unless ($space eq '0') {
12974: 	    my @parts=split(/_/,$space);
12975: 	    my $id=pop(@parts);
12976: 	    my $part=join('_',@parts);
12977: 	    if ($part eq '') { $part='0'; }
12978: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12979: 				 $symbparm,$udom,$uname,$section,1);
12980: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12981: 	}
12982: 	if ($recurse) { return undef; }
12983: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12984: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12985: # ---------------------------------------------------- Any other user namespace
12986:     } elsif ($realm eq 'environment') {
12987: # ----------------------------------------------------------------- environment
12988: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12989: 	    return $env{'environment.'.$spacequalifierrest};
12990: 	} else {
12991: 	    if ($uname eq 'anonymous' && $udom eq '') {
12992: 		return '';
12993: 	    }
12994: 	    my %returnhash=&userenvironment($udom,$uname,
12995: 					    $spacequalifierrest);
12996: 	    return $returnhash{$spacequalifierrest};
12997: 	}
12998:     } elsif ($realm eq 'system') {
12999: # ----------------------------------------------------------------- system.time
13000: 	if ($space eq 'time') {
13001: 	    return time;
13002:         }
13003:     } elsif ($realm eq 'server') {
13004: # ----------------------------------------------------------------- system.time
13005: 	if ($space eq 'name') {
13006: 	    return $ENV{'SERVER_NAME'};
13007:         }
13008:     } elsif ($realm eq 'client') {
13009:         if ($space eq 'remote_addr') {
13010:             return &get_requestor_ip();
13011:         }
13012:     }
13013:     return '';
13014: }
13015: 
13016: sub get_reply {
13017:     my ($reply_value) = @_;
13018:     if (ref($reply_value) eq 'ARRAY') {
13019:         if (wantarray) {
13020: 	    return @$reply_value;
13021:         }
13022:         return $reply_value->[0];
13023:     } else {
13024:         return $reply_value;
13025:     }
13026: }
13027: 
13028: sub check_group_parms {
13029:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13030:         $recursed,$recurseupref) = @_;
13031:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13032:                   [$what,'course']);
13033:     my $coursereply;
13034:     foreach my $group (@{$groups}) {
13035:         my @groupitems = ();
13036:         foreach my $level (@levels) {
13037:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13038:              push(@groupitems,[$item,$level->[1]]);
13039:         }
13040:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13041:                                    $env{'course.'.$courseid.'.domain'},
13042:                                    'course',$mapp,$recursed,$recurseupref,
13043:                                    $courseid,'.['.$group.'].',$what,
13044:                                    @groupitems);
13045:         last if (defined($coursereply));
13046:     }
13047:     return $coursereply;
13048: }
13049: 
13050: sub get_map_hierarchy {
13051:     my ($mapname,$courseid) = @_;
13052:     my @recurseup = ();
13053:     if ($mapname) {
13054:         if (($cachedmapkey eq $courseid) &&
13055:             (abs($cachedmaptime-time)<5)) {
13056:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13057:                 return @{$cachedmaps{$mapname}};
13058:             }
13059:         }
13060:         my $navmap = Apache::lonnavmaps::navmap->new();
13061:         if (ref($navmap)) {
13062:             @recurseup = $navmap->recurseup_maps($mapname);
13063:             undef($navmap);
13064:             $cachedmaps{$mapname} = \@recurseup;
13065:             $cachedmaptime=time;
13066:             $cachedmapkey=$courseid;
13067:         }
13068:     }
13069:     return @recurseup;
13070: }
13071: 
13072: }
13073: 
13074: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13075:     my ($courseid,@groups) = @_;
13076:     @groups = sort(@groups);
13077:     return @groups;
13078: }
13079: 
13080: sub packages_tab_default {
13081:     my ($uri,$varname,$toolsymb)=@_;
13082:     my (undef,$part,$name)=split(/\./,$varname);
13083: 
13084:     my (@extension,@specifics,$do_default);
13085:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13086: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13087: 	if ($pack_type eq 'default') {
13088: 	    $do_default=1;
13089: 	} elsif ($pack_type eq 'extension') {
13090: 	    push(@extension,[$package,$pack_type,$pack_part]);
13091: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13092: 	    # only look at packages defaults for packages that this id is
13093: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13094: 	}
13095:     }
13096:     # first look for a package that matches the requested part id
13097:     foreach my $package (@specifics) {
13098: 	my (undef,$pack_type,$pack_part)=@{$package};
13099: 	next if ($pack_part ne $part);
13100: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13101: 	    return $packagetab{"$pack_type&$name&default"};
13102: 	}
13103:     }
13104:     # look for any possible matching non extension_ package
13105:     foreach my $package (@specifics) {
13106: 	my (undef,$pack_type,$pack_part)=@{$package};
13107: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13108: 	    return $packagetab{"$pack_type&$name&default"};
13109: 	}
13110: 	if ($pack_type eq 'part') { $pack_part='0'; }
13111: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13112: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13113: 	}
13114:     }
13115:     # look for any posible extension_ match
13116:     foreach my $package (@extension) {
13117: 	my ($package,$pack_type)=@{$package};
13118: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13119: 	    return $packagetab{"$pack_type&$name&default"};
13120: 	}
13121: 	if (defined($packagetab{$package."&$name&default"})) {
13122: 	    return $packagetab{$package."&$name&default"};
13123: 	}
13124:     }
13125:     # look for a global default setting
13126:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13127: 	return $packagetab{"default&$name&default"};
13128:     }
13129:     return undef;
13130: }
13131: 
13132: sub add_prefix_and_part {
13133:     my ($prefix,$part)=@_;
13134:     my $keyroot;
13135:     if (defined($prefix) && $prefix !~ /^__/) {
13136: 	# prefix that has a part already
13137: 	$keyroot=$prefix;
13138:     } elsif (defined($prefix)) {
13139: 	# prefix that is missing a part
13140: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13141:     } else {
13142: 	# no prefix at all
13143: 	if (defined($part)) { $keyroot='_'.$part; }
13144:     }
13145:     return $keyroot;
13146: }
13147: 
13148: # ---------------------------------------------------------------- Get metadata
13149: 
13150: my %metaentry;
13151: my %importedpartids;
13152: my %importedrespids;
13153: sub metadata {
13154:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13155:     $uri=&declutter($uri);
13156:     # if it is a non metadata possible uri return quickly
13157:     if (($uri eq '') || 
13158: 	(($uri =~ m|^/*adm/|) && 
13159: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13160:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13161: 	return undef;
13162:     }
13163:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13164: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13165: 	return undef;
13166:     }
13167:     my $filename=$uri;
13168:     $uri=~s/\.meta$//;
13169: #
13170: # Is the metadata already cached?
13171: # Look at timestamp of caching
13172: # Everything is cached by the main uri, libraries are never directly cached
13173: #
13174:     if (!defined($liburi)) {
13175: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13176: 	if (defined($cached)) { return $result->{':'.$what}; }
13177:     }
13178: 
13179: #
13180: # If the uri is for an external tool the file from
13181: # which metadata should be retrieved depends on whether
13182: # the tool had been configured to be gradable (set in the Course
13183: # Editor or Resource Editor).
13184: #
13185: # If a valid symb has been included as the third arg in the call
13186: # to &metadata() that can be used to retrieve the value of
13187: # parameter_0_gradable set for the resource, and included in the
13188: # uploaded map containing the tool. The value is retrieved via
13189: # &EXT(), if a valid symb is available.  Otherwise the value of
13190: # gradable in the exttool_$marker.db file for the tool instance
13191: # is retrieved via &get().
13192: #
13193: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13194: # hiddenresource and encrypturl (during course initialization)
13195: # the map-level parameter for resource.0.gradable included in the 
13196: # uploaded map containing the tool will not yet have been stored
13197: # in the user_course_parms.db file for the user's session, so in 
13198: # this case fall back to retrieving gradable status from the
13199: # exttool_$marker.db file.
13200: #
13201: # In order to avoid an infinite loop, &metadata() will return
13202: # before a call to &EXT(), if the uri is for an external tool
13203: # and the $what for which metadata is being requested is
13204: # parameter_0_gradable or 0_gradable.
13205: #
13206: 
13207:     if ($uri =~ /ext\.tool$/) {
13208:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13209:             return;
13210:         } else {
13211:             my ($checked,$use_passback);
13212:             if ($toolsymb ne '') {
13213:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13214:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13215:                     $checked = 1;
13216:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13217:                         $use_passback = 1;
13218:                     }
13219:                 }
13220:             }
13221:             unless ($checked) {
13222:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13223:                 $marker=~s/\D//g;
13224:                 if ($marker) {
13225:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13226:                     $use_passback = $toolsettings{'gradable'};
13227:                 }
13228:             }
13229:             if ($use_passback) {
13230:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13231:             } else {
13232:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13233:             }
13234:         }
13235:     }
13236: 
13237:     {
13238: # Imported parts would go here
13239:         my @origfiletagids=();
13240:         my $importedparts=0;
13241: 
13242: # Imported responseids would go here
13243:         my $importedresponses=0;
13244: #
13245: # Is this a recursive call for a library?
13246: #
13247: #	if (! exists($metacache{$uri})) {
13248: #	    $metacache{$uri}={};
13249: #	}
13250: 	my $cachetime = 60*60;
13251:         if ($liburi) {
13252: 	    $liburi=&declutter($liburi);
13253:             $filename=$liburi;
13254:         } else {
13255: 	    &devalidate_cache_new('meta',$uri);
13256: 	    undef(%metaentry);
13257: 	}
13258:         my %metathesekeys=();
13259:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13260: 	my $metastring;
13261: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13262: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13263: 	    $metastring = 
13264: 		&Apache::lonnet::ssi_body($which,
13265: 					  ('grade_target' => 'meta'));
13266: 	    $cachetime = 1; # only want this cached in the child not long term
13267: 	} elsif (($uri !~ m -^(editupload)/-) && 
13268:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13269: 	    my $file=&filelocation('',&clutter($filename));
13270: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13271: 	    $metastring=&getfile($file);
13272: 	}
13273:         my $parser=HTML::LCParser->new(\$metastring);
13274:         my $token;
13275:         undef %metathesekeys;
13276:         while ($token=$parser->get_token) {
13277: 	    if ($token->[0] eq 'S') {
13278: 		if (defined($token->[2]->{'package'})) {
13279: #
13280: # This is a package - get package info
13281: #
13282: 		    my $package=$token->[2]->{'package'};
13283: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13284: 		    if (defined($token->[2]->{'id'})) { 
13285: 			$keyroot.='_'.$token->[2]->{'id'}; 
13286: 		    }
13287: 		    if ($metaentry{':packages'}) {
13288: 			$metaentry{':packages'}.=','.$package.$keyroot;
13289: 		    } else {
13290: 			$metaentry{':packages'}=$package.$keyroot;
13291: 		    }
13292: 		    foreach my $pack_entry (keys(%packagetab)) {
13293: 			my $part=$keyroot;
13294: 			$part=~s/^\_//;
13295: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13296: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13297: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13298: 			    # ignore package.tab specified default values
13299:                             # here &package_tab_default() will fetch those
13300: 			    if ($subp eq 'default') { next; }
13301: 			    my $value=$packagetab{$pack_entry};
13302: 			    my $unikey;
13303: 			    if ($pack =~ /_0$/) {
13304: 				$unikey='parameter_0_'.$name;
13305: 				$part=0;
13306: 			    } else {
13307: 				$unikey='parameter'.$keyroot.'_'.$name;
13308: 			    }
13309: 			    if ($subp eq 'display') {
13310: 				$value.=' [Part: '.$part.']';
13311: 			    }
13312: 			    $metaentry{':'.$unikey.'.part'}=$part;
13313: 			    $metathesekeys{$unikey}=1;
13314: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13315: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13316: 			    }
13317: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13318: 				$metaentry{':'.$unikey}=
13319: 				    $metaentry{':'.$unikey.'.default'};
13320: 			    }
13321: 			}
13322: 		    }
13323: 		} else {
13324: #
13325: # This is not a package - some other kind of start tag
13326: #
13327: 		    my $entry=$token->[1];
13328: 		    my $unikey='';
13329: 
13330: 		    if ($entry eq 'import') {
13331: #
13332: # Importing a library here
13333: #
13334:                         my $location=$parser->get_text('/import');
13335:                         my $dir=$filename;
13336:                         $dir=~s|[^/]*$||;
13337:                         $location=&filelocation($dir,$location);
13338: 
13339:                         my $importid=$token->[2]->{'id'};
13340:                         my $importmode=$token->[2]->{'importmode'};
13341: #
13342: # Check metadata for imported file to
13343: # see if it contained response items
13344: #
13345:                         my ($origfile,@libfilekeys);
13346:                         my %currmetaentry = %metaentry;
13347:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13348:                                                            $depthcount+1));
13349:                         if (grep(/^responseorder$/,@libfilekeys)) {
13350:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13351:                                                              undef,$depthcount+1);
13352:                             if ($libresponseorder ne '') {
13353:                                 if ($#origfiletagids<0) {
13354:                                     undef(%importedrespids);
13355:                                     undef(%importedpartids);
13356:                                 }
13357:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13358:                                 if (@respids) {
13359:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13360:                                 }
13361:                                 if ($importedrespids{$importid} ne '') {
13362:                                     $importedresponses = 1;
13363: # We need to get the original file and the imported file to get the response order correct
13364: # Load and inspect original file
13365:                                     if ($#origfiletagids<0) {
13366:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13367:                                         $origfile=&getfile($origfilelocation);
13368:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13369:                                     }
13370:                                 }
13371:                             }
13372:                         }
13373: # Do not overwrite contents of %metaentry hash for resource itself with 
13374: # hash populated for imported library file
13375:                         %metaentry = %currmetaentry;
13376:                         undef(%currmetaentry);
13377:                         if ($importmode eq 'part') {
13378: # Import as part(s)
13379:                            $importedparts=1;
13380: # We need to get the original file and the imported file to get the part order correct
13381: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13382: # Load and inspect original file if we didn't do that already
13383:                            if ($#origfiletagids<0) {
13384:                                undef(%importedrespids);
13385:                                undef(%importedpartids);
13386:                                if ($origfile eq '') {
13387:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13388:                                    $origfile=&getfile($origfilelocation);
13389:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13390:                                }
13391:                            }
13392:                            my @impfilepartids;
13393: # If <partorder> tag is included in metadata for the imported file
13394: # get the parts in the imported file from that.
13395:                            if (grep(/^partorder$/,@libfilekeys)) {
13396:                                %currmetaentry = %metaentry;
13397:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13398:                                                             $depthcount+1);
13399:                                %metaentry = %currmetaentry;
13400:                                undef(%currmetaentry);
13401:                                if ($libpartorder ne '') {
13402:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13403:                                }
13404:                            } else {
13405: # If no <partorder> tag available, load and inspect imported file
13406:                                my $impfile=&getfile($location);
13407:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13408:                            }
13409:                            if ($#impfilepartids>=0) {
13410: # This problem had parts
13411:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13412:                            } else {
13413: # Importing by turning a single problem into a problem part
13414: # It gets the import-tags ID as part-ID
13415:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13416:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13417:                            }
13418:                         } else {
13419: # Import as problem or as normal import
13420:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13421:                             unless ($importmode eq 'problem') {
13422: # Normal import
13423:                                 if (defined($token->[2]->{'id'})) {
13424:                                     $unikey.='_'.$token->[2]->{'id'};
13425:                                 }
13426:                             }
13427: # Check metadata for imported file to
13428: # see if it contained parts
13429:                             if (grep(/^partorder$/,@libfilekeys)) {
13430:                                 %currmetaentry = %metaentry;
13431:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13432:                                                              $depthcount+1);
13433:                                 %metaentry = %currmetaentry;
13434:                                 undef(%currmetaentry);
13435:                                 if ($libpartorder ne '') {
13436:                                     $importedparts = 1;
13437:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13438:                                 }
13439:                             }
13440:                         }
13441: 			if ($depthcount<20) {
13442: 			    my $metadata = 
13443: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13444: 					  $depthcount+1);
13445: 			    foreach my $meta (split(',',$metadata)) {
13446: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13447: 				$metathesekeys{$meta}=1;
13448: 			    }
13449:                         }
13450: 		    } else {
13451: #
13452: # Not importing, some other kind of non-package, non-library start tag
13453: # 
13454:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13455:                         if (defined($token->[2]->{'id'})) {
13456:                             $unikey.='_'.$token->[2]->{'id'};
13457:                         }
13458: 			if (defined($token->[2]->{'name'})) { 
13459: 			    $unikey.='_'.$token->[2]->{'name'}; 
13460: 			}
13461: 			$metathesekeys{$unikey}=1;
13462: 			foreach my $param (@{$token->[3]}) {
13463: 			    $metaentry{':'.$unikey.'.'.$param} =
13464: 				$token->[2]->{$param};
13465: 			}
13466: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13467: 			my $default=$metaentry{':'.$unikey.'.default'};
13468: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13469: 		 # only ws inside the tag, and not in default, so use default
13470: 		 # as value
13471: 			    $metaentry{':'.$unikey}=$default;
13472: 			} elsif ( $internaltext =~ /\S/ ) {
13473: 		  # something interesting inside the tag
13474: 			    $metaentry{':'.$unikey}=$internaltext;
13475: 			} else {
13476: 		  # no interesting values, don't set a default
13477: 			}
13478: # end of not-a-package not-a-library import
13479: 		    }
13480: # end of not-a-package start tag
13481: 		}
13482: # the next is the end of "start tag"
13483: 	    }
13484: 	}
13485: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13486: 	$extension = lc($extension);
13487: 	if ($extension eq 'htm') { $extension='html'; }
13488: 
13489: 	foreach my $key (keys(%packagetab)) {
13490: 	    #no specific packages #how's our extension
13491: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13492: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13493: 					 \%metathesekeys);
13494: 	}
13495: 
13496: 	if (!exists($metaentry{':packages'})
13497: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13498: 	    foreach my $key (keys(%packagetab)) {
13499: 		#no specific packages well let's get default then
13500: 		if ($key!~/^default&/) { next; }
13501: 		&metadata_create_package_def($uri,$key,'default',
13502: 					     \%metathesekeys);
13503: 	    }
13504: 	}
13505: # are there custom rights to evaluate
13506: 	if ($metaentry{':copyright'} eq 'custom') {
13507: 
13508:     #
13509:     # Importing a rights file here
13510:     #
13511: 	    unless ($depthcount) {
13512: 		my $location=$metaentry{':customdistributionfile'};
13513: 		my $dir=$filename;
13514: 		$dir=~s|[^/]*$||;
13515: 		$location=&filelocation($dir,$location);
13516: 		my $rights_metadata =
13517: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13518: 			      $depthcount+1);
13519: 		foreach my $rights (split(',',$rights_metadata)) {
13520: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13521: 		    $metathesekeys{$rights}=1;
13522: 		}
13523: 	    }
13524: 	}
13525: 	# uniqifiy package listing
13526: 	my %seen;
13527: 	my @uniq_packages =
13528: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13529: 	$metaentry{':packages'} = join(',',@uniq_packages);
13530: 
13531:         if (($importedresponses) || ($importedparts)) {
13532:             if ($importedparts) {
13533: # We had imported parts and need to rebuild partorder
13534:                 $metaentry{':partorder'}='';
13535:                 $metathesekeys{'partorder'}=1;
13536:             }
13537:             if ($importedresponses) {
13538: # We had imported responses and need to rebuil responseorder
13539:                 $metaentry{':responseorder'}='';
13540:                 $metathesekeys{'responseorder'}=1;
13541:             }
13542:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13543:                 my $origid = $origfiletagids[$index+1];
13544:                 if ($origfiletagids[$index] eq 'part') {
13545: # Original part, part of the problem
13546:                     if ($importedparts) {
13547:                         $metaentry{':partorder'}.=','.$origid;
13548:                     }
13549:                 } elsif ($origfiletagids[$index] eq 'import') {
13550:                     if ($importedparts) {
13551: # We have imported parts at this position
13552:                         if ($importedpartids{$origid} ne '') {
13553:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13554:                         }
13555:                     }
13556:                     if ($importedresponses) {
13557: # We have imported responses at this position
13558:                         if ($importedrespids{$origid} ne '') {
13559:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13560:                         }
13561:                     }
13562:                 } else {
13563: # Original response item, part of the problem
13564:                     if ($importedresponses) {
13565:                         $metaentry{':responseorder'}.=','.$origid;
13566:                     }
13567:                 }
13568:             }
13569:             if ($importedparts) {
13570:                 $metaentry{':partorder'}=~s/^\,//;
13571:             }
13572:             if ($importedresponses) {
13573:                 $metaentry{':responseorder'}=~s/^\,//;
13574:             }
13575:         }
13576: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13577: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13578: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13579:         unless ($liburi) {
13580: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13581:         }
13582: # this is the end of "was not already recently cached
13583:     }
13584:     return $metaentry{':'.$what};
13585: }
13586: 
13587: sub metadata_create_package_def {
13588:     my ($uri,$key,$package,$metathesekeys)=@_;
13589:     my ($pack,$name,$subp)=split(/\&/,$key);
13590:     if ($subp eq 'default') { next; }
13591:     
13592:     if (defined($metaentry{':packages'})) {
13593: 	$metaentry{':packages'}.=','.$package;
13594:     } else {
13595: 	$metaentry{':packages'}=$package;
13596:     }
13597:     my $value=$packagetab{$key};
13598:     my $unikey;
13599:     $unikey='parameter_0_'.$name;
13600:     $metaentry{':'.$unikey.'.part'}=0;
13601:     $$metathesekeys{$unikey}=1;
13602:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13603: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13604:     }
13605:     if (defined($metaentry{':'.$unikey.'.default'})) {
13606: 	$metaentry{':'.$unikey}=
13607: 	    $metaentry{':'.$unikey.'.default'};
13608:     }
13609: }
13610: 
13611: sub metadata_generate_part0 {
13612:     my ($metadata,$metacache,$uri) = @_;
13613:     my %allnames;
13614:     foreach my $metakey (keys(%$metadata)) {
13615: 	if ($metakey=~/^parameter\_(.*)/) {
13616: 	  my $part=$$metacache{':'.$metakey.'.part'};
13617: 	  my $name=$$metacache{':'.$metakey.'.name'};
13618: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13619: 	    $allnames{$name}=$part;
13620: 	  }
13621: 	}
13622:     }
13623:     foreach my $name (keys(%allnames)) {
13624:       $$metadata{"parameter_0_$name"}=1;
13625:       my $key=":parameter_0_$name";
13626:       $$metacache{"$key.part"}='0';
13627:       $$metacache{"$key.name"}=$name;
13628:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13629: 					   $allnames{$name}.'_'.$name.
13630: 					   '.type'};
13631:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13632: 			     '.display'};
13633:       my $expr='[Part: '.$allnames{$name}.']';
13634:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13635:       $$metacache{"$key.display"}=$olddis;
13636:     }
13637: }
13638: 
13639: # ------------------------------------------------------ Devalidate title cache
13640: 
13641: sub devalidate_title_cache {
13642:     my ($url)=@_;
13643:     if (!$env{'request.course.id'}) { return; }
13644:     my $symb=&symbread($url);
13645:     if (!$symb) { return; }
13646:     my $key=$env{'request.course.id'}."\0".$symb;
13647:     &devalidate_cache_new('title',$key);
13648: }
13649: 
13650: # ------------------------------------------------- Get the title of a course
13651: 
13652: sub current_course_title {
13653:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13654: }
13655: # ------------------------------------------------- Get the title of a resource
13656: 
13657: sub gettitle {
13658:     my $urlsymb=shift;
13659:     my $symb=&symbread($urlsymb);
13660:     if ($symb) {
13661: 	my $key=$env{'request.course.id'}."\0".$symb;
13662: 	my ($result,$cached)=&is_cached_new('title',$key);
13663: 	if (defined($cached)) { 
13664: 	    return $result;
13665: 	}
13666: 	my ($map,$resid,$url)=&decode_symb($symb);
13667: 	my $title='';
13668: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13669: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13670: 	} else {
13671: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13672: 		    &GDBM_READER(),0640)) {
13673: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13674: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13675: 		untie(%bighash);
13676: 	    }
13677: 	}
13678: 	$title=~s/\&colon\;/\:/gs;
13679: 	if ($title) {
13680: # Remember both $symb and $title for dynamic metadata
13681:             $accesshash{$symb.'___crstitle'}=$title;
13682:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13683: # Cache this title and then return it
13684: 	    return &do_cache_new('title',$key,$title,600);
13685: 	}
13686: 	$urlsymb=$url;
13687:     }
13688:     my $title=&metadata($urlsymb,'title');
13689:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13690:     return $title;
13691: }
13692: 
13693: sub get_slot {
13694:     my ($which,$cnum,$cdom)=@_;
13695:     if (!$cnum || !$cdom) {
13696: 	(undef,my $courseid)=&whichuser();
13697: 	$cdom=$env{'course.'.$courseid.'.domain'};
13698: 	$cnum=$env{'course.'.$courseid.'.num'};
13699:     }
13700:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13701:     my %slotinfo;
13702:     if (exists($remembered{$key})) {
13703: 	$slotinfo{$which} = $remembered{$key};
13704:     } else {
13705: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13706: 	&Apache::lonhomework::showhash(%slotinfo);
13707: 	my ($tmp)=keys(%slotinfo);
13708: 	if ($tmp=~/^error:/) { return (); }
13709: 	$remembered{$key} = $slotinfo{$which};
13710:     }
13711:     if (ref($slotinfo{$which}) eq 'HASH') {
13712: 	return %{$slotinfo{$which}};
13713:     }
13714:     return $slotinfo{$which};
13715: }
13716: 
13717: sub get_reservable_slots {
13718:     my ($cnum,$cdom,$uname,$udom) = @_;
13719:     my $now = time;
13720:     my $reservable_info;
13721:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13722:     if (exists($remembered{$key})) {
13723:         $reservable_info = $remembered{$key};
13724:     } else {
13725:         my %resv;
13726:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13727:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13728:         $reservable_info = \%resv;
13729:         $remembered{$key} = $reservable_info;
13730:     }
13731:     return $reservable_info;
13732: }
13733: 
13734: sub get_course_slots {
13735:     my ($cnum,$cdom) = @_;
13736:     my $hashid=$cnum.':'.$cdom;
13737:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
13738:     if (defined($cached)) {
13739:         if (ref($result) eq 'HASH') {
13740:             return %{$result};
13741:         }
13742:     } else {
13743:         my %slots=&dump('slots',$cdom,$cnum);
13744:         my ($tmp) = keys(%slots);
13745:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13746:             &do_cache_new('allslots',$hashid,\%slots,600);
13747:             return %slots;
13748:         }
13749:     }
13750:     return;
13751: }
13752: 
13753: sub devalidate_slots_cache {
13754:     my ($cnum,$cdom)=@_;
13755:     my $hashid=$cnum.':'.$cdom;
13756:     &devalidate_cache_new('allslots',$hashid);
13757: }
13758: 
13759: sub get_coursechange {
13760:     my ($cdom,$cnum) = @_;
13761:     if ($cdom eq '' || $cnum eq '') {
13762:         return unless ($env{'request.course.id'});
13763:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13764:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13765:     }
13766:     my $hashid=$cdom.'_'.$cnum;
13767:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13768:     if ((defined($cached)) && ($change ne '')) {
13769:         return $change;
13770:     } else {
13771:         my %crshash;
13772:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13773:         if ($crshash{'internal.contentchange'} eq '') {
13774:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13775:             if ($change eq '') {
13776:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13777:                 $change = $crshash{'internal.created'};
13778:             }
13779:         } else {
13780:             $change = $crshash{'internal.contentchange'};
13781:         }
13782:         my $cachetime = 600;
13783:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13784:     }
13785:     return $change;
13786: }
13787: 
13788: sub devalidate_coursechange_cache {
13789:     my ($cdom,$cnum)=@_;
13790:     my $hashid=$cdom.'_'.$cnum;
13791:     &devalidate_cache_new('crschange',$hashid);
13792: }
13793: 
13794: sub get_suppchange {
13795:     my ($cdom,$cnum) = @_;
13796:     if ($cdom eq '' || $cnum eq '') {
13797:         return unless ($env{'request.course.id'});
13798:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13799:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13800:     }
13801:     my $hashid=$cdom.'_'.$cnum;
13802:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
13803:     if ((defined($cached)) && ($change ne '')) {
13804:         return $change;
13805:     } else {
13806:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
13807:         if ($crshash{'internal.supplementalchange'} eq '') {
13808:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13809:             if ($change eq '') {
13810:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13811:                 $change = $crshash{'internal.created'};
13812:             }
13813:         } else {
13814:             $change = $crshash{'internal.supplementalchange'};
13815:         }
13816:         my $cachetime = 600;
13817:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
13818:     }
13819:     return $change;
13820: }
13821: 
13822: sub devalidate_suppchange_cache {
13823:     my ($cdom,$cnum)=@_;
13824:     my $hashid=$cdom.'_'.$cnum;
13825:     &devalidate_cache_new('suppchange',$hashid);
13826: }
13827: 
13828: sub update_supp_caches {
13829:     my ($cdom,$cnum) = @_;
13830:     my %servers = &internet_dom_servers($cdom);
13831:     my @ids=&current_machine_ids();
13832:     foreach my $server (keys(%servers)) {
13833:         next if (grep(/^\Q$server\E$/,@ids));
13834:         my $hashid=$cnum.':'.$cdom;
13835:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
13836:         &remote_devalidate_cache($server,[$cachekey]);
13837:     }
13838:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
13839:     &count_supptools($cnum,$cdom,1);
13840:     my $now = time;
13841:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
13842:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
13843:     }
13844:     &put('environment',{'internal.supplementalchange' => $now},
13845:          $cdom,$cnum);
13846:     &Apache::lonnet::appenv(
13847:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
13848:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
13849: }
13850: 
13851: # ------------------------------------------------- Update symbolic store links
13852: 
13853: sub symblist {
13854:     my ($mapname,%newhash)=@_;
13855:     $mapname=&deversion(&declutter($mapname));
13856:     my %hash;
13857:     if (($env{'request.course.fn'}) && (%newhash)) {
13858:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13859:                       &GDBM_WRCREAT(),0640)) {
13860: 	    foreach my $url (keys(%newhash)) {
13861: 		next if ($url eq 'last_known'
13862: 			 && $env{'form.no_update_last_known'});
13863: 		$hash{declutter($url)}=&encode_symb($mapname,
13864: 						    $newhash{$url}->[1],
13865: 						    $newhash{$url}->[0]);
13866:             }
13867:             if (untie(%hash)) {
13868: 		return 'ok';
13869:             }
13870:         }
13871:     }
13872:     return 'error';
13873: }
13874: 
13875: # --------------------------------------------------------------- Verify a symb
13876: 
13877: sub symbverify {
13878:     my ($symb,$thisurl,$encstate)=@_;
13879:     my $thisfn=$thisurl;
13880:     $thisfn=&declutter($thisfn);
13881: # direct jump to resource in page or to a sequence - will construct own symbs
13882:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13883: # check URL part
13884:     my ($map,$resid,$url)=&decode_symb($symb);
13885: 
13886:     unless ($url eq $thisfn) { return 0; }
13887: 
13888:     $symb=&symbclean($symb);
13889:     $thisurl=&deversion($thisurl);
13890:     $thisfn=&deversion($thisfn);
13891: 
13892:     my %bighash;
13893:     my $okay=0;
13894: 
13895:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13896:                             &GDBM_READER(),0640)) {
13897:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13898:             $thisurl =~ s/\?.+$//;
13899:             if ($map =~ m{^uploaded/.+\.page$}) {
13900:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13901:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13902:             }
13903:         }
13904:         my $ids;
13905:         if ($map =~ m{^uploaded/.+\.page$}) {
13906:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13907:         } else {
13908:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13909:         }
13910:         unless ($ids) {
13911:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13912:             $ids=$bighash{$idkey};
13913:         }
13914:         if ($ids) {
13915: # ------------------------------------------------------------------- Has ID(s)
13916:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13917:                 $symb =~ s/\?.+$//;
13918:             }
13919: 	    foreach my $id (split(/\,/,$ids)) {
13920: 	       my ($mapid,$resid)=split(/\./,$id);
13921:                if (
13922:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13923:    eq $symb) {
13924:                    if (ref($encstate)) {
13925:                        $$encstate = $bighash{'encrypted_'.$id};
13926:                    }
13927: 		   if (($env{'request.role.adv'}) ||
13928: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13929:                        ($thisurl eq '/adm/navmaps')) {
13930: 		       $okay=1;
13931:                        last;
13932: 		   }
13933: 	       }
13934: 	   }
13935:         }
13936: 	untie(%bighash);
13937:     }
13938:     return $okay;
13939: }
13940: 
13941: # --------------------------------------------------------------- Clean-up symb
13942: 
13943: sub symbclean {
13944:     my $symb=shift;
13945:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13946: # remove version from map
13947:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13948: 
13949: # remove version from URL
13950:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13951: 
13952: # remove wrapper
13953: 
13954:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13955:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13956:     return $symb;
13957: }
13958: 
13959: # ---------------------------------------------- Split symb to find map and url
13960: 
13961: sub encode_symb {
13962:     my ($map,$resid,$url)=@_;
13963:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13964: }
13965: 
13966: sub decode_symb {
13967:     my $symb=shift;
13968:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13969:     my ($map,$resid,$url)=split(/___/,$symb);
13970:     return (&fixversion($map),$resid,&fixversion($url));
13971: }
13972: 
13973: sub fixversion {
13974:     my $fn=shift;
13975:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13976:     my %bighash;
13977:     my $uri=&clutter($fn);
13978:     my $key=$env{'request.course.id'}.'_'.$uri;
13979: # is this cached?
13980:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13981:     if (defined($cached)) { return $result; }
13982: # unfortunately not cached, or expired
13983:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13984: 	    &GDBM_READER(),0640)) {
13985:  	if ($bighash{'version_'.$uri}) {
13986:  	    my $version=$bighash{'version_'.$uri};
13987:  	    unless (($version eq 'mostrecent') || 
13988: 		    ($version==&getversion($uri))) {
13989:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13990:  	    }
13991:  	}
13992:  	untie %bighash;
13993:     }
13994:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13995: }
13996: 
13997: sub deversion {
13998:     my $url=shift;
13999:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14000:     return $url;
14001: }
14002: 
14003: # ------------------------------------------------------ Return symb list entry
14004: 
14005: sub symbread {
14006:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14007:         $ignoresymbdb,$noenccheck)=@_;
14008:     my $cache_str='request.symbread.cached.'.$thisfn;
14009:     if (defined($env{$cache_str})) {
14010:         unless (ref($possibles) eq 'HASH') {
14011:             if ($ignorecachednull) {
14012:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14013:             } else {
14014:                 return $env{$cache_str};
14015:             }
14016:         }
14017:     }
14018: # no filename provided? try from environment
14019:     unless ($thisfn) {
14020:         if ($env{'request.symb'}) {
14021:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14022: 	}
14023: 	$thisfn=$env{'request.filename'};
14024:     }
14025:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14026: # is that filename actually a symb? Verify, clean, and return
14027:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14028: 	if (&symbverify($thisfn,$1)) {
14029: 	    return $env{$cache_str}=&symbclean($thisfn);
14030: 	}
14031:     }
14032:     $thisfn=declutter($thisfn);
14033:     my %hash;
14034:     my %bighash;
14035:     my $syval='';
14036:     if (($env{'request.course.fn'}) && ($thisfn)) {
14037:         unless ($ignoresymbdb) {
14038:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14039:                           &GDBM_READER(),0640)) {
14040: 	        $syval=$hash{$thisfn};
14041:                 untie(%hash);
14042:             }
14043:             if ($syval && $checkforblock) {
14044:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14045:                 if (@blockers) {
14046:                     $syval='';
14047:                 }
14048:             }
14049:         }
14050: # ---------------------------------------------------------- There was an entry
14051:         if ($syval) {
14052: 	    #unless ($syval=~/\_\d+$/) {
14053: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14054: 		    #&appenv({'request.ambiguous' => $thisfn});
14055: 		    #return $env{$cache_str}='';
14056: 		#}    
14057: 		#$syval.=$1;
14058: 	    #}
14059:         } else {
14060: # ------------------------------------------------------- Was not in symb table
14061:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14062:                             &GDBM_READER(),0640)) {
14063: # ---------------------------------------------- Get ID(s) for current resource
14064:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14065:               unless ($ids) { 
14066:                  $ids=$bighash{'ids_/'.$thisfn};
14067:               }
14068:               unless ($ids) {
14069: # alias?
14070: 		  $ids=$bighash{'mapalias_'.$thisfn};
14071:               }
14072:               if ($ids) {
14073: # ------------------------------------------------------------------- Has ID(s)
14074:                  my @possibilities=split(/\,/,$ids);
14075:                  if ($#possibilities==0) {
14076: # ----------------------------------------------- There is only one possibility
14077: 		     my ($mapid,$resid)=split(/\./,$ids);
14078: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14079: 						    $resid,$thisfn);
14080:                      if (ref($possibles) eq 'HASH') {
14081:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14082:                              $possibles->{$syval} = 1;
14083:                          }
14084:                      }
14085:                      if ($checkforblock) {
14086:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14087:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14088:                              if (@blockers) {
14089:                                  $syval = '';
14090:                                  untie(%bighash);
14091:                                  return $env{$cache_str}='';
14092:                              }
14093:                          }
14094:                      }
14095:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14096: # ------------------------------------------ There is more than one possibility
14097:                      my $realpossible=0;
14098:                      foreach my $id (@possibilities) {
14099: 			 my $file=$bighash{'src_'.$id};
14100:                          my $canaccess;
14101:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14102:                              $canaccess = 1;
14103:                          } else { 
14104:                              $canaccess = &allowed('bre',$file);
14105:                          }
14106:                          if ($canaccess) {
14107:          		     my ($mapid,$resid)=split(/\./,$id);
14108:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14109:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14110: 						             $resid,$thisfn);
14111:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14112:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14113:                                  if ($checkforblock) {
14114:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14115:                                      if (@blockers > 0) {
14116:                                          $syval = '';
14117:                                      } else {
14118:                                          $syval = $poss_syval;
14119:                                          $realpossible++;
14120:                                      }
14121:                                  } else {
14122:                                      $syval = $poss_syval;
14123:                                      $realpossible++;
14124:                                  }
14125:                                  if ($syval) {
14126:                                      if (ref($possibles) eq 'HASH') {
14127:                                          $possibles->{$syval} = 1;
14128:                                      }
14129:                                  }
14130:                              }
14131: 			 }
14132:                      }
14133: 		     if ($realpossible!=1) { $syval=''; }
14134:                  } else {
14135:                      $syval='';
14136:                  }
14137: 	      }
14138:               untie(%bighash);
14139:            }
14140:         }
14141:         if ($syval) {
14142: 	    return $env{$cache_str}=$syval;
14143:         }
14144:     }
14145:     &appenv({'request.ambiguous' => $thisfn});
14146:     return $env{$cache_str}='';
14147: }
14148: 
14149: # ---------------------------------------------------------- Return random seed
14150: 
14151: sub numval {
14152:     my $txt=shift;
14153:     $txt=~tr/A-J/0-9/;
14154:     $txt=~tr/a-j/0-9/;
14155:     $txt=~tr/K-T/0-9/;
14156:     $txt=~tr/k-t/0-9/;
14157:     $txt=~tr/U-Z/0-5/;
14158:     $txt=~tr/u-z/0-5/;
14159:     $txt=~s/\D//g;
14160:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14161:     return int($txt);
14162: }
14163: 
14164: sub numval2 {
14165:     my $txt=shift;
14166:     $txt=~tr/A-J/0-9/;
14167:     $txt=~tr/a-j/0-9/;
14168:     $txt=~tr/K-T/0-9/;
14169:     $txt=~tr/k-t/0-9/;
14170:     $txt=~tr/U-Z/0-5/;
14171:     $txt=~tr/u-z/0-5/;
14172:     $txt=~s/\D//g;
14173:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14174:     my $total;
14175:     foreach my $val (@txts) { $total+=$val; }
14176:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14177:     return int($total);
14178: }
14179: 
14180: sub numval3 {
14181:     use integer;
14182:     my $txt=shift;
14183:     $txt=~tr/A-J/0-9/;
14184:     $txt=~tr/a-j/0-9/;
14185:     $txt=~tr/K-T/0-9/;
14186:     $txt=~tr/k-t/0-9/;
14187:     $txt=~tr/U-Z/0-5/;
14188:     $txt=~tr/u-z/0-5/;
14189:     $txt=~s/\D//g;
14190:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14191:     my $total;
14192:     foreach my $val (@txts) { $total+=$val; }
14193:     if ($_64bit) { $total=(($total<<32)>>32); }
14194:     return $total;
14195: }
14196: 
14197: sub digest {
14198:     my ($data)=@_;
14199:     my $digest=&Digest::MD5::md5($data);
14200:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14201:     my ($e,$f);
14202:     {
14203:         use integer;
14204:         $e=($a+$b);
14205:         $f=($c+$d);
14206:         if ($_64bit) {
14207:             $e=(($e<<32)>>32);
14208:             $f=(($f<<32)>>32);
14209:         }
14210:     }
14211:     if (wantarray) {
14212: 	return ($e,$f);
14213:     } else {
14214: 	my $g;
14215: 	{
14216: 	    use integer;
14217: 	    $g=($e+$f);
14218: 	    if ($_64bit) {
14219: 		$g=(($g<<32)>>32);
14220: 	    }
14221: 	}
14222: 	return $g;
14223:     }
14224: }
14225: 
14226: sub latest_rnd_algorithm_id {
14227:     return '64bit5';
14228: }
14229: 
14230: sub get_rand_alg {
14231:     my ($courseid)=@_;
14232:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14233:     if ($courseid) {
14234: 	return $env{"course.$courseid.rndseed"};
14235:     }
14236:     return &latest_rnd_algorithm_id();
14237: }
14238: 
14239: sub validCODE {
14240:     my ($CODE)=@_;
14241:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14242:     return 0;
14243: }
14244: 
14245: sub getCODE {
14246:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14247:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14248: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14249: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14250: 	return $Apache::lonhomework::history{'resource.CODE'};
14251:     }
14252:     return undef;
14253: }
14254: #
14255: #  Determines the random seed for a specific context:
14256: #
14257: # parameters:
14258: #   symb      - in course context the symb for the seed.
14259: #   course_id - The course id of the form domain_coursenum.
14260: #   domain    - Domain for the user.
14261: #   course    - Course for the user.
14262: #   cenv      - environment of the course.
14263: #
14264: # NOTE:
14265: #   All parameters are picked out of the environment if missing
14266: #   or not defined.
14267: #   If a symb cannot be determined the current time is used instead.
14268: #
14269: #  For a given well defined symb, courside, domain, username,
14270: #  and course environment, the seed is reproducible.
14271: #
14272: sub rndseed {
14273:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14274:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14275:     if (!defined($symb)) {
14276: 	unless ($symb=$wsymb) { return time; }
14277:     }
14278:     if (!defined $courseid) { 
14279: 	$courseid=$wcourseid; 
14280:     }
14281:     if (!defined $domain) { $domain=$wdomain; }
14282:     if (!defined $username) { $username=$wusername }
14283: 
14284:     my $which;
14285:     if (defined($cenv->{'rndseed'})) {
14286: 	$which = $cenv->{'rndseed'};
14287:     } else {
14288: 	$which =&get_rand_alg($courseid);
14289:     }
14290:     if (defined(&getCODE())) {
14291: 
14292: 	if ($which eq '64bit5') {
14293: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14294: 	} elsif ($which eq '64bit4') {
14295: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14296: 	} else {
14297: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14298: 	}
14299:     } elsif ($which eq '64bit5') {
14300: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14301:     } elsif ($which eq '64bit4') {
14302: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14303:     } elsif ($which eq '64bit3') {
14304: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14305:     } elsif ($which eq '64bit2') {
14306: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14307:     } elsif ($which eq '64bit') {
14308: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14309:     }
14310:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14311: }
14312: 
14313: sub rndseed_32bit {
14314:     my ($symb,$courseid,$domain,$username)=@_;
14315:     {
14316: 	use integer;
14317: 	my $symbchck=unpack("%32C*",$symb) << 27;
14318: 	my $symbseed=numval($symb) << 22;
14319: 	my $namechck=unpack("%32C*",$username) << 17;
14320: 	my $nameseed=numval($username) << 12;
14321: 	my $domainseed=unpack("%32C*",$domain) << 7;
14322: 	my $courseseed=unpack("%32C*",$courseid);
14323: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14324: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14325: 	#&logthis("rndseed :$num:$symb");
14326: 	if ($_64bit) { $num=(($num<<32)>>32); }
14327: 	return $num;
14328:     }
14329: }
14330: 
14331: sub rndseed_64bit {
14332:     my ($symb,$courseid,$domain,$username)=@_;
14333:     {
14334: 	use integer;
14335: 	my $symbchck=unpack("%32S*",$symb) << 21;
14336: 	my $symbseed=numval($symb) << 10;
14337: 	my $namechck=unpack("%32S*",$username);
14338: 	
14339: 	my $nameseed=numval($username) << 21;
14340: 	my $domainseed=unpack("%32S*",$domain) << 10;
14341: 	my $courseseed=unpack("%32S*",$courseid);
14342: 	
14343: 	my $num1=$symbchck+$symbseed+$namechck;
14344: 	my $num2=$nameseed+$domainseed+$courseseed;
14345: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14346: 	#&logthis("rndseed :$num:$symb");
14347: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14348: 	return "$num1,$num2";
14349:     }
14350: }
14351: 
14352: sub rndseed_64bit2 {
14353:     my ($symb,$courseid,$domain,$username)=@_;
14354:     {
14355: 	use integer;
14356: 	# strings need to be an even # of cahracters long, it it is odd the
14357:         # last characters gets thrown away
14358: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14359: 	my $symbseed=numval($symb) << 10;
14360: 	my $namechck=unpack("%32S*",$username.' ');
14361: 	
14362: 	my $nameseed=numval($username) << 21;
14363: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14364: 	my $courseseed=unpack("%32S*",$courseid.' ');
14365: 	
14366: 	my $num1=$symbchck+$symbseed+$namechck;
14367: 	my $num2=$nameseed+$domainseed+$courseseed;
14368: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14369: 	#&logthis("rndseed :$num:$symb");
14370: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14371: 	return "$num1,$num2";
14372:     }
14373: }
14374: 
14375: sub rndseed_64bit3 {
14376:     my ($symb,$courseid,$domain,$username)=@_;
14377:     {
14378: 	use integer;
14379: 	# strings need to be an even # of cahracters long, it it is odd the
14380:         # last characters gets thrown away
14381: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14382: 	my $symbseed=numval2($symb) << 10;
14383: 	my $namechck=unpack("%32S*",$username.' ');
14384: 	
14385: 	my $nameseed=numval2($username) << 21;
14386: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14387: 	my $courseseed=unpack("%32S*",$courseid.' ');
14388: 	
14389: 	my $num1=$symbchck+$symbseed+$namechck;
14390: 	my $num2=$nameseed+$domainseed+$courseseed;
14391: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14392: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14393: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14394: 	
14395: 	return "$num1:$num2";
14396:     }
14397: }
14398: 
14399: sub rndseed_64bit4 {
14400:     my ($symb,$courseid,$domain,$username)=@_;
14401:     {
14402: 	use integer;
14403: 	# strings need to be an even # of cahracters long, it it is odd the
14404:         # last characters gets thrown away
14405: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14406: 	my $symbseed=numval3($symb) << 10;
14407: 	my $namechck=unpack("%32S*",$username.' ');
14408: 	
14409: 	my $nameseed=numval3($username) << 21;
14410: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14411: 	my $courseseed=unpack("%32S*",$courseid.' ');
14412: 	
14413: 	my $num1=$symbchck+$symbseed+$namechck;
14414: 	my $num2=$nameseed+$domainseed+$courseseed;
14415: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14416: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14417: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14418: 	
14419: 	return "$num1:$num2";
14420:     }
14421: }
14422: 
14423: sub rndseed_64bit5 {
14424:     my ($symb,$courseid,$domain,$username)=@_;
14425:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14426:     return "$num1:$num2";
14427: }
14428: 
14429: sub rndseed_CODE_64bit {
14430:     my ($symb,$courseid,$domain,$username)=@_;
14431:     {
14432: 	use integer;
14433: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14434: 	my $symbseed=numval2($symb);
14435: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14436: 	my $CODEseed=numval(&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_64bit4 {
14449:     my ($symb,$courseid,$domain,$username)=@_;
14450:     {
14451: 	use integer;
14452: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14453: 	my $symbseed=numval3($symb);
14454: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14455: 	my $CODEseed=numval3(&getCODE());
14456: 	my $courseseed=unpack("%32S*",$courseid.' ');
14457: 	my $num1=$symbseed+$CODEchck;
14458: 	my $num2=$CODEseed+$courseseed+$symbchck;
14459: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14460: 	#&logthis("rndseed :$num1:$num2:$symb");
14461: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14462: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14463: 	return "$num1:$num2";
14464:     }
14465: }
14466: 
14467: sub rndseed_CODE_64bit5 {
14468:     my ($symb,$courseid,$domain,$username)=@_;
14469:     my $code = &getCODE();
14470:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14471:     return "$num1:$num2";
14472: }
14473: 
14474: sub setup_random_from_rndseed {
14475:     my ($rndseed)=@_;
14476:     if ($rndseed =~/([,:])/) {
14477:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14478:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14479:             &Math::Random::random_set_seed_from_phrase($rndseed);
14480:         } else {
14481:             &Math::Random::random_set_seed($num1,$num2);
14482:         }
14483:     } else {
14484: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14485:     }
14486: }
14487: 
14488: sub latest_receipt_algorithm_id {
14489:     return 'receipt3';
14490: }
14491: 
14492: sub recunique {
14493:     my $fucourseid=shift;
14494:     my $unique;
14495:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14496: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14497: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14498:     } else {
14499: 	$unique=$perlvar{'lonReceipt'};
14500:     }
14501:     return unpack("%32C*",$unique);
14502: }
14503: 
14504: sub recprefix {
14505:     my $fucourseid=shift;
14506:     my $prefix;
14507:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14508: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14509: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14510:     } else {
14511: 	$prefix=$perlvar{'lonHostID'};
14512:     }
14513:     return unpack("%32C*",$prefix);
14514: }
14515: 
14516: sub ireceipt {
14517:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14518: 
14519:     my $return =&recprefix($fucourseid).'-';
14520: 
14521:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14522: 	$env{'request.state'} eq 'construct') {
14523: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14524: 	return $return;
14525:     }
14526: 
14527:     my $cuname=unpack("%32C*",$funame);
14528:     my $cudom=unpack("%32C*",$fudom);
14529:     my $cucourseid=unpack("%32C*",$fucourseid);
14530:     my $cusymb=unpack("%32C*",$fusymb);
14531:     my $cunique=&recunique($fucourseid);
14532:     my $cpart=unpack("%32S*",$part);
14533:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14534: 
14535: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14536: 			       
14537: 	$return.= ($cunique%$cuname+
14538: 		   $cunique%$cudom+
14539: 		   $cusymb%$cuname+
14540: 		   $cusymb%$cudom+
14541: 		   $cucourseid%$cuname+
14542: 		   $cucourseid%$cudom+
14543: 		   $cpart%$cuname+
14544: 		   $cpart%$cudom);
14545:     } else {
14546: 	$return.= ($cunique%$cuname+
14547: 		   $cunique%$cudom+
14548: 		   $cusymb%$cuname+
14549: 		   $cusymb%$cudom+
14550: 		   $cucourseid%$cuname+
14551: 		   $cucourseid%$cudom);
14552:     }
14553:     return $return;
14554: }
14555: 
14556: sub receipt {
14557:     my ($part)=@_;
14558:     my ($symb,$courseid,$domain,$name) = &whichuser();
14559:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14560: }
14561: 
14562: sub whichuser {
14563:     my ($passedsymb)=@_;
14564:     my ($symb,$courseid,$domain,$name,$publicuser);
14565:     if (defined($env{'form.grade_symb'})) {
14566: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14567: 	my $allowed=&allowed('vgr',$tmp_courseid);
14568: 	if (!$allowed &&
14569: 	    exists($env{'request.course.sec'}) &&
14570: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14571: 	    $allowed=&allowed('vgr',$tmp_courseid.
14572: 			      '/'.$env{'request.course.sec'});
14573: 	}
14574: 	if ($allowed) {
14575: 	    ($symb)=&get_env_multiple('form.grade_symb');
14576: 	    $courseid=$tmp_courseid;
14577: 	    ($domain)=&get_env_multiple('form.grade_domain');
14578: 	    ($name)=&get_env_multiple('form.grade_username');
14579: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14580: 	}
14581:     }
14582:     if (!$passedsymb) {
14583: 	$symb=&symbread();
14584:     } else {
14585: 	$symb=$passedsymb;
14586:     }
14587:     $courseid=$env{'request.course.id'};
14588:     $domain=$env{'user.domain'};
14589:     $name=$env{'user.name'};
14590:     if ($name eq 'public' && $domain eq 'public') {
14591: 	if (!defined($env{'form.username'})) {
14592: 	    $env{'form.username'}.=time.rand(10000000);
14593: 	}
14594: 	$name.=$env{'form.username'};
14595:     }
14596:     return ($symb,$courseid,$domain,$name,$publicuser);
14597: 
14598: }
14599: 
14600: # ------------------------------------------------------------ Serves up a file
14601: # returns either the contents of the file or 
14602: # -1 if the file doesn't exist
14603: #
14604: # if the target is a file that was uploaded via DOCS, 
14605: # a check will be made to see if a current copy exists on the local server,
14606: # if it does this will be served, otherwise a copy will be retrieved from
14607: # the home server for the course and stored in /home/httpd/html/userfiles on
14608: # the local server.   
14609: 
14610: sub getfile {
14611:     my ($file) = @_;
14612:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14613:     &repcopy($file);
14614:     return &readfile($file);
14615: }
14616: 
14617: sub repcopy_userfile {
14618:     my ($file)=@_;
14619:     my $londocroot = $perlvar{'lonDocRoot'};
14620:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14621:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14622:     my ($cdom,$cnum,$filename) = 
14623: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14624:     my $uri="/uploaded/$cdom/$cnum/$filename";
14625:     if (-e "$file") {
14626: # we already have a local copy, check it out
14627: 	my @fileinfo = stat($file);
14628: 	my $rtncode;
14629: 	my $info;
14630: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14631: 	if ($lwpresp ne 'ok') {
14632: # there is no such file anymore, even though we had a local copy
14633: 	    if ($rtncode eq '404') {
14634: 		unlink($file);
14635: 	    }
14636: 	    return -1;
14637: 	}
14638: 	if ($info < $fileinfo[9]) {
14639: # nice, the file we have is up-to-date, just say okay
14640: 	    return 'ok';
14641: 	} else {
14642: # the file is outdated, get rid of it
14643: 	    unlink($file);
14644: 	}
14645:     }
14646: # one way or the other, at this point, we don't have the file
14647: # construct the correct path for the file
14648:     my @parts = ($cdom,$cnum); 
14649:     if ($filename =~ m|^(.+)/[^/]+$|) {
14650: 	push @parts, split(/\//,$1);
14651:     }
14652:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14653:     foreach my $part (@parts) {
14654: 	$path .= '/'.$part;
14655: 	if (!-e $path) {
14656: 	    mkdir($path,0770);
14657: 	}
14658:     }
14659: # now the path exists for sure
14660: # get a user agent
14661:     my $transferfile=$file.'.in.transfer';
14662: # FIXME: this should flock
14663:     if (-e $transferfile) { return 'ok'; }
14664:     my $request;
14665:     $uri=~s/^\///;
14666:     my $homeserver = &homeserver($cnum,$cdom);
14667:     my $hostname = &hostname($homeserver);
14668:     my $protocol = $protocol{$homeserver};
14669:     $protocol = 'http' if ($protocol ne 'https');
14670:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14671:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14672: # did it work?
14673:     if ($response->is_error()) {
14674: 	unlink($transferfile);
14675: 	&logthis("Userfile repcopy failed for $uri");
14676: 	return -1;
14677:     }
14678: # worked, rename the transfer file
14679:     rename($transferfile,$file);
14680:     return 'ok';
14681: }
14682: 
14683: sub tokenwrapper {
14684:     my $uri=shift;
14685:     $uri=~s|^https?\://([^/]+)||;
14686:     $uri=~s|^/||;
14687:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14688:     my $token=$1;
14689:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14690:     if ($udom && $uname && $file) {
14691: 	$file=~s|(\?\.*)*$||;
14692:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14693:         my $homeserver = &homeserver($uname,$udom);
14694:         my $hostname = &hostname($homeserver);
14695:         my $protocol = $protocol{$homeserver};
14696:         $protocol = 'http' if ($protocol ne 'https');
14697:         return $protocol.'://'.$hostname.'/'.$uri.
14698:                (($uri=~/\?/)?'&':'?').'token='.$token.
14699:                                '&tokenissued='.$perlvar{'lonHostID'};
14700:     } else {
14701:         return '/adm/notfound.html';
14702:     }
14703: }
14704: 
14705: # call with reqtype HEAD: get last modification time
14706: # call with reqtype GET: get the file contents
14707: # Do not call this with reqtype GET for large files! It loads everything into memory
14708: #
14709: sub getuploaded {
14710:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14711:     $uri=~s/^\///;
14712:     my $homeserver = &homeserver($cnum,$cdom);
14713:     my $hostname = &hostname($homeserver);
14714:     my $protocol = $protocol{$homeserver};
14715:     $protocol = 'http' if ($protocol ne 'https');
14716:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14717:     my $request=new HTTP::Request($reqtype,$uri);
14718:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14719:     $$rtncode = $response->code;
14720:     if (! $response->is_success()) {
14721: 	return 'failed';
14722:     }      
14723:     if ($reqtype eq 'HEAD') {
14724: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14725:     } elsif ($reqtype eq 'GET') {
14726: 	$$info = $response->content;
14727:     }
14728:     return 'ok';
14729: }
14730: 
14731: sub readfile {
14732:     my $file = shift;
14733:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14734:     my $fh;
14735:     open($fh,"<",$file);
14736:     my $a='';
14737:     while (my $line = <$fh>) { $a .= $line; }
14738:     return $a;
14739: }
14740: 
14741: sub filelocation {
14742:     my ($dir,$file) = @_;
14743:     my $location;
14744:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14745: 
14746:     if ($file =~ m-^/adm/-) {
14747: 	$file=~s-^/adm/wrapper/-/-;
14748: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14749:     }
14750: 
14751:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14752:         $location = $file;
14753:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14754:         my ($udom,$uname,$filename)=
14755:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14756:         my $home=&homeserver($uname,$udom);
14757:         my $is_me=0;
14758:         my @ids=&current_machine_ids();
14759:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14760:         if ($is_me) {
14761:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14762:         } else {
14763:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14764:   	      $udom.'/'.$uname.'/'.$filename;
14765:         }
14766:     } elsif ($file =~ m-^/adm/-) {
14767: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14768:     } else {
14769:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14770:         $file=~s:^/(res|priv)/:/:;
14771:         my $space=$1;
14772:         if ( !( $file =~ m:^/:) ) {
14773:             $location = $dir. '/'.$file;
14774:         } else {
14775:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14776:         }
14777:     }
14778:     $location=~s://+:/:g; # remove duplicate /
14779:     while ($location=~m{/\.\./}) {
14780: 	if ($location =~ m{/[^/]+/\.\./}) {
14781: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14782: 	} else {
14783: 	    $location=~ s{/\.\./}{/}g;
14784: 	}
14785:     } #remove dir/..
14786:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14787:     return $location;
14788: }
14789: 
14790: sub hreflocation {
14791:     my ($dir,$file)=@_;
14792:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14793: 	$file=filelocation($dir,$file);
14794:     } elsif ($file=~m-^/adm/-) {
14795: 	$file=~s-^/adm/wrapper/-/-;
14796: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14797:     }
14798:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14799: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14800:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14801: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14802: 	        {/uploaded/$1/$2/}x;
14803:     }
14804:     if ($file=~ m{^/userfiles/}) {
14805: 	$file =~ s{^/userfiles/}{/uploaded/};
14806:     }
14807:     return $file;
14808: }
14809: 
14810: 
14811: 
14812: 
14813: 
14814: sub current_machine_domains {
14815:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14816: }
14817: 
14818: sub machine_domains {
14819:     my ($hostname) = @_;
14820:     my @domains;
14821:     my %hostname = &all_hostnames();
14822:     while( my($id, $name) = each(%hostname)) {
14823: #	&logthis("-$id-$name-$hostname-");
14824: 	if ($hostname eq $name) {
14825: 	    push(@domains,&host_domain($id));
14826: 	}
14827:     }
14828:     return @domains;
14829: }
14830: 
14831: sub current_machine_ids {
14832:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14833: }
14834: 
14835: sub machine_ids {
14836:     my ($hostname) = @_;
14837:     $hostname ||= &hostname($perlvar{'lonHostID'});
14838:     my @ids;
14839:     my %name_to_host = &all_names();
14840:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14841: 	return @{ $name_to_host{$hostname} };
14842:     }
14843:     return;
14844: }
14845: 
14846: sub additional_machine_domains {
14847:     my @domains;
14848:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14849:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14850:             while (my $line = <$fh>) {
14851:                 chomp($line);           
14852:                 $line =~ s/\s//g;
14853:                 push(@domains,$line);
14854:             }
14855:             close($fh);
14856:         }
14857:     }
14858:     return @domains;
14859: }
14860: 
14861: sub default_login_domain {
14862:     my $domain = $perlvar{'lonDefDomain'};
14863:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14864:     foreach my $posdom (&current_machine_domains(),
14865:                         &additional_machine_domains()) {
14866:         if (lc($posdom) eq lc($testdomain)) {
14867:             $domain=$posdom;
14868:             last;
14869:         }
14870:     }
14871:     return $domain;
14872: }
14873: 
14874: sub shared_institution {
14875:     my ($dom,$lonhost) = @_;
14876:     if ($lonhost eq '') {
14877:         $lonhost = $perlvar{'lonHostID'};
14878:     }
14879:     my $same_intdom;
14880:     my $hostintdom = &internet_dom($lonhost);
14881:     if ($hostintdom ne '') {
14882:         my %iphost = &get_iphost();
14883:         my $primary_id = &domain($dom,'primary');
14884:         my $primary_ip = &get_host_ip($primary_id);
14885:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14886:             foreach my $id (@{$iphost{$primary_ip}}) {
14887:                 my $intdom = &internet_dom($id);
14888:                 if ($intdom eq $hostintdom) {
14889:                     $same_intdom = 1;
14890:                     last;
14891:                 }
14892:             }
14893:         }
14894:     }
14895:     return $same_intdom;
14896: }
14897: 
14898: sub uses_sts {
14899:     my ($ignore_cache) = @_;
14900:     my $lonhost = $perlvar{'lonHostID'};
14901:     my $hostname = &hostname($lonhost);
14902:     my $sts_on;
14903:     if ($protocol{$lonhost} eq 'https') {
14904:         my $cachetime = 12*3600;
14905:         if (!$ignore_cache) {
14906:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14907:             if (defined($cached)) {
14908:                 return $sts_on;
14909:             }
14910:         }
14911:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14912:         my $request=new HTTP::Request('HEAD',$url);
14913:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14914:         if ($response->is_success) {
14915:             my $has_sts = $response->header('Strict-Transport-Security');
14916:             if ($has_sts eq '') {
14917:                 $sts_on = 0;
14918:             } else {
14919:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14920:                     my $maxage = $1;
14921:                     if ($maxage) {
14922:                         $sts_on = 1;
14923:                     } else {
14924:                         $sts_on = 0;
14925:                     }
14926:                 } else {
14927:                     $sts_on = 0;
14928:                 }
14929:             }
14930:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14931:         }
14932:     }
14933:     return;
14934: }
14935: 
14936: sub waf_allssl {
14937:     my ($host_name) = @_;
14938:     my $alias = &get_proxy_alias();
14939:     if ($host_name eq '') {
14940:         $host_name = $ENV{'SERVER_NAME'};
14941:     }
14942:     if (($host_name ne '') && ($alias eq $host_name)) {
14943:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14944:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14945:         if ($defdomdefaults{'waf_sslopt'}) {
14946:             return $defdomdefaults{'waf_sslopt'};
14947:         }
14948:     }
14949:     return;
14950: }
14951: 
14952: sub get_requestor_ip {
14953:     my ($r,$nolookup,$noproxy) = @_;
14954:     my $from_ip;
14955:     if (ref($r)) {
14956:         if ($r->can('useragent_ip')) {
14957:             if ($noproxy && $r->can('client_ip')) {
14958:                 $from_ip = $r->client_ip();
14959:             } else {
14960:                 $from_ip = $r->useragent_ip();
14961:             }
14962:         } elsif ($r->connection->can('remote_ip')) {
14963:             $from_ip = $r->connection->remote_ip();
14964:         } else {
14965:             $from_ip = $r->get_remote_host($nolookup);
14966:         }
14967:     } else {
14968:         $from_ip = $ENV{'REMOTE_ADDR'};
14969:     }
14970:     return $from_ip if ($noproxy); 
14971:     # Who controls proxy settings for server
14972:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14973:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14974:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14975:         if ($proxyinfo->{'vpnint'}) {
14976:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14977:                 return $from_ip;
14978:             }
14979:         }
14980:         if ($proxyinfo->{'trusted'}) {
14981:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14982:                 my $ipheader = $proxyinfo->{'ipheader'};
14983:                 my ($ip,$xfor);
14984:                 if (ref($r)) {
14985:                     if ($ipheader) {
14986:                         $ip = $r->headers_in->{$ipheader};
14987:                     }
14988:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14989:                 } else {
14990:                     if ($ipheader) {
14991:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14992:                     }
14993:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14994:                 }
14995:                 if (($ip eq '') && ($xfor ne '')) {
14996:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14997:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14998:                             $ip = $poss_ip;
14999:                             last;
15000:                         }
15001:                     }
15002:                 }
15003:                 if ($ip ne '') {
15004:                     return $ip;
15005:                 }
15006:             }
15007:         }
15008:     }
15009:     return $from_ip;
15010: }
15011: 
15012: sub get_proxy_settings {
15013:     my ($dom_in_use) = @_;
15014:     my %domdefaults = &get_domain_defaults($dom_in_use);
15015:     my $proxyinfo = {
15016:                        ipheader => $domdefaults{'waf_ipheader'},
15017:                        trusted  => $domdefaults{'waf_trusted'},
15018:                        vpnint   => $domdefaults{'waf_vpnint'},
15019:                        vpnext   => $domdefaults{'waf_vpnext'},
15020:                        sslopt   => $domdefaults{'waf_sslopt'},
15021:                     };
15022:     return $proxyinfo;
15023: }
15024: 
15025: sub ip_match {
15026:     my ($ip,$pattern_str) = @_;
15027:     $ip=Net::CIDR::cidrvalidate($ip);
15028:     if ($ip) {
15029:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15030:     }
15031:     return;
15032: }
15033: 
15034: sub get_proxy_alias {
15035:     my ($lonid) = @_;
15036:     if ($lonid eq '') {
15037:         $lonid = $perlvar{'lonHostID'};
15038:     }
15039:     if (!defined(&hostname($lonid))) {
15040:         return;
15041:     }
15042:     if ($lonid ne '') {
15043:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15044:         if ($cached) {
15045:             return $alias;
15046:         }
15047:         my $dom = &host_domain($lonid);
15048:         if ($dom ne '') {
15049:             my $cachetime = 60*60*24;
15050:             my %domconfig =
15051:                 &get_dom('configuration',['wafproxy'],$dom);
15052:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15053:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15054:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15055:                 }
15056:             }
15057:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15058:         }
15059:     }
15060:     return;
15061: }
15062: 
15063: sub use_proxy_alias {
15064:     my ($r,$lonid) = @_;
15065:     my $alias = &get_proxy_alias($lonid);
15066:     if ($alias) {
15067:         my $dom = &host_domain($lonid);
15068:         if ($dom ne '') {
15069:             my $proxyinfo = &get_proxy_settings($dom);
15070:             my ($vpnint,$remote_ip);
15071:             if (ref($proxyinfo) eq 'HASH') {
15072:                 $vpnint = $proxyinfo->{'vpnint'};
15073:                 if ($vpnint) {
15074:                     $remote_ip = &get_requestor_ip($r,1,1);
15075:                 }
15076:             }
15077:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15078:                 return $alias;
15079:             }
15080:         }
15081:     }
15082:     return;
15083: }
15084: 
15085: sub alias_sso {
15086:     my ($lonid) = @_;
15087:     if ($lonid eq '') {
15088:         $lonid = $perlvar{'lonHostID'};
15089:     }
15090:     if (!defined(&hostname($lonid))) {
15091:         return;
15092:     }
15093:     if ($lonid ne '') {
15094:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15095:         if ($cached) {
15096:             return $use_alias;
15097:         }
15098:         my $dom = &host_domain($lonid);
15099:         if ($dom ne '') {
15100:             my $cachetime = 60*60*24;
15101:             my %domconfig =
15102:                 &get_dom('configuration',['wafproxy'],$dom);
15103:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15104:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15105:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15106:                 }
15107:             }
15108:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15109:         }
15110:     }
15111:     return;
15112: }
15113: 
15114: sub get_saml_landing {
15115:     my ($lonid) = @_;
15116:     if ($lonid eq '') {
15117:         my $defdom = &default_login_domain();
15118:         my @hosts = &current_machine_ids();
15119:         if (@hosts > 1) {
15120:             foreach my $hostid (@hosts) {
15121:                 if (&host_domain($hostid) eq $defdom) {
15122:                     $lonid = $hostid;
15123:                     last;
15124:                 }
15125:             }
15126:         } else {
15127:             $lonid = $perlvar{'lonHostID'};
15128:         }
15129:         if ($lonid) {
15130:             unless (&host_domain($lonid) eq $defdom) {
15131:                 return;
15132:             }
15133:         } else {
15134:             return;
15135:         }
15136:     } elsif (!defined(&hostname($lonid))) {
15137:         return;
15138:     }
15139:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15140:     if ($cached) {
15141:         return $landing;
15142:     }
15143:     my $dom = &host_domain($lonid);
15144:     if ($dom ne '') {
15145:         my $cachetime = 60*60*24;
15146:         my %domconfig =
15147:             &get_dom('configuration',['login'],$dom);
15148:         if (ref($domconfig{'login'}) eq 'HASH') {
15149:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15150:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15151:                     $landing = 1;
15152:                 }
15153:             }
15154:         }
15155:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15156:     }
15157:     return;
15158: }
15159: 
15160: # ------------------------------------------------------------- Declutters URLs
15161: 
15162: sub declutter {
15163:     my $thisfn=shift;
15164:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15165:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15166:         $thisfn=~s{^/home/httpd/html}{};
15167:     }
15168:     $thisfn=~s/^\///;
15169:     $thisfn=~s|^adm/wrapper/||;
15170:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15171:     $thisfn=~s/^res\///;
15172:     $thisfn=~s/^priv\///;
15173:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15174:         $thisfn=~s/\?.+$//;
15175:     }
15176:     return $thisfn;
15177: }
15178: 
15179: # ------------------------------------------------------------- Clutter up URLs
15180: 
15181: sub clutter {
15182:     my $thisfn='/'.&declutter(shift);
15183:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15184: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15185:        $thisfn='/res'.$thisfn; 
15186:     }
15187:     if ($thisfn !~m|^/adm|) {
15188: 	if ($thisfn =~ m|^/ext/|) {
15189: 	    $thisfn='/adm/wrapper'.$thisfn;
15190: 	} else {
15191: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15192: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15193: 	    if ($embstyle eq 'ssi'
15194: 		|| ($embstyle eq 'hdn')
15195: 		|| ($embstyle eq 'rat')
15196: 		|| ($embstyle eq 'prv')
15197: 		|| ($embstyle eq 'ign')) {
15198: 		#do nothing with these
15199: 	    } elsif (($embstyle eq 'img') 
15200: 		|| ($embstyle eq 'emb')
15201: 		|| ($embstyle eq 'wrp')) {
15202: 		$thisfn='/adm/wrapper'.$thisfn;
15203: 	    } elsif ($embstyle eq 'unk'
15204: 		     && $thisfn!~/\.(sequence|page)$/) {
15205: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15206: 	    } else {
15207: #		&logthis("Got a blank emb style");
15208: 	    }
15209: 	}
15210:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15211:         $thisfn='/adm/wrapper'.$thisfn;
15212:     }
15213:     return $thisfn;
15214: }
15215: 
15216: sub clutter_with_no_wrapper {
15217:     my $uri = &clutter(shift);
15218:     if ($uri =~ m-^/adm/-) {
15219: 	$uri =~ s-^/adm/wrapper/-/-;
15220: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15221:     }
15222:     return $uri;
15223: }
15224: 
15225: sub freeze_escape {
15226:     my ($value)=@_;
15227:     if (ref($value)) {
15228: 	$value=&nfreeze($value);
15229: 	return '__FROZEN__'.&escape($value);
15230:     }
15231:     return &escape($value);
15232: }
15233: 
15234: 
15235: sub thaw_unescape {
15236:     my ($value)=@_;
15237:     if ($value =~ /^__FROZEN__/) {
15238: 	substr($value,0,10,undef);
15239: 	$value=&unescape($value);
15240: 	return &thaw($value);
15241:     }
15242:     return &unescape($value);
15243: }
15244: 
15245: sub correct_line_ends {
15246:     my ($result)=@_;
15247:     $$result =~s/\r\n/\n/mg;
15248:     $$result =~s/\r/\n/mg;
15249: }
15250: # ================================================================ Main Program
15251: 
15252: sub goodbye {
15253:    &logthis("Starting Shut down");
15254: #not converted to using infrastruture and probably shouldn't be
15255:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15256: #converted
15257: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15258:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15259: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15260: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15261: #1.1 only
15262: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15263: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15264: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15265: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15266:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15267:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15268:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15269:    &flushcourselogs();
15270:    &logthis("Shutting down");
15271: }
15272: 
15273: sub get_dns {
15274:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15275:     if (!$ignore_cache) {
15276: 	my ($content,$cached)=
15277: 	    &is_cached_new('dns',$url);
15278: 	if ($cached) {
15279: 	    &$func($content,$hashref);
15280: 	    return;
15281: 	}
15282:     }
15283: 
15284:     my %alldns;
15285:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15286:         foreach my $dns (<$config>) {
15287: 	    next if ($dns !~ /^\^(\S*)/x);
15288:             my $line = $1;
15289:             my ($host,$protocol) = split(/:/,$line);
15290:             if ($protocol ne 'https') {
15291:                 $protocol = 'http';
15292:             }
15293: 	    $alldns{$host} = $protocol;
15294:         }
15295:         close($config);
15296:     }
15297:     while (%alldns) {
15298: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15299:         my ($contents,@content);
15300:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15301:             my $command = (split('/',$url))[3];
15302:             my ($dir,$file) = &parse_getdns_url($command,$url);
15303:             delete($alldns{$dns});
15304:             next if (($dir eq '') || ($file eq ''));
15305:             if (open(my $config,'<',"$dir/$file")) {
15306:                 @content = <$config>;
15307:                 close($config);
15308:             }
15309:             if ($url eq '/adm/dns/loncapaCRL') {
15310:                 $contents = join('',@content);
15311:             }
15312:         } else {
15313: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15314:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15315:             delete($alldns{$dns});
15316: 	    next if ($response->is_error());
15317:             if ($url eq '/adm/dns/loncapaCRL') {
15318:                 $contents = $response->content;
15319:             } else {
15320:                 @content = split("\n",$response->content);
15321:             }
15322:         }
15323:         if ($url eq '/adm/dns/loncapaCRL') {
15324:             return &$func($contents);
15325:         } else {
15326: 	    unless ($nocache) {
15327: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15328: 	    }
15329: 	    &$func(\@content,$hashref);
15330:             return;
15331:         }
15332:     }
15333:     my $which = (split('/',$url,4))[3];
15334:     if ($which eq 'loncapaCRL') {
15335:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15336:         if (-e $diskfile) {
15337:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15338:         } else {
15339:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15340:         }
15341:     } else {
15342:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15343:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15344:             my @content = <$config>;
15345:             close($config);
15346:             &$func(\@content,$hashref);
15347:         }
15348:     }
15349:     return;
15350: }
15351: 
15352: # ------------------------------------------------------Get DNS checksums file
15353: sub parse_dns_checksums_tab {
15354:     my ($lines,$hashref) = @_;
15355:     my $lonhost = $perlvar{'lonHostID'};
15356:     my $machine_dom = &host_domain($lonhost);
15357:     my $loncaparev = &get_server_loncaparev($machine_dom);
15358:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15359:     my $webconfdir = '/etc/httpd/conf';
15360:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15361:         $webconfdir = '/etc/apache2';
15362:     } elsif ($distro =~ /^sles(\d+)$/) {
15363:         if ($1 >= 10) {
15364:             $webconfdir = '/etc/apache2';
15365:         }
15366:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15367:         if ($1 >= 10.0) {
15368:             $webconfdir = '/etc/apache2';
15369:         }
15370:     }
15371:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15372:     my (%chksum,%revnum);
15373:     if (ref($lines) eq 'ARRAY') {
15374:         chomp(@{$lines});
15375:         my $version = shift(@{$lines});
15376:         if ($version eq $release) {  
15377:             foreach my $line (@{$lines}) {
15378:                 my ($file,$version,$shasum) = split(/,/,$line);
15379:                 if ($file =~ m{^/etc/httpd/conf}) {
15380:                     if ($webconfdir eq '/etc/apache2') {
15381:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15382:                     }
15383:                 }
15384:                 $chksum{$file} = $shasum;
15385:                 $revnum{$file} = $version;
15386:             }
15387:             if (ref($hashref) eq 'HASH') {
15388:                 %{$hashref} = (
15389:                                 sums     => \%chksum,
15390:                                 versions => \%revnum,
15391:                               );
15392:             }
15393:         }
15394:     }
15395:     return;
15396: }
15397: 
15398: sub fetch_dns_checksums {
15399:     my %checksums;
15400:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15401:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15402:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15403:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15404:              \%checksums);
15405:     return \%checksums;
15406: }
15407: 
15408: sub fetch_crl_pemfile {
15409:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15410: }
15411: 
15412: sub save_crl_pem {
15413:     my ($content) = @_;
15414:     my ($msg,$hadchanges);
15415:     if ($content ne '') {
15416:         my $now = time;
15417:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15418:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15419:         if (open(my $fh,'>',"$tmpcrl")) {
15420:             print $fh $content;
15421:             close($fh);
15422:             if (-e $lonca) {
15423:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15424:                     my $check = <PIPE>;
15425:                     close(PIPE);
15426:                     chomp($check);
15427:                     if ($check eq 'verify OK') {
15428:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15429:                         my $backup;
15430:                         if (-e $dest) {
15431:                             if (&File::Copy::move($dest,"$dest.bak")) {
15432:                                 $backup = 'ok';
15433:                             }
15434:                         }
15435:                         if (&File::Copy::move($tmpcrl,$dest)) {
15436:                             $msg = 'ok';
15437:                             if ($backup) {
15438:                                 my (%oldnums,%newnums);
15439:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15440:                                     while (<PIPE>) {
15441:                                         $oldnums{(split(/:/))[1]} = 1;
15442:                                     }
15443:                                     close(PIPE);
15444:                                 }
15445:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15446:                                     while(<PIPE>) {
15447:                                         $newnums{(split(/:/))[1]} = 1;
15448:                                     }
15449:                                     close(PIPE);
15450:                                 }
15451:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15452:                                     unless (exists($oldnums{$key})) {
15453:                                         $hadchanges = 1;
15454:                                         last;
15455:                                     }
15456:                                 }
15457:                                 unless ($hadchanges) {
15458:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15459:                                         unless (exists($newnums{$key})) {
15460:                                             $hadchanges = 1;
15461:                                             last;
15462:                                         }
15463:                                     }
15464:                                 }
15465:                             }
15466:                         }
15467:                     } else {
15468:                         unlink($tmpcrl);
15469:                     }
15470:                 } else {
15471:                     unlink($tmpcrl);
15472:                 }
15473:             } else {
15474:                 unlink($tmpcrl);
15475:             }
15476:         }
15477:     }
15478:     return ($msg,$hadchanges);
15479: }
15480: 
15481: sub parse_getdns_url {
15482:     my ($command,$url) = @_;
15483:     my $dir = $perlvar{'lonTabDir'};
15484:     my $file;
15485:     if ($command eq 'hosts') {
15486:         $file = 'dns_hosts.tab';
15487:     } elsif ($command eq 'domain') {
15488:         $file = 'dns_domain.tab';
15489:     } elsif ($command eq 'checksums') {
15490:         my $version = (split('/',$url))[4];
15491:         $file = "dns_checksums/$version.tab",
15492:     } elsif ($command eq 'loncapaCRL') {
15493:         $dir = $perlvar{'lonCertificateDirectory'};
15494:         $file = $perlvar{'lonnetCertRevocationList'};
15495:     }
15496:     return ($dir,$file);
15497: }
15498: 
15499: # ------------------------------------------------------------ Read domain file
15500: {
15501:     my $loaded;
15502:     my %domain;
15503: 
15504:     sub parse_domain_tab {
15505: 	my ($lines) = @_;
15506: 	foreach my $line (@$lines) {
15507: 	    next if ($line =~ /^(\#|\s*$ )/x);
15508: 
15509: 	    chomp($line);
15510: 	    my ($name,@elements) = split(/:/,$line,9);
15511: 	    my %this_domain;
15512: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15513: 			       'lang_def', 'city', 'longi', 'lati',
15514: 			       'primary') {
15515: 		$this_domain{$field} = shift(@elements);
15516: 	    }
15517: 	    $domain{$name} = \%this_domain;
15518: 	}
15519:     }
15520: 
15521:     sub reset_domain_info {
15522: 	undef($loaded);
15523: 	undef(%domain);
15524:     }
15525: 
15526:     sub load_domain_tab {
15527: 	my ($ignore_cache,$nocache) = @_;
15528: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15529: 	my $fh;
15530: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15531: 	    my @lines = <$fh>;
15532: 	    &parse_domain_tab(\@lines);
15533: 	}
15534: 	close($fh);
15535: 	$loaded = 1;
15536:     }
15537: 
15538:     sub domain {
15539: 	&load_domain_tab() if (!$loaded);
15540: 
15541: 	my ($name,$what) = @_;
15542: 	return if ( !exists($domain{$name}) );
15543: 
15544: 	if (!$what) {
15545: 	    return $domain{$name}{'description'};
15546: 	}
15547: 	return $domain{$name}{$what};
15548:     }
15549: 
15550:     sub domain_info {
15551:         &load_domain_tab() if (!$loaded);
15552:         return %domain;
15553:     }
15554: 
15555: }
15556: 
15557: 
15558: # ------------------------------------------------------------- Read hosts file
15559: {
15560:     my %hostname;
15561:     my %hostdom;
15562:     my %libserv;
15563:     my $loaded;
15564:     my %name_to_host;
15565:     my %internetdom;
15566:     my %LC_dns_serv;
15567: 
15568:     sub parse_hosts_tab {
15569: 	my ($file) = @_;
15570: 	foreach my $configline (@$file) {
15571: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15572:             chomp($configline);
15573: 	    if ($configline =~ /^\^/) {
15574:                 if ($configline =~ /^\^([\w.\-]+)/) {
15575:                     $LC_dns_serv{$1} = 1;
15576:                 }
15577:                 next;
15578:             }
15579: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15580: 	    $name=~s/\s//g;
15581: 	    if ($id && $domain && $role && $name) {
15582:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15583:                     my $curr = $hostname{$id};
15584:                     my $skip;
15585:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15586:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15587:                             $skip = 1;
15588:                         } else {
15589:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15590:                         }
15591:                     }
15592:                     unless ($skip) {
15593:                         push(@{$name_to_host{$name}},$id);
15594:                     }
15595:                 } else {
15596:                     push(@{$name_to_host{$name}},$id);
15597:                 }
15598: 		$hostname{$id}=$name;
15599: 		$hostdom{$id}=$domain;
15600: 		if ($role eq 'library') { $libserv{$id}=$name; }
15601:                 if (defined($protocol)) {
15602:                     if ($protocol eq 'https') {
15603:                         $protocol{$id} = $protocol;
15604:                     } else {
15605:                         $protocol{$id} = 'http'; 
15606:                     }
15607:                 } else {
15608:                     $protocol{$id} = 'http';
15609:                 }
15610:                 if (defined($intdom)) {
15611:                     $internetdom{$id} = $intdom;
15612:                 }
15613: 	    }
15614: 	}
15615:     }
15616:     
15617:     sub reset_hosts_info {
15618: 	&purge_remembered();
15619: 	&reset_domain_info();
15620: 	&reset_hosts_ip_info();
15621:         undef(%internetdom);
15622: 	undef(%name_to_host);
15623: 	undef(%hostname);
15624: 	undef(%hostdom);
15625: 	undef(%libserv);
15626: 	undef($loaded);
15627:     }
15628: 
15629:     sub load_hosts_tab {
15630: 	my ($ignore_cache,$nocache) = @_;
15631: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15632: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15633: 	my @config = <$config>;
15634: 	&parse_hosts_tab(\@config);
15635: 	close($config);
15636: 	$loaded=1;
15637:     }
15638: 
15639:     sub hostname {
15640: 	&load_hosts_tab() if (!$loaded);
15641: 
15642: 	my ($lonid) = @_;
15643: 	return $hostname{$lonid};
15644:     }
15645: 
15646:     sub all_hostnames {
15647: 	&load_hosts_tab() if (!$loaded);
15648: 
15649: 	return %hostname;
15650:     }
15651: 
15652:     sub all_names {
15653:         my ($ignore_cache,$nocache) = @_;
15654: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15655: 
15656: 	return %name_to_host;
15657:     }
15658: 
15659:     sub all_host_domain {
15660:         &load_hosts_tab() if (!$loaded);
15661:         return %hostdom;
15662:     }
15663: 
15664:     sub all_host_intdom {
15665:         &load_hosts_tab() if (!$loaded);
15666:         return %internetdom;
15667:     }
15668: 
15669:     sub is_library {
15670: 	&load_hosts_tab() if (!$loaded);
15671: 
15672: 	return exists($libserv{$_[0]});
15673:     }
15674: 
15675:     sub all_library {
15676: 	&load_hosts_tab() if (!$loaded);
15677: 
15678: 	return %libserv;
15679:     }
15680: 
15681:     sub unique_library {
15682: 	#2x reverse removes all hostnames that appear more than once
15683:         my %unique = reverse &all_library();
15684:         return reverse %unique;
15685:     }
15686: 
15687:     sub get_servers {
15688: 	&load_hosts_tab() if (!$loaded);
15689: 
15690: 	my ($domain,$type) = @_;
15691: 	my %possible_hosts = ($type eq 'library') ? %libserv
15692: 	                                          : %hostname;
15693: 	my %result;
15694: 	if (ref($domain) eq 'ARRAY') {
15695: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15696: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15697: 		    $result{$host} = $hostname;
15698: 		}
15699: 	    }
15700: 	} else {
15701: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15702: 		if ($hostdom{$host} eq $domain) {
15703: 		    $result{$host} = $hostname;
15704: 		}
15705: 	    }
15706: 	}
15707: 	return %result;
15708:     }
15709: 
15710:     sub get_unique_servers {
15711:         my %unique = reverse &get_servers(@_);
15712: 	return reverse %unique;
15713:     }
15714: 
15715:     sub host_domain {
15716: 	&load_hosts_tab() if (!$loaded);
15717: 
15718: 	my ($lonid) = @_;
15719: 	return $hostdom{$lonid};
15720:     }
15721: 
15722:     sub all_domains {
15723: 	&load_hosts_tab() if (!$loaded);
15724: 
15725: 	my %seen;
15726: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15727: 	return @uniq;
15728:     }
15729: 
15730:     sub internet_dom {
15731:         &load_hosts_tab() if (!$loaded);
15732: 
15733:         my ($lonid) = @_;
15734:         return $internetdom{$lonid};
15735:     }
15736: 
15737:     sub is_LC_dns {
15738:         &load_hosts_tab() if (!$loaded);
15739: 
15740:         my ($hostname) = @_;
15741:         return exists($LC_dns_serv{$hostname});
15742:     }
15743: 
15744: }
15745: 
15746: { 
15747:     my %iphost;
15748:     my %name_to_ip;
15749:     my %lonid_to_ip;
15750: 
15751:     sub get_hosts_from_ip {
15752: 	my ($ip) = @_;
15753: 	my %iphosts = &get_iphost();
15754: 	if (ref($iphosts{$ip})) {
15755: 	    return @{$iphosts{$ip}};
15756: 	}
15757: 	return;
15758:     }
15759:     
15760:     sub reset_hosts_ip_info {
15761: 	undef(%iphost);
15762: 	undef(%name_to_ip);
15763: 	undef(%lonid_to_ip);
15764:     }
15765: 
15766:     sub get_host_ip {
15767: 	my ($lonid) = @_;
15768: 	if (exists($lonid_to_ip{$lonid})) {
15769: 	    return $lonid_to_ip{$lonid};
15770: 	}
15771: 	my $name=&hostname($lonid);
15772:    	my $ip = gethostbyname($name);
15773: 	return if (!$ip || length($ip) ne 4);
15774: 	$ip=inet_ntoa($ip);
15775: 	$name_to_ip{$name}   = $ip;
15776: 	$lonid_to_ip{$lonid} = $ip;
15777: 	return $ip;
15778:     }
15779:     
15780:     sub get_iphost {
15781: 	my ($ignore_cache,$nocache) = @_;
15782: 
15783: 	if (!$ignore_cache) {
15784: 	    if (%iphost) {
15785: 		return %iphost;
15786: 	    }
15787: 	    my ($ip_info,$cached)=
15788: 		&is_cached_new('iphost','iphost');
15789: 	    if ($cached) {
15790: 		%iphost      = %{$ip_info->[0]};
15791: 		%name_to_ip  = %{$ip_info->[1]};
15792: 		%lonid_to_ip = %{$ip_info->[2]};
15793: 		return %iphost;
15794: 	    }
15795: 	}
15796: 
15797: 	# get yesterday's info for fallback
15798: 	my %old_name_to_ip;
15799: 	my ($ip_info,$cached)=
15800: 	    &is_cached_new('iphost','iphost');
15801: 	if ($cached) {
15802: 	    %old_name_to_ip = %{$ip_info->[1]};
15803: 	}
15804: 
15805: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15806: 	foreach my $name (keys(%name_to_host)) {
15807: 	    my $ip;
15808: 	    if (!exists($name_to_ip{$name})) {
15809: 		$ip = gethostbyname($name);
15810: 		if (!$ip || length($ip) ne 4) {
15811: 		    if (defined($old_name_to_ip{$name})) {
15812: 			$ip = $old_name_to_ip{$name};
15813: 			&logthis("Can't find $name defaulting to old $ip");
15814: 		    } else {
15815: 			&logthis("Name $name no IP found");
15816: 			next;
15817: 		    }
15818: 		} else {
15819: 		    $ip=inet_ntoa($ip);
15820: 		}
15821: 		$name_to_ip{$name} = $ip;
15822: 	    } else {
15823: 		$ip = $name_to_ip{$name};
15824: 	    }
15825: 	    foreach my $id (@{ $name_to_host{$name} }) {
15826: 		$lonid_to_ip{$id} = $ip;
15827: 	    }
15828: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15829: 	}
15830:         unless ($nocache) {
15831: 	    &do_cache_new('iphost','iphost',
15832: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15833: 		          48*60*60);
15834:         }
15835: 
15836: 	return %iphost;
15837:     }
15838: 
15839:     #
15840:     #  Given a DNS returns the loncapa host name for that DNS 
15841:     # 
15842:     sub host_from_dns {
15843:         my ($dns) = @_;
15844:         my @hosts;
15845:         my $ip;
15846: 
15847:         if (exists($name_to_ip{$dns})) {
15848:             $ip = $name_to_ip{$dns};
15849:         }
15850:         if (!$ip) {
15851:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15852:             if (length($ip) == 4) { 
15853: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15854:             }
15855:         }
15856:         if ($ip) {
15857: 	    @hosts = get_hosts_from_ip($ip);
15858: 	    return $hosts[0];
15859:         }
15860:         return undef;
15861:     }
15862: 
15863:     sub get_internet_names {
15864:         my ($lonid) = @_;
15865:         return if ($lonid eq '');
15866:         my ($idnref,$cached)=
15867:             &is_cached_new('internetnames',$lonid);
15868:         if ($cached) {
15869:             return $idnref;
15870:         }
15871:         my $ip = &get_host_ip($lonid);
15872:         my @hosts = &get_hosts_from_ip($ip);
15873:         my %iphost = &get_iphost();
15874:         my (@idns,%seen);
15875:         foreach my $id (@hosts) {
15876:             my $dom = &host_domain($id);
15877:             my $prim_id = &domain($dom,'primary');
15878:             my $prim_ip = &get_host_ip($prim_id);
15879:             next if ($seen{$prim_ip});
15880:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15881:                 foreach my $id (@{$iphost{$prim_ip}}) {
15882:                     my $intdom = &internet_dom($id);
15883:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15884:                         push(@idns,$intdom);
15885:                     }
15886:                 }
15887:             }
15888:             $seen{$prim_ip} = 1;
15889:         }
15890:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15891:     }
15892: 
15893: }
15894: 
15895: sub all_loncaparevs {
15896:     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);
15897: }
15898: 
15899: # ---------------------------------------------------------- Read loncaparev table
15900: {
15901:     sub load_loncaparevs { 
15902:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15903:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15904:                 while (my $configline=<$config>) {
15905:                     chomp($configline);
15906:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15907:                     $loncaparevs{$hostid}=$loncaparev;
15908:                 }
15909:                 close($config);
15910:             }
15911:         }
15912:     }
15913: }
15914: 
15915: # ---------------------------------------------------------- Read serverhostID table
15916: {
15917:     sub load_serverhomeIDs {
15918:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15919:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15920:                 while (my $configline=<$config>) {
15921:                     chomp($configline);
15922:                     my ($name,$id)=split(/:/,$configline);
15923:                     $serverhomeIDs{$name}=$id;
15924:                 }
15925:                 close($config);
15926:             }
15927:         }
15928:     }
15929: }
15930: 
15931: 
15932: BEGIN {
15933: 
15934: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15935:     unless ($readit) {
15936: {
15937:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15938:     %perlvar = (%perlvar,%{$configvars});
15939: }
15940: 
15941: 
15942: # ------------------------------------------------------ Read spare server file
15943: {
15944:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15945: 
15946:     while (my $configline=<$config>) {
15947:        chomp($configline);
15948:        if ($configline) {
15949: 	   my ($host,$type) = split(':',$configline,2);
15950: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15951: 	   push(@{ $spareid{$type} }, $host);
15952:        }
15953:     }
15954:     close($config);
15955: }
15956: # ------------------------------------------------------------ Read permissions
15957: {
15958:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15959: 
15960:     while (my $configline=<$config>) {
15961: 	chomp($configline);
15962: 	if ($configline) {
15963: 	    my ($role,$perm)=split(/ /,$configline);
15964: 	    if ($perm ne '') { $pr{$role}=$perm; }
15965: 	}
15966:     }
15967:     close($config);
15968: }
15969: 
15970: # -------------------------------------------- Read plain texts for permissions
15971: {
15972:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15973: 
15974:     while (my $configline=<$config>) {
15975: 	chomp($configline);
15976: 	if ($configline) {
15977: 	    my ($short,@plain)=split(/:/,$configline);
15978:             %{$prp{$short}} = ();
15979: 	    if (@plain > 0) {
15980:                 $prp{$short}{'std'} = $plain[0];
15981:                 for (my $i=1; $i<@plain; $i++) {
15982:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15983:                 }
15984:             }
15985: 	}
15986:     }
15987:     close($config);
15988: }
15989: 
15990: # ---------------------------------------------------------- Read package table
15991: {
15992:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15993: 
15994:     while (my $configline=<$config>) {
15995: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15996: 	chomp($configline);
15997: 	my ($short,$plain)=split(/:/,$configline);
15998: 	my ($pack,$name)=split(/\&/,$short);
15999: 	if ($plain ne '') {
16000: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16001: 	    $packagetab{$short}=$plain; 
16002: 	}
16003:     }
16004:     close($config);
16005: }
16006: 
16007: # ---------------------------------------------------------- Read loncaparev table
16008: 
16009: &load_loncaparevs();
16010: 
16011: # ---------------------------------------------------------- Read serverhostID table
16012: 
16013: &load_serverhomeIDs();
16014: 
16015: # ---------------------------------------------------------- Read releaseslist XML
16016: {
16017:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16018:     if (-e $file) {
16019:         my $parser = HTML::LCParser->new($file);
16020:         while (my $token = $parser->get_token()) {
16021:             if ($token->[0] eq 'S') {
16022:                 my $item = $token->[1];
16023:                 my $name = $token->[2]{'name'};
16024:                 my $value = $token->[2]{'value'};
16025:                 my $valuematch = $token->[2]{'valuematch'};
16026:                 my $namematch = $token->[2]{'namematch'};
16027:                 if ($item eq 'parameter') {
16028:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16029:                         my $release = $parser->get_text();
16030:                         $release =~ s/(^\s*|\s*$ )//gx;
16031:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16032:                     }
16033:                 } elsif ($item ne '' && $name ne '') {
16034:                     my $release = $parser->get_text();
16035:                     $release =~ s/(^\s*|\s*$ )//gx;
16036:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16037:                 }
16038:             }
16039:         }
16040:     }
16041: }
16042: 
16043: # ---------------------------------------------------------- Read managers table
16044: {
16045:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16046:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16047:             while (my $configline=<$config>) {
16048:                 chomp($configline);
16049:                 next if ($configline =~ /^\#/);
16050:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16051:                     $managerstab{$configline} = 1;
16052:                 }
16053:             }
16054:             close($config);
16055:         }
16056:     }
16057: }
16058: 
16059: # ------------- set up temporary directory
16060: {
16061:     $tmpdir = LONCAPA::tempdir();
16062: 
16063: }
16064: 
16065: # ------------- set default texengine (domain default overrides this)
16066: {
16067:     $deftex = LONCAPA::texengine();
16068: }
16069: 
16070: # ------------- set default minimum length for passwords for internal auth users
16071: {
16072:     $passwdmin = LONCAPA::passwd_min();
16073: }
16074: 
16075: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16076: 				'compress_threshold'=> 20_000,
16077:  			        });
16078: 
16079: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16080: $dumpcount=0;
16081: $locknum=0;
16082: 
16083: &logtouch();
16084: &logthis('<font color="yellow">INFO: Read configuration</font>');
16085: $readit=1;
16086:     {
16087: 	use integer;
16088: 	my $test=(2**32)+1;
16089: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16090: 	&logthis(" Detected 64bit platform ($_64bit)");
16091:     }
16092: }
16093: }
16094: 
16095: 1;
16096: __END__
16097: 
16098: =pod
16099: 
16100: =head1 NAME
16101: 
16102: Apache::lonnet - Subroutines to ask questions about things in the network.
16103: 
16104: =head1 SYNOPSIS
16105: 
16106: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16107: 
16108:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16109: 
16110: Common parameters:
16111: 
16112: =over 4
16113: 
16114: =item *
16115: 
16116: $uname : an internal username (if $cname expecting a course Id specifically)
16117: 
16118: =item *
16119: 
16120: $udom : a domain (if $cdom expecting a course's domain specifically)
16121: 
16122: =item *
16123: 
16124: $symb : a resource instance identifier
16125: 
16126: =item *
16127: 
16128: $namespace : the name of a .db file that contains the data needed or
16129: being set.
16130: 
16131: =back
16132: 
16133: =head1 OVERVIEW
16134: 
16135: lonnet provides subroutines which interact with the
16136: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16137: about classes, users, and resources.
16138: 
16139: For many of these objects you can also use this to store data about
16140: them or modify them in various ways.
16141: 
16142: =head2 Symbs
16143: 
16144: To identify a specific instance of a resource, LON-CAPA uses symbols
16145: or "symbs"X<symb>. These identifiers are built from the URL of the
16146: map, the resource number of the resource in the map, and the URL of
16147: the resource itself. The latter is somewhat redundant, but might help
16148: if maps change.
16149: 
16150: An example is
16151: 
16152:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16153: 
16154: The respective map entry is
16155: 
16156:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16157:   title="Problem 2">
16158:  </resource>
16159: 
16160: Symbs are used by the random number generator, as well as to store and
16161: restore data specific to a certain instance of for example a problem.
16162: 
16163: =head2 Storing And Retrieving Data
16164: 
16165: X<store()>X<cstore()>X<restore()>Three of the most important functions
16166: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16167: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16168: is is the non-critical message twin of cstore. These functions are for
16169: handlers to store a perl hash to a user's permanent data space in an
16170: easy manner, and to retrieve it again on another call. It is expected
16171: that a handler would use this once at the beginning to retrieve data,
16172: and then again once at the end to send only the new data back.
16173: 
16174: The data is stored in the user's data directory on the user's
16175: homeserver under the ID of the course.
16176: 
16177: The hash that is returned by restore will have all of the previous
16178: value for all of the elements of the hash.
16179: 
16180: Example:
16181: 
16182:  #creating a hash
16183:  my %hash;
16184:  $hash{'foo'}='bar';
16185: 
16186:  #storing it
16187:  &Apache::lonnet::cstore(\%hash);
16188: 
16189:  #changing a value
16190:  $hash{'foo'}='notbar';
16191: 
16192:  #adding a new value
16193:  $hash{'bar'}='foo';
16194:  &Apache::lonnet::cstore(\%hash);
16195: 
16196:  #retrieving the hash
16197:  my %history=&Apache::lonnet::restore();
16198: 
16199:  #print the hash
16200:  foreach my $key (sort(keys(%history))) {
16201:    print("\%history{$key} = $history{$key}");
16202:  }
16203: 
16204: Will print out:
16205: 
16206:  %history{1:foo} = bar
16207:  %history{1:keys} = foo:timestamp
16208:  %history{1:timestamp} = 990455579
16209:  %history{2:bar} = foo
16210:  %history{2:foo} = notbar
16211:  %history{2:keys} = foo:bar:timestamp
16212:  %history{2:timestamp} = 990455580
16213:  %history{bar} = foo
16214:  %history{foo} = notbar
16215:  %history{timestamp} = 990455580
16216:  %history{version} = 2
16217: 
16218: Note that the special hash entries C<keys>, C<version> and
16219: C<timestamp> were added to the hash. C<version> will be equal to the
16220: total number of versions of the data that have been stored. The
16221: C<timestamp> attribute will be the UNIX time the hash was
16222: stored. C<keys> is available in every historical section to list which
16223: keys were added or changed at a specific historical revision of a
16224: hash.
16225: 
16226: B<Warning>: do not store the hash that restore returns directly. This
16227: will cause a mess since it will restore the historical keys as if the
16228: were new keys. I.E. 1:foo will become 1:1:foo etc.
16229: 
16230: Calling convention:
16231: 
16232:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16233:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16234: 
16235: For more detailed information, see lonnet specific documentation.
16236: 
16237: =head1 RETURN MESSAGES
16238: 
16239: =over 4
16240: 
16241: =item * B<con_lost>: unable to contact remote host
16242: 
16243: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16244: when the connection is brought back up
16245: 
16246: =item * B<con_failed>: unable to contact remote host and unable to save message
16247: for later delivery
16248: 
16249: =item * B<error:>: an error a occurred, a description of the error follows the :
16250: 
16251: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16252: that was requested
16253: 
16254: =back
16255: 
16256: =head1 PUBLIC SUBROUTINES
16257: 
16258: =head2 Session Environment Functions
16259: 
16260: =over 4
16261: 
16262: =item * 
16263: X<appenv()>
16264: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16265: the user envirnoment file, and will be restored for each access this
16266: user makes during this session, also modifies the %env for the current
16267: process. Optional rolesarrayref - if defined contains a reference to an array
16268: of roles which are exempt from the restriction on modifying user.role entries 
16269: in the user's environment.db and in %env.    
16270: 
16271: =item *
16272: X<delenv()>
16273: B<delenv($delthis,$regexp)>: removes all items from the session
16274: environment file that begin with $delthis. If the 
16275: optional second arg - $regexp - is true, $delthis is treated as a 
16276: regular expression, otherwise \Q$delthis\E is used. 
16277: The values are also deleted from the current processes %env.
16278: 
16279: =item * get_env_multiple($name) 
16280: 
16281: gets $name from the %env hash, it seemlessly handles the cases where multiple
16282: values may be defined and end up as an array ref.
16283: 
16284: returns an array of values
16285: 
16286: =back
16287: 
16288: =head2 User Information
16289: 
16290: =over 4
16291: 
16292: =item *
16293: X<queryauthenticate()>
16294: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16295: authentication scheme
16296: 
16297: =item *
16298: X<authenticate()>
16299: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16300: authenticate user from domain's lib servers (first use the current
16301: one). C<$upass> should be the users password.
16302: $checkdefauth is optional (value is 1 if a check should be made to
16303:    authenticate user using default authentication method, and allow
16304:    account creation if username does not have account in the domain).
16305: $clientcancheckhost is optional (value is 1 if checking whether the
16306:    server can host will occur on the client side in lonauth.pm).   
16307: 
16308: =item *
16309: X<homeserver()>
16310: B<homeserver($uname,$udom)>: find the server which has
16311: the user's directory and files (there must be only one), this caches
16312: the answer, and also caches if there is a borken connection.
16313: 
16314: =item *
16315: X<idget()>
16316: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16317: a list of student/employee IDs or clicker IDs
16318: (student/employee IDs are a unique resource in a domain, there must be 
16319: only 1 ID per username, and only 1 username per ID in a specific domain).
16320: clickerIDs are not necessarily unique, as students might share clickers.
16321: (returns hash: id=>name,id=>name)
16322: 
16323: =item *
16324: X<idrget()>
16325: B<idrget($udom,@unames)>: find the IDs behind a list of
16326: usernames (returns hash: name=>id,name=>id)
16327: 
16328: =item *
16329: X<idput()>
16330: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16331: names and associated student/employee IDs or clicker IDs.
16332: 
16333: =item *
16334: X<iddel()>
16335: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16336: student/employee ID or clicker ID username look-ups from domain.
16337: The homeserver ($uhome) and namespace ($namespace) are optional.
16338: If no $uhome is provided, it will be determined usig &homeserver()
16339: for each user.  If no $namespace is provided, the default is ids.
16340: 
16341: =item *
16342: X<updateclickers()>
16343: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16344: clicker ID-to-username look-ups in clickers.db on library server.
16345: Permitted actions are add or del (i.e., add or delete). The 
16346: clickers.db contains clickerID as keys (escaped), and each corresponding
16347: value is an escaped comma-separated list of usernames (for whom the
16348: library server is the homeserver), who registered that particular ID.
16349: If $critical is true, the update will be sent via &critical, otherwise
16350: &reply() will be used.
16351: 
16352: =item *
16353: X<rolesinit()>
16354: B<rolesinit($udom,$username)>: get user privileges.
16355: returns user role, first access and timer interval hashes
16356: 
16357: =item *
16358: X<privileged()>
16359: B<privileged($username,$domain)>: returns a true if user has a
16360: privileged and active role (i.e. su or dc), false otherwise.
16361: 
16362: =item *
16363: X<getsection()>
16364: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16365: course $cname, return section name/number or '' for "not in course"
16366: and '-1' for "no section"
16367: 
16368: =item *
16369: X<userenvironment()>
16370: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16371: passed in @what from the requested user's environment, returns a hash
16372: 
16373: =item * 
16374: X<userlog_query()>
16375: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16376: activity.log file. %filters defines filters applied when parsing the
16377: log file. These can be start or end timestamps, or the type of action
16378: - log to look for Login or Logout events, check for Checkin or
16379: Checkout, role for role selection. The response is in the form
16380: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16381: escaped strings of the action recorded in the activity.log file.
16382: 
16383: =back
16384: 
16385: =head2 User Roles
16386: 
16387: =over 4
16388: 
16389: =item *
16390: 
16391: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16392: returns codes for allowed actions.
16393: 
16394: The first argument is required, all others are optional.
16395: 
16396: $priv is the privilege being checked.
16397: $uri contains additional information about what is being checked for access (e.g.,
16398: URL, course ID etc.). 
16399: $symb is the unique resource instance identifier in a course; if needed,
16400: but not provided, it will be retrieved via a call to &symbread(). 
16401: $role is the role for which a priv is being checked (only used if priv is evb). 
16402: $clientip is the user's IP address (only used when checking for access to portfolio 
16403: files).
16404: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16405: prevents recursive calls to &allowed.
16406: 
16407:  F: full access
16408:  U,I,K: authentication modes (cxx only)
16409:  '': forbidden
16410:  1: user needs to choose course
16411:  2: browse allowed
16412:  A: passphrase authentication needed
16413:  B: access temporarily blocked because of a blocking event in a course.
16414:  D: access blocked because access is required via session initiated via deep-link 
16415: 
16416: =item *
16417: 
16418: constructaccess($url,$setpriv) : check for access to construction space URL
16419: 
16420: See if the owner domain and name in the URL match those in the
16421: expected environment.  If so, return three element list
16422: ($ownername,$ownerdomain,$ownerhome).
16423: 
16424: Otherwise return the null string.
16425: 
16426: If second argument 'setpriv' is true, it assigns the privileges,
16427: and returns the same three element list, unless the owner has
16428: blocked "ad hoc" Domain Coordinator access to the Author Space,
16429: in which case the null string is returned.
16430: 
16431: =item *
16432: 
16433: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16434: define a custom role rolename set privileges in format of lonTabs/roles.tab
16435: for system, domain, and course level. $uname and $udom are optional (current
16436: user's username and domain will be used when either of $uname or $udom are absent.
16437: 
16438: =item *
16439: 
16440: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16441: (rolesplain.tab); plain text explanation of a user role term.
16442: $type is Course (default) or Community.
16443: If $forcedefault evaluates to true, text returned will be default 
16444: text for $type. Otherwise, if this is a course, the text returned 
16445: will be a custom name for the role (if defined in the course's 
16446: environment).  If no custom name is defined the default is returned.
16447:    
16448: =item *
16449: 
16450: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16451: All arguments are optional. Returns a hash of a roles, either for
16452: co-author/assistant author roles for a user's Construction Space
16453: (default), or if $context is 'userroles', roles for the user himself,
16454: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16455: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16456: For each key, value is set to colon-separated start and end times for
16457: the role.  If no username and domain are specified, will default to
16458: current user/domain. Types, roles, and roledoms are references to arrays
16459: of role statuses (active, future or previous), roles 
16460: (e.g., cc,in, st etc.) and domains of the roles which can be used
16461: to restrict the list of roles reported. If no array ref is 
16462: provided for types, will default to return only active roles.
16463: 
16464: =item *
16465: 
16466: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16467: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16468: 
16469: Additional optional arguments are: $type (if role checking is to be restricted 
16470: to certain user status types -- previous (expired roles), active (currently
16471: available roles) or future (roles available in the future), and
16472: $hideprivileged -- if true will not report course roles for users who
16473: have active Domain Coordinator role in course's domain or in additional
16474: domains (specified in 'Domains to check for privileged users' in course
16475: environment -- set via:  Course Settings -> Classlists and staff listing).
16476: 
16477: =item *
16478: 
16479: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16480: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16481: $possdomains and $possroles are optional array refs -- to domains to check and
16482: roles to check.  If $possdomains is not specified, a dump will be done of the
16483: users' roles.db to check for a dc or su role in any domain. This can be
16484: time consuming if &privileged is called repeatedly (e.g., when displaying a
16485: classlist), so in such cases, supplying a $possdomains array is preferred, as
16486: this then allows &privileged_by_domain() to be used, which caches the identity
16487: of privileged users, eliminating the need for repeated calls to &dump().
16488: 
16489: =item *
16490: 
16491: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16492: where the outer hash keys are domains specified in the $possdomains array ref,
16493: next inner hash keys are privileged roles specified in the $roles array ref,
16494: and the innermost hash contains key = value pairs for username:domain = end:start
16495: for active or future "privileged" users with that role in that domain. To avoid
16496: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16497: innerhash are cached using priv_$role and $dom as the identifiers.
16498: 
16499: =back
16500: 
16501: =head2 User Modification
16502: 
16503: =over 4
16504: 
16505: =item *
16506: 
16507: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16508: user for the level given by URL.  Optional start and end dates (leave empty
16509: string or zero for "no date")
16510: 
16511: =item *
16512: 
16513: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16514: change a users, password, possible return values are: ok,
16515: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16516: refused
16517: 
16518: =item *
16519: 
16520: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16521: 
16522: =item *
16523: 
16524: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16525:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16526: 
16527: will update user information (firstname,middlename,lastname,generation,
16528: permanentemail), and if forceid is true, student/employee ID also.
16529: A user's institutional affiliation(s) can also be updated.
16530: User information fields will not be overwritten with empty entries 
16531: unless the field is included in the $candelete array reference.
16532: This array is included when a single user is modified via "Manage Users",
16533: or when Autoupdate.pl is run by cron in a domain.
16534: 
16535: =item *
16536: 
16537: modifystudent
16538: 
16539: modify a student's enrollment and identification information.
16540: The course id is resolved based on the current user's environment.  
16541: This means the invoking user must be a course coordinator or otherwise
16542: associated with a course.
16543: 
16544: This call is essentially a wrapper for lonnet::modifyuser and
16545: lonnet::modify_student_enrollment
16546: 
16547: Inputs: 
16548: 
16549: =over 4
16550: 
16551: =item B<$udom> Student's loncapa domain
16552: 
16553: =item B<$uname> Student's loncapa login name
16554: 
16555: =item B<$uid> Student/Employee ID
16556: 
16557: =item B<$umode> Student's authentication mode
16558: 
16559: =item B<$upass> Student's password
16560: 
16561: =item B<$first> Student's first name
16562: 
16563: =item B<$middle> Student's middle name
16564: 
16565: =item B<$last> Student's last name
16566: 
16567: =item B<$gene> Student's generation
16568: 
16569: =item B<$usec> Student's section in course
16570: 
16571: =item B<$end> Unix time of the roles expiration
16572: 
16573: =item B<$start> Unix time of the roles start date
16574: 
16575: =item B<$forceid> If defined, allow $uid to be changed
16576: 
16577: =item B<$desiredhome> server to use as home server for student
16578: 
16579: =item B<$email> Student's permanent e-mail address
16580: 
16581: =item B<$type> Type of enrollment (auto or manual)
16582: 
16583: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16584: 
16585: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16586: 
16587: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16588: 
16589: =item B<$context> role change context (shown in User Management Logs display in a course)
16590: 
16591: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16592: 
16593: =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.
16594: 
16595: =back
16596: 
16597: =item *
16598: 
16599: modify_student_enrollment
16600: 
16601: Change a student's enrollment status in a class.  The environment variable
16602: 'role.request.course' must be defined for this function to proceed.
16603: 
16604: Inputs:
16605: 
16606: =over 4
16607: 
16608: =item $udom, student's domain
16609: 
16610: =item $uname, student's name
16611: 
16612: =item $uid, student's user id
16613: 
16614: =item $first, student's first name
16615: 
16616: =item $middle
16617: 
16618: =item $last
16619: 
16620: =item $gene
16621: 
16622: =item $usec
16623: 
16624: =item $end
16625: 
16626: =item $start
16627: 
16628: =item $type
16629: 
16630: =item $locktype
16631: 
16632: =item $cid
16633: 
16634: =item $selfenroll
16635: 
16636: =item $context
16637: 
16638: =item $credits, number of credits student will earn from this class
16639: 
16640: =item $instsec, institutional course section code for student
16641: 
16642: =back
16643: 
16644: 
16645: =item *
16646: 
16647: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16648: custom role; give a custom role to a user for the level given by URL.  Specify
16649: name and domain of role author, and role name
16650: 
16651: =item *
16652: 
16653: revokerole($udom,$uname,$url,$role) : revoke a role for url
16654: 
16655: =item *
16656: 
16657: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16658: 
16659: =back
16660: 
16661: =head2 Course Infomation
16662: 
16663: =over 4
16664: 
16665: =item *
16666: 
16667: coursedescription($courseid,$options) : returns a hash of information about the
16668: specified course id, including all environment settings for the
16669: course, the description of the course will be in the hash under the
16670: key 'description'
16671: 
16672: $options is an optional parameter that if supplied is a hash reference that controls
16673: what how this function works.  It has the following key/values:
16674: 
16675: =over 4
16676: 
16677: =item freshen_cache
16678: 
16679: If defined, and the environment cache for the course is valid, it is 
16680: returned in the returned hash.
16681: 
16682: =item one_time
16683: 
16684: If defined, the last cache time is set to _now_
16685: 
16686: =item user
16687: 
16688: If defined, the supplied username is used instead of the current user.
16689: 
16690: 
16691: =back
16692: 
16693: =item *
16694: 
16695: resdata($name,$domain,$type,@which) : request for current parameter
16696: setting for a specific $type, where $type is either 'course' or 'user',
16697: @what should be a list of parameters to ask about. This routine caches
16698: answers for 10 minutes.
16699: 
16700: =item *
16701: 
16702: get_courseresdata($courseid, $domain) : dump the entire course resource
16703: data base, returning a hash that is keyed by the resource name and has
16704: values that are the resource value.  I believe that the timestamps and
16705: versions are also returned.
16706: 
16707: =back
16708: 
16709: =head2 Course Modification
16710: 
16711: =over 4
16712: 
16713: =item *
16714: 
16715: writecoursepref($courseid,%prefs) : write preferences (environment
16716: database) for a course
16717: 
16718: =item *
16719: 
16720: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16721: 
16722: =item *
16723: 
16724: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16725: 
16726: =item *
16727: 
16728: is_course($courseid), is_course($cdom, $cnum)
16729: 
16730: Accepts either a combined $courseid (in the form of domain_courseid) or the
16731: two component version $cdom, $cnum. It checks if the specified course exists.
16732: 
16733: Returns:
16734:     undef if the course doesn't exist, otherwise
16735:     in scalar context the combined courseid.
16736:     in list context the two components of the course identifier, domain and 
16737:     courseid.    
16738: 
16739: =back
16740: 
16741: =head2 Bubblesheet Configuration
16742: 
16743: =over 4
16744: 
16745: =item *
16746: 
16747: get_scantron_config($which)
16748: 
16749: $which - the name of the configuration to parse from the file.
16750: 
16751: Parses and returns the bubblesheet configuration line selected as a
16752: hash of configuration file fields.
16753: 
16754: 
16755: Returns:
16756:     If the named configuration is not in the file, an empty
16757:     hash is returned.
16758: 
16759:     a hash with the fields
16760:       name         - internal name for the this configuration setup
16761:       description  - text to display to operator that describes this config
16762:       CODElocation - if 0 or the string 'none'
16763:                           - no CODE exists for this config
16764:                      if -1 || the string 'letter'
16765:                           - a CODE exists for this config and is
16766:                             a string of letters
16767:                      Unsupported value (but planned for future support)
16768:                           if a positive integer
16769:                                - The CODE exists as the first n items from
16770:                                  the question section of the form
16771:                           if the string 'number'
16772:                                - The CODE exists for this config and is
16773:                                  a string of numbers
16774:       CODEstart   - (only matter if a CODE exists) column in the line where
16775:                      the CODE starts
16776:       CODElength  - length of the CODE
16777:       IDstart     - column where the student/employee ID starts
16778:       IDlength    - length of the student/employee ID info
16779:       Qstart      - column where the information from the bubbled
16780:                     'questions' start
16781:       Qlength     - number of columns comprising a single bubble line from
16782:                     the sheet. (usually either 1 or 10)
16783:       Qon         - either a single character representing the character used
16784:                     to signal a bubble was chosen in the positional setup, or
16785:                     the string 'letter' if the letter of the chosen bubble is
16786:                     in the final, or 'number' if a number representing the
16787:                     chosen bubble is in the file (1->A 0->J)
16788:       Qoff        - the character used to represent that a bubble was
16789:                     left blank
16790:       PaperID     - if the scanning process generates a unique number for each
16791:                     sheet scanned the column that this ID number starts in
16792:       PaperIDlength - number of columns that comprise the unique ID number
16793:                       for the sheet of paper
16794:       FirstName   - column that the first name starts in
16795:       FirstNameLength - number of columns that the first name spans
16796:       LastName    - column that the last name starts in
16797:       LastNameLength - number of columns that the last name spans
16798:       BubblesPerRow - number of bubbles available in each row used to
16799:                       bubble an answer. (If not specified, 10 assumed).
16800: 
16801: 
16802: =item *
16803: 
16804: get_scantronformat_file($cdom)
16805: 
16806: $cdom - the course's domain (optional); if not supplied, uses
16807: domain for current $env{'request.course.id'}.
16808: 
16809: Returns an array containing lines from the scantron format file for
16810: the domain of the course.
16811: 
16812: If a url for a custom.tab file is listed in domain's configuration.db,
16813: lines are from this file.
16814: 
16815: Otherwise, if a default.tab has been published in RES space by the
16816: domainconfig user, lines are from this file.
16817: 
16818: Otherwise, fall back to getting lines from the legacy file on the
16819: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16820: 
16821: =back
16822: 
16823: =head2 Resource Subroutines
16824: 
16825: =over 4
16826: 
16827: =item *
16828: 
16829: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16830: 
16831: =item *
16832: 
16833: repcopy($filename) : subscribes to the requested file, and attempts to
16834: replicate from the owning library server, Might return
16835: 'unavailable', 'not_found', 'forbidden', 'ok', or
16836: 'bad_request', also attempts to grab the metadata for the
16837: resource. Expects the local filesystem pathname
16838: (/home/httpd/html/res/....)
16839: 
16840: =back
16841: 
16842: =head2 Resource Information
16843: 
16844: =over 4
16845: 
16846: =item *
16847: 
16848: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16849: and returns the value of a variety of different possible values,
16850: $varname should be a request string, and the other parameters can be
16851: used to specify who and what one is asking about. Ordinarily, $cid 
16852: does not need to be specified, as it is retrived from 
16853: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16854: within lonuserstate::loadmap() when initializing a course, before
16855: $env{'request.course.id'} has been set, so it needs to be provided
16856: in that one case.
16857: 
16858: Possible values for $varname are environment.lastname (or other item
16859: from the envirnment hash), user.name (or someother aspect about the
16860: user), resource.0.maxtries (or some other part and parameter of a
16861: resource)
16862: 
16863: =item *
16864: 
16865: directcondval($number) : get current value of a condition; reads from a state
16866: string
16867: 
16868: =item *
16869: 
16870: condval($condidx) : value of condition index based on state
16871: 
16872: =item *
16873: 
16874: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16875: resource's metadata, $what should be either a specific key, or either
16876: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16877: packages that this resource currently uses, the last 3 arguments are 
16878: only used internally for recursive metadata.
16879: 
16880: the toolsymb is only used where the uri is for an external tool (for which
16881: the uri as well as the symb are guaranteed to be unique).
16882: 
16883: this function automatically caches all requests except any made recursively
16884: to retrieve a list of metadata keys for an imported library file ($liburi is 
16885: defined).
16886: 
16887: =item *
16888: 
16889: metadata_query($query,$custom,$customshow) : make a metadata query against the
16890: network of library servers; returns file handle of where SQL and regex results
16891: will be stored for query
16892: 
16893: =item *
16894: 
16895: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16896: return symbolic list entry (all arguments optional). 
16897: 
16898: Args: filename is the filename (including path) for the file for which a symb 
16899: is required; donotrecurse, if true will prevent calls to allowed() being made 
16900: to check access status if more than one resource was found in the bighash 
16901: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16902: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16903: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16904: cause possible symbs to be checked to determine if they are subject to content
16905: blocking, if so they will not be included as possible symbs; possibles is a
16906: ref to a hash, which, as a side effect, will be populated with all possible 
16907: symbs (content blocking not tested).
16908:  
16909: returns the data handle
16910: 
16911: =item *
16912: 
16913: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16914: and is a possible symb for the URL in $thisfn, and if is an encrypted
16915: resource that the user accessed using /enc/ returns a 1 on success, 0
16916: on failure, user must be in a course, as it assumes the existence of
16917: the course initial hash, and uses $env('request.course.id'}.  The third
16918: arg is an optional reference to a scalar.  If this arg is passed in the 
16919: call to symbverify, it will be set to 1 if the symb has been set to be 
16920: encrypted; otherwise it will be null.  
16921: 
16922: =item *
16923: 
16924: symbclean($symb) : removes versions numbers from a symb, returns the
16925: cleaned symb
16926: 
16927: =item *
16928: 
16929: is_on_map($uri) : checks if the $uri is somewhere on the current
16930: course map, user must be in a course for it to work.
16931: 
16932: =item *
16933: 
16934: numval($salt) : return random seed value (addend for rndseed)
16935: 
16936: =item *
16937: 
16938: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16939: a random seed, all arguments are optional, if they aren't sent it uses the
16940: environment to derive them. Note: if symb isn't sent and it can't get one
16941: from &symbread it will use the current time as its return value
16942: 
16943: =item *
16944: 
16945: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16946: unfakeable, receipt
16947: 
16948: =item *
16949: 
16950: receipt() : API to ireceipt working off of env values; given out to users
16951: 
16952: =item *
16953: 
16954: countacc($url) : count the number of accesses to a given URL
16955: 
16956: =item *
16957: 
16958: 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
16959: 
16960: =item *
16961: 
16962: 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)
16963: 
16964: =item *
16965: 
16966: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16967: 
16968: =item *
16969: 
16970: devalidate($symb) : devalidate temporary spreadsheet calculations,
16971: forcing spreadsheet to reevaluate the resource scores next time.
16972: 
16973: =item * 
16974: 
16975: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16976: when viewing in course context.
16977: 
16978:  input: six args -- filename (decluttered), course number, course domain,
16979:                     url, symb (if registered) and group (if this is a 
16980:                     group item -- e.g., bulletin board, group page etc.).
16981: 
16982:  output: array of five scalars --
16983:          $cfile -- url for file editing if editable on current server
16984:          $home -- homeserver of resource (i.e., for author if published,
16985:                                           or course if uploaded.).
16986:          $switchserver --  1 if server switch will be needed.
16987:          $forceedit -- 1 if icon/link should be to go to edit mode 
16988:          $forceview -- 1 if icon/link should be to go to view mode
16989: 
16990: =item *
16991: 
16992: is_course_upload($file,$cnum,$cdom)
16993: 
16994: Used in course context to determine if current file was uploaded to 
16995: the course (i.e., would be found in /userfiles/docs on the course's 
16996: homeserver.
16997: 
16998:   input: 3 args -- filename (decluttered), course number and course domain.
16999:   output: boolean -- 1 if file was uploaded.
17000: 
17001: =back
17002: 
17003: =head2 Storing/Retreiving Data
17004: 
17005: =over 4
17006: 
17007: =item *
17008: 
17009: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17010: permanently for this url; hashref needs to be given and should be a \%hashname;
17011: the remaining args aren't required and if they aren't passed or are '' they will
17012: be derived from the env (with the exception of $laststore, which is an 
17013: optional arg used when a user's submission is stored in grading).
17014: $laststore is $version=$timestamp, where $version is the most recent version
17015: number retrieved for the corresponding $symb in the $namespace db file, and
17016: $timestamp is the timestamp for that transaction (UNIX time).
17017: $laststore is currently only passed when cstore() is called by 
17018: structuretags::finalize_storage().
17019: 
17020: =item *
17021: 
17022: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17023: but uses critical subroutine
17024: 
17025: =item *
17026: 
17027: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17028: all args are optional
17029: 
17030: =item *
17031: 
17032: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17033: dumps the complete (or key matching regexp) namespace into a hash
17034: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17035: normally &store()ed into
17036: 
17037: $range should be either an integer '100' (give me the first 100
17038:                                            matching records)
17039:               or be  two integers sperated by a - with no spaces
17040:                  '30-50' (give me the 30th through the 50th matching
17041:                           records)
17042: 
17043: 
17044: =item *
17045: 
17046: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17047: replaces a &store() version of data with a replacement set of data
17048: for a particular resource in a namespace passed in the $storehash hash 
17049: reference. If $tolog is true, the transaction is logged in the courselog
17050: with an action=PUTSTORE.
17051: 
17052: =item *
17053: 
17054: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17055: works very similar to store/cstore, but all data is stored in a
17056: temporary location and can be reset using tmpreset, $storehash should
17057: be a hash reference, returns nothing on success
17058: 
17059: =item *
17060: 
17061: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17062: similar to restore, but all data is stored in a temporary location and
17063: can be reset using tmpreset. Returns a hash of values on success,
17064: error string otherwise.
17065: 
17066: =item *
17067: 
17068: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17069: deltes all keys for $symb form the temporary storage hash.
17070: 
17071: =item *
17072: 
17073: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17074: reference filled in from namesp ($udom and $uname are optional)
17075: 
17076: =item *
17077: 
17078: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17079: namesp ($udom and $uname are optional)
17080: 
17081: =item *
17082: 
17083: dump($namespace,$udom,$uname,$regexp,$range) : 
17084: dumps the complete (or key matching regexp) namespace into a hash
17085: ($udom, $uname, $regexp, $range are optional)
17086: 
17087: $range should be either an integer '100' (give me the first 100
17088:                                            matching records)
17089:               or be  two integers sperated by a - with no spaces
17090:                  '30-50' (give me the 30th through the 50th matching
17091:                           records)
17092: =item *
17093: 
17094: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17095: $store can be a scalar, an array reference, or if the amount to be 
17096: incremented is > 1, a hash reference.
17097: 
17098: ($udom and $uname are optional)
17099: 
17100: =item *
17101: 
17102: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17103: ($udom and $uname are optional)
17104: 
17105: =item *
17106: 
17107: cput($namespace,$storehash,$udom,$uname) : critical put
17108: ($udom and $uname are optional)
17109: 
17110: =item *
17111: 
17112: newput($namespace,$storehash,$udom,$uname) :
17113: 
17114: Attempts to store the items in the $storehash, but only if they don't
17115: currently exist, if this succeeds you can be certain that you have 
17116: successfully created a new key value pair in the $namespace db.
17117: 
17118: 
17119: Args:
17120:  $namespace: name of database to store values to
17121:  $storehash: hashref to store to the db
17122:  $udom: (optional) domain of user containing the db
17123:  $uname: (optional) name of user caontaining the db
17124: 
17125: Returns:
17126:  'ok' -> succeeded in storing all keys of $storehash
17127:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17128:                         least <key> already existed in the db (other
17129:                         requested keys may also already exist)
17130:  'error: <msg>' -> unable to tie the DB or other error occurred
17131:  'con_lost' -> unable to contact request server
17132:  'refused' -> action was not allowed by remote machine
17133: 
17134: 
17135: =item *
17136: 
17137: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17138: reference filled in from namesp (encrypts the return communication)
17139: ($udom and $uname are optional)
17140: 
17141: =item *
17142: 
17143: log($udom,$name,$home,$message) : write to permanent log for user; use
17144: critical subroutine
17145: 
17146: =item *
17147: 
17148: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17149: array reference filled in from namespace found in domain level on either
17150: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17151: 
17152: =item *
17153: 
17154: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17155: domain level either on specified domain server ($uhome) or primary domain 
17156: server ($udom and $uhome are optional)
17157: 
17158: =item * 
17159: 
17160: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17161: for: authentication, language, quotas, timezone, date locale, and portal URL in
17162: the target domain.
17163: 
17164: May also include additional key => value pairs for the following groups:
17165: 
17166: =over
17167: 
17168: =item
17169: disk quotas (MB allocated by default to portfolios and authoring spaces).
17170: 
17171: =over
17172: 
17173: =item defaultquota, authorquota
17174: 
17175: =back
17176: 
17177: =item
17178: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17179: portfolio for users).
17180: 
17181: =over
17182: 
17183: =item
17184: aboutme, blog, webdav, portfolio
17185: 
17186: =back
17187: 
17188: =item
17189: requestcourses: ability to request courses, and how requests are processed.
17190: 
17191: =over
17192: 
17193: =item
17194: official, unofficial, community, textbook, placement
17195: 
17196: =back
17197: 
17198: =item
17199: inststatus: types of institutional affiliation, and order in which they are displayed.
17200: 
17201: =over
17202: 
17203: =item
17204: inststatustypes, inststatusorder, inststatusguest
17205: 
17206: =back
17207: 
17208: =item
17209: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17210: for course's uploaded content.
17211: 
17212: =over
17213: 
17214: =item
17215: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17216: communityquota, textbookquota, placementquota
17217: 
17218: =back
17219: 
17220: =item
17221: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17222: on your servers.
17223: 
17224: =over
17225: 
17226: =item 
17227: remotesessions, hostedsessions
17228: 
17229: =back
17230: 
17231: =back
17232: 
17233: In cases where a domain coordinator has never used the "Set Domain Configuration"
17234: utility to create a configuration.db file on a domain's primary library server 
17235: only the following domain defaults: auth_def, auth_arg_def, lang_def
17236: -- corresponding values are authentication type (internal, krb4, krb5,
17237: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17238: will be available. Values are retrieved from cache (if current), unless the
17239: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17240: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17241: 
17242: Typical usage:
17243: 
17244: %domdefaults = &get_domain_defaults($target_domain);
17245: 
17246: =back
17247: 
17248: =head2 Network Status Functions
17249: 
17250: =over 4
17251: 
17252: =item *
17253: 
17254: dirlist() : return directory list based on URI (first arg).
17255: 
17256: Inputs: 1 required, 5 optional.
17257: 
17258: =over
17259: 
17260: =item 
17261: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17262: 
17263: =item
17264: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17265: 
17266: =item
17267: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17268: 
17269: =item
17270: $getpropath - boolean: 1 if prepend path using &propath(). 
17271: 
17272: =item
17273: $getuserdir - boolean: 1 if prepend path for "userfiles".
17274: 
17275: =item 
17276: $alternateRoot - path to prepend in place of path from $uri.
17277: 
17278: =back
17279: 
17280: Returns: Array of up to two items.
17281: 
17282: =over
17283: 
17284: a reference to an array of files/subdirectories
17285: 
17286: =over
17287: 
17288: Each element in the array of files/subdirectories is a & separated list of
17289: item name and the result of running stat on the item.  If dirlist was requested
17290: for a file instead of a directory, the item name will be ''. For a directory 
17291: listing, if the item is a metadata file, the element will end &N&M 
17292: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17293: default copyright set (1).  
17294: 
17295: =back
17296: 
17297: a scalar containing error condition (if encountered).
17298: 
17299: =over
17300: 
17301: =item 
17302: no_host (no homeserver identified for $username:$domain).
17303: 
17304: =item 
17305: no_such_host (server contacted for listing not identified as valid host).
17306: 
17307: =item 
17308: con_lost (connection to remote server failed).
17309: 
17310: =item 
17311: refused (invalid $username:$domain received on lond side).
17312: 
17313: =item 
17314: no_such_dir (directory at specified path on lond side does not exist). 
17315: 
17316: =item 
17317: empty (directory at specified path on lond side is empty).
17318: 
17319: =over
17320: 
17321: This is currently not encountered because the &ls3, &ls2, 
17322: &ls (_handler) routines on the lond side do not filter out
17323: . and .. from a directory listing. 
17324: 
17325: =back
17326: 
17327: =back
17328: 
17329: =back
17330: 
17331: =item *
17332: 
17333: spareserver() : find server with least workload from spare.tab
17334: 
17335: 
17336: =item *
17337: 
17338: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17339: if there is no corresponding loncapa host.
17340: 
17341: =back
17342: 
17343: 
17344: =head2 Apache Request
17345: 
17346: =over 4
17347: 
17348: =item *
17349: 
17350: ssi($url,%hash) : server side include, does a complete request cycle on url to
17351: localhost, posts hash
17352: 
17353: =back
17354: 
17355: =head2 Data to String to Data
17356: 
17357: =over 4
17358: 
17359: =item *
17360: 
17361: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17362: and '&' separators, supports elements that are arrayrefs and hashrefs
17363: 
17364: =item *
17365: 
17366: hashref2str($hashref) : convert a hashref into a string complete with
17367: escaping and '=' and '&' separators, supports elements that are
17368: arrayrefs and hashrefs
17369: 
17370: =item *
17371: 
17372: arrayref2str($arrayref) : convert an arrayref into a string complete
17373: with escaping and '&' separators, supports elements that are arrayrefs
17374: and hashrefs
17375: 
17376: =item *
17377: 
17378: str2hash($string) : convert string to hash using unescaping and
17379: splitting on '=' and '&', supports elements that are arrayrefs and
17380: hashrefs
17381: 
17382: =item *
17383: 
17384: str2array($string) : convert string to hash using unescaping and
17385: splitting on '&', supports elements that are arrayrefs and hashrefs
17386: 
17387: =back
17388: 
17389: =head2 Logging Routines
17390: 
17391: 
17392: These routines allow one to make log messages in the lonnet.log and
17393: lonnet.perm logfiles.
17394: 
17395: =over 4
17396: 
17397: =item *
17398: 
17399: logtouch() : make sure the logfile, lonnet.log, exists
17400: 
17401: =item *
17402: 
17403: logthis() : append message to the normal lonnet.log file, it gets
17404: preiodically rolled over and deleted.
17405: 
17406: =item *
17407: 
17408: logperm() : append a permanent message to lonnet.perm.log, this log
17409: file never gets deleted by any automated portion of the system, only
17410: messages of critical importance should go in here.
17411: 
17412: 
17413: =back
17414: 
17415: =head2 General File Helper Routines
17416: 
17417: =over 4
17418: 
17419: =item *
17420: 
17421: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17422: (a) files in /uploaded
17423:   (i) If a local copy of the file exists - 
17424:       compares modification date of local copy with last-modified date for 
17425:       definitive version stored on home server for course. If local copy is 
17426:       stale, requests a new version from the home server and stores it. 
17427:       If the original has been removed from the home server, then local copy 
17428:       is unlinked.
17429:   (ii) If local copy does not exist -
17430:       requests the file from the home server and stores it. 
17431:   
17432:   If $caller is 'uploadrep':  
17433:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17434:     for request for files originally uploaded via DOCS. 
17435:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17436:   
17437:   Otherwise:
17438:      This indicates a call from the content generation phase of the request.
17439:      -  returns the entire contents of the file or -1.
17440:      
17441: (b) files in /res
17442:    - returns the entire contents of a file or -1; 
17443:    it properly subscribes to and replicates the file if neccessary.
17444: 
17445: 
17446: =item *
17447: 
17448: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17449:                   reference
17450: 
17451: returns either a stat() list of data about the file or an empty list
17452: if the file doesn't exist or couldn't find out about it (connection
17453: problems or user unknown)
17454: 
17455: =item *
17456: 
17457: filelocation($dir,$file) : returns file system location of a file
17458: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17459: directory that relative $file lookups are to looked in ($dir of /a/dir
17460: and a file of ../bob will become /a/bob)
17461: 
17462: =item *
17463: 
17464: hreflocation($dir,$file) : returns file system location or a URL; same as
17465: filelocation except for hrefs
17466: 
17467: =item *
17468: 
17469: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17470: also removes beginning /home/httpd/html unless /priv/ follows it.
17471: 
17472: =back
17473: 
17474: =head2 Usererfile file routines (/uploaded*)
17475: 
17476: =over 4
17477: 
17478: =item *
17479: 
17480: userfileupload(): main rotine for putting a file in a user or course's
17481:                   filespace, arguments are,
17482: 
17483:  formname - required - this is the name of the element in $env where the
17484:            filename, and the contents of the file to create/modifed exist
17485:            the filename is in $env{'form.'.$formname.'.filename'} and the
17486:            contents of the file is located in $env{'form.'.$formname}
17487:  context - if coursedoc, store the file in the course of the active role
17488:              of the current user; 
17489:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17490:            if 'canceloverwrite': delete file in tmp/overwrites directory
17491:  subdir - required - subdirectory to put the file in under ../userfiles/
17492:          if undefined, it will be placed in "unknown"
17493: 
17494:  (This routine calls clean_filename() to remove any dangerous
17495:  characters from the filename, and then calls finuserfileupload() to
17496:  complete the transaction)
17497: 
17498:  returns either the url of the uploaded file (/uploaded/....) if successful
17499:  and /adm/notfound.html if unsuccessful
17500: 
17501: =item *
17502: 
17503: clean_filename(): routine for cleaing a filename up for storage in
17504:                  userfile space, argument is:
17505: 
17506:  filename - proposed filename
17507: 
17508: returns: the new clean filename
17509: 
17510: =item *
17511: 
17512: finishuserfileupload(): routine that creates and sends the file to
17513: userspace, probably shouldn't be called directly
17514: 
17515:   docuname: username or courseid of destination for the file
17516:   docudom: domain of user/course of destination for the file
17517:   formname: same as for userfileupload()
17518:   fname: filename (including subdirectories) for the file
17519:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17520:           if hashref, and context is scantron, will convert csv format to standard format
17521:   allfiles: reference to hash used to store objects found by parser
17522:   codebase: reference to hash used for codebases of java objects found by parser
17523:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17524:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17525:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17526:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17527:   context: if 'overwrite', will move the uploaded file from its temporary location to
17528:             userfiles to facilitate overwriting a previously uploaded file with same name.
17529:   mimetype: reference to scalar to accommodate mime type determined
17530:             from File::MMagic if $parser = parse.
17531: 
17532:  returns either the url of the uploaded file (/uploaded/....) if successful
17533:  and /adm/notfound.html if unsuccessful (or an error message if context 
17534:  was 'overwrite').
17535:  
17536: 
17537: =item *
17538: 
17539: renameuserfile(): renames an existing userfile to a new name
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:    old: current file name (including any subdirs under userfiles)
17545:    new: desired file name (including any subdirs under userfiles)
17546: 
17547: =item *
17548: 
17549: mkdiruserfile(): creates a directory is a userfiles dir
17550: 
17551:   Args:
17552:    docuname: username or courseid of destination for the file
17553:    docudom: domain of user/course of destination for the file
17554:    dir: dir to create (including any subdirs under userfiles)
17555: 
17556: =item *
17557: 
17558: removeuserfile(): removes a file that exists in userfiles
17559: 
17560:   Args:
17561:    docuname: username or courseid of destination for the file
17562:    docudom: domain of user/course of destination for the file
17563:    fname: filname to delete (including any subdirs under userfiles)
17564: 
17565: =item *
17566: 
17567: removeuploadedurl(): convience function for removeuserfile()
17568: 
17569:   Args:
17570:    url:  a full /uploaded/... url to delete
17571: 
17572: =item * 
17573: 
17574: get_portfile_permissions():
17575:   Args:
17576:     domain: domain of user or course contain the portfolio files
17577:     user: name of user or num of course contain the portfolio files
17578:   Returns:
17579:     hashref of a dump of the proper file_permissions.db
17580:    
17581: 
17582: =item * 
17583: 
17584: get_access_controls():
17585: 
17586: Args:
17587:   current_permissions: the hash ref returned from get_portfile_permissions()
17588:   group: (optional) the group you want the files associated with
17589:   file: (optional) the file you want access info on
17590: 
17591: Returns:
17592:     a hash (keys are file names) of hashes containing
17593:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17594:         values are XML containing access control settings (see below) 
17595: 
17596: Internal notes:
17597: 
17598:  access controls are stored in file_permissions.db as key=value pairs.
17599:     key -> path to file/file_name\0uniqueID:scope_end_start
17600:         where scope -> public,guest,course,group,domains or users.
17601:               end -> UNIX time for end of access (0 -> no end date)
17602:               start -> UNIX time for start of access
17603: 
17604:     value -> XML description of access control
17605:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17606:             <start></start>
17607:             <end></end>
17608: 
17609:             <password></password>  for scope type = guest
17610: 
17611:             <domain></domain>     for scope type = course or group
17612:             <number></number>
17613:             <roles id="">
17614:              <role></role>
17615:              <access></access>
17616:              <section></section>
17617:              <group></group>
17618:             </roles>
17619: 
17620:             <dom></dom>         for scope type = domains
17621: 
17622:             <users>             for scope type = users
17623:              <user>
17624:               <uname></uname>
17625:               <udom></udom>
17626:              </user>
17627:             </users>
17628:            </scope> 
17629:               
17630:  Access data is also aggregated for each file in an additional key=value pair:
17631:  key -> path to file/file_name\0accesscontrol 
17632:  value -> reference to hash
17633:           hash contains key = value pairs
17634:           where key = uniqueID:scope_end_start
17635:                 value = UNIX time record was last updated
17636: 
17637:           Used to improve speed of look-ups of access controls for each file.  
17638:  
17639:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17640: 
17641: =item *
17642: 
17643: modify_access_controls():
17644: 
17645: Modifies access controls for a portfolio file
17646: Args
17647: 1. file name
17648: 2. reference to hash of required changes,
17649: 3. domain
17650: 4. username
17651:   where domain,username are the domain of the portfolio owner 
17652:   (either a user or a course) 
17653: 
17654: Returns:
17655: 1. result of additions or updates ('ok' or 'error', with error message). 
17656: 2. result of deletions ('ok' or 'error', with error message).
17657: 3. reference to hash of any new or updated access controls.
17658: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17659:    key = integer (inbound ID)
17660:    value = uniqueID
17661: 
17662: =item *
17663: 
17664: get_timebased_id():
17665: 
17666: Attempts to get a unique timestamp-based suffix for use with items added to a 
17667: course via the Course Editor (e.g., folders, composite pages, 
17668: group bulletin boards).
17669: 
17670: Args: (first three required; six others optional)
17671: 
17672: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17673:    docssequence, or name of group
17674: 
17675: 2. keyid (alphanumeric): name of temporary locking key in hash,
17676:    e.g., num, boardids
17677: 
17678: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17679:    file will be named nohist_namespace.db
17680: 
17681: 4. cdom: domain of course; default is current course domain from %env
17682: 
17683: 5. cnum: course number; default is current course number from %env
17684: 
17685: 6. idtype: set to concat if an additional digit is to be appended to the 
17686:    unix timestamp to form the suffix, if the plain timestamp is already
17687:    in use.  Default is to not do this, but simply increment the unix 
17688:    timestamp by 1 until a unique key is obtained.
17689: 
17690: 7. who: holder of locking key; defaults to user:domain for user.
17691: 
17692: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17693:    retrying); default is 3.
17694: 
17695: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17696: 
17697: Returns:
17698: 
17699: 1. suffix obtained (numeric)
17700: 
17701: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17702: 
17703: 3. error: contains (localized) error message if an error occurred.
17704: 
17705: 
17706: =back
17707: 
17708: =head2 HTTP Helper Routines
17709: 
17710: =over 4
17711: 
17712: =item *
17713: 
17714: escape() : unpack non-word characters into CGI-compatible hex codes
17715: 
17716: =item *
17717: 
17718: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17719: 
17720: =back
17721: 
17722: =head1 PRIVATE SUBROUTINES
17723: 
17724: =head2 Underlying communication routines (Shouldn't call)
17725: 
17726: =over 4
17727: 
17728: =item *
17729: 
17730: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17731: 
17732: =item *
17733: 
17734: reply() : uses subreply to send a message to remote machine, logs all failures
17735: 
17736: =item *
17737: 
17738: critical() : passes a critical message to another server; if cannot
17739: get through then place message in connection buffer directory and
17740: returns con_delayed, if incapable of saving message, returns
17741: con_failed
17742: 
17743: =item *
17744: 
17745: reconlonc() : tries to reconnect lonc client processes.
17746: 
17747: =back
17748: 
17749: =head2 Resource Access Logging
17750: 
17751: =over 4
17752: 
17753: =item *
17754: 
17755: flushcourselogs() : flush (save) buffer logs and access logs
17756: 
17757: =item *
17758: 
17759: courselog($what) : save message for course in hash
17760: 
17761: =item *
17762: 
17763: courseacclog($what) : save message for course using &courselog().  Perform
17764: special processing for specific resource types (problems, exams, quizzes, etc).
17765: 
17766: =item *
17767: 
17768: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17769: as a PerlChildExitHandler
17770: 
17771: =back
17772: 
17773: =head2 Other
17774: 
17775: =over 4
17776: 
17777: =item *
17778: 
17779: symblist($mapname,%newhash) : update symbolic storage links
17780: 
17781: =back
17782: 
17783: =cut
17784: 

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