File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1408: download - view: text, annotated - select for diffs
Fri Apr 26 20:22:27 2019 UTC (5 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain Configuration for Passwords for internally authenticated users.
  - Rules for LON-CAPA passwords can include: number of user's previous
    passwords to save (with reuser by that user disallowed).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1408 2019/04/26 20:22:27 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);
   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 LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: 
  117: # ------------------------------------ Logging (parameters, docs, slots, roles)
  118: {
  119:     my $logid;
  120:     sub write_log {
  121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  122:         if ($context eq 'course') {
  123:             if (($cnum eq '') || ($cdom eq '')) {
  124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  126:             }
  127:         }
  128: 	$logid ++;
  129:         my $now = time();
  130: 	my $id=$now.'00000'.$$.'00000'.$logid;
  131:         my $logentry = { 
  132:                           $id => {
  133:                                    'exe_uname' => $env{'user.name'},
  134:                                    'exe_udom'  => $env{'user.domain'},
  135:                                    'exe_time'  => $now,
  136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  137:                                    'delflag'   => $delflag,
  138:                                    'logentry'  => $storehash,
  139:                                    'uname'     => $uname,
  140:                                    'udom'      => $udom,
  141:                                   }
  142:                        };
  143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_servercerts_info {
  234:     my ($lonhost,$hostname,$context) = @_;
  235:     return if ($lonhost eq '');
  236:     if ($hostname eq '') {
  237:         $hostname = &hostname($lonhost);
  238:     }
  239:     return if ($hostname eq '');
  240:     my ($rep,$uselocal);
  241:     if ($context eq 'install') {
  242:         $uselocal = 1;
  243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  244:         $uselocal = 1;
  245:     }
  246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  248:         if ($distro eq '') {
  249:             $uselocal = 0;
  250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  251:             if ($1 < 6) {
  252:                 $uselocal = 0;
  253:             }
  254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  255:             if ($1 < 12) {
  256:                 $uselocal = 0;
  257:             }
  258:         }
  259:     }
  260:     if ($uselocal) {
  261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  262:     } else {
  263:         $rep=&reply('servercerts',$lonhost);
  264:     }
  265:     my ($result,%returnhash);
  266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  267:         ($rep eq 'unknown_cmd')) {
  268:         $result = $rep;
  269:     } else {
  270:         $result = 'ok';
  271:         my @pairs=split(/\&/,$rep);
  272:         foreach my $item (@pairs) {
  273:             my ($key,$value)=split(/=/,$item,2);
  274:             my $what = &unescape($key);
  275:             $returnhash{$what}=&thaw_unescape($value);
  276:         }
  277:     }
  278:     return ($result,\%returnhash);
  279: }
  280: 
  281: sub get_server_loncaparev {
  282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  283:     if (defined($lonhost)) {
  284:         if (!defined(&hostname($lonhost))) {
  285:             undef($lonhost);
  286:         }
  287:     }
  288:     if (!defined($lonhost)) {
  289:         if (defined(&domain($dom,'primary'))) {
  290:             $lonhost=&domain($dom,'primary');
  291:             if ($lonhost eq 'no_host') {
  292:                 undef($lonhost);
  293:             }
  294:         }
  295:     }
  296:     if (defined($lonhost)) {
  297:         my $cachetime = 12*3600;
  298:         if (!$ignore_cache) {
  299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  300:             if (defined($cached)) {
  301:                 return $loncaparev;
  302:             }
  303:         }
  304:         my ($answer,$loncaparev);
  305:         my @ids=&current_machine_ids();
  306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  307:             $answer = $perlvar{'lonVersion'};
  308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  309:                 $loncaparev = $1;
  310:             }
  311:         } else {
  312:             $answer = &reply('serverloncaparev',$lonhost);
  313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  314:                 if ($caller eq 'loncron') {
  315:                     my $hostname = &hostname($lonhost);
  316:                     my $protocol = $protocol{$lonhost};
  317:                     $protocol = 'http' if ($protocol ne 'https');
  318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  319:                     my $request=new HTTP::Request('GET',$url);
  320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  321:                     unless ($response->is_error()) {
  322:                         my $content = $response->content;
  323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  324:                             $loncaparev = $1;
  325:                         }
  326:                     }
  327:                 } else {
  328:                     $loncaparev = $loncaparevs{$lonhost};
  329:                 }
  330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  331:                 $loncaparev = $1;
  332:             }
  333:         }
  334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  335:     }
  336: }
  337: 
  338: sub get_server_homeID {
  339:     my ($hostname,$ignore_cache,$caller) = @_;
  340:     unless ($ignore_cache) {
  341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  342:         if (defined($cached)) {
  343:             return $serverhomeID;
  344:         }
  345:     }
  346:     my $cachetime = 12*3600;
  347:     my $serverhomeID;
  348:     if ($caller eq 'loncron') { 
  349:         my @machine_ids = &machine_ids($hostname);
  350:         foreach my $id (@machine_ids) {
  351:             my $response = &reply('serverhomeID',$id);
  352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  353:                 $serverhomeID = $response;
  354:                 last;
  355:             }
  356:         }
  357:         if ($serverhomeID eq '') {
  358:             $serverhomeID = $machine_ids[-1];
  359:         }
  360:     } else {
  361:         $serverhomeID = $serverhomeIDs{$hostname};
  362:     }
  363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  364: }
  365: 
  366: sub get_remote_globals {
  367:     my ($lonhost,$whathash,$ignore_cache) = @_;
  368:     my ($result,%returnhash,%whatneeded);
  369:     if (ref($whathash) eq 'HASH') {
  370:         foreach my $what (sort(keys(%{$whathash}))) {
  371:             my $hashid = $lonhost.'-'.$what;
  372:             my ($response,$cached);
  373:             unless ($ignore_cache) {
  374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  375:             }
  376:             if (defined($cached)) {
  377:                 $returnhash{$what} = $response;
  378:             } else {
  379:                 $whatneeded{$what} = 1;
  380:             }
  381:         }
  382:         if (keys(%whatneeded) == 0) {
  383:             $result = 'ok';
  384:         } else {
  385:             my $requested = &freeze_escape(\%whatneeded);
  386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  388:                 ($rep eq 'unknown_cmd')) {
  389:                 $result = $rep;
  390:             } else {
  391:                 $result = 'ok';
  392:                 my @pairs=split(/\&/,$rep);
  393:                 foreach my $item (@pairs) {
  394:                     my ($key,$value)=split(/=/,$item,2);
  395:                     my $what = &unescape($key);
  396:                     my $hashid = $lonhost.'-'.$what;
  397:                     $returnhash{$what}=&thaw_unescape($value);
  398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  399:                 }
  400:             }
  401:         }
  402:     }
  403:     return ($result,\%returnhash);
  404: }
  405: 
  406: sub remote_devalidate_cache {
  407:     my ($lonhost,$cachekeys) = @_;
  408:     my $items;
  409:     return unless (ref($cachekeys) eq 'ARRAY');
  410:     my $cachestr = join('&',@{$cachekeys});
  411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  412:     return $response;
  413: }
  414: 
  415: # -------------------------------------------------- Non-critical communication
  416: sub subreply {
  417:     my ($cmd,$server)=@_;
  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  419:     #
  420:     #  With loncnew process trimming, there's a timing hole between lonc server
  421:     #  process exit and the master server picking up the listen on the AF_UNIX
  422:     #  socket.  In that time interval, a lock file will exist:
  423: 
  424:     my $lockfile=$peerfile.".lock";
  425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  426: 	sleep(0.1);
  427:     }
  428:     # At this point, either a loncnew parent is listening or an old lonc
  429:     # or loncnew child is listening so we can connect or everything's dead.
  430:     #
  431:     #   We'll give the connection a few tries before abandoning it.  If
  432:     #   connection is not possible, we'll con_lost back to the client.
  433:     #   
  434:     my $client;
  435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  437: 				      Type    => SOCK_STREAM,
  438: 				      Timeout => 10);
  439: 	if ($client) {
  440: 	    last;		# Connected!
  441: 	} else {
  442: 	    &create_connection(&hostname($server),$server);
  443: 	}
  444:         sleep(0.1);	# Try again later if failed connection.
  445:     }
  446:     my $answer;
  447:     if ($client) {
  448: 	print $client "sethost:$server:$cmd\n";
  449: 	$answer=<$client>;
  450: 	if (!$answer) { $answer="con_lost"; }
  451: 	chomp($answer);
  452:     } else {
  453: 	$answer = 'con_lost';	# Failed connection.
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: sub reply {
  459:     my ($cmd,$server)=@_;
  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  461:     my $answer=subreply($cmd,$server);
  462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  463:         my $logged = $cmd;
  464:         if ($cmd =~ /^encrypt:([^:]+):/) {
  465:             my $subcmd = $1;
  466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  469:                 (undef,undef,my @rest) = split(/:/,$cmd);
  470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  471:                     splice(@rest,2,1,'Hidden');
  472:                 } elsif ($subcmd eq 'passwd') {
  473:                     splice(@rest,2,2,('Hidden','Hidden'));
  474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  475:                          ($subcmd eq 'autoexportgrades')) {
  476:                     splice(@rest,3,1,'Hidden');
  477:                 }
  478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  479:             }
  480:         }
  481:         &logthis("<font color=\"blue\">WARNING:".
  482:                  " $logged to $server returned $answer</font>");
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: # ----------------------------------------------------------- Send USR1 to lonc
  488: 
  489: sub reconlonc {
  490:     my ($lonid) = @_;
  491:     if ($lonid) {
  492:         my $hostname = &hostname($lonid);
  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  494: 	if ($hostname && -e $peerfile) {
  495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  497: 					     Type    => SOCK_STREAM,
  498: 					     Timeout => 10);
  499: 	    if ($client) {
  500: 		print $client ("reset_retries\n");
  501: 		my $answer=<$client>;
  502: 		#reset just this one.
  503: 	    }
  504: 	}
  505: 	return;
  506:     }
  507: 
  508:     &logthis("Trying to reconnect lonc");
  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  510:     if (open(my $fh,"<",$loncfile)) {
  511: 	my $loncpid=<$fh>;
  512:         chomp($loncpid);
  513:         if (kill 0 => $loncpid) {
  514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  515:             kill USR1 => $loncpid;
  516:             sleep 1;
  517:         } else {
  518: 	    &logthis(
  519:                "<font color=\"blue\">WARNING:".
  520:                " lonc at pid $loncpid not responding, giving up</font>");
  521:         }
  522:     } else {
  523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  524:     }
  525: }
  526: 
  527: # ------------------------------------------------------ Critical communication
  528: 
  529: sub critical {
  530:     my ($cmd,$server)=@_;
  531:     unless (&hostname($server)) {
  532:         &logthis("<font color=\"blue\">WARNING:".
  533:                " Critical message to unknown server ($server)</font>");
  534:         return 'no_such_host';
  535:     }
  536:     my $answer=reply($cmd,$server);
  537:     if ($answer eq 'con_lost') {
  538: 	&reconlonc($server);
  539: 	my $answer=reply($cmd,$server);
  540:         if ($answer eq 'con_lost') {
  541:             my $now=time;
  542:             my $middlename=$cmd;
  543:             $middlename=substr($middlename,0,16);
  544:             $middlename=~s/\W//g;
  545:             my $dfilename=
  546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  547:             $dumpcount++;
  548:             {
  549: 		my $dfh;
  550: 		if (open($dfh,">",$dfilename)) {
  551: 		    print $dfh "$cmd\n"; 
  552: 		    close($dfh);
  553: 		}
  554:             }
  555:             sleep 1;
  556:             my $wcmd='';
  557:             {
  558: 		my $dfh;
  559: 		if (open($dfh,"<",$dfilename)) {
  560: 		    $wcmd=<$dfh>; 
  561: 		    close($dfh);
  562: 		}
  563:             }
  564:             chomp($wcmd);
  565:             if ($wcmd eq $cmd) {
  566: 		&logthis("<font color=\"blue\">WARNING: ".
  567:                          "Connection buffer $dfilename: $cmd</font>");
  568:                 &logperm("D:$server:$cmd");
  569: 	        return 'con_delayed';
  570:             } else {
  571:                 &logthis("<font color=\"red\">CRITICAL:"
  572:                         ." Critical connection failed: $server $cmd</font>");
  573:                 &logperm("F:$server:$cmd");
  574:                 return 'con_failed';
  575:             }
  576:         }
  577:     }
  578:     return $answer;
  579: }
  580: 
  581: # ------------------------------------------- check if return value is an error
  582: 
  583: sub error {
  584:     my ($result) = @_;
  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  586: 	if ($2 == 2) { return undef; }
  587: 	return $1;
  588:     }
  589:     return undef;
  590: }
  591: 
  592: sub convert_and_load_session_env {
  593:     my ($lonidsdir,$handle)=@_;
  594:     my @profile;
  595:     {
  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  597: 	if (!$opened) {
  598: 	    return 0;
  599: 	}
  600: 	flock($idf,LOCK_SH);
  601: 	@profile=<$idf>;
  602: 	close($idf);
  603:     }
  604:     my %temp_env;
  605:     foreach my $line (@profile) {
  606: 	if ($line !~ m/=/) {
  607: 	    return 0;
  608: 	}
  609: 	chomp($line);
  610: 	my ($envname,$envvalue)=split(/=/,$line,2);
  611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  612:     }
  613:     unlink("$lonidsdir/$handle.id");
  614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  615: 	    0640)) {
  616: 	%disk_env = %temp_env;
  617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  618: 	untie(%disk_env);
  619:     }
  620:     return 1;
  621: }
  622: 
  623: # ------------------------------------------- Transfer profile into environment
  624: my $env_loaded;
  625: sub transfer_profile_to_env {
  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
  627:     if (!$force_transfer && $env_loaded) { return; } 
  628: 
  629:     if (!defined($lonidsdir)) {
  630: 	$lonidsdir = $perlvar{'lonIDsDir'};
  631:     }
  632:     if (!defined($handle)) {
  633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  634:     }
  635: 
  636:     my $convert;
  637:     {
  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  639: 	if (!$opened) {
  640: 	    return;
  641: 	}
  642: 	flock($idf,LOCK_SH);
  643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  644: 		&GDBM_READER(),0640)) {
  645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  646: 	    untie(%disk_env);
  647: 	} else {
  648: 	    $convert = 1;
  649: 	}
  650:     }
  651:     if ($convert) {
  652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  653: 	    &logthis("Failed to load session, or convert session.");
  654: 	}
  655:     }
  656: 
  657:     my %remove;
  658:     while ( my $envname = each(%env) ) {
  659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  660:             if ($time < time-300) {
  661:                 $remove{$key}++;
  662:             }
  663:         }
  664:     }
  665: 
  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  667:     $env_loaded=1;
  668:     foreach my $expired_key (keys(%remove)) {
  669:         &delenv($expired_key);
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------- Check for valid session 
  674: sub check_for_valid_session {
  675:     my ($r,$name,$userhashref,$domref) = @_;
  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  678:     if ($name eq 'lonDAV') {
  679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  680:     } else {
  681:         $lonidsdir=$r->dir_config('lonIDsDir');
  682:         if ($name eq '') {
  683:             $name = 'lonID';
  684:         }
  685:     }
  686:     if ($name eq 'lonID') {
  687:         $secure = 'lonSID';
  688:         $linkname = 'lonLinkID';
  689:         $pubname = 'lonPubID';
  690:         if (exists($cookies{$secure})) {
  691:             $lonid=$cookies{$secure};
  692:         } elsif (exists($cookies{$name})) {
  693:             $lonid=$cookies{$name};
  694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  695:             $lonid=$cookies{$linkname};
  696:         } elsif (exists($cookies{$pubname})) {
  697:             $lonid=$cookies{$pubname};
  698:         }
  699:     } else {
  700:         $lonid=$cookies{$name};
  701:     }
  702:     return undef if (!$lonid);
  703: 
  704:     my $handle=&LONCAPA::clean_handle($lonid->value);
  705:     if (-l "$lonidsdir/$handle.id") {
  706:         my $link = readlink("$lonidsdir/$handle.id");
  707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  708:             $handle = $1;
  709:         }
  710:     }
  711:     if (!-e "$lonidsdir/$handle.id") {
  712:         if ((ref($domref)) && ($name eq 'lonID') && 
  713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  716:                 $$domref = $possudom;
  717:             }
  718:         }
  719:         return undef;
  720:     }
  721: 
  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  723:     return undef if (!$opened);
  724: 
  725:     flock($idf,LOCK_SH);
  726:     my %disk_env;
  727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  728: 	    &GDBM_READER(),0640)) {
  729: 	return undef;	
  730:     }
  731: 
  732:     if (!defined($disk_env{'user.name'})
  733: 	|| !defined($disk_env{'user.domain'})) {
  734:         untie(%disk_env);
  735: 	return undef;
  736:     }
  737: 
  738:     if (ref($userhashref) eq 'HASH') {
  739:         $userhashref->{'name'} = $disk_env{'user.name'};
  740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  742:         if ($userhashref->{'lti'}) {
  743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  745:         }
  746:     }
  747:     untie(%disk_env);
  748: 
  749:     return $handle;
  750: }
  751: 
  752: sub timed_flock {
  753:     my ($file,$lock_type) = @_;
  754:     my $failed=0;
  755:     eval {
  756: 	local $SIG{__DIE__}='DEFAULT';
  757: 	local $SIG{ALRM}=sub {
  758: 	    $failed=1;
  759: 	    die("failed lock");
  760: 	};
  761: 	alarm(13);
  762: 	flock($file,$lock_type);
  763: 	alarm(0);
  764:     };
  765:     if ($failed) {
  766: 	return undef;
  767:     } else {
  768: 	return 1;
  769:     }
  770: }
  771: 
  772: sub get_sessionfile_vars {
  773:     my ($handle,$lonidsdir,$storearr) = @_;
  774:     my %returnhash;
  775:     unless (ref($storearr) eq 'ARRAY') {
  776:         return %returnhash;
  777:     }
  778:     if (-l "$lonidsdir/$handle.id") {
  779:         my $link = readlink("$lonidsdir/$handle.id");
  780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  781:             $handle = $1;
  782:         }
  783:     }
  784:     if ((-e "$lonidsdir/$handle.id") &&
  785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  789:                 flock($idf,LOCK_SH);
  790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  791:                         &GDBM_READER(),0640)) {
  792:                     foreach my $item (@{$storearr}) {
  793:                         $returnhash{$item} = $disk_env{$item};
  794:                     }
  795:                     untie(%disk_env);
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return %returnhash;
  801: }
  802: 
  803: # ---------------------------------------------------------- Append Environment
  804: 
  805: sub appenv {
  806:     my ($newenv,$roles) = @_;
  807:     if (ref($newenv) eq 'HASH') {
  808:         foreach my $key (keys(%{$newenv})) {
  809:             my $refused = 0;
  810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  811:                 $refused = 1;
  812:                 if (ref($roles) eq 'ARRAY') {
  813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  815:                         $refused = 0;
  816:                     }
  817:                 }
  818:             }
  819:             if ($refused) {
  820:                 &logthis("<font color=\"blue\">WARNING: ".
  821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  822:                          .'</font>');
  823: 	        delete($newenv->{$key});
  824:             } else {
  825:                 $env{$key}=$newenv->{$key};
  826:             }
  827:         }
  828:         my $lonids = $perlvar{'lonIDsDir'};
  829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  831:             if ($opened
  832: 	        && &timed_flock($env_file,LOCK_EX)
  833: 	        &&
  834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  836: 	        while (my ($key,$value) = each(%{$newenv})) {
  837: 	            $disk_env{$key} = $value;
  838: 	        }
  839: 	        untie(%disk_env);
  840:             }
  841:         }
  842:     }
  843:     return 'ok';
  844: }
  845: # ----------------------------------------------------- Delete from Environment
  846: 
  847: sub delenv {
  848:     my ($delthis,$regexp,$roles) = @_;
  849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  850:         my $refused = 1;
  851:         if (ref($roles) eq 'ARRAY') {
  852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  853:             if (grep(/^\Q$role\E$/,@{$roles})) {
  854:                 $refused = 0;
  855:             }
  856:         }
  857:         if ($refused) {
  858:             &logthis("<font color=\"blue\">WARNING: ".
  859:                      "Attempt to delete from environment ".$delthis);
  860:             return 'error';
  861:         }
  862:     }
  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  864:     if ($opened
  865: 	&& &timed_flock($env_file,LOCK_EX)
  866: 	&&
  867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  869: 	foreach my $key (keys(%disk_env)) {
  870: 	    if ($regexp) {
  871:                 if ($key=~/^$delthis/) {
  872:                     delete($env{$key});
  873:                     delete($disk_env{$key});
  874:                 } 
  875:             } else {
  876:                 if ($key=~/^\Q$delthis\E/) {
  877: 		    delete($env{$key});
  878: 		    delete($disk_env{$key});
  879: 	        }
  880:             }
  881: 	}
  882: 	untie(%disk_env);
  883:     }
  884:     return 'ok';
  885: }
  886: 
  887: sub get_env_multiple {
  888:     my ($name) = @_;
  889:     my @values;
  890:     if (defined($env{$name})) {
  891:         # exists is it an array
  892:         if (ref($env{$name})) {
  893:             @values=@{ $env{$name} };
  894:         } else {
  895:             $values[0]=$env{$name};
  896:         }
  897:     }
  898:     return(@values);
  899: }
  900: 
  901: # ------------------------------------------------------------------- Locking
  902: 
  903: sub set_lock {
  904:     my ($text)=@_;
  905:     $locknum++;
  906:     my $id=$$.'-'.$locknum;
  907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  908:              'session.lock.'.$id => $text});
  909:     return $id;
  910: }
  911: 
  912: sub get_locks {
  913:     my $num=0;
  914:     my %texts=();
  915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  916:        if ($lock=~/\w/) {
  917:           $num++;
  918:           $texts{$lock}=$env{'session.lock.'.$lock};
  919:        }
  920:    }
  921:    return ($num,%texts);
  922: }
  923: 
  924: sub remove_lock {
  925:     my ($id)=@_;
  926:     my $newlocks='';
  927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  928:        if (($lock=~/\w/) && ($lock ne $id)) {
  929:           $newlocks.=','.$lock;
  930:        }
  931:     }
  932:     &appenv({'session.locks' => $newlocks});
  933:     &delenv('session.lock.'.$id);
  934: }
  935: 
  936: sub remove_all_locks {
  937:     my $activelocks=$env{'session.locks'};
  938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  939:        if ($lock=~/\w/) {
  940:           &remove_lock($lock);
  941:        }
  942:     }
  943: }
  944: 
  945: 
  946: # ------------------------------------------ Find out current server userload
  947: sub userload {
  948:     my $numusers=0;
  949:     {
  950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  951: 	my $filename;
  952: 	my $curtime=time;
  953: 	while ($filename=readdir(LONIDS)) {
  954: 	    next if ($filename eq '.' || $filename eq '..');
  955: 	    next if ($filename =~ /publicuser_\d+\.id/);
  956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  959: 	}
  960: 	closedir(LONIDS);
  961:     }
  962:     my $userloadpercent=0;
  963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  964:     if ($maxuserload) {
  965: 	$userloadpercent=100*$numusers/$maxuserload;
  966:     }
  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  968:     return $userloadpercent;
  969: }
  970: 
  971: # ------------------------------ Find server with least workload from spare.tab
  972: 
  973: sub spareserver {
  974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  975:     my $spare_server;
  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  978:                                                      :  $userloadpercent;
  979:     my ($uint_dom,$remotesessions);
  980:     if (($udom ne '') && (&domain($udom) ne '')) {
  981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  984:         $remotesessions = $udomdefaults{'remotesessions'};
  985:     }
  986:     my $spareshash = &this_host_spares($udom);
  987:     if (ref($spareshash) eq 'HASH') {
  988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  991:                                              $try_server));
  992: 	        ($spare_server, $lowest_load) =
  993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  994:             }
  995:         }
  996: 
  997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  998: 
  999:         if (!$found_server) {
 1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1002:                     next unless (&spare_can_host($udom,$uint_dom,
 1003:                                                  $remotesessions,$try_server));
 1004: 	            ($spare_server, $lowest_load) =
 1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1006:                 }
 1007: 	    }
 1008:         }
 1009:     }
 1010: 
 1011:     if (!$want_server_name) {
 1012:         if (defined($spare_server)) {
 1013:             my $hostname = &hostname($spare_server);
 1014:             if (defined($hostname)) {
 1015:                 my $protocol = 'http';
 1016:                 if ($protocol{$spare_server} eq 'https') {
 1017:                     $protocol = $protocol{$spare_server};
 1018:                 }
 1019: 	        $spare_server = $protocol.'://'.$hostname;
 1020:             }
 1021:         }
 1022:     }
 1023:     return $spare_server;
 1024: }
 1025: 
 1026: sub compare_server_load {
 1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1028: 
 1029:     if ($required) {
 1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1033:         if (($major eq '' && $minor eq '') ||
 1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1035:             return ($spare_server,$lowest_load);
 1036:         }
 1037:     }
 1038: 
 1039:     my $loadans     = &reply('load',    $try_server);
 1040:     my $userloadans = &reply('userload',$try_server);
 1041: 
 1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1044:     }
 1045: 
 1046:     my $load;
 1047:     if ($loadans =~ /\d/) {
 1048: 	if ($userloadans =~ /\d/) {
 1049: 	    #both are numbers, pick the bigger one
 1050: 	    $load = ($loadans > $userloadans) ? $loadans 
 1051: 		                              : $userloadans;
 1052: 	} else {
 1053: 	    $load = $loadans;
 1054: 	}
 1055:     } else {
 1056: 	$load = $userloadans;
 1057:     }
 1058: 
 1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1060: 	$spare_server = $try_server;
 1061: 	$lowest_load  = $load;
 1062:     }
 1063:     return ($spare_server,$lowest_load);
 1064: }
 1065: 
 1066: # --------------------------- ask offload servers if user already has a session
 1067: sub find_existing_session {
 1068:     my ($udom,$uname) = @_;
 1069:     my $spareshash = &this_host_spares($udom);
 1070:     if (ref($spareshash) eq 'HASH') {
 1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1074:             }
 1075:         }
 1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1079:             }
 1080:         }
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: # check if user's browser sent load balancer cookie and server still has session
 1086: # and is not overloaded.
 1087: sub check_for_balancer_cookie {
 1088:     my ($r,$update_mtime) = @_;
 1089:     my ($otherserver,$cookie);
 1090:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1091:     if (exists($cookies{'balanceID'})) {
 1092:         my $balid = $cookies{'balanceID'};
 1093:         $cookie=&LONCAPA::clean_handle($balid->value);
 1094:         my $balancedir=$r->dir_config('lonBalanceDir');
 1095:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1096:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1097:                 my ($possudom,$possuname) = ($1,$2);
 1098:                 my $has_session = 0;
 1099:                 if ((&domain($possudom) ne '') &&
 1100:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1101:                     my $try_server;
 1102:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1103:                     if ($opened) {
 1104:                         flock($idf,LOCK_SH);
 1105:                         while (my $line = <$idf>) {
 1106:                             chomp($line);
 1107:                             if (&hostname($line) ne '') {
 1108:                                 $try_server = $line;
 1109:                                 last;
 1110:                             }
 1111:                         }
 1112:                         close($idf);
 1113:                         if (($try_server) &&
 1114:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1115:                             my $lowest_load = 30000;
 1116:                             ($otherserver,$lowest_load) =
 1117:                                 &compare_server_load($try_server,undef,$lowest_load);
 1118:                             if ($otherserver ne '' && $lowest_load < 100) {
 1119:                                 $has_session = 1;
 1120:                             } else {
 1121:                                 undef($otherserver);
 1122:                             }
 1123:                         }
 1124:                     }
 1125:                 }
 1126:                 if ($has_session) {
 1127:                     if ($update_mtime) {
 1128:                         my $atime = my $mtime = time;
 1129:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1130:                     }
 1131:                 } else {
 1132:                     unlink("$balancedir/$cookie.id");
 1133:                 }
 1134:             }
 1135:         }
 1136:     }
 1137:     return ($otherserver,$cookie);
 1138: }
 1139: 
 1140: sub delbalcookie {
 1141:     my ($cookie,$balancer) =@_;
 1142:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1143:         my ($udom,$uname) = ($1,$2);
 1144:         my $uprimary_id = &domain($udom,'primary');
 1145:         my $uintdom = &internet_dom($uprimary_id);
 1146:         my $intdom = &internet_dom($balancer);
 1147:         my $serverhomedom = &host_domain($balancer);
 1148:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1149:             return &reply("delbalcookie:$cookie",$balancer);
 1150:         }
 1151:     }
 1152: }
 1153: 
 1154: # -------------------------------- ask if server already has a session for user
 1155: sub has_user_session {
 1156:     my ($lonid,$udom,$uname) = @_;
 1157:     my $result = &reply(join(':','userhassession',
 1158: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1159:     return 1 if ($result eq 'ok');
 1160: 
 1161:     return 0;
 1162: }
 1163: 
 1164: # --------- determine least loaded server in a user's domain which allows login
 1165: 
 1166: sub choose_server {
 1167:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1168:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1169:     my %servers = &get_servers($udom);
 1170:     my $lowest_load = 30000;
 1171:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1172:     if ($skiploadbal) {
 1173:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1174:         unless (defined($cached)) {
 1175:             my $cachetime = 60*60*24;
 1176:             my %domconfig =
 1177:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1178:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1179:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1180:                                            $cachetime);
 1181:             }
 1182:         }
 1183:     }
 1184:     foreach my $lonhost (keys(%servers)) {
 1185:         if ($skiploadbal) {
 1186:             if (ref($balancers) eq 'HASH') {
 1187:                 next if (exists($balancers->{$lonhost}));
 1188:             }
 1189:         }
 1190:         my $loginvia;
 1191:         if ($checkloginvia) {
 1192:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1193:             if ($loginvia) {
 1194:                 my ($server,$path) = split(/:/,$loginvia);
 1195:                 ($login_host, $lowest_load) =
 1196:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1197:                 if ($login_host eq $server) {
 1198:                     $portal_path = $path;
 1199:                     $isredirect = 1;
 1200:                 }
 1201:             } else {
 1202:                 ($login_host, $lowest_load) =
 1203:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1204:                 if ($login_host eq $lonhost) {
 1205:                     $portal_path = '';
 1206:                     $isredirect = ''; 
 1207:                 }
 1208:             }
 1209:         } else {
 1210:             ($login_host, $lowest_load) =
 1211:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1212:         }
 1213:     }
 1214:     if ($login_host ne '') {
 1215:         $hostname = &hostname($login_host);
 1216:     }
 1217:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1218: }
 1219: 
 1220: # --------------------------------------------- Try to change a user's password
 1221: 
 1222: sub changepass {
 1223:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1224:     $currentpass = &escape($currentpass);
 1225:     $newpass     = &escape($newpass);
 1226:     my $lonhost = $perlvar{'lonHostID'};
 1227:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1228: 		       $server);
 1229:     if (! $answer) {
 1230: 	&logthis("No reply on password change request to $server ".
 1231: 		 "by $uname in domain $udom.");
 1232:     } elsif ($answer =~ "^ok") {
 1233:         &logthis("$uname in $udom successfully changed their password ".
 1234: 		 "on $server.");
 1235:     } elsif ($answer =~ "^pwchange_failure") {
 1236: 	&logthis("$uname in $udom was unable to change their password ".
 1237: 		 "on $server.  The action was blocked by either lcpasswd ".
 1238: 		 "or pwchange");
 1239:     } elsif ($answer =~ "^non_authorized") {
 1240:         &logthis("$uname in $udom did not get their password correct when ".
 1241: 		 "attempting to change it on $server.");
 1242:     } elsif ($answer =~ "^auth_mode_error") {
 1243:         &logthis("$uname in $udom attempted to change their password despite ".
 1244: 		 "not being locally or internally authenticated on $server.");
 1245:     } elsif ($answer =~ "^unknown_user") {
 1246:         &logthis("$uname in $udom attempted to change their password ".
 1247: 		 "on $server but were unable to because $server is not ".
 1248: 		 "their home server.");
 1249:     } elsif ($answer =~ "^refused") {
 1250: 	&logthis("$server refused to change $uname in $udom password because ".
 1251: 		 "it was sent an unencrypted request to change the password.");
 1252:     } elsif ($answer =~ "invalid_client") {
 1253:         &logthis("$server refused to change $uname in $udom password because ".
 1254:                  "it was a reset by e-mail originating from an invalid server.");
 1255:     } elsif ($answer =~ "^prioruse") {
 1256:        &logthis("$server refused to change $uname in $udom password because ".
 1257:                 "the password had been used before");
 1258:     }
 1259:     return $answer;
 1260: }
 1261: 
 1262: # ----------------------- Try to determine user's current authentication scheme
 1263: 
 1264: sub queryauthenticate {
 1265:     my ($uname,$udom)=@_;
 1266:     my $uhome=&homeserver($uname,$udom);
 1267:     if (!$uhome) {
 1268: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1269: 	return 'no_host';
 1270:     }
 1271:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1272:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1273: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1274:     }
 1275:     return $answer;
 1276: }
 1277: 
 1278: # --------- Try to authenticate user from domain's lib servers (first this one)
 1279: 
 1280: sub authenticate {
 1281:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1282:     $upass=&escape($upass);
 1283:     $uname= &LONCAPA::clean_username($uname);
 1284:     my $uhome=&homeserver($uname,$udom,1);
 1285:     my $newhome;
 1286:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1287: # Maybe the machine was offline and only re-appeared again recently?
 1288:         &reconlonc();
 1289: # One more
 1290: 	$uhome=&homeserver($uname,$udom,1);
 1291:         if (($uhome eq 'no_host') && $checkdefauth) {
 1292:             if (defined(&domain($udom,'primary'))) {
 1293:                 $newhome=&domain($udom,'primary');
 1294:             }
 1295:             if ($newhome ne '') {
 1296:                 $uhome = $newhome;
 1297:             }
 1298:         }
 1299: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1300: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1301: 	    return 'no_host';
 1302:         }
 1303:     }
 1304:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1305:     if ($answer eq 'authorized') {
 1306:         if ($newhome) {
 1307:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1308:             return 'no_account_on_host'; 
 1309:         } else {
 1310:             &logthis("User $uname at $udom authorized by $uhome");
 1311:             return $uhome;
 1312:         }
 1313:     }
 1314:     if ($answer eq 'non_authorized') {
 1315: 	&logthis("User $uname at $udom rejected by $uhome");
 1316: 	return 'no_host'; 
 1317:     }
 1318:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1319:     return 'no_host';
 1320: }
 1321: 
 1322: sub can_host_session {
 1323:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1324:     my $canhost = 1;
 1325:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1326:     if (ref($remotesessions) eq 'HASH') {
 1327:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1328:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1329:                 $canhost = 0;
 1330:             } else {
 1331:                 $canhost = 1;
 1332:             }
 1333:         }
 1334:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1335:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1336:                 $canhost = 1;
 1337:             } else {
 1338:                 $canhost = 0;
 1339:             }
 1340:         }
 1341:         if ($canhost) {
 1342:             if ($remotesessions->{'version'} ne '') {
 1343:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1344:                 if ($reqmajor ne '' && $reqminor ne '') {
 1345:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1346:                         my $major = $1;
 1347:                         my $minor = $2;
 1348:                         if (($major < $reqmajor ) ||
 1349:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1350:                             $canhost = 0;
 1351:                         }
 1352:                     } else {
 1353:                         $canhost = 0;
 1354:                     }
 1355:                 }
 1356:             }
 1357:         }
 1358:     }
 1359:     if ($canhost) {
 1360:         if (ref($hostedsessions) eq 'HASH') {
 1361:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1362:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1363:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1364:                 if (($uint_dom ne '') && 
 1365:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1366:                     $canhost = 0;
 1367:                 } else {
 1368:                     $canhost = 1;
 1369:                 }
 1370:             }
 1371:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1372:                 if (($uint_dom ne '') && 
 1373:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1374:                     $canhost = 1;
 1375:                 } else {
 1376:                     $canhost = 0;
 1377:                 }
 1378:             }
 1379:         }
 1380:     }
 1381:     return $canhost;
 1382: }
 1383: 
 1384: sub spare_can_host {
 1385:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1386:     my $canhost=1;
 1387:     my $try_server_hostname = &hostname($try_server);
 1388:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1389:     my $serverhomedom = &host_domain($serverhomeID);
 1390:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1391:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1392:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1393:             $canhost = 0;
 1394:         }
 1395:     }
 1396:     if (($canhost) && ($uint_dom)) {
 1397:         my @intdoms;
 1398:         my $internet_names = &get_internet_names($try_server);
 1399:         if (ref($internet_names) eq 'ARRAY') {
 1400:             @intdoms = @{$internet_names};
 1401:         }
 1402:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1403:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1404:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1405:                                          $remotesessions,
 1406:                                          $defdomdefaults{'hostedsessions'});
 1407:         }
 1408:     }
 1409:     return $canhost;
 1410: }
 1411: 
 1412: sub this_host_spares {
 1413:     my ($dom) = @_;
 1414:     my ($dom_in_use,$lonhost_in_use,$result);
 1415:     my @hosts = &current_machine_ids();
 1416:     foreach my $lonhost (@hosts) {
 1417:         if (&host_domain($lonhost) eq $dom) {
 1418:             $dom_in_use = $dom;
 1419:             $lonhost_in_use = $lonhost;
 1420:             last;
 1421:         }
 1422:     }
 1423:     if ($dom_in_use ne '') {
 1424:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1425:     }
 1426:     if (ref($result) ne 'HASH') {
 1427:         $lonhost_in_use = $perlvar{'lonHostID'};
 1428:         $dom_in_use = &host_domain($lonhost_in_use);
 1429:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1430:         if (ref($result) ne 'HASH') {
 1431:             $result = \%spareid;
 1432:         }
 1433:     }
 1434:     return $result;
 1435: }
 1436: 
 1437: sub spares_for_offload  {
 1438:     my ($dom_in_use,$lonhost_in_use) = @_;
 1439:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1440:     if (defined($cached)) {
 1441:         return $result;
 1442:     } else {
 1443:         my $cachetime = 60*60*24;
 1444:         my %domconfig =
 1445:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1446:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1447:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1448:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1449:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1450:                 }
 1451:             }
 1452:         }
 1453:     }
 1454:     return;
 1455: }
 1456: 
 1457: sub get_lonbalancer_config {
 1458:     my ($servers) = @_;
 1459:     my ($currbalancer,$currtargets);
 1460:     if (ref($servers) eq 'HASH') {
 1461:         foreach my $server (keys(%{$servers})) {
 1462:             my %what = (
 1463:                          spareid => 1,
 1464:                          perlvar => 1,
 1465:                        );
 1466:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1467:             if ($result eq 'ok') {
 1468:                 if (ref($returnhash) eq 'HASH') {
 1469:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1470:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1471:                             $currbalancer = $server;
 1472:                             $currtargets = {};
 1473:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1474:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1475:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1476:                                 }
 1477:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1478:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1479:                                 }
 1480:                             }
 1481:                             last;
 1482:                         }
 1483:                     }
 1484:                 }
 1485:             }
 1486:         }
 1487:     }
 1488:     return ($currbalancer,$currtargets);
 1489: }
 1490: 
 1491: sub check_loadbalancing {
 1492:     my ($uname,$udom,$caller) = @_;
 1493:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1494:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1495:     my $lonhost = $perlvar{'lonHostID'};
 1496:     my @hosts = &current_machine_ids();
 1497:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1498:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1499:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1500:     my $serverhomedom = &host_domain($lonhost);
 1501:     my $domneedscache;
 1502:     my $cachetime = 60*60*24;
 1503: 
 1504:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1505:         $dom_in_use = $udom;
 1506:         $homeintdom = 1;
 1507:     } else {
 1508:         $dom_in_use = $serverhomedom;
 1509:     }
 1510:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1511:     unless (defined($cached)) {
 1512:         my %domconfig =
 1513:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1514:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1515:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1516:         } else {
 1517:             $domneedscache = $dom_in_use;
 1518:         }
 1519:     }
 1520:     if (ref($result) eq 'HASH') {
 1521:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1522:             &check_balancer_result($result,@hosts);
 1523:         if ($is_balancer) {
 1524:             if (ref($currrules) eq 'HASH') {
 1525:                 if ($homeintdom) {
 1526:                     if ($uname ne '') {
 1527:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1528:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1529:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1530:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1531:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1532:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1533:                             }
 1534:                         }
 1535:                         if ($rule_in_effect eq '') {
 1536:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1537:                             if ($userenv{'inststatus'} ne '') {
 1538:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1539:                                 my ($othertitle,$usertypes,$types) =
 1540:                                     &Apache::loncommon::sorted_inst_types($udom);
 1541:                                 if (ref($types) eq 'ARRAY') {
 1542:                                     foreach my $type (@{$types}) {
 1543:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1544:                                             if (exists($currrules->{$type})) {
 1545:                                                 $rule_in_effect = $currrules->{$type};
 1546:                                             }
 1547:                                         }
 1548:                                     }
 1549:                                 }
 1550:                             } else {
 1551:                                 if (exists($currrules->{'default'})) {
 1552:                                     $rule_in_effect = $currrules->{'default'};
 1553:                                 }
 1554:                             }
 1555:                         }
 1556:                     } else {
 1557:                         if (exists($currrules->{'default'})) {
 1558:                             $rule_in_effect = $currrules->{'default'};
 1559:                         }
 1560:                     }
 1561:                 } else {
 1562:                     if ($currrules->{'_LC_external'} ne '') {
 1563:                         $rule_in_effect = $currrules->{'_LC_external'};
 1564:                     }
 1565:                 }
 1566:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1567:                                                        $uname,$udom);
 1568:             }
 1569:         }
 1570:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1571:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1572:         unless (defined($cached)) {
 1573:             my %domconfig =
 1574:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1575:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1577:             } else {
 1578:                 $domneedscache = $serverhomedom;
 1579:             }
 1580:         }
 1581:         if (ref($result) eq 'HASH') {
 1582:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1583:                 &check_balancer_result($result,@hosts);
 1584:             if ($is_balancer) {
 1585:                 if (ref($currrules) eq 'HASH') {
 1586:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1587:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1588:                     }
 1589:                 }
 1590:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1591:                                                        $uname,$udom);
 1592:             }
 1593:         } else {
 1594:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1595:                 $is_balancer = 1;
 1596:                 $offloadto = &this_host_spares($dom_in_use);
 1597:             }
 1598:             unless (defined($cached)) {
 1599:                 $domneedscache = $serverhomedom;
 1600:             }
 1601:         }
 1602:     } else {
 1603:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1604:             $is_balancer = 1;
 1605:             $offloadto = &this_host_spares($dom_in_use);
 1606:         }
 1607:         unless (defined($cached)) {
 1608:             $domneedscache = $serverhomedom;
 1609:         }
 1610:     }
 1611:     if ($domneedscache) {
 1612:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1613:     }
 1614:     if ($is_balancer) {
 1615:         my $lowest_load = 30000;
 1616:         if (ref($offloadto) eq 'HASH') {
 1617:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1618:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1619:                     ($otherserver,$lowest_load) =
 1620:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1621:                 }
 1622:             }
 1623:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1624: 
 1625:             if (!$found_server) {
 1626:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1627:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1628:                         ($otherserver,$lowest_load) =
 1629:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1630:                     }
 1631:                 }
 1632:             }
 1633:         } elsif (ref($offloadto) eq 'ARRAY') {
 1634:             if (@{$offloadto} == 1) {
 1635:                 $otherserver = $offloadto->[0];
 1636:             } elsif (@{$offloadto} > 1) {
 1637:                 foreach my $try_server (@{$offloadto}) {
 1638:                     ($otherserver,$lowest_load) =
 1639:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1640:                 }
 1641:             }
 1642:         }
 1643:         unless ($caller eq 'login') {
 1644:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1645:                 $is_balancer = 0;
 1646:                 if ($uname ne '' && $udom ne '') {
 1647:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1648:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1649:                                  'user.loadbalcheck.time' => time});
 1650:                     }
 1651:                 }
 1652:             }
 1653:         }
 1654:         unless ($homeintdom) {
 1655:             undef($setcookie);
 1656:         }
 1657:     }
 1658:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1659: }
 1660: 
 1661: sub check_balancer_result {
 1662:     my ($result,@hosts) = @_;
 1663:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1664:     if (ref($result) eq 'HASH') {
 1665:         if ($result->{'lonhost'} ne '') {
 1666:             my $currbalancer = $result->{'lonhost'};
 1667:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1668:                 $is_balancer = 1;
 1669:                 $currtargets = $result->{'targets'};
 1670:                 $currrules = $result->{'rules'};
 1671:             }
 1672:             $dom_balancers = $currbalancer;
 1673:         } else {
 1674:             if (keys(%{$result})) {
 1675:                 foreach my $key (keys(%{$result})) {
 1676:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1677:                         (ref($result->{$key}) eq 'HASH')) {
 1678:                         $is_balancer = 1;
 1679:                         $currrules = $result->{$key}{'rules'};
 1680:                         $currtargets = $result->{$key}{'targets'};
 1681:                         $setcookie = $result->{$key}{'cookie'};
 1682:                         last;
 1683:                     }
 1684:                 }
 1685:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1686:             }
 1687:         }
 1688:     }
 1689:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1690: }
 1691: 
 1692: sub get_loadbalancer_targets {
 1693:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1694:     my $offloadto;
 1695:     if ($rule_in_effect eq 'none') {
 1696:         return [$perlvar{'lonHostID'}];
 1697:     } elsif ($rule_in_effect eq '') {
 1698:         $offloadto = $currtargets;
 1699:     } else {
 1700:         if ($rule_in_effect eq 'homeserver') {
 1701:             my $homeserver = &homeserver($uname,$udom);
 1702:             if ($homeserver ne 'no_host') {
 1703:                 $offloadto = [$homeserver];
 1704:             }
 1705:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1706:             my %domconfig =
 1707:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1708:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1709:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1710:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1711:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1712:                     }
 1713:                 }
 1714:             } else {
 1715:                 my %servers = &internet_dom_servers($udom);
 1716:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1717:                 if (&hostname($remotebalancer) ne '') {
 1718:                     $offloadto = [$remotebalancer];
 1719:                 }
 1720:             }
 1721:         } elsif (&hostname($rule_in_effect) ne '') {
 1722:             $offloadto = [$rule_in_effect];
 1723:         }
 1724:     }
 1725:     return $offloadto;
 1726: }
 1727: 
 1728: sub internet_dom_servers {
 1729:     my ($dom) = @_;
 1730:     my (%uniqservers,%servers);
 1731:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1732:     my @machinedoms = &machine_domains($primaryserver);
 1733:     foreach my $mdom (@machinedoms) {
 1734:         my %currservers = %servers;
 1735:         my %server = &get_servers($mdom);
 1736:         %servers = (%currservers,%server);
 1737:     }
 1738:     my %by_hostname;
 1739:     foreach my $id (keys(%servers)) {
 1740:         push(@{$by_hostname{$servers{$id}}},$id);
 1741:     }
 1742:     foreach my $hostname (sort(keys(%by_hostname))) {
 1743:         if (@{$by_hostname{$hostname}} > 1) {
 1744:             my $match = 0;
 1745:             foreach my $id (@{$by_hostname{$hostname}}) {
 1746:                 if (&host_domain($id) eq $dom) {
 1747:                     $uniqservers{$id} = $hostname;
 1748:                     $match = 1;
 1749:                 }
 1750:             }
 1751:             unless ($match) {
 1752:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1753:             }
 1754:         } else {
 1755:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1756:         }
 1757:     }
 1758:     return %uniqservers;
 1759: }
 1760: 
 1761: sub trusted_domains {
 1762:     my ($cmdtype,$calldom) = @_;
 1763:     my ($trusted,$untrusted);
 1764:     if (&domain($calldom) eq '') {
 1765:         return ($trusted,$untrusted);
 1766:     }
 1767:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1768:         return ($trusted,$untrusted);
 1769:     }
 1770:     my $callprimary = &domain($calldom,'primary');
 1771:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1772:     if ($intcalldom eq '') {
 1773:         return ($trusted,$untrusted);
 1774:     }
 1775: 
 1776:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1777:     unless (defined($cached)) {
 1778:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1779:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1780:         $trustconfig = $domconfig{'trust'};
 1781:     }
 1782:     if (ref($trustconfig)) {
 1783:         my (%possexc,%possinc,@allexc,@allinc); 
 1784:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1785:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1786:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1787:             }
 1788:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1789:                 $possinc{$intcalldom} = 1;
 1790:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1791:             }
 1792:         }
 1793:         if (keys(%possexc)) {
 1794:             if (keys(%possinc)) {
 1795:                 foreach my $key (sort(keys(%possexc))) {
 1796:                     next if ($key eq $intcalldom);
 1797:                     unless ($possinc{$key}) {
 1798:                         push(@allexc,$key);
 1799:                     }
 1800:                 }
 1801:             } else {
 1802:                 @allexc = sort(keys(%possexc));
 1803:             }
 1804:         }
 1805:         if (keys(%possinc)) {
 1806:             $possinc{$intcalldom} = 1;
 1807:             @allinc = sort(keys(%possinc));
 1808:         }
 1809:         if ((@allexc > 0) || (@allinc > 0)) {
 1810:             my %doms_by_intdom;
 1811:             my %allintdoms = &all_host_intdom();
 1812:             my %alldoms = &all_host_domain();
 1813:             foreach my $key (%allintdoms) {
 1814:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1815:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1816:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1817:                     }
 1818:                 } else {
 1819:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1820:                 }
 1821:             }
 1822:             foreach my $exc (@allexc) {
 1823:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1824:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1825:                 }
 1826:             }
 1827:             foreach my $inc (@allinc) {
 1828:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1829:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1830:                 }
 1831:             }
 1832:         }
 1833:     }
 1834:     return ($trusted,$untrusted);
 1835: }
 1836: 
 1837: sub will_trust {
 1838:     my ($cmdtype,$domain,$possdom) = @_;
 1839:     return 1 if ($domain eq $possdom);
 1840:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1841:     my $willtrust; 
 1842:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1843:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1844:             $willtrust = 1;
 1845:         }
 1846:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1847:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1848:             $willtrust = 1;
 1849:         }
 1850:     } else {
 1851:         $willtrust = 1;
 1852:     }
 1853:     return $willtrust;
 1854: }
 1855: 
 1856: # ---------------------- Find the homebase for a user from domain's lib servers
 1857: 
 1858: my %homecache;
 1859: sub homeserver {
 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
 1861:     my $index="$uname:$udom";
 1862: 
 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1864: 
 1865:     my %servers = &get_servers($udom,'library');
 1866:     foreach my $tryserver (keys(%servers)) {
 1867:         next if ($ignoreBadCache ne 'true' && 
 1868: 		 exists($badServerCache{$tryserver}));
 1869: 
 1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1871: 	if ($answer eq 'found') {
 1872: 	    delete($badServerCache{$tryserver}); 
 1873: 	    return $homecache{$index}=$tryserver;
 1874: 	} elsif ($answer eq 'no_host') {
 1875: 	    $badServerCache{$tryserver}=1;
 1876: 	}
 1877:     }    
 1878:     return 'no_host';
 1879: }
 1880: 
 1881: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1882: 
 1883: sub idget {
 1884:     my ($udom,$idsref,$namespace)=@_;
 1885:     my %returnhash=();
 1886:     my @ids=(); 
 1887:     if (ref($idsref) eq 'ARRAY') {
 1888:         @ids = @{$idsref};
 1889:     } else {
 1890:         return %returnhash; 
 1891:     }
 1892:     if ($namespace eq '') {
 1893:         $namespace = 'ids';
 1894:     }
 1895:     
 1896:     my %servers = &get_servers($udom,'library');
 1897:     foreach my $tryserver (keys(%servers)) {
 1898: 	my $idlist=join('&', map { &escape($_); } @ids);
 1899: 	if ($namespace eq 'ids') {
 1900: 	    $idlist=~tr/A-Z/a-z/;
 1901: 	}
 1902: 	my $reply;
 1903: 	if ($namespace eq 'ids') {
 1904: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1905: 	} else {
 1906: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1907: 	}
 1908: 	my @answer=();
 1909: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1910: 	    @answer=split(/\&/,$reply);
 1911: 	}                    ;
 1912: 	my $i;
 1913: 	for ($i=0;$i<=$#ids;$i++) {
 1914: 	    if ($answer[$i]) {
 1915: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1916: 	    }
 1917: 	}
 1918:     }
 1919:     return %returnhash;
 1920: }
 1921: 
 1922: # ------------------------------------- Find the IDs behind a list of usernames
 1923: 
 1924: sub idrget {
 1925:     my ($udom,@unames)=@_;
 1926:     my %returnhash=();
 1927:     foreach my $uname (@unames) {
 1928:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1929:     }
 1930:     return %returnhash;
 1931: }
 1932: 
 1933: # Store away a list of names and associated student/employee IDs or clicker IDs
 1934: 
 1935: sub idput {
 1936:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1937:     my %servers=();
 1938:     my %ids=();
 1939:     my %byid = ();
 1940:     if (ref($idsref) eq 'HASH') {
 1941:         %ids=%{$idsref};
 1942:     }
 1943:     if ($namespace eq '') {
 1944:         $namespace = 'ids'; 
 1945:     }
 1946:     foreach my $uname (keys(%ids)) {
 1947: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1948:         if ($uhom eq '') {
 1949:             $uhom=&homeserver($uname,$udom);
 1950:         }
 1951:         if ($uhom ne 'no_host') {
 1952:             my $esc_unam=&escape($uname);
 1953:             if ($namespace eq 'ids') {
 1954:                 my $id=&escape($ids{$uname});
 1955:                 $id=~tr/A-Z/a-z/;
 1956:                 my $esc_unam=&escape($uname);
 1957:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1958:             } else {
 1959:                 my @currids = split(/,/,$ids{$uname});
 1960:                 foreach my $id (@currids) {
 1961:                     $byid{$uhom}{$id} .= $uname.',';
 1962:                 }
 1963:             }
 1964:         }
 1965:     }
 1966:     if ($namespace eq 'clickers') {
 1967:         foreach my $server (keys(%byid)) {
 1968:             if (ref($byid{$server}) eq 'HASH') {
 1969:                 foreach my $id (keys(%{$byid{$server}})) {
 1970:                     $byid{$server} =~ s/,$//;
 1971:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1972:                 }
 1973:             }
 1974:         }
 1975:     }
 1976:     foreach my $server (keys(%servers)) {
 1977:         $servers{$server} =~ s/\&$//;
 1978:         if ($namespace eq 'ids') {     
 1979:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1980:         } else {
 1981:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1982:         }
 1983:     }
 1984: }
 1985: 
 1986: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1987: 
 1988: sub iddel {
 1989:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1990:     my %result=();
 1991:     my %ids=();
 1992:     my %byid = ();
 1993:     if (ref($idshashref) eq 'HASH') {
 1994:         %ids=%{$idshashref};
 1995:     } else {
 1996:         return %result;
 1997:     }
 1998:     if ($namespace eq '') {
 1999:         $namespace = 'ids';
 2000:     }
 2001:     my %servers=();
 2002:     while (my ($id,$unamestr) = each(%ids)) {
 2003:         if ($namespace eq 'ids') {
 2004:             my $uhom = $uhome;
 2005:             if ($uhom eq '') { 
 2006:                 $uhom=&homeserver($unamestr,$udom);
 2007:             }
 2008:             if ($uhom ne 'no_host') {
 2009:                 $servers{$uhom}.='&'.&escape($id);
 2010:             }
 2011:          } else {
 2012:             my @curritems = split(/,/,$ids{$id});
 2013:             foreach my $uname (@curritems) {
 2014:                 my $uhom = $uhome;
 2015:                 if ($uhom eq '') {
 2016:                     $uhom=&homeserver($uname,$udom);
 2017:                 }
 2018:                 if ($uhom ne 'no_host') { 
 2019:                     $byid{$uhom}{$id} .= $uname.',';
 2020:                 }
 2021:             }
 2022:         }
 2023:     }
 2024:     if ($namespace eq 'clickers') {
 2025:         foreach my $server (keys(%byid)) {
 2026:             if (ref($byid{$server}) eq 'HASH') {
 2027:                 foreach my $id (keys(%{$byid{$server}})) {
 2028:                     $byid{$server}{$id} =~ s/,$//;
 2029:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     foreach my $server (keys(%servers)) {
 2035:         $servers{$server} =~ s/\&$//;
 2036:         if ($namespace eq 'ids') {
 2037:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2038:         } elsif ($namespace eq 'clickers') {
 2039:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2040:         }
 2041:     }
 2042:     return %result;
 2043: }
 2044: 
 2045: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2046: 
 2047: sub updateclickers {
 2048:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2049:     my %clickers;
 2050:     if (ref($idshashref) eq 'HASH') {
 2051:         %clickers=%{$idshashref};
 2052:     } else {
 2053:         return;
 2054:     }
 2055:     my $items='';
 2056:     foreach my $item (keys(%clickers)) {
 2057:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2058:     }
 2059:     $items=~s/\&$//;
 2060:     my $request = "updateclickers:$udom:$action:$items";
 2061:     if ($critical) {
 2062:         return &critical($request,$uhome);
 2063:     } else {
 2064:         return &reply($request,$uhome);
 2065:     }
 2066: }
 2067: 
 2068: # ------------------------------dump from db file owned by domainconfig user
 2069: sub dump_dom {
 2070:     my ($namespace, $udom, $regexp) = @_;
 2071: 
 2072:     $udom ||= $env{'user.domain'};
 2073: 
 2074:     return () unless $udom;
 2075: 
 2076:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2077: }
 2078: 
 2079: # ------------------------------------------ get items from domain db files   
 2080: 
 2081: sub get_dom {
 2082:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2083:     return if ($udom eq 'public');
 2084:     my $items='';
 2085:     foreach my $item (@$storearr) {
 2086:         $items.=&escape($item).'&';
 2087:     }
 2088:     $items=~s/\&$//;
 2089:     if (!$udom) {
 2090:         $udom=$env{'user.domain'};
 2091:         return if ($udom eq 'public');
 2092:         if (defined(&domain($udom,'primary'))) {
 2093:             $uhome=&domain($udom,'primary');
 2094:         } else {
 2095:             undef($uhome);
 2096:         }
 2097:     } else {
 2098:         if (!$uhome) {
 2099:             if (defined(&domain($udom,'primary'))) {
 2100:                 $uhome=&domain($udom,'primary');
 2101:             }
 2102:         }
 2103:     }
 2104:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2105:         my $rep;
 2106:         if ($namespace =~ /^enc/) {
 2107:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2108:         } else {
 2109:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2110:         }
 2111:         my %returnhash;
 2112:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2113:             return %returnhash;
 2114:         }
 2115:         my @pairs=split(/\&/,$rep);
 2116:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2117:             return @pairs;
 2118:         }
 2119:         my $i=0;
 2120:         foreach my $item (@$storearr) {
 2121:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2122:             $i++;
 2123:         }
 2124:         return %returnhash;
 2125:     } else {
 2126:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2127:     }
 2128: }
 2129: 
 2130: # -------------------------------------------- put items in domain db files 
 2131: 
 2132: sub put_dom {
 2133:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2134:     if (!$udom) {
 2135:         $udom=$env{'user.domain'};
 2136:         if (defined(&domain($udom,'primary'))) {
 2137:             $uhome=&domain($udom,'primary');
 2138:         } else {
 2139:             undef($uhome);
 2140:         }
 2141:     } else {
 2142:         if (!$uhome) {
 2143:             if (defined(&domain($udom,'primary'))) {
 2144:                 $uhome=&domain($udom,'primary');
 2145:             }
 2146:         }
 2147:     } 
 2148:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2149:         my $items='';
 2150:         foreach my $item (keys(%$storehash)) {
 2151:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2152:         }
 2153:         $items=~s/\&$//;
 2154:         if ($namespace =~ /^enc/) {
 2155:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2156:         } else {
 2157:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2158:         }
 2159:     } else {
 2160:         &logthis("put_dom failed - no homeserver and/or domain");
 2161:     }
 2162: }
 2163: 
 2164: # --------------------- newput for items in db file owned by domainconfig user
 2165: sub newput_dom {
 2166:     my ($namespace,$storehash,$udom) = @_;
 2167:     my $result;
 2168:     if (!$udom) {
 2169:         $udom=$env{'user.domain'};
 2170:     }
 2171:     if ($udom) {
 2172:         my $uname = &get_domainconfiguser($udom);
 2173:         $result = &newput($namespace,$storehash,$udom,$uname);
 2174:     }
 2175:     return $result;
 2176: }
 2177: 
 2178: # --------------------- delete for items in db file owned by domainconfig user
 2179: sub del_dom {
 2180:     my ($namespace,$storearr,$udom)=@_;
 2181:     if (ref($storearr) eq 'ARRAY') {
 2182:         if (!$udom) {
 2183:             $udom=$env{'user.domain'};
 2184:         }
 2185:         if ($udom) {
 2186:             my $uname = &get_domainconfiguser($udom); 
 2187:             return &del($namespace,$storearr,$udom,$uname);
 2188:         }
 2189:     }
 2190: }
 2191: 
 2192: # ----------------------------------construct domainconfig user for a domain 
 2193: sub get_domainconfiguser {
 2194:     my ($udom) = @_;
 2195:     return $udom.'-domainconfig';
 2196: }
 2197: 
 2198: sub retrieve_inst_usertypes {
 2199:     my ($udom) = @_;
 2200:     my (%returnhash,@order);
 2201:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2202:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2203:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2204:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2205:     } else {
 2206:         if (defined(&domain($udom,'primary'))) {
 2207:             my $uhome=&domain($udom,'primary');
 2208:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2209:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2210:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2211:                 return (\%returnhash,\@order);
 2212:             }
 2213:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2214:             my @pairs=split(/\&/,$hashitems);
 2215:             foreach my $item (@pairs) {
 2216:                 my ($key,$value)=split(/=/,$item,2);
 2217:                 $key = &unescape($key);
 2218:                 next if ($key =~ /^error: 2 /);
 2219:                 $returnhash{$key}=&thaw_unescape($value);
 2220:             }
 2221:             my @esc_order = split(/\&/,$orderitems);
 2222:             foreach my $item (@esc_order) {
 2223:                 push(@order,&unescape($item));
 2224:             }
 2225:         } else {
 2226:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2227:         }
 2228:         return (\%returnhash,\@order);
 2229:     }
 2230: }
 2231: 
 2232: sub is_domainimage {
 2233:     my ($url) = @_;
 2234:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2235:         if (&domain($1) ne '') {
 2236:             return '1';
 2237:         }
 2238:     }
 2239:     return;
 2240: }
 2241: 
 2242: sub inst_directory_query {
 2243:     my ($srch) = @_;
 2244:     my $udom = $srch->{'srchdomain'};
 2245:     my %results;
 2246:     my $homeserver = &domain($udom,'primary');
 2247:     my $outcome;
 2248:     if ($homeserver ne '') {
 2249:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2250:             if ($srch->{'srchby'} eq 'email') {
 2251:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2252:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2253:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2254:                     (($major == 2) && ($minor < 12))) {
 2255:                     return;
 2256:                 }
 2257:             }
 2258:         }
 2259: 	my $queryid=&reply("querysend:instdirsearch:".
 2260: 			   &escape($srch->{'srchby'}).':'.
 2261: 			   &escape($srch->{'srchterm'}).':'.
 2262: 			   &escape($srch->{'srchtype'}),$homeserver);
 2263: 	my $host=&hostname($homeserver);
 2264: 	if ($queryid !~/^\Q$host\E\_/) {
 2265: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2266: 	    return;
 2267: 	}
 2268: 	my $response = &get_query_reply($queryid);
 2269: 	my $maxtries = 5;
 2270: 	my $tries = 1;
 2271: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2272: 	    $response = &get_query_reply($queryid);
 2273: 	    $tries ++;
 2274: 	}
 2275: 
 2276:         if (!&error($response) && $response ne 'refused') {
 2277:             if ($response eq 'unavailable') {
 2278:                 $outcome = $response;
 2279:             } else {
 2280:                 $outcome = 'ok';
 2281:                 my @matches = split(/\n/,$response);
 2282:                 foreach my $match (@matches) {
 2283:                     my ($key,$value) = split(/=/,$match);
 2284:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2285:                 }
 2286:             }
 2287:         }
 2288:     }
 2289:     return ($outcome,%results);
 2290: }
 2291: 
 2292: sub usersearch {
 2293:     my ($srch) = @_;
 2294:     my $dom = $srch->{'srchdomain'};
 2295:     my %results;
 2296:     my %libserv = &all_library();
 2297:     my $query = 'usersearch';
 2298:     foreach my $tryserver (keys(%libserv)) {
 2299:         if (&host_domain($tryserver) eq $dom) {
 2300:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2301:                 if ($srch->{'srchby'} eq 'email') {
 2302:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2303:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2304:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2305:                              (($major == 2) && ($minor < 12)));
 2306:                 }
 2307:             }
 2308:             my $host=&hostname($tryserver);
 2309:             my $queryid=
 2310:                 &reply("querysend:".&escape($query).':'.
 2311:                        &escape($srch->{'srchby'}).':'.
 2312:                        &escape($srch->{'srchtype'}).':'.
 2313:                        &escape($srch->{'srchterm'}),$tryserver);
 2314:             if ($queryid !~/^\Q$host\E\_/) {
 2315:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2316:                 next;
 2317:             }
 2318:             my $reply = &get_query_reply($queryid);
 2319:             my $maxtries = 1;
 2320:             my $tries = 1;
 2321:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2322:                 $reply = &get_query_reply($queryid);
 2323:                 $tries ++;
 2324:             }
 2325:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2326:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2327:             } else {
 2328:                 my @matches;
 2329:                 if ($reply =~ /\n/) {
 2330:                     @matches = split(/\n/,$reply);
 2331:                 } else {
 2332:                     @matches = split(/\&/,$reply);
 2333:                 }
 2334:                 foreach my $match (@matches) {
 2335:                     my ($uname,$udom,%userhash);
 2336:                     foreach my $entry (split(/:/,$match)) {
 2337:                         my ($key,$value) =
 2338:                             map {&unescape($_);} split(/=/,$entry);
 2339:                         $userhash{$key} = $value;
 2340:                         if ($key eq 'username') {
 2341:                             $uname = $value;
 2342:                         } elsif ($key eq 'domain') {
 2343:                             $udom = $value;
 2344:                         }
 2345:                     }
 2346:                     $results{$uname.':'.$udom} = \%userhash;
 2347:                 }
 2348:             }
 2349:         }
 2350:     }
 2351:     return %results;
 2352: }
 2353: 
 2354: sub get_instuser {
 2355:     my ($udom,$uname,$id) = @_;
 2356:     my $homeserver = &domain($udom,'primary');
 2357:     my ($outcome,%results);
 2358:     if ($homeserver ne '') {
 2359:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2360:                            &escape($id).':'.&escape($udom),$homeserver);
 2361:         my $host=&hostname($homeserver);
 2362:         if ($queryid !~/^\Q$host\E\_/) {
 2363:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2364:             return;
 2365:         }
 2366:         my $response = &get_query_reply($queryid);
 2367:         my $maxtries = 5;
 2368:         my $tries = 1;
 2369:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2370:             $response = &get_query_reply($queryid);
 2371:             $tries ++;
 2372:         }
 2373:         if (!&error($response) && $response ne 'refused') {
 2374:             if ($response eq 'unavailable') {
 2375:                 $outcome = $response;
 2376:             } else {
 2377:                 $outcome = 'ok';
 2378:                 my @matches = split(/\n/,$response);
 2379:                 foreach my $match (@matches) {
 2380:                     my ($key,$value) = split(/=/,$match);
 2381:                     $results{&unescape($key)} = &thaw_unescape($value);
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     my %userinfo;
 2387:     if (ref($results{$uname}) eq 'HASH') {
 2388:         %userinfo = %{$results{$uname}};
 2389:     } 
 2390:     return ($outcome,%userinfo);
 2391: }
 2392: 
 2393: sub get_multiple_instusers {
 2394:     my ($udom,$users,$caller) = @_;
 2395:     my ($outcome,$results);
 2396:     if (ref($users) eq 'HASH') {
 2397:         my $count = keys(%{$users}); 
 2398:         my $requested = &freeze_escape($users);
 2399:         my $homeserver = &domain($udom,'primary');
 2400:         if ($homeserver ne '') {
 2401:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2402:             my $host=&hostname($homeserver);
 2403:             if ($queryid !~/^\Q$host\E\_/) {
 2404:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2405:                          ' for host: '.$homeserver.'in domain '.$udom);
 2406:                 return ($outcome,$results);
 2407:             }
 2408:             my $response = &get_query_reply($queryid);
 2409:             my $maxtries = 5;
 2410:             if ($count > 100) {
 2411:                 $maxtries = 1+int($count/20);
 2412:             }
 2413:             my $tries = 1;
 2414:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2415:                 $response = &get_query_reply($queryid);
 2416:                 $tries ++;
 2417:             }
 2418:             if ($response eq '') {
 2419:                 $results = {};
 2420:                 foreach my $key (keys(%{$users})) {
 2421:                     my ($uname,$id);
 2422:                     if ($caller eq 'id') {
 2423:                         $id = $key;
 2424:                     } else {
 2425:                         $uname = $key;
 2426:                     }
 2427:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2428:                     $outcome = $resp;
 2429:                     if ($resp eq 'ok') {
 2430:                         %{$results} = (%{$results}, %info);
 2431:                     } else {
 2432:                         last;
 2433:                     }
 2434:                 }
 2435:             } elsif(!&error($response) && ($response ne 'refused')) {
 2436:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2437:                     $outcome = $response;
 2438:                 } else {
 2439:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2440:                     if ($outcome eq 'ok') {
 2441:                         $results = &thaw_unescape($userdata); 
 2442:                     }
 2443:                 }
 2444:             }
 2445:         }
 2446:     }
 2447:     return ($outcome,$results);
 2448: }
 2449: 
 2450: sub inst_rulecheck {
 2451:     my ($udom,$uname,$id,$item,$rules) = @_;
 2452:     my %returnhash;
 2453:     if ($udom ne '') {
 2454:         if (ref($rules) eq 'ARRAY') {
 2455:             @{$rules} = map {&escape($_);} (@{$rules});
 2456:             my $rulestr = join(':',@{$rules});
 2457:             my $homeserver=&domain($udom,'primary');
 2458:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2459:                 my $response;
 2460:                 if ($item eq 'username') {                
 2461:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2462:                                               ':'.&escape($uname).':'.$rulestr,
 2463:                                               $homeserver));
 2464:                 } elsif ($item eq 'id') {
 2465:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2466:                                               ':'.&escape($id).':'.$rulestr,
 2467:                                               $homeserver));
 2468:                 } elsif ($item eq 'selfcreate') {
 2469:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2470:                                                &escape($udom).':'.&escape($uname).
 2471:                                               ':'.$rulestr,$homeserver));
 2472:                 }
 2473:                 if ($response ne 'refused') {
 2474:                     my @pairs=split(/\&/,$response);
 2475:                     foreach my $item (@pairs) {
 2476:                         my ($key,$value)=split(/=/,$item,2);
 2477:                         $key = &unescape($key);
 2478:                         next if ($key =~ /^error: 2 /);
 2479:                         $returnhash{$key}=&thaw_unescape($value);
 2480:                     }
 2481:                 }
 2482:             }
 2483:         }
 2484:     }
 2485:     return %returnhash;
 2486: }
 2487: 
 2488: sub inst_userrules {
 2489:     my ($udom,$check) = @_;
 2490:     my (%ruleshash,@ruleorder);
 2491:     if ($udom ne '') {
 2492:         my $homeserver=&domain($udom,'primary');
 2493:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2494:             my $response;
 2495:             if ($check eq 'id') {
 2496:                 $response=&reply('instidrules:'.&escape($udom),
 2497:                                  $homeserver);
 2498:             } elsif ($check eq 'email') {
 2499:                 $response=&reply('instemailrules:'.&escape($udom),
 2500:                                  $homeserver);
 2501:             } else {
 2502:                 $response=&reply('instuserrules:'.&escape($udom),
 2503:                                  $homeserver);
 2504:             }
 2505:             if (($response ne 'refused') && ($response ne 'error') && 
 2506:                 ($response ne 'unknown_cmd') && 
 2507:                 ($response ne 'no_such_host')) {
 2508:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2509:                 my @pairs=split(/\&/,$hashitems);
 2510:                 foreach my $item (@pairs) {
 2511:                     my ($key,$value)=split(/=/,$item,2);
 2512:                     $key = &unescape($key);
 2513:                     next if ($key =~ /^error: 2 /);
 2514:                     $ruleshash{$key}=&thaw_unescape($value);
 2515:                 }
 2516:                 my @esc_order = split(/\&/,$orderitems);
 2517:                 foreach my $item (@esc_order) {
 2518:                     push(@ruleorder,&unescape($item));
 2519:                 }
 2520:             }
 2521:         }
 2522:     }
 2523:     return (\%ruleshash,\@ruleorder);
 2524: }
 2525: 
 2526: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2527: 
 2528: sub get_domain_defaults {
 2529:     my ($domain,$ignore_cache) = @_;
 2530:     return if (($domain eq '') || ($domain eq 'public'));
 2531:     my $cachetime = 60*60*24;
 2532:     unless ($ignore_cache) {
 2533:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2534:         if (defined($cached)) {
 2535:             if (ref($result) eq 'HASH') {
 2536:                 return %{$result};
 2537:             }
 2538:         }
 2539:     }
 2540:     my %domdefaults;
 2541:     my %domconfig =
 2542:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2543:                                   'requestcourses','inststatus',
 2544:                                   'coursedefaults','usersessions',
 2545:                                   'requestauthor','selfenrollment',
 2546:                                   'coursecategories','ssl','autoenroll',
 2547:                                   'trust','helpsettings'],$domain);
 2548:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2549:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2550:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2551:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2552:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2553:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2554:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2555:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2556:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2557:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2558:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2559:     } else {
 2560:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2561:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2562:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2563:     }
 2564:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2565:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2566:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2567:         } else {
 2568:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2569:         }
 2570:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2571:         foreach my $item (@usertools) {
 2572:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2573:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2574:             }
 2575:         }
 2576:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2577:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2578:         }
 2579:     }
 2580:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2581:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2582:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2583:         }
 2584:     }
 2585:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2586:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2587:     }
 2588:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2589:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2590:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2591:         }
 2592:     }
 2593:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2594:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2595:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2596:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2597:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2598:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2599:         }
 2600:         foreach my $type (@coursetypes) {
 2601:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2602:                 unless ($type eq 'community') {
 2603:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2604:                 }
 2605:             }
 2606:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2607:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2608:             }
 2609:             if ($domdefaults{'postsubmit'} eq 'on') {
 2610:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2611:                     $domdefaults{$type.'postsubtimeout'} = 
 2612:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2613:                 }
 2614:             }
 2615:         }
 2616:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2617:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2618:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2619:                 if (@clonecodes) {
 2620:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2621:                 }
 2622:             }
 2623:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2624:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2625:         }
 2626:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2627:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2628:         } 
 2629:     }
 2630:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2631:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2632:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2633:         }
 2634:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2635:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2636:         }
 2637:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2638:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2639:         }
 2640:     }
 2641:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2642:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2643:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2644:                             'approval','limit');
 2645:             foreach my $type (@coursetypes) {
 2646:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2647:                     my @mgrdc = ();
 2648:                     foreach my $item (@settings) {
 2649:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2650:                             push(@mgrdc,$item);
 2651:                         }
 2652:                     }
 2653:                     if (@mgrdc) {
 2654:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2655:                     }
 2656:                 }
 2657:             }
 2658:         }
 2659:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2660:             foreach my $type (@coursetypes) {
 2661:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2662:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2663:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2664:                     }
 2665:                 }
 2666:             }
 2667:         }
 2668:     }
 2669:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2670:         $domdefaults{'catauth'} = 'std';
 2671:         $domdefaults{'catunauth'} = 'std';
 2672:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2673:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2674:         }
 2675:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2676:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2677:         }
 2678:     }
 2679:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2680:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2681:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2682:         }
 2683:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2684:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2685:         }
 2686:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2687:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2688:         }
 2689:     }
 2690:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2691:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2692:         foreach my $prefix (@prefixes) {
 2693:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2694:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2695:             }
 2696:         }
 2697:     }
 2698:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2699:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2700:     }
 2701:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2702:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2703:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2704:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2705:         }
 2706:     }
 2707:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2708:     return %domdefaults;
 2709: }
 2710: 
 2711: sub course_portal_url {
 2712:     my ($cnum,$cdom) = @_;
 2713:     my $chome = &homeserver($cnum,$cdom);
 2714:     my $hostname = &hostname($chome);
 2715:     my $protocol = $protocol{$chome};
 2716:     $protocol = 'http' if ($protocol ne 'https');
 2717:     my %domdefaults = &get_domain_defaults($cdom);
 2718:     my $firsturl;
 2719:     if ($domdefaults{'portal_def'}) {
 2720:         $firsturl = $domdefaults{'portal_def'};
 2721:     } else {
 2722:         $firsturl = $protocol.'://'.$hostname;
 2723:     }
 2724:     return $firsturl;
 2725: }
 2726: 
 2727: # --------------------------------------------- Get domain config for passwords
 2728: 
 2729: sub get_passwdconf {
 2730:     my ($dom) = @_;
 2731:     my (%passwdconf,$gotconf,$lookup);
 2732:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2733:     if (defined($cached)) {
 2734:         if (ref($result) eq 'HASH') {
 2735:             %passwdconf = %{$result};
 2736:             $gotconf = 1;
 2737:         }
 2738:     }
 2739:     unless ($gotconf) {
 2740:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2741:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2742:             %passwdconf = %{$domconfig{'passwords'}};
 2743:         }
 2744:         my $cachetime = 24*60*60;
 2745:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2746:     }
 2747:     return %passwdconf;
 2748: }
 2749: 
 2750: # --------------------------------------------------- Assign a key to a student
 2751: 
 2752: sub assign_access_key {
 2753: #
 2754: # a valid key looks like uname:udom#comments
 2755: # comments are being appended
 2756: #
 2757:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2758:     $kdom=
 2759:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2760:     $knum=
 2761:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2762:     $cdom=
 2763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2764:     $cnum=
 2765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2766:     $udom=$env{'user.name'} unless (defined($udom));
 2767:     $uname=$env{'user.domain'} unless (defined($uname));
 2768:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2769:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2770:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2771:                                                   # assigned to this person
 2772:                                                   # - this should not happen,
 2773:                                                   # unless something went wrong
 2774:                                                   # the first time around
 2775: # ready to assign
 2776:         $logentry=$1.'; '.$logentry;
 2777:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2778:                                                  $kdom,$knum) eq 'ok') {
 2779: # key now belongs to user
 2780: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2781:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2782:                 &appenv({'environment.'.$envkey => $ckey});
 2783:                 return 'ok';
 2784:             } else {
 2785:                 return 
 2786:   'error: Count not permanently assign key, will need to be re-entered later.';
 2787: 	    }
 2788:         } else {
 2789:             return 'error: Could not assign key, try again later.';
 2790:         }
 2791:     } elsif (!$existing{$ckey}) {
 2792: # the key does not exist
 2793: 	return 'error: The key does not exist';
 2794:     } else {
 2795: # the key is somebody else's
 2796: 	return 'error: The key is already in use';
 2797:     }
 2798: }
 2799: 
 2800: # ------------------------------------------ put an additional comment on a key
 2801: 
 2802: sub comment_access_key {
 2803: #
 2804: # a valid key looks like uname:udom#comments
 2805: # comments are being appended
 2806: #
 2807:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2808:     $cdom=
 2809:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2810:     $cnum=
 2811:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2812:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2813:     if ($existing{$ckey}) {
 2814:         $existing{$ckey}.='; '.$logentry;
 2815: # ready to assign
 2816:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2817:                                                  $cdom,$cnum) eq 'ok') {
 2818: 	    return 'ok';
 2819:         } else {
 2820: 	    return 'error: Count not store comment.';
 2821:         }
 2822:     } else {
 2823: # the key does not exist
 2824: 	return 'error: The key does not exist';
 2825:     }
 2826: }
 2827: 
 2828: # ------------------------------------------------------ Generate a set of keys
 2829: 
 2830: sub generate_access_keys {
 2831:     my ($number,$cdom,$cnum,$logentry)=@_;
 2832:     $cdom=
 2833:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2834:     $cnum=
 2835:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2836:     unless (&allowed('mky',$cdom)) { return 0; }
 2837:     unless (($cdom) && ($cnum)) { return 0; }
 2838:     if ($number>10000) { return 0; }
 2839:     sleep(2); # make sure don't get same seed twice
 2840:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2841:     my $total=0;
 2842:     for (my $i=1;$i<=$number;$i++) {
 2843:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2844:                   sprintf("%lx",int(100000*rand)).'-'.
 2845:                   sprintf("%lx",int(100000*rand));
 2846:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2847:        $newkey=~s/0/h/g; # and also 0 and O
 2848:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2849:        if ($existing{$newkey}) {
 2850:            $i--;
 2851:        } else {
 2852: 	  if (&put('accesskeys',
 2853:               { $newkey => '# generated '.localtime().
 2854:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2855:                            '; '.$logentry },
 2856: 		   $cdom,$cnum) eq 'ok') {
 2857:               $total++;
 2858: 	  }
 2859:        }
 2860:     }
 2861:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2862:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2863:     return $total;
 2864: }
 2865: 
 2866: # ------------------------------------------------------- Validate an accesskey
 2867: 
 2868: sub validate_access_key {
 2869:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2870:     $cdom=
 2871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2872:     $cnum=
 2873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2874:     $udom=$env{'user.domain'} unless (defined($udom));
 2875:     $uname=$env{'user.name'} unless (defined($uname));
 2876:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2877:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2878: }
 2879: 
 2880: # ------------------------------------- Find the section of student in a course
 2881: sub devalidate_getsection_cache {
 2882:     my ($udom,$unam,$courseid)=@_;
 2883:     my $hashid="$udom:$unam:$courseid";
 2884:     &devalidate_cache_new('getsection',$hashid);
 2885: }
 2886: 
 2887: sub courseid_to_courseurl {
 2888:     my ($courseid) = @_;
 2889:     #already url style courseid
 2890:     return $courseid if ($courseid =~ m{^/});
 2891: 
 2892:     if (exists($env{'course.'.$courseid.'.num'})) {
 2893: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2894: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2895: 	return "/$cdom/$cnum";
 2896:     }
 2897: 
 2898:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2899:     if (exists($courseinfo{'num'})) {
 2900: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2901:     }
 2902: 
 2903:     return undef;
 2904: }
 2905: 
 2906: sub getsection {
 2907:     my ($udom,$unam,$courseid)=@_;
 2908:     my $cachetime=1800;
 2909: 
 2910:     my $hashid="$udom:$unam:$courseid";
 2911:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2912:     if (defined($cached)) { return $result; }
 2913: 
 2914:     my %Pending; 
 2915:     my %Expired;
 2916:     #
 2917:     # Each role can either have not started yet (pending), be active, 
 2918:     #    or have expired.
 2919:     #
 2920:     # If there is an active role, we are done.
 2921:     #
 2922:     # If there is more than one role which has not started yet, 
 2923:     #     choose the one which will start sooner
 2924:     # If there is one role which has not started yet, return it.
 2925:     #
 2926:     # If there is more than one expired role, choose the one which ended last.
 2927:     # If there is a role which has expired, return it.
 2928:     #
 2929:     $courseid = &courseid_to_courseurl($courseid);
 2930:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2931:     foreach my $key (keys(%roleshash)) {
 2932:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2933:         my $section=$1;
 2934:         if ($key eq $courseid.'_st') { $section=''; }
 2935:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2936:         my $now=time;
 2937:         if (defined($end) && $end && ($now > $end)) {
 2938:             $Expired{$end}=$section;
 2939:             next;
 2940:         }
 2941:         if (defined($start) && $start && ($now < $start)) {
 2942:             $Pending{$start}=$section;
 2943:             next;
 2944:         }
 2945:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2946:     }
 2947:     #
 2948:     # Presumedly there will be few matching roles from the above
 2949:     # loop and the sorting time will be negligible.
 2950:     if (scalar(keys(%Pending))) {
 2951:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2952:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2953:     } 
 2954:     if (scalar(keys(%Expired))) {
 2955:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2956:         my $time = pop(@sorted);
 2957:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2958:     }
 2959:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2960: }
 2961: 
 2962: sub save_cache {
 2963:     &purge_remembered();
 2964:     #&Apache::loncommon::validate_page();
 2965:     undef(%env);
 2966:     undef($env_loaded);
 2967: }
 2968: 
 2969: my $to_remember=-1;
 2970: my %remembered;
 2971: my %accessed;
 2972: my $kicks=0;
 2973: my $hits=0;
 2974: sub make_key {
 2975:     my ($name,$id) = @_;
 2976:     if (length($id) > 65 
 2977: 	&& length(&escape($id)) > 200) {
 2978: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2979:     }
 2980:     return &escape($name.':'.$id);
 2981: }
 2982: 
 2983: sub devalidate_cache_new {
 2984:     my ($name,$id,$debug) = @_;
 2985:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2986:     my $remembered_id=$name.':'.$id;
 2987:     $id=&make_key($name,$id);
 2988:     $memcache->delete($id);
 2989:     delete($remembered{$remembered_id});
 2990:     delete($accessed{$remembered_id});
 2991: }
 2992: 
 2993: sub is_cached_new {
 2994:     my ($name,$id,$debug) = @_;
 2995:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2996:     if (exists($remembered{$remembered_id})) {
 2997: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2998: 	$accessed{$remembered_id}=[&gettimeofday()];
 2999: 	$hits++;
 3000: 	return ($remembered{$remembered_id},1);
 3001:     }
 3002:     $id=&make_key($name,$id);
 3003:     my $value = $memcache->get($id);
 3004:     if (!(defined($value))) {
 3005: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3006: 	return (undef,undef);
 3007:     }
 3008:     if ($value eq '__undef__') {
 3009: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3010: 	$value=undef;
 3011:     }
 3012:     &make_room($remembered_id,$value,$debug);
 3013:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3014:     return ($value,1);
 3015: }
 3016: 
 3017: sub do_cache_new {
 3018:     my ($name,$id,$value,$time,$debug) = @_;
 3019:     my $remembered_id=$name.':'.$id;
 3020:     $id=&make_key($name,$id);
 3021:     my $setvalue=$value;
 3022:     if (!defined($setvalue)) {
 3023: 	$setvalue='__undef__';
 3024:     }
 3025:     if (!defined($time) ) {
 3026: 	$time=600;
 3027:     }
 3028:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3029:     my $result = $memcache->set($id,$setvalue,$time);
 3030:     if (! $result) {
 3031: 	&logthis("caching of id -> $id  failed");
 3032: 	$memcache->disconnect_all();
 3033:     }
 3034:     # need to make a copy of $value
 3035:     &make_room($remembered_id,$value,$debug);
 3036:     return $value;
 3037: }
 3038: 
 3039: sub make_room {
 3040:     my ($remembered_id,$value,$debug)=@_;
 3041: 
 3042:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3043:                                     : $value;
 3044:     if ($to_remember<0) { return; }
 3045:     $accessed{$remembered_id}=[&gettimeofday()];
 3046:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3047:     my $to_kick;
 3048:     my $max_time=0;
 3049:     foreach my $other (keys(%accessed)) {
 3050: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3051: 	    $to_kick=$other;
 3052: 	    $max_time=&tv_interval($accessed{$other});
 3053: 	}
 3054:     }
 3055:     delete($remembered{$to_kick});
 3056:     delete($accessed{$to_kick});
 3057:     $kicks++;
 3058:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3059:     return;
 3060: }
 3061: 
 3062: sub purge_remembered {
 3063:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3064:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3065:     undef(%remembered);
 3066:     undef(%accessed);
 3067: }
 3068: # ------------------------------------- Read an entry from a user's environment
 3069: 
 3070: sub userenvironment {
 3071:     my ($udom,$unam,@what)=@_;
 3072:     my $items;
 3073:     foreach my $item (@what) {
 3074:         $items.=&escape($item).'&';
 3075:     }
 3076:     $items=~s/\&$//;
 3077:     my %returnhash=();
 3078:     my $uhome = &homeserver($unam,$udom);
 3079:     unless ($uhome eq 'no_host') {
 3080:         my @answer=split(/\&/, 
 3081:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3082:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3083:             return %returnhash;
 3084:         }
 3085:         my $i;
 3086:         for ($i=0;$i<=$#what;$i++) {
 3087: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3088:         }
 3089:     }
 3090:     return %returnhash;
 3091: }
 3092: 
 3093: # ---------------------------------------------------------- Get a studentphoto
 3094: sub studentphoto {
 3095:     my ($udom,$unam,$ext) = @_;
 3096:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3097:     if (defined($env{'request.course.id'})) {
 3098:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3099:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3100:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3101:             } else {
 3102:                 my ($result,$perm_reqd)=
 3103: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3104:                 if ($result eq 'ok') {
 3105:                     if (!($perm_reqd eq 'yes')) {
 3106:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3107:                     }
 3108:                 }
 3109:             }
 3110:         }
 3111:     } else {
 3112:         my ($result,$perm_reqd) = 
 3113: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3114:         if ($result eq 'ok') {
 3115:             if (!($perm_reqd eq 'yes')) {
 3116:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3117:             }
 3118:         }
 3119:     }
 3120:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3121: }
 3122: 
 3123: sub retrievestudentphoto {
 3124:     my ($udom,$unam,$ext,$type) = @_;
 3125:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3126:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3127:     if ($ret eq 'ok') {
 3128:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3129:         if ($type eq 'thumbnail') {
 3130:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3131:         }
 3132:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3133:         return $tokenurl;
 3134:     } else {
 3135:         if ($type eq 'thumbnail') {
 3136:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3137:         } else { 
 3138:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3139:         }
 3140:     }
 3141: }
 3142: 
 3143: # -------------------------------------------------------------------- New chat
 3144: 
 3145: sub chatsend {
 3146:     my ($newentry,$anon,$group)=@_;
 3147:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3148:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3149:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3150:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3151: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3152: 		   &escape($newentry)).':'.$group,$chome);
 3153: }
 3154: 
 3155: # ------------------------------------------ Find current version of a resource
 3156: 
 3157: sub getversion {
 3158:     my $fname=&clutter(shift);
 3159:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3160:     return &currentversion(&filelocation('',$fname));
 3161: }
 3162: 
 3163: sub currentversion {
 3164:     my $fname=shift;
 3165:     my $author=$fname;
 3166:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3167:     my ($udom,$uname)=split(/\//,$author);
 3168:     my $home=&homeserver($uname,$udom);
 3169:     if ($home eq 'no_host') { 
 3170:         return -1; 
 3171:     }
 3172:     my $answer=&reply("currentversion:$fname",$home);
 3173:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3174: 	return -1;
 3175:     }
 3176:     return $answer;
 3177: }
 3178: 
 3179: #
 3180: # Return special version number of resource if set by override, empty otherwise
 3181: #
 3182: sub usedversion {
 3183:     my $fname=shift;
 3184:     unless ($fname) { $fname=$env{'request.uri'}; }
 3185:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3186:     if ($urlversion) { return $urlversion; }
 3187:     return '';
 3188: }
 3189: 
 3190: # ----------------------------- Subscribe to a resource, return URL if possible
 3191: 
 3192: sub subscribe {
 3193:     my $fname=shift;
 3194:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3195:     $fname=~s/[\n\r]//g;
 3196:     my $author=$fname;
 3197:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3198:     my ($udom,$uname)=split(/\//,$author);
 3199:     my $home=homeserver($uname,$udom);
 3200:     if ($home eq 'no_host') {
 3201:         return 'not_found';
 3202:     }
 3203:     my $answer=reply("sub:$fname",$home);
 3204:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3205: 	$answer.=' by '.$home;
 3206:     }
 3207:     return $answer;
 3208: }
 3209:     
 3210: # -------------------------------------------------------------- Replicate file
 3211: 
 3212: sub repcopy {
 3213:     my $filename=shift;
 3214:     $filename=~s/\/+/\//g;
 3215:     my $londocroot = $perlvar{'lonDocRoot'};
 3216:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3217:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3218:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3219: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3220: 	return &repcopy_userfile($filename);
 3221:     }
 3222:     $filename=~s/[\n\r]//g;
 3223:     my $transname="$filename.in.transfer";
 3224: # FIXME: this should flock
 3225:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3226:     my $remoteurl=subscribe($filename);
 3227:     if ($remoteurl =~ /^con_lost by/) {
 3228: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3229:            return 'unavailable';
 3230:     } elsif ($remoteurl eq 'not_found') {
 3231: 	   #&logthis("Subscribe returned not_found: $filename");
 3232: 	   return 'not_found';
 3233:     } elsif ($remoteurl =~ /^rejected by/) {
 3234: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3235:            return 'forbidden';
 3236:     } elsif ($remoteurl eq 'directory') {
 3237:            return 'ok';
 3238:     } else {
 3239:         my $author=$filename;
 3240:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3241:         my ($udom,$uname)=split(/\//,$author);
 3242:         my $home=homeserver($uname,$udom);
 3243:         unless ($home eq $perlvar{'lonHostID'}) {
 3244:            my @parts=split(/\//,$filename);
 3245:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3246:            if ($path ne "$londocroot/res") {
 3247:                &logthis("Malconfiguration for replication: $filename");
 3248: 	       return 'bad_request';
 3249:            }
 3250:            my $count;
 3251:            for ($count=5;$count<$#parts;$count++) {
 3252:                $path.="/$parts[$count]";
 3253:                if ((-e $path)!=1) {
 3254: 		   mkdir($path,0777);
 3255:                }
 3256:            }
 3257:            my $request=new HTTP::Request('GET',"$remoteurl");
 3258:            my $response;
 3259:            if ($remoteurl =~ m{/raw/}) {
 3260:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3261:            } else {
 3262:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3263:            }
 3264:            if ($response->is_error()) {
 3265: 	       unlink($transname);
 3266:                my $message=$response->status_line;
 3267:                &logthis("<font color=\"blue\">WARNING:"
 3268:                        ." LWP get: $message: $filename</font>");
 3269:                return 'unavailable';
 3270:            } else {
 3271: 	       if ($remoteurl!~/\.meta$/) {
 3272:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3273:                   my $mresponse;
 3274:                   if ($remoteurl =~ m{/raw/}) {
 3275:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3276:                   } else {
 3277:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3278:                   }
 3279:                   if ($mresponse->is_error()) {
 3280: 		      unlink($filename.'.meta');
 3281:                       &logthis(
 3282:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3283:                   }
 3284: 	       }
 3285:                rename($transname,$filename);
 3286:                return 'ok';
 3287:            }
 3288:        }
 3289:     }
 3290: }
 3291: 
 3292: # ------------------------------------------------ Get server side include body
 3293: sub ssi_body {
 3294:     my ($filelink,%form)=@_;
 3295:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3296:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3297:     }
 3298:     my $output='';
 3299:     my $response;
 3300:     if ($filelink=~/^https?\:/) {
 3301:        ($output,$response)=&externalssi($filelink);
 3302:     } else {
 3303:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3304:        $filelink .= 'inhibitmenu=yes';
 3305:        ($output,$response)=&ssi($filelink,%form);
 3306:     }
 3307:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3308:     $output=~s/^.*?\<body[^\>]*\>//si;
 3309:     $output=~s/\<\/body\s*\>.*?$//si;
 3310:     if (wantarray) {
 3311:         return ($output, $response);
 3312:     } else {
 3313:         return $output;
 3314:     }
 3315: }
 3316: 
 3317: # --------------------------------------------------------- Server Side Include
 3318: 
 3319: sub absolute_url {
 3320:     my ($host_name) = @_;
 3321:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3322:     if ($host_name eq '') {
 3323: 	$host_name = $ENV{'SERVER_NAME'};
 3324:     }
 3325:     return $protocol.$host_name;
 3326: }
 3327: 
 3328: #
 3329: #   Server side include.
 3330: # Parameters:
 3331: #  fn     Possibly encrypted resource name/id.
 3332: #  form   Hash that describes how the rendering should be done
 3333: #         and other things.
 3334: # Returns:
 3335: #   Scalar context: The content of the response.
 3336: #   Array context:  2 element list of the content and the full response object.
 3337: #     
 3338: sub ssi {
 3339: 
 3340:     my ($fn,%form)=@_;
 3341:     my $request;
 3342: 
 3343:     $form{'no_update_last_known'}=1;
 3344:     &Apache::lonenc::check_encrypt(\$fn);
 3345:     if (%form) {
 3346:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3347:       $request->content(join('&',map { 
 3348:             my $name = escape($_);
 3349:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3350:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3351:             : &escape($form{$_}) );    
 3352:         } keys(%form)));
 3353:     } else {
 3354:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3355:     }
 3356: 
 3357:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3358:     my $lonhost = $perlvar{'lonHostID'};
 3359:     my $islocal;
 3360:     if (($env{'request.course.id'}) &&
 3361:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3362:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3363:         ($form{'grade_symb'} ne '') &&
 3364:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3365:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3366:         $islocal = 1;
 3367:     }
 3368:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3369:                                                 '','','',$islocal);
 3370: 
 3371:     if (wantarray) {
 3372: 	return ($response->content, $response);
 3373:     } else {
 3374: 	return $response->content;
 3375:     }
 3376: }
 3377: 
 3378: sub externalssi {
 3379:     my ($url)=@_;
 3380:     my $request=new HTTP::Request('GET',$url);
 3381:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3382:     if (wantarray) {
 3383:         return ($response->content, $response);
 3384:     } else {
 3385:         return $response->content;
 3386:     }
 3387: }
 3388: 
 3389: 
 3390: # If the local copy of a replicated resource is outdated, trigger a  
 3391: # connection from the homeserver to flush the delayed queue. If no update 
 3392: # happens, remove local copies of outdated resource (and corresponding
 3393: # metadata file).
 3394: 
 3395: sub remove_stale_resfile {
 3396:     my ($url) = @_;
 3397:     my $removed;
 3398:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3399:         my $audom = $1;
 3400:         my $auname = $2;
 3401:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3402:             my $homeserver = &homeserver($auname,$audom);
 3403:             unless (($homeserver eq 'no_host') ||
 3404:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3405:                 my $fname = &filelocation('',$url);
 3406:                 if (-e $fname) {
 3407:                     my $hostname = &hostname($homeserver);
 3408:                     if ($hostname) {
 3409:                         my $protocol = $protocol{$homeserver};
 3410:                         $protocol = 'http' if ($protocol ne 'https');
 3411:                         my $uri = &declutter($url);
 3412:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3413:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3414:                         if ($response->is_success()) {
 3415:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3416:                             my $locmodtime = (stat($fname))[9];
 3417:                             if ($locmodtime < $remmodtime) {
 3418:                                 my $stale;
 3419:                                 my $answer = &reply('pong',$homeserver);
 3420:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3421:                                     sleep(0.2);
 3422:                                     $locmodtime = (stat($fname))[9];
 3423:                                     if ($locmodtime < $remmodtime) {
 3424:                                         my $posstransfer = $fname.'.in.transfer';
 3425:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3426:                                             $removed = 1;
 3427:                                         } else {
 3428:                                             $stale = 1;
 3429:                                         }
 3430:                                     } else {
 3431:                                         $removed = 1;
 3432:                                     }
 3433:                                 } else {
 3434:                                     $stale = 1;
 3435:                                 }
 3436:                                 if ($stale) {
 3437:                                     unlink($fname);
 3438:                                     if ($uri!~/\.meta$/) {
 3439:                                         unlink($fname.'.meta');
 3440:                                     }
 3441:                                     &reply("unsub:$fname",$homeserver);
 3442:                                     $removed = 1;
 3443:                                 }
 3444:                             }
 3445:                         }
 3446:                     }
 3447:                 }
 3448:             }
 3449:         }
 3450:     }
 3451:     return $removed;
 3452: }
 3453: 
 3454: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3455: 
 3456: sub allowuploaded {
 3457:     my ($srcurl,$url)=@_;
 3458:     $url=&clutter(&declutter($url));
 3459:     my $dir=$url;
 3460:     $dir=~s/\/[^\/]+$//;
 3461:     my %httpref=();
 3462:     my $httpurl=&hreflocation('',$url);
 3463:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3464:     &Apache::lonnet::appenv(\%httpref);
 3465: }
 3466: 
 3467: #
 3468: # Determine if the current user should be able to edit a particular resource,
 3469: # when viewing in course context.
 3470: # (a) When viewing resource used to determine if "Edit" item is included in 
 3471: #     Functions.
 3472: # (b) When displaying folder contents in course editor, used to determine if
 3473: #     "Edit" link will be displayed alongside resource.
 3474: #
 3475: #  input: six args -- filename (decluttered), course number, course domain,
 3476: #                   url, symb (if registered) and group (if this is a group
 3477: #                   item -- e.g., bulletin board, group page etc.).
 3478: #  output: array of five scalars -- 
 3479: #          $cfile -- url for file editing if editable on current server
 3480: #          $home -- homeserver of resource (i.e., for author if published,
 3481: #                                           or course if uploaded.).
 3482: #          $switchserver --  1 if server switch will be needed.
 3483: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3484: #          $forceview -- 1 if icon/link should be to go to view mode
 3485: #
 3486: 
 3487: sub can_edit_resource {
 3488:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3489:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3490: #
 3491: # For aboutme pages user can only edit his/her own.
 3492: #
 3493:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3494:         my ($sdom,$sname) = ($1,$2);
 3495:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3496:             $home = $env{'user.home'};
 3497:             $cfile = $resurl;
 3498:             if ($env{'form.forceedit'}) {
 3499:                 $forceview = 1;
 3500:             } else {
 3501:                 $forceedit = 1;
 3502:             }
 3503:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3504:         } else {
 3505:             return;
 3506:         }
 3507:     }
 3508: 
 3509:     if ($env{'request.course.id'}) {
 3510:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3511:         if ($group ne '') {
 3512: # if this is a group homepage or group bulletin board, check group privs
 3513:             my $allowed = 0;
 3514:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3515:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3516:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3517:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3518:                     $allowed = 1;
 3519:                 }
 3520:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3521:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3522:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3523:                     $allowed = 1;
 3524:                 }
 3525:             }
 3526:             if ($allowed) {
 3527:                 $home=&homeserver($cnum,$cdom);
 3528:                 if ($env{'form.forceedit'}) {
 3529:                     $forceview = 1;
 3530:                 } else {
 3531:                     $forceedit = 1;
 3532:                 }
 3533:                 $cfile = $resurl;
 3534:             } else {
 3535:                 return;
 3536:             }
 3537:         } else {
 3538:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3539:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3540:                     return;
 3541:                 }
 3542:             } elsif (!$crsedit) {
 3543: #
 3544: # No edit allowed where CC has switched to student role.
 3545: #
 3546:                 return;
 3547:             }
 3548:         }
 3549:     }
 3550: 
 3551:     if ($file ne '') {
 3552:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3553:             if (&is_course_upload($file,$cnum,$cdom)) {
 3554:                 $uploaded = 1;
 3555:                 $incourse = 1;
 3556:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3557:                     $cfile = &hreflocation('',$file);
 3558:                     if ($env{'form.forceedit'}) {
 3559:                         $forceview = 1;
 3560:                     } else {
 3561:                         $forceedit = 1;
 3562:                     }
 3563:                 }
 3564:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3565:                 $incourse = 1;
 3566:                 if ($env{'form.forceedit'}) {
 3567:                     $forceview = 1;
 3568:                 } else {
 3569:                     $forceedit = 1;
 3570:                 }
 3571:                 $cfile = $resurl;
 3572:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3573:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3574:                     $incourse = 1;
 3575:                     if ($env{'form.forceedit'}) {
 3576:                         $forceview = 1;
 3577:                     } else {
 3578:                         $forceedit = 1;
 3579:                     }
 3580:                     $cfile = $resurl;
 3581:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3582:                     $incourse = 1;
 3583:                     $cfile = $resurl.'/smpedit';
 3584:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3585:                     $incourse = 1;
 3586:                     if ($env{'form.forceedit'}) {
 3587:                         $forceview = 1;
 3588:                     } else {
 3589:                         $forceedit = 1;
 3590:                     }
 3591:                     $cfile = $resurl;
 3592:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3593:                     $incourse = 1;
 3594:                     if ($env{'form.forceedit'}) {
 3595:                         $forceview = 1;
 3596:                     } else {
 3597:                         $forceedit = 1;
 3598:                     }
 3599:                     $cfile = $resurl;
 3600:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3601:                     $incourse = 1;
 3602:                     if ($env{'form.forceedit'}) {
 3603:                         $forceview = 1;
 3604:                     } else {
 3605:                         $forceedit = 1;
 3606:                     }
 3607:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3608:                 }
 3609:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3610:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3611:                 if (&is_on_map($template)) { 
 3612:                     $incourse = 1;
 3613:                     $forceview = 1;
 3614:                     $cfile = $template;
 3615:                 }
 3616:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3617:                     $incourse = 1;
 3618:                     if ($env{'form.forceedit'}) {
 3619:                         $forceview = 1;
 3620:                     } else {
 3621:                         $forceedit = 1;
 3622:                     }
 3623:                     $cfile = $resurl;
 3624:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3625:                 $incourse = 1;
 3626:                 if ($env{'form.forceedit'}) {
 3627:                     $forceview = 1;
 3628:                 } else {
 3629:                     $forceedit = 1;
 3630:                 }
 3631:                 $cfile = $resurl;
 3632:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3633:                 $incourse = 1;
 3634:                 $forceview = 1;
 3635:                 if ($symb) {
 3636:                     my ($map,$id,$res)=&decode_symb($symb);
 3637:                     $env{'request.symb'} = $symb;
 3638:                     $cfile = &clutter($res);
 3639:                 } else {
 3640:                     $cfile = $env{'form.suppurl'};
 3641:                     my $escfile = &unescape($cfile);
 3642:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3643:                         $cfile = '/adm/wrapper'.$escfile;
 3644:                     } else {
 3645:                         $escfile =~ s{^http://}{};
 3646:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3647:                     }
 3648:                 }
 3649:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3650:                 if ($env{'form.forceedit'}) {
 3651:                     $forceview = 1;
 3652:                 } else {
 3653:                     $forceedit = 1;
 3654:                 }
 3655:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3656:             }
 3657:         }
 3658:         if ($uploaded || $incourse) {
 3659:             $home=&homeserver($cnum,$cdom);
 3660:         } elsif ($file !~ m{/$}) {
 3661:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3662:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3663:             # Check that the user has permission to edit this resource
 3664:             my $setpriv = 1;
 3665:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3666:             if (defined($cfudom)) {
 3667:                 $home=&homeserver($cfuname,$cfudom);
 3668:                 $cfile=$file;
 3669:             }
 3670:         }
 3671:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3672:             (($home ne '') && ($home ne 'no_host'))) {
 3673:             my @ids=&current_machine_ids();
 3674:             unless (grep(/^\Q$home\E$/,@ids)) {
 3675:                 $switchserver=1;
 3676:             }
 3677:         }
 3678:     }
 3679:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3680: }
 3681: 
 3682: sub is_course_upload {
 3683:     my ($file,$cnum,$cdom) = @_;
 3684:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3685:     $uploadpath =~ s{^\/}{};
 3686:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3687:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3688:         return 1;
 3689:     }
 3690:     return;
 3691: }
 3692: 
 3693: sub in_course {
 3694:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3695:     if ($hideprivileged) {
 3696:         my $skipuser;
 3697:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3698:         my @possdoms = ($cdom);  
 3699:         if ($coursehash{'checkforpriv'}) { 
 3700:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3701:         }
 3702:         if (&privileged($uname,$udom,\@possdoms)) {
 3703:             $skipuser = 1;
 3704:             if ($coursehash{'nothideprivileged'}) {
 3705:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3706:                     my $user;
 3707:                     if ($item =~ /:/) {
 3708:                         $user = $item;
 3709:                     } else {
 3710:                         $user = join(':',split(/[\@]/,$item));
 3711:                     }
 3712:                     if ($user eq $uname.':'.$udom) {
 3713:                         undef($skipuser);
 3714:                         last;
 3715:                     }
 3716:                 }
 3717:             }
 3718:             if ($skipuser) {
 3719:                 return 0;
 3720:             }
 3721:         }
 3722:     }
 3723:     $type ||= 'any';
 3724:     if (!defined($cdom) || !defined($cnum)) {
 3725:         my $cid  = $env{'request.course.id'};
 3726:         $cdom = $env{'course.'.$cid.'.domain'};
 3727:         $cnum = $env{'course.'.$cid.'.num'};
 3728:     }
 3729:     my $typesref;
 3730:     if (($type eq 'any') || ($type eq 'all')) {
 3731:         $typesref = ['active','previous','future'];
 3732:     } elsif ($type eq 'previous' || $type eq 'future') {
 3733:         $typesref = [$type];
 3734:     }
 3735:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3736:                               $typesref,undef,[$cdom]);
 3737:     my ($tmp) = keys(%roles);
 3738:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3739:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3740:     if (@course_roles > 0) {
 3741:         return 1;
 3742:     }
 3743:     return 0;
 3744: }
 3745: 
 3746: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3747: # input: action, courseID, current domain, intended
 3748: #        path to file, source of file, instruction to parse file for objects,
 3749: #        ref to hash for embedded objects,
 3750: #        ref to hash for codebase of java objects.
 3751: #        reference to scalar to accommodate mime type determined
 3752: #          from File::MMagic if $parser = parse.
 3753: #
 3754: # output: url to file (if action was uploaddoc), 
 3755: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3756: #
 3757: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3758: # course.
 3759: #
 3760: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3761: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3762: #          course's home server.
 3763: #
 3764: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3765: #          be copied from $source (current location) to 
 3766: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3767: #         and will then be copied to
 3768: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3769: #         course's home server.
 3770: #
 3771: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3772: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3773: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3774: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3775: #         in course's home server.
 3776: #
 3777: 
 3778: sub process_coursefile {
 3779:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3780:         $mimetype)=@_;
 3781:     my $fetchresult;
 3782:     my $home=&homeserver($docuname,$docudom);
 3783:     if ($action eq 'propagate') {
 3784:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3785: 			     $home);
 3786:     } else {
 3787:         my $fpath = '';
 3788:         my $fname = $file;
 3789:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3790:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3791:         my $filepath = &build_filepath($fpath);
 3792:         if ($action eq 'copy') {
 3793:             if ($source eq '') {
 3794:                 $fetchresult = 'no source file';
 3795:                 return $fetchresult;
 3796:             } else {
 3797:                 my $destination = $filepath.'/'.$fname;
 3798:                 rename($source,$destination);
 3799:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3800:                                  $home);
 3801:             }
 3802:         } elsif ($action eq 'uploaddoc') {
 3803:             open(my $fh,'>',$filepath.'/'.$fname);
 3804:             print $fh $env{'form.'.$source};
 3805:             close($fh);
 3806:             if ($parser eq 'parse') {
 3807:                 my $mm = new File::MMagic;
 3808:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3809:                 if ($type eq 'text/html') {
 3810:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3811:                     unless ($parse_result eq 'ok') {
 3812:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3813:                     }
 3814:                 }
 3815:                 if (ref($mimetype)) {
 3816:                     $$mimetype = $type;
 3817:                 } 
 3818:             }
 3819:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3820:                                  $home);
 3821:             if ($fetchresult eq 'ok') {
 3822:                 return '/uploaded/'.$fpath.'/'.$fname;
 3823:             } else {
 3824:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3825:                         ' to host '.$home.': '.$fetchresult);
 3826:                 return '/adm/notfound.html';
 3827:             }
 3828:         }
 3829:     }
 3830:     unless ( $fetchresult eq 'ok') {
 3831:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3832:              ' to host '.$home.': '.$fetchresult);
 3833:     }
 3834:     return $fetchresult;
 3835: }
 3836: 
 3837: sub build_filepath {
 3838:     my ($fpath) = @_;
 3839:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3840:     unless ($fpath eq '') {
 3841:         my @parts=split('/',$fpath);
 3842:         foreach my $part (@parts) {
 3843:             $filepath.= '/'.$part;
 3844:             if ((-e $filepath)!=1) {
 3845:                 mkdir($filepath,0777);
 3846:             }
 3847:         }
 3848:     }
 3849:     return $filepath;
 3850: }
 3851: 
 3852: sub store_edited_file {
 3853:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3854:     my $file = $primary_url;
 3855:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3856:     my $fpath = '';
 3857:     my $fname = $file;
 3858:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3859:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3860:     my $filepath = &build_filepath($fpath);
 3861:     open(my $fh,'>',$filepath.'/'.$fname);
 3862:     print $fh $content;
 3863:     close($fh);
 3864:     my $home=&homeserver($docuname,$docudom);
 3865:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3866: 			  $home);
 3867:     if ($$fetchresult eq 'ok') {
 3868:         return '/uploaded/'.$fpath.'/'.$fname;
 3869:     } else {
 3870:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3871: 		 ' to host '.$home.': '.$$fetchresult);
 3872:         return '/adm/notfound.html';
 3873:     }
 3874: }
 3875: 
 3876: sub clean_filename {
 3877:     my ($fname,$args)=@_;
 3878: # Replace Windows backslashes by forward slashes
 3879:     $fname=~s/\\/\//g;
 3880:     if (!$args->{'keep_path'}) {
 3881:         # Get rid of everything but the actual filename
 3882: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3883:     }
 3884: # Replace spaces by underscores
 3885:     $fname=~s/\s+/\_/g;
 3886: # Transliterate non-ascii text to ascii
 3887:     my $lang = &Apache::lonlocal::current_language();
 3888:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3889: # Replace all other weird characters by nothing
 3890:     $fname=~s{[^/\w\.\-]}{}g;
 3891: # Replace all .\d. sequences with _\d. so they no longer look like version
 3892: # numbers
 3893:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3894:     return $fname;
 3895: }
 3896: 
 3897: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3898: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3899: # image with the same aspect ratio as the original, but with dimensions which do 
 3900: # not exceed $resizewidth and $resizeheight.
 3901:  
 3902: sub resizeImage {
 3903:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3904:     my $ima = Image::Magick->new;
 3905:     my $resized;
 3906:     if (-e $img_path) {
 3907:         $ima->Read($img_path);
 3908:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3909:             my $width = $ima->Get('width');
 3910:             my $height = $ima->Get('height');
 3911:             if ($width > $resizewidth) {
 3912: 	        my $factor = $width/$resizewidth;
 3913:                 my $newheight = $height/$factor;
 3914:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3915:                 $resized = 1;
 3916:             }
 3917:         }
 3918:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3919:             my $width = $ima->Get('width');
 3920:             my $height = $ima->Get('height');
 3921:             if ($height > $resizeheight) {
 3922:                 my $factor = $height/$resizeheight;
 3923:                 my $newwidth = $width/$factor;
 3924:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3925:                 $resized = 1;
 3926:             }
 3927:         }
 3928:         if ($resized) {
 3929:             $ima->Write($img_path);
 3930:         }
 3931:     }
 3932:     return;
 3933: }
 3934: 
 3935: # --------------- Take an uploaded file and put it into the userfiles directory
 3936: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3937: #                    the desired filename is in $env{"form.$formname.filename"}
 3938: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3939: #                                    canceloverwrite, scantron or ''.
 3940: #                   if 'coursedoc': upload to the current course
 3941: #                   if 'existingfile': write file to tmp/overwrites directory 
 3942: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3943: #                   $context is passed as argument to &finishuserfileupload
 3944: #        $subdir - directory in userfile to store the file into
 3945: #        $parser - instruction to parse file for objects ($parser = parse) or
 3946: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3947: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3948: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3949: #        $allfiles - reference to hash for embedded objects
 3950: #        $codebase - reference to hash for codebase of java objects
 3951: #        $desuname - username for permanent storage of uploaded file
 3952: #        $dsetudom - domain for permanaent storage of uploaded file
 3953: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3954: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3955: #        $resizewidth - width (pixels) to which to resize uploaded image
 3956: #        $resizeheight - height (pixels) to which to resize uploaded image
 3957: #        $mimetype - reference to scalar to accommodate mime type determined
 3958: #                    from File::MMagic.
 3959: # 
 3960: # output: url of file in userspace, or error: <message> 
 3961: #             or /adm/notfound.html if failure to upload occurse
 3962: 
 3963: sub userfileupload {
 3964:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3965:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3966:     if (!defined($subdir)) { $subdir='unknown'; }
 3967:     my $fname=$env{'form.'.$formname.'.filename'};
 3968:     $fname=&clean_filename($fname);
 3969:     # See if there is anything left
 3970:     unless ($fname) { return 'error: no uploaded file'; }
 3971:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3972:     if ($fname =~ /^\./) {
 3973:         my ($s,$usec) = &gettimeofday();
 3974:         while (length($usec) < 6) {
 3975:             $usec = '0'.$usec;
 3976:         }
 3977:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3978:     }
 3979:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3980:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3981:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3982:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3983:         my $now = time;
 3984:         my $filepath;
 3985:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3986:              $filepath = 'tmp/helprequests/'.$now;
 3987:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3988:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3989:                          '_'.$env{'user.domain'}.'/pending';
 3990:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3991:             my ($docuname,$docudom);
 3992:             if ($destudom =~ /^$match_domain$/) {
 3993:                 $docudom = $destudom;
 3994:             } else {
 3995:                 $docudom = $env{'user.domain'};
 3996:             }
 3997:             if ($destuname =~ /^$match_username$/) {
 3998:                 $docuname = $destuname;
 3999:             } else {
 4000:                 $docuname = $env{'user.name'};
 4001:             }
 4002:             if (exists($env{'form.group'})) {
 4003:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4004:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4005:             }
 4006:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4007:             if ($context eq 'canceloverwrite') {
 4008:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4009:                 if (-e  $tempfile) {
 4010:                     my @info = stat($tempfile);
 4011:                     if ($info[9] eq $env{'form.timestamp'}) {
 4012:                         unlink($tempfile);
 4013:                     }
 4014:                 }
 4015:                 return;
 4016:             }
 4017:         }
 4018:         # Create the directory if not present
 4019:         my @parts=split(/\//,$filepath);
 4020:         my $fullpath = $perlvar{'lonDaemons'};
 4021:         for (my $i=0;$i<@parts;$i++) {
 4022:             $fullpath .= '/'.$parts[$i];
 4023:             if ((-e $fullpath)!=1) {
 4024:                 mkdir($fullpath,0777);
 4025:             }
 4026:         }
 4027:         open(my $fh,'>',$fullpath.'/'.$fname);
 4028:         print $fh $env{'form.'.$formname};
 4029:         close($fh);
 4030:         if ($context eq 'existingfile') {
 4031:             my @info = stat($fullpath.'/'.$fname);
 4032:             return ($fullpath.'/'.$fname,$info[9]);
 4033:         } else {
 4034:             return $fullpath.'/'.$fname;
 4035:         }
 4036:     }
 4037:     if ($subdir eq 'scantron') {
 4038:         $fname = 'scantron_orig_'.$fname;
 4039:     } else {
 4040:         $fname="$subdir/$fname";
 4041:     }
 4042:     if ($context eq 'coursedoc') {
 4043: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4044: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4045:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4046:             return &finishuserfileupload($docuname,$docudom,
 4047: 					 $formname,$fname,$parser,$allfiles,
 4048: 					 $codebase,$thumbwidth,$thumbheight,
 4049:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4050:         } else {
 4051:             if ($env{'form.folder'}) {
 4052:                 $fname=$env{'form.folder'}.'/'.$fname;
 4053:             }
 4054:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4055: 				       $fname,$formname,$parser,
 4056: 				       $allfiles,$codebase,$mimetype);
 4057:         }
 4058:     } elsif (defined($destuname)) {
 4059:         my $docuname=$destuname;
 4060:         my $docudom=$destudom;
 4061: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4062: 				     $parser,$allfiles,$codebase,
 4063:                                      $thumbwidth,$thumbheight,
 4064:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4065:     } else {
 4066:         my $docuname=$env{'user.name'};
 4067:         my $docudom=$env{'user.domain'};
 4068:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4069:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4070:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4071:         }
 4072: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4073: 				     $parser,$allfiles,$codebase,
 4074:                                      $thumbwidth,$thumbheight,
 4075:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4076:     }
 4077: }
 4078: 
 4079: sub finishuserfileupload {
 4080:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4081:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4082:     my $path=$docudom.'/'.$docuname.'/';
 4083:     my $filepath=$perlvar{'lonDocRoot'};
 4084:   
 4085:     my ($fnamepath,$file,$fetchthumb);
 4086:     $file=$fname;
 4087:     if ($fname=~m|/|) {
 4088:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4089: 	$path.=$fnamepath.'/';
 4090:     }
 4091:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4092:     my $count;
 4093:     for ($count=4;$count<=$#parts;$count++) {
 4094:         $filepath.="/$parts[$count]";
 4095:         if ((-e $filepath)!=1) {
 4096: 	    mkdir($filepath,0777);
 4097:         }
 4098:     }
 4099: 
 4100: # Save the file
 4101:     {
 4102: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4103: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4104: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4105: 	    return '/adm/notfound.html';
 4106: 	}
 4107:         if ($context eq 'overwrite') {
 4108:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4109:             my $target = $filepath.'/'.$file;
 4110:             if (-e $source) {
 4111:                 my @info = stat($source);
 4112:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4113:                     unless (&File::Copy::move($source,$target)) {
 4114:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4115:                         return "Moving from $source failed";
 4116:                     }
 4117:                 } else {
 4118:                     return "Temporary file: $source had unexpected date/time for last modification";
 4119:                 }
 4120:             } else {
 4121:                 return "Temporary file: $source missing";
 4122:             }
 4123:         } elsif (!print FH ($env{'form.'.$formname})) {
 4124: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4125: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4126: 	    return '/adm/notfound.html';
 4127: 	}
 4128: 	close(FH);
 4129:         if ($resizewidth && $resizeheight) {
 4130:             my $mm = new File::MMagic;
 4131:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4132:             if ($mime_type =~ m{^image/}) {
 4133: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4134:             }  
 4135: 	}
 4136:     }
 4137:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4138:         if (ref($mimetype)) {
 4139:             if ($$mimetype eq '') {
 4140:                 my $mm = new File::MMagic;
 4141:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4142:                 $$mimetype = $type;
 4143:             }
 4144:         }
 4145:     }
 4146:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4147:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4148:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4149:                                                        $allfiles,$codebase);
 4150:             unless ($parse_result eq 'ok') {
 4151:                 &logthis('Failed to parse '.$filepath.$file.
 4152: 	   	         ' for embedded media: '.$parse_result); 
 4153:             }
 4154:         }
 4155:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4156:         my $format = $env{'form.scantron_format'};
 4157:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4158:     }
 4159:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4160:         my $input = $filepath.'/'.$file;
 4161:         my $output = $filepath.'/'.'tn-'.$file;
 4162:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4163:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4164:         system({$args[0]} @args);
 4165:         if (-e $filepath.'/'.'tn-'.$file) {
 4166:             $fetchthumb  = 1; 
 4167:         }
 4168:     }
 4169:  
 4170: # Notify homeserver to grep it
 4171: #
 4172:     my $docuhome=&homeserver($docuname,$docudom);	
 4173:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4174:     if ($fetchresult eq 'ok') {
 4175:         if ($fetchthumb) {
 4176:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4177:             if ($thumbresult ne 'ok') {
 4178:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4179:                          $docuhome.': '.$thumbresult);
 4180:             }
 4181:         }
 4182: #
 4183: # Return the URL to it
 4184:         return '/uploaded/'.$path.$file;
 4185:     } else {
 4186:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4187: 		 ': '.$fetchresult);
 4188:         return '/adm/notfound.html';
 4189:     }
 4190: }
 4191: 
 4192: sub extract_embedded_items {
 4193:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4194:     my @state = ();
 4195:     my (%lastids,%related,%shockwave,%flashvars);
 4196:     my %javafiles = (
 4197:                       codebase => '',
 4198:                       code => '',
 4199:                       archive => ''
 4200:                     );
 4201:     my %mediafiles = (
 4202:                       src => '',
 4203:                       movie => '',
 4204:                      );
 4205:     my $p;
 4206:     if ($content) {
 4207:         $p = HTML::LCParser->new($content);
 4208:     } else {
 4209:         $p = HTML::LCParser->new($fullpath);
 4210:     }
 4211:     while (my $t=$p->get_token()) {
 4212: 	if ($t->[0] eq 'S') {
 4213: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4214: 	    push(@state, $tagname);
 4215:             if (lc($tagname) eq 'allow') {
 4216:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4217:             }
 4218: 	    if (lc($tagname) eq 'img') {
 4219: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4220: 	    }
 4221: 	    if (lc($tagname) eq 'a') {
 4222:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4223:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4224:                 }
 4225: 	    }
 4226:             if (lc($tagname) eq 'script') {
 4227:                 my $src;
 4228:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4229:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4230:                 } else {
 4231:                     if ($attr->{'src'} ne '') {
 4232:                         $src = $attr->{'src'};
 4233:                         &add_filetype($allfiles,$src,'src');
 4234:                     }
 4235:                 }
 4236:                 my $text = $p->get_trimmed_text();
 4237:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4238:                     my @swfargs = split(/,/,$1);
 4239:                     foreach my $item (@swfargs) {
 4240:                         $item =~ s/["']//g;
 4241:                         $item =~ s/^\s+//;
 4242:                         $item =~ s/\s+$//;
 4243:                     }
 4244:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4245:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4246:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4247:                         } else {
 4248:                             $related{$swfargs[0]} = [$swfargs[2]];
 4249:                         }
 4250:                     }
 4251:                 }
 4252:             }
 4253:             if (lc($tagname) eq 'link') {
 4254:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4255:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4256:                 }
 4257:             }
 4258: 	    if (lc($tagname) eq 'object' ||
 4259: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4260: 		foreach my $item (keys(%javafiles)) {
 4261: 		    $javafiles{$item} = '';
 4262: 		}
 4263:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4264:                     $lastids{lc($tagname)} = $attr->{'id'};
 4265:                 }
 4266: 	    }
 4267: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4268: 		my $name = lc($attr->{'name'});
 4269: 		foreach my $item (keys(%javafiles)) {
 4270: 		    if ($name eq $item) {
 4271: 			$javafiles{$item} = $attr->{'value'};
 4272: 			last;
 4273: 		    }
 4274: 		}
 4275:                 my $pathfrom;
 4276: 		foreach my $item (keys(%mediafiles)) {
 4277: 		    if ($name eq $item) {
 4278:                         $pathfrom = $attr->{'value'};
 4279:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4280: 			&add_filetype($allfiles,$pathfrom,$name);
 4281: 			last;
 4282: 		    }
 4283: 		}
 4284:                 if ($name eq 'flashvars') {
 4285:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4286:                 }
 4287:                 if ($pathfrom ne '') {
 4288:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4289:                                          $pathfrom);
 4290:                 }
 4291: 	    }
 4292: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4293: 		foreach my $item (keys(%javafiles)) {
 4294: 		    if ($attr->{$item}) {
 4295: 			$javafiles{$item} = $attr->{$item};
 4296: 			last;
 4297: 		    }
 4298: 		}
 4299: 		foreach my $item (keys(%mediafiles)) {
 4300: 		    if ($attr->{$item}) {
 4301: 			&add_filetype($allfiles,$attr->{$item},$item);
 4302: 			last;
 4303: 		    }
 4304: 		}
 4305:                 if (lc($tagname) eq 'embed') {
 4306:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4307:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4308:                                              $attr->{'src'});
 4309:                     }
 4310:                 }
 4311: 	    }
 4312:             if (lc($tagname) eq 'iframe') {
 4313:                 my $src = $attr->{'src'} ;
 4314:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4315:                     &add_filetype($allfiles,$src,'src');
 4316:                 } elsif ($src =~ m{^/}) {
 4317:                     if ($env{'request.course.id'}) {
 4318:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4319:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4320:                         my $url = &hreflocation('',$fullpath);
 4321:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4322:                             my $relpath = $1;
 4323:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4324:                                 &add_filetype($allfiles,$1,'src');
 4325:                             }
 4326:                         }
 4327:                     }
 4328:                 }
 4329:             }
 4330:             if ($t->[4] =~ m{/>$}) {
 4331:                 pop(@state);
 4332:             }
 4333: 	} elsif ($t->[0] eq 'E') {
 4334: 	    my ($tagname) = ($t->[1]);
 4335: 	    if ($javafiles{'codebase'} ne '') {
 4336: 		$javafiles{'codebase'} .= '/';
 4337: 	    }  
 4338: 	    if (lc($tagname) eq 'applet' ||
 4339: 		lc($tagname) eq 'object' ||
 4340: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4341: 		) {
 4342: 		foreach my $item (keys(%javafiles)) {
 4343: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4344: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4345: 			&add_filetype($allfiles,$file,$item);
 4346: 		    }
 4347: 		}
 4348: 	    } 
 4349: 	    pop @state;
 4350: 	}
 4351:     }
 4352:     foreach my $id (sort(keys(%flashvars))) {
 4353:         if ($shockwave{$id} ne '') {
 4354:             my @pairs = split(/\&/,$flashvars{$id});
 4355:             foreach my $pair (@pairs) {
 4356:                 my ($key,$value) = split(/\=/,$pair);
 4357:                 if ($key eq 'thumb') {
 4358:                     &add_filetype($allfiles,$value,$key);
 4359:                 } elsif ($key eq 'content') {
 4360:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4361:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4362:                     if ($ext ne '') {
 4363:                         &add_filetype($allfiles,$path.$value,$ext);
 4364:                     }
 4365:                 }
 4366:             }
 4367:         }
 4368:     }
 4369:     return 'ok';
 4370: }
 4371: 
 4372: sub add_filetype {
 4373:     my ($allfiles,$file,$type)=@_;
 4374:     if (exists($allfiles->{$file})) {
 4375: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4376: 	    push(@{$allfiles->{$file}}, &escape($type));
 4377: 	}
 4378:     } else {
 4379: 	@{$allfiles->{$file}} = (&escape($type));
 4380:     }
 4381: }
 4382: 
 4383: sub embedded_dependency {
 4384:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4385:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4386:         if (($identifier ne '') &&
 4387:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4388:             ($pathfrom ne '')) {
 4389:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4390:             foreach my $dep (@{$related->{$identifier}}) {
 4391:                 &add_filetype($allfiles,$path.$dep,'object');
 4392:             }
 4393:         }
 4394:     }
 4395:     return;
 4396: }
 4397: 
 4398: sub bubblesheet_converter {
 4399:     my ($cdom,$fullpath,$config,$format) = @_;
 4400:     if ((&domain($cdom) ne '') &&
 4401:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4402:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4403:         my (%csvcols,%csvoptions);
 4404:         if (ref($config->{'fields'}) eq 'HASH') {  
 4405:             %csvcols = %{$config->{'fields'}};
 4406:         }
 4407:         if (ref($config->{'options'}) eq 'HASH') {
 4408:             %csvoptions = %{$config->{'options'}};
 4409:         }
 4410:         my %csvbynum = reverse(%csvcols);
 4411:         my %scantronconf = &get_scantron_config($format,$cdom);
 4412:         if (keys(%scantronconf)) {
 4413:             my %bynum = (
 4414:                           $scantronconf{CODEstart} => 'CODEstart',
 4415:                           $scantronconf{IDstart}   => 'IDstart',
 4416:                           $scantronconf{PaperID}   => 'PaperID',
 4417:                           $scantronconf{FirstName} => 'FirstName',
 4418:                           $scantronconf{LastName}  => 'LastName',
 4419:                           $scantronconf{Qstart}    => 'Qstart',
 4420:                         );
 4421:             my @ordered;
 4422:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4423:                 push(@ordered,$bynum{$item});
 4424:             }
 4425:             my %mapstart = (
 4426:                               CODEstart => 'CODE',
 4427:                               IDstart   => 'ID',
 4428:                               PaperID   => 'PaperID',
 4429:                               FirstName => 'FirstName',
 4430:                               LastName  => 'LastName',
 4431:                               Qstart    => 'FirstQuestion',
 4432:                            );
 4433:             my %maplength = (
 4434:                               CODEstart => 'CODElength',
 4435:                               IDstart   => 'IDlength',
 4436:                               PaperID   => 'PaperIDlength',
 4437:                               FirstName => 'FirstNamelength',
 4438:                               LastName  => 'LastNamelength',
 4439:             );
 4440:             if (open(my $fh,'<',$fullpath)) {
 4441:                 my $output;
 4442:                 my %lettdig = &letter_to_digits();
 4443:                 my %diglett = reverse(%lettdig);
 4444:                 my $numletts = scalar(keys(%lettdig));
 4445:                 my $num = 0;
 4446:                 while (my $line=<$fh>) {
 4447:                     $num ++;
 4448:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4449:                     $line =~ s{[\r\n]+$}{};
 4450:                     my %found;
 4451:                     my @values = split(/,/,$line);
 4452:                     my ($qstart,$record);
 4453:                     for (my $i=0; $i<@values; $i++) {
 4454:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4455:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4456:                             if ($values[$i] eq '') {
 4457:                                 $values[$i] = $scantronconf{'Qoff'};
 4458:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4459:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4460:                                     $values[$i] = $lettdig{uc($values[$i])};
 4461:                                 }
 4462:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4463:                                 if ($values[$i] =~ /^[0-9]$/) {
 4464:                                     $values[$i] = $diglett{$values[$i]};
 4465:                                 }
 4466:                             } else {
 4467:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4468:                                     my $digit;
 4469:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4470:                                         $digit = $lettdig{uc($values[$i])}-1;
 4471:                                         if ($values[$i] eq 'J') {
 4472:                                             $digit += $numletts;
 4473:                                         }
 4474:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4475:                                         $digit = $values[$i]-1;
 4476:                                         if ($values[$i] eq '0') {
 4477:                                             $digit += $numletts;
 4478:                                         }
 4479:                                     }
 4480:                                     my $qval='';
 4481:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4482:                                         if ($j == $digit) {
 4483:                                             $qval .= $scantronconf{'Qon'};
 4484:                                         } else {
 4485:                                             $qval .= $scantronconf{'Qoff'};
 4486:                                         }
 4487:                                     }
 4488:                                     $values[$i] = $qval;
 4489:                                 }
 4490:                             }
 4491:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4492:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4493:                             }
 4494:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4495:                             if ($numblank > 0) {
 4496:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4497:                             }
 4498:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4499:                                 $qstart = $i;
 4500:                                 $found{$csvbynum{$i}} = $values[$i];
 4501:                             } else {
 4502:                                 $found{'FirstQuestion'} .= $values[$i];
 4503:                             }
 4504:                         } elsif (exists($csvbynum{$i})) {
 4505:                             if ($csvoptions{'rem'}) {
 4506:                                 $values[$i] =~ s/^\s+//;
 4507:                             }
 4508:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4509:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4510:                                     $values[$i] = '0'.$values[$i];
 4511:                                 }
 4512:                             }
 4513:                             $found{$csvbynum{$i}} = $values[$i];
 4514:                         }
 4515:                     }
 4516:                     foreach my $item (@ordered) {
 4517:                         my $currlength = 1+length($record);
 4518:                         my $numspaces = $scantronconf{$item} - $currlength;
 4519:                         if ($numspaces > 0) {
 4520:                             $record .= (' ' x $numspaces);
 4521:                         }
 4522:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4523:                             unless ($item eq 'Qstart') {
 4524:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4525:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4526:                                 }
 4527:                             }
 4528:                             $record .= $found{$mapstart{$item}};
 4529:                         }
 4530:                     }
 4531:                     $output .= "$record\n";
 4532:                 }
 4533:                 close($fh);
 4534:                 if ($output) {
 4535:                     if (open(my $fh,'>',$fullpath)) {
 4536:                         print $fh $output;
 4537:                         close($fh);
 4538:                     }
 4539:                 }
 4540:             }
 4541:         }
 4542:         return;
 4543:     }
 4544: }
 4545: 
 4546: sub letter_to_digits {
 4547:     my %lettdig = (
 4548:                     A => 1,
 4549:                     B => 2,
 4550:                     C => 3,
 4551:                     D => 4,
 4552:                     E => 5,
 4553:                     F => 6,
 4554:                     G => 7,
 4555:                     H => 8,
 4556:                     I => 9,
 4557:                     J => 0,
 4558:                   );
 4559:     return %lettdig;
 4560: }
 4561: 
 4562: sub get_scantron_config {
 4563:     my ($which,$cdom) = @_;
 4564:     my @lines = &get_scantronformat_file($cdom);
 4565:     my %config;
 4566:     #FIXME probably should move to XML it has already gotten a bit much now
 4567:     foreach my $line (@lines) {
 4568:         my ($name,$descrip)=split(/:/,$line);
 4569:         if ($name ne $which ) { next; }
 4570:         chomp($line);
 4571:         my @config=split(/:/,$line);
 4572:         $config{'name'}=$config[0];
 4573:         $config{'description'}=$config[1];
 4574:         $config{'CODElocation'}=$config[2];
 4575:         $config{'CODEstart'}=$config[3];
 4576:         $config{'CODElength'}=$config[4];
 4577:         $config{'IDstart'}=$config[5];
 4578:         $config{'IDlength'}=$config[6];
 4579:         $config{'Qstart'}=$config[7];
 4580:         $config{'Qlength'}=$config[8];
 4581:         $config{'Qoff'}=$config[9];
 4582:         $config{'Qon'}=$config[10];
 4583:         $config{'PaperID'}=$config[11];
 4584:         $config{'PaperIDlength'}=$config[12];
 4585:         $config{'FirstName'}=$config[13];
 4586:         $config{'FirstNamelength'}=$config[14];
 4587:         $config{'LastName'}=$config[15];
 4588:         $config{'LastNamelength'}=$config[16];
 4589:         $config{'BubblesPerRow'}=$config[17];
 4590:         last;
 4591:     }
 4592:     return %config;
 4593: }
 4594: 
 4595: sub get_scantronformat_file {
 4596:     my ($cdom) = @_;
 4597:     if ($cdom eq '') {
 4598:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4599:     }
 4600:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4601:     my $gottab = 0;
 4602:     my @lines;
 4603:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4604:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4605:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4606:             if ($formatfile ne '-1') {
 4607:                 @lines = split("\n",$formatfile,-1);
 4608:                 $gottab = 1;
 4609:             }
 4610:         }
 4611:     }
 4612:     if (!$gottab) {
 4613:         my $confname = $cdom.'-domainconfig';
 4614:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4615:         my $formatfile = &getfile($default);
 4616:         if ($formatfile ne '-1') {
 4617:             @lines = split("\n",$formatfile,-1);
 4618:             $gottab = 1;
 4619:         }
 4620:     }
 4621:     if (!$gottab) {
 4622:         my @domains = &current_machine_domains();
 4623:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4624:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4625:                 @lines = <$fh>;
 4626:                 close($fh);
 4627:             }
 4628:         } else {
 4629:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4630:                 @lines = <$fh>;
 4631:                 close($fh);
 4632:             }
 4633:         }
 4634:     }
 4635:     return @lines;
 4636: }
 4637: 
 4638: sub removeuploadedurl {
 4639:     my ($url)=@_;	
 4640:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4641:     return &removeuserfile($uname,$udom,$fname);
 4642: }
 4643: 
 4644: sub removeuserfile {
 4645:     my ($docuname,$docudom,$fname)=@_;
 4646:     my $home=&homeserver($docuname,$docudom);    
 4647:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4648:     if ($result eq 'ok') {	
 4649:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4650:             my $metafile = $fname.'.meta';
 4651:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4652: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4653:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4654:             my $sqlresult = 
 4655:                 &update_portfolio_table($docuname,$docudom,$file,
 4656:                                         'portfolio_metadata',$group,
 4657:                                         'delete');
 4658:         }
 4659:     }
 4660:     return $result;
 4661: }
 4662: 
 4663: sub mkdiruserfile {
 4664:     my ($docuname,$docudom,$dir)=@_;
 4665:     my $home=&homeserver($docuname,$docudom);
 4666:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4667: }
 4668: 
 4669: sub renameuserfile {
 4670:     my ($docuname,$docudom,$old,$new)=@_;
 4671:     my $home=&homeserver($docuname,$docudom);
 4672:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4673:                         &escape("$old").':'.&escape("$new"),$home);
 4674:     if ($result eq 'ok') {
 4675:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4676:             my $oldmeta = $old.'.meta';
 4677:             my $newmeta = $new.'.meta';
 4678:             my $metaresult = 
 4679:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4680: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4681:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4682:             my $sqlresult = 
 4683:                 &update_portfolio_table($docuname,$docudom,$file,
 4684:                                         'portfolio_metadata',$group,
 4685:                                         'delete');
 4686:         }
 4687:     }
 4688:     return $result;
 4689: }
 4690: 
 4691: # ------------------------------------------------------------------------- Log
 4692: 
 4693: sub log {
 4694:     my ($dom,$nam,$hom,$what)=@_;
 4695:     return critical("log:$dom:$nam:$what",$hom);
 4696: }
 4697: 
 4698: # ------------------------------------------------------------------ Course Log
 4699: #
 4700: # This routine flushes several buffers of non-mission-critical nature
 4701: #
 4702: 
 4703: sub flushcourselogs {
 4704:     &logthis('Flushing log buffers');
 4705: #
 4706: # course logs
 4707: # This is a log of all transactions in a course, which can be used
 4708: # for data mining purposes
 4709: #
 4710: # It also collects the courseid database, which lists last transaction
 4711: # times and course titles for all courseids
 4712: #
 4713:     my %courseidbuffer=();
 4714:     foreach my $crsid (keys(%courselogs)) {
 4715:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4716: 		          &escape($courselogs{$crsid}),
 4717: 		          $coursehombuf{$crsid}) eq 'ok') {
 4718: 	    delete $courselogs{$crsid};
 4719:         } else {
 4720:             &logthis('Failed to flush log buffer for '.$crsid);
 4721:             if (length($courselogs{$crsid})>40000) {
 4722:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4723:                         " exceeded maximum size, deleting.</font>");
 4724:                delete $courselogs{$crsid};
 4725:             }
 4726:         }
 4727:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4728:             'description' => $coursedescrbuf{$crsid},
 4729:             'inst_code'    => $courseinstcodebuf{$crsid},
 4730:             'type'        => $coursetypebuf{$crsid},
 4731:             'owner'       => $courseownerbuf{$crsid},
 4732:         };
 4733:     }
 4734: #
 4735: # Write course id database (reverse lookup) to homeserver of courses 
 4736: # Is used in pickcourse
 4737: #
 4738:     foreach my $crs_home (keys(%courseidbuffer)) {
 4739:         my $response = &courseidput(&host_domain($crs_home),
 4740:                                     $courseidbuffer{$crs_home},
 4741:                                     $crs_home,'timeonly');
 4742:     }
 4743: #
 4744: # File accesses
 4745: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4746: #
 4747:     foreach my $entry (keys(%accesshash)) {
 4748:         if ($entry =~ /___count$/) {
 4749:             my ($dom,$name);
 4750:             ($dom,$name,undef)=
 4751: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4752:             if (! defined($dom) || $dom eq '' || 
 4753:                 ! defined($name) || $name eq '') {
 4754:                 my $cid = $env{'request.course.id'};
 4755:                 $dom  = $env{'request.'.$cid.'.domain'};
 4756:                 $name = $env{'request.'.$cid.'.num'};
 4757:             }
 4758:             my $value = $accesshash{$entry};
 4759:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4760:             my %temphash=($url => $value);
 4761:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4762:             if ($result eq 'ok') {
 4763:                 delete $accesshash{$entry};
 4764:             }
 4765:         } else {
 4766:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4767:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4768:             my %temphash=($entry => $accesshash{$entry});
 4769:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4770:                 delete $accesshash{$entry};
 4771:             }
 4772:         }
 4773:     }
 4774: #
 4775: # Roles
 4776: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4777: #
 4778:     foreach my $entry (keys(%userrolehash)) {
 4779:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4780: 	    split(/\:/,$entry);
 4781:         if (&Apache::lonnet::put('nohist_userroles',
 4782:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4783:                 $rudom,$runame) eq 'ok') {
 4784: 	    delete $userrolehash{$entry};
 4785:         }
 4786:     }
 4787: #
 4788: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4789: #
 4790:     my %domrolebuffer = ();
 4791:     foreach my $entry (keys(%domainrolehash)) {
 4792:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4793:         if ($domrolebuffer{$rudom}) {
 4794:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4795:                       '='.&escape($domainrolehash{$entry});
 4796:         } else {
 4797:             $domrolebuffer{$rudom}.=&escape($entry).
 4798:                       '='.&escape($domainrolehash{$entry});
 4799:         }
 4800:         delete $domainrolehash{$entry};
 4801:     }
 4802:     foreach my $dom (keys(%domrolebuffer)) {
 4803: 	my %servers;
 4804: 	if (defined(&domain($dom,'primary'))) {
 4805: 	    my $primary=&domain($dom,'primary');
 4806: 	    my $hostname=&hostname($primary);
 4807: 	    $servers{$primary} = $hostname;
 4808: 	} else { 
 4809: 	    %servers = &get_servers($dom,'library');
 4810: 	}
 4811: 	foreach my $tryserver (keys(%servers)) {
 4812: 	    if (&reply('domroleput:'.$dom.':'.
 4813: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4814: 		last;
 4815: 	    } else {  
 4816: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4817: 	    }
 4818:         }
 4819:     }
 4820:     $dumpcount++;
 4821: }
 4822: 
 4823: sub courselog {
 4824:     my $what=shift;
 4825:     $what=time.':'.$what;
 4826:     unless ($env{'request.course.id'}) { return ''; }
 4827:     $coursedombuf{$env{'request.course.id'}}=
 4828:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4829:     $coursenumbuf{$env{'request.course.id'}}=
 4830:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4831:     $coursehombuf{$env{'request.course.id'}}=
 4832:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4833:     $coursedescrbuf{$env{'request.course.id'}}=
 4834:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4835:     $courseinstcodebuf{$env{'request.course.id'}}=
 4836:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4837:     $courseownerbuf{$env{'request.course.id'}}=
 4838:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4839:     $coursetypebuf{$env{'request.course.id'}}=
 4840:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4841:     if (defined $courselogs{$env{'request.course.id'}}) {
 4842: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4843:     } else {
 4844: 	$courselogs{$env{'request.course.id'}}.=$what;
 4845:     }
 4846:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4847: 	&flushcourselogs();
 4848:     }
 4849: }
 4850: 
 4851: sub courseacclog {
 4852:     my $fnsymb=shift;
 4853:     unless ($env{'request.course.id'}) { return ''; }
 4854:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4855:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4856:         $what.=':POST';
 4857:         # FIXME: Probably ought to escape things....
 4858: 	foreach my $key (keys(%env)) {
 4859:             if ($key=~/^form\.(.*)/) {
 4860:                 my $formitem = $1;
 4861:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4862:                     $what.=':'.$formitem.'='.$env{$key};
 4863:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4864:                     $what.=':'.$formitem.'='.$env{$key};
 4865:                 }
 4866:             }
 4867:         }
 4868:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4869:         # FIXME: We should not be depending on a form parameter that someone
 4870:         # editing lonsearchcat.pm might change in the future.
 4871:         if ($env{'form.phase'} eq 'course_search') {
 4872:             $what.= ':POST';
 4873:             # FIXME: Probably ought to escape things....
 4874:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4875:                                  'crsdiscuss') {
 4876:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4877:             }
 4878:         }
 4879:     }
 4880:     &courselog($what);
 4881: }
 4882: 
 4883: sub countacc {
 4884:     my $url=&declutter(shift);
 4885:     return if (! defined($url) || $url eq '');
 4886:     unless ($env{'request.course.id'}) { return ''; }
 4887: #
 4888: # Mark that this url was used in this course
 4889: #
 4890:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4891: #
 4892: # Increase the access count for this resource in this child process
 4893: #
 4894:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4895:     $accesshash{$key}++;
 4896: }
 4897: 
 4898: sub linklog {
 4899:     my ($from,$to)=@_;
 4900:     $from=&declutter($from);
 4901:     $to=&declutter($to);
 4902:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4903:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4904: }
 4905: 
 4906: sub statslog {
 4907:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4908:     if ($users<2) { return; }
 4909:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4910:             'course'       => $env{'request.course.id'},
 4911:             'sections'     => '"all"',
 4912:             'num_students' => $users,
 4913:             'part'         => $part,
 4914:             'symb'         => $symb,
 4915:             'mean_tries'   => $av_attempts,
 4916:             'deg_of_diff'  => $degdiff});
 4917:     foreach my $key (keys(%dynstore)) {
 4918:         $accesshash{$key}=$dynstore{$key};
 4919:     }
 4920: }
 4921:   
 4922: sub userrolelog {
 4923:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4924:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4925:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4926:        $userrolehash
 4927:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4928:                     =$tend.':'.$tstart;
 4929:     }
 4930:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4931:        $userrolehash
 4932:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4933:                     =$tend.':'.$tstart;
 4934:     }
 4935:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4936:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4937:        $domainrolehash
 4938:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4939:                     = $tend.':'.$tstart;
 4940:     }
 4941: }
 4942: 
 4943: sub courserolelog {
 4944:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4945:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4946:         my $cdom = $1;
 4947:         my $cnum = $2;
 4948:         my $sec = $3;
 4949:         my $namespace = 'rolelog';
 4950:         my %storehash = (
 4951:                            role    => $trole,
 4952:                            start   => $tstart,
 4953:                            end     => $tend,
 4954:                            selfenroll => $selfenroll,
 4955:                            context    => $context,
 4956:                         );
 4957:         if ($trole eq 'gr') {
 4958:             $namespace = 'groupslog';
 4959:             $storehash{'group'} = $sec;
 4960:         } else {
 4961:             $storehash{'section'} = $sec;
 4962:         }
 4963:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4964:                    $domain,$cnum,$cdom);
 4965:         if (($trole ne 'st') || ($sec ne '')) {
 4966:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4967:         }
 4968:     }
 4969:     return;
 4970: }
 4971: 
 4972: sub domainrolelog {
 4973:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4974:     if ($area =~ m{^/($match_domain)/$}) {
 4975:         my $cdom = $1;
 4976:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4977:         my $namespace = 'rolelog';
 4978:         my %storehash = (
 4979:                            role    => $trole,
 4980:                            start   => $tstart,
 4981:                            end     => $tend,
 4982:                            context => $context,
 4983:                         );
 4984:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4985:                    $domain,$domconfiguser,$cdom);
 4986:     }
 4987:     return;
 4988: 
 4989: }
 4990: 
 4991: sub coauthorrolelog {
 4992:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4993:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4994:         my $audom = $1;
 4995:         my $auname = $2;
 4996:         my $namespace = 'rolelog';
 4997:         my %storehash = (
 4998:                            role    => $trole,
 4999:                            start   => $tstart,
 5000:                            end     => $tend,
 5001:                            context => $context,
 5002:                         );
 5003:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5004:                    $domain,$auname,$audom);
 5005:     }
 5006:     return;
 5007: }
 5008: 
 5009: sub get_course_adv_roles {
 5010:     my ($cid,$codes) = @_;
 5011:     $cid=$env{'request.course.id'} unless (defined($cid));
 5012:     my %coursehash=&coursedescription($cid);
 5013:     my $crstype = &Apache::loncommon::course_type($cid);
 5014:     my %nothide=();
 5015:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5016:         if ($user !~ /:/) {
 5017: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5018:         } else {
 5019:             $nothide{$user}=1;
 5020:         }
 5021:     }
 5022:     my @possdoms = ($coursehash{'domain'});
 5023:     if ($coursehash{'checkforpriv'}) {
 5024:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5025:     }
 5026:     my %returnhash=();
 5027:     my %dumphash=
 5028:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5029:     my $now=time;
 5030:     my %privileged;
 5031:     foreach my $entry (keys(%dumphash)) {
 5032: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5033:         if (($tstart) && ($tstart<0)) { next; }
 5034:         if (($tend) && ($tend<$now)) { next; }
 5035:         if (($tstart) && ($now<$tstart)) { next; }
 5036:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5037: 	if ($username eq '' || $domain eq '') { next; }
 5038:         if ((&privileged($username,$domain,\@possdoms)) &&
 5039:             (!$nothide{$username.':'.$domain})) { next; }
 5040: 	if ($role eq 'cr') { next; }
 5041:         if ($codes) {
 5042:             if ($section) { $role .= ':'.$section; }
 5043:             if ($returnhash{$role}) {
 5044:                 $returnhash{$role}.=','.$username.':'.$domain;
 5045:             } else {
 5046:                 $returnhash{$role}=$username.':'.$domain;
 5047:             }
 5048:         } else {
 5049:             my $key=&plaintext($role,$crstype);
 5050:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5051:             if ($returnhash{$key}) {
 5052: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5053:             } else {
 5054:                 $returnhash{$key}=$username.':'.$domain;
 5055:             }
 5056:         }
 5057:     }
 5058:     return %returnhash;
 5059: }
 5060: 
 5061: sub get_my_roles {
 5062:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5063:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5064:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5065:     my (%dumphash,%nothide);
 5066:     if ($context eq 'userroles') {
 5067:         %dumphash = &dump('roles',$udom,$uname);
 5068:     } else {
 5069:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5070:         if ($hidepriv) {
 5071:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5072:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5073:                 if ($user !~ /:/) {
 5074:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5075:                 } else {
 5076:                     $nothide{$user} = 1;
 5077:                 }
 5078:             }
 5079:         }
 5080:     }
 5081:     my %returnhash=();
 5082:     my $now=time;
 5083:     my %privileged;
 5084:     foreach my $entry (keys(%dumphash)) {
 5085:         my ($role,$tend,$tstart);
 5086:         if ($context eq 'userroles') {
 5087:             next if ($entry =~ /^rolesdef/);
 5088: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5089:         } else {
 5090:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5091:         }
 5092:         if (($tstart) && ($tstart<0)) { next; }
 5093:         my $status = 'active';
 5094:         if (($tend) && ($tend<=$now)) {
 5095:             $status = 'previous';
 5096:         } 
 5097:         if (($tstart) && ($now<$tstart)) {
 5098:             $status = 'future';
 5099:         }
 5100:         if (ref($types) eq 'ARRAY') {
 5101:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5102:                 next;
 5103:             } 
 5104:         } else {
 5105:             if ($status ne 'active') {
 5106:                 next;
 5107:             }
 5108:         }
 5109:         my ($rolecode,$username,$domain,$section,$area);
 5110:         if ($context eq 'userroles') {
 5111:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5112:             (undef,$domain,$username,$section) = split(/\//,$area);
 5113:         } else {
 5114:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5115:         }
 5116:         if (ref($roledoms) eq 'ARRAY') {
 5117:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5118:                 next;
 5119:             }
 5120:         }
 5121:         if (ref($roles) eq 'ARRAY') {
 5122:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5123:                 if ($role =~ /^cr\//) {
 5124:                     if (!grep(/^cr$/,@{$roles})) {
 5125:                         next;
 5126:                     }
 5127:                 } elsif ($role =~ /^gr\//) {
 5128:                     if (!grep(/^gr$/,@{$roles})) {
 5129:                         next;
 5130:                     }
 5131:                 } else {
 5132:                     next;
 5133:                 }
 5134:             }
 5135:         }
 5136:         if ($hidepriv) {
 5137:             my @privroles = ('dc','su');
 5138:             if ($context eq 'userroles') {
 5139:                 next if (grep(/^\Q$role\E$/,@privroles));
 5140:             } else {
 5141:                 my $possdoms = [$domain];
 5142:                 if (ref($roledoms) eq 'ARRAY') {
 5143:                    push(@{$possdoms},@{$roledoms}); 
 5144:                 }
 5145:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5146:                     if (!$nothide{$username.':'.$domain}) {
 5147:                         next;
 5148:                     }
 5149:                 }
 5150:             }
 5151:         }
 5152:         if ($withsec) {
 5153:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5154:                 $tstart.':'.$tend;
 5155:         } else {
 5156:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5157:         }
 5158:     }
 5159:     return %returnhash;
 5160: }
 5161: 
 5162: sub get_all_adhocroles {
 5163:     my ($dom) = @_;
 5164:     my @roles_by_num = ();
 5165:     my %domdefaults = &get_domain_defaults($dom);
 5166:     my (%description,%access_in_dom,%access_info);
 5167:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5168:         my $count = 0;
 5169:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5170:         my %ordered;
 5171:         foreach my $role (sort(keys(%domcurrent))) {
 5172:             my ($order,$desc,$access_in_dom);
 5173:             if (ref($domcurrent{$role}) eq 'HASH') {
 5174:                 $order = $domcurrent{$role}{'order'};
 5175:                 $desc = $domcurrent{$role}{'desc'};
 5176:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5177:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5178:             }
 5179:             if ($order eq '') {
 5180:                 $order = $count;
 5181:             }
 5182:             $ordered{$order} = $role;
 5183:             if ($desc ne '') {
 5184:                 $description{$role} = $desc;
 5185:             } else {
 5186:                 $description{$role}= $role;
 5187:             }
 5188:             $count++;
 5189:         }
 5190:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5191:             push(@roles_by_num,$ordered{$item});
 5192:         }
 5193:     }
 5194:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5195: }
 5196: 
 5197: sub get_my_adhocroles {
 5198:     my ($cid,$checkreg) = @_;
 5199:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5200:     if ($env{'request.course.id'} eq $cid) {
 5201:         $cdom = $env{'course.'.$cid.'.domain'};
 5202:         $cnum = $env{'course.'.$cid.'.num'};
 5203:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5204:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5205:         $cdom = $1;
 5206:         $cnum = $2;
 5207:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5208:                                      $cdom,$cnum);
 5209:     }
 5210:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5211:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5212:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5213:         if ($rosterhash{$user} ne '') {
 5214:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5215:             return ([],{}) if ($type eq 'auto');
 5216:         }
 5217:     }
 5218:     if (($cdom ne '') && ($cnum ne ''))  {
 5219:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5220:             my $then=$env{'user.login.time'};
 5221:             my $update=$env{'user.update.time'};
 5222:             if (!$update) {
 5223:                 $update = $then;
 5224:             }
 5225:             my @liveroles;
 5226:             foreach my $role ('dh','da') {
 5227:                 if ($env{"user.role.$role./$cdom/"}) {
 5228:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5229:                     my $limit = $update;
 5230:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5231:                         $limit = $then;
 5232:                     }
 5233:                     my $activerole = 1;
 5234:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5235:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5236:                     if ($activerole) {
 5237:                         push(@liveroles,$role);
 5238:                     }
 5239:                 }
 5240:             }
 5241:             if (@liveroles) {
 5242:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5243:                     my ($accessref,$accessinfo,%access_in_dom);
 5244:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5245:                     if (ref($roles_by_num) eq 'ARRAY') {
 5246:                         if (@{$roles_by_num}) {
 5247:                             my %settings;
 5248:                             if ($env{'request.course.id'} eq $cid) {
 5249:                                 foreach my $envkey (keys(%env)) {
 5250:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5251:                                         $settings{$1} = $env{$envkey};
 5252:                                     }
 5253:                                 }
 5254:                             } else {
 5255:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5256:                             }
 5257:                             my %setincrs;
 5258:                             if ($settings{'internal.adhocaccess'}) {
 5259:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5260:                             }
 5261:                             my @statuses;
 5262:                             if ($env{'environment.inststatus'}) {
 5263:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5264:                             }
 5265:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5266:                             if (ref($accessref) eq 'HASH') {
 5267:                                 %access_in_dom = %{$accessref};
 5268:                             }
 5269:                             foreach my $role (@{$roles_by_num}) {
 5270:                                 my ($curraccess,@okstatus,@personnel);
 5271:                                 if ($setincrs{$role}) {
 5272:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5273:                                     if ($curraccess eq 'status') {
 5274:                                         @okstatus = split(/\&/,$rest);
 5275:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5276:                                         @personnel = split(/\&/,$rest);
 5277:                                     }
 5278:                                 } else {
 5279:                                     $curraccess = $access_in_dom{$role};
 5280:                                     if (ref($accessinfo) eq 'HASH') {
 5281:                                         if ($curraccess eq 'status') {
 5282:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5283:                                                 @okstatus = @{$accessinfo->{$role}};
 5284:                                             }
 5285:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5286:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5287:                                                 @personnel = @{$accessinfo->{$role}};
 5288:                                             }
 5289:                                         }
 5290:                                     }
 5291:                                 }
 5292:                                 if ($curraccess eq 'none') {
 5293:                                     next;
 5294:                                 } elsif ($curraccess eq 'all') {
 5295:                                     push(@possroles,$role);
 5296:                                 } elsif ($curraccess eq 'dh') {
 5297:                                     if (grep(/^dh$/,@liveroles)) {
 5298:                                         push(@possroles,$role);
 5299:                                     } else {
 5300:                                         next;
 5301:                                     }
 5302:                                 } elsif ($curraccess eq 'da') {
 5303:                                     if (grep(/^da$/,@liveroles)) {
 5304:                                         push(@possroles,$role);
 5305:                                     } else {
 5306:                                         next;
 5307:                                     }
 5308:                                 } elsif ($curraccess eq 'status') {
 5309:                                     if (@okstatus) {
 5310:                                         if (!@statuses) {
 5311:                                             if (grep(/^default$/,@okstatus)) {
 5312:                                                 push(@possroles,$role);
 5313:                                             }
 5314:                                         } else {
 5315:                                             foreach my $status (@okstatus) {
 5316:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5317:                                                     push(@possroles,$role);
 5318:                                                     last;
 5319:                                                 }
 5320:                                             }
 5321:                                         }
 5322:                                     }
 5323:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5324:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5325:                                         if ($curraccess eq 'exc') {
 5326:                                             push(@possroles,$role);
 5327:                                         }
 5328:                                     } elsif ($curraccess eq 'inc') {
 5329:                                         push(@possroles,$role);
 5330:                                     }
 5331:                                 }
 5332:                             }
 5333:                         }
 5334:                     }
 5335:                 }
 5336:             }
 5337:         }
 5338:     }
 5339:     unless (ref($description) eq 'HASH') {
 5340:         if (ref($roles_by_num) eq 'ARRAY') {
 5341:             my %desc;
 5342:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5343:             $description = \%desc;
 5344:         } else {
 5345:             $description = {};
 5346:         }
 5347:     }
 5348:     return (\@possroles,$description);
 5349: }
 5350: 
 5351: # ----------------------------------------------------- Frontpage Announcements
 5352: #
 5353: #
 5354: 
 5355: sub postannounce {
 5356:     my ($server,$text)=@_;
 5357:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5358:     unless ($text=~/\w/) { $text=''; }
 5359:     return &reply('setannounce:'.&escape($text),$server);
 5360: }
 5361: 
 5362: sub getannounce {
 5363: 
 5364:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5365: 	my $announcement='';
 5366: 	while (my $line = <$fh>) { $announcement .= $line; }
 5367: 	close($fh);
 5368: 	if ($announcement=~/\w/) { 
 5369: 	    return 
 5370:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5371:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5372: 	} else {
 5373: 	    return '';
 5374: 	}
 5375:     } else {
 5376: 	return '';
 5377:     }
 5378: }
 5379: 
 5380: # ---------------------------------------------------------- Course ID routines
 5381: # Deal with domain's nohist_courseid.db files
 5382: #
 5383: 
 5384: sub courseidput {
 5385:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5386:     return unless (ref($storehash) eq 'HASH');
 5387:     my $outcome;
 5388:     if ($caller eq 'timeonly') {
 5389:         my $cids = '';
 5390:         foreach my $item (keys(%$storehash)) {
 5391:             $cids.=&escape($item).'&';
 5392:         }
 5393:         $cids=~s/\&$//;
 5394:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5395:                           $coursehome);       
 5396:     } else {
 5397:         my $items = '';
 5398:         foreach my $item (keys(%$storehash)) {
 5399:             $items.= &escape($item).'='.
 5400:                      &freeze_escape($$storehash{$item}).'&';
 5401:         }
 5402:         $items=~s/\&$//;
 5403:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5404:                           $coursehome);
 5405:     }
 5406:     if ($outcome eq 'unknown_cmd') {
 5407:         my $what;
 5408:         foreach my $cid (keys(%$storehash)) {
 5409:             $what .= &escape($cid).'=';
 5410:             foreach my $item ('description','inst_code','owner','type') {
 5411:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5412:             }
 5413:             $what =~ s/\:$/&/;
 5414:         }
 5415:         $what =~ s/\&$//;  
 5416:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5417:     } else {
 5418:         return $outcome;
 5419:     }
 5420: }
 5421: 
 5422: sub courseiddump {
 5423:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5424:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5425:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5426:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5427:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5428:     my $as_hash = 1;
 5429:     my %returnhash;
 5430:     if (!$domfilter) { $domfilter=''; }
 5431:     my %libserv = &all_library();
 5432:     foreach my $tryserver (keys(%libserv)) {
 5433:         if ( (  $hostidflag == 1 
 5434: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5435: 	     || (!defined($hostidflag)) ) {
 5436: 
 5437: 	    if (($domfilter eq '') ||
 5438: 		(&host_domain($tryserver) eq $domfilter)) {
 5439:                 my $rep;
 5440:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5441:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5442:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5443:                                 &escape($descfilter), &escape($instcodefilter), 
 5444:                                 &escape($ownerfilter), &escape($coursefilter),
 5445:                                 &escape($typefilter), &escape($regexp_ok), 
 5446:                                 $as_hash, &escape($selfenrollonly), 
 5447:                                 &escape($catfilter), $showhidden, $caller, 
 5448:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5449:                                 &escape($createdbefore), &escape($createdafter), 
 5450:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5451:                                 $reqcrsdom,&escape($reqinstcode))));
 5452:                 } else {
 5453:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5454:                              $sincefilter.':'.&escape($descfilter).':'.
 5455:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5456:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5457:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5458:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5459:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5460:                              &escape($cc_clone).':'.$cloneonly.':'.
 5461:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5462:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5463:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5464:                 }
 5465:                      
 5466:                 my @pairs=split(/\&/,$rep);
 5467:                 foreach my $item (@pairs) {
 5468:                     my ($key,$value)=split(/\=/,$item,2);
 5469:                     $key = &unescape($key);
 5470:                     next if ($key =~ /^error: 2 /);
 5471:                     my $result = &thaw_unescape($value);
 5472:                     if (ref($result) eq 'HASH') {
 5473:                         $returnhash{$key}=$result;
 5474:                     } else {
 5475:                         my @responses = split(/:/,$value);
 5476:                         my @items = ('description','inst_code','owner','type');
 5477:                         for (my $i=0; $i<@responses; $i++) {
 5478:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5479:                         }
 5480:                     }
 5481:                 }
 5482:             }
 5483:         }
 5484:     }
 5485:     return %returnhash;
 5486: }
 5487: 
 5488: sub courselastaccess {
 5489:     my ($cdom,$cnum,$hostidref) = @_;
 5490:     my %returnhash;
 5491:     if ($cdom && $cnum) {
 5492:         my $chome = &homeserver($cnum,$cdom);
 5493:         if ($chome ne 'no_host') {
 5494:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5495:             &extract_lastaccess(\%returnhash,$rep);
 5496:         }
 5497:     } else {
 5498:         if (!$cdom) { $cdom=''; }
 5499:         my %libserv = &all_library();
 5500:         foreach my $tryserver (keys(%libserv)) {
 5501:             if (ref($hostidref) eq 'ARRAY') {
 5502:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5503:             } 
 5504:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5505:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5506:                 &extract_lastaccess(\%returnhash,$rep);
 5507:             }
 5508:         }
 5509:     }
 5510:     return %returnhash;
 5511: }
 5512: 
 5513: sub extract_lastaccess {
 5514:     my ($returnhash,$rep) = @_;
 5515:     if (ref($returnhash) eq 'HASH') {
 5516:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5517:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5518:                  $rep eq '') {
 5519:             my @pairs=split(/\&/,$rep);
 5520:             foreach my $item (@pairs) {
 5521:                 my ($key,$value)=split(/\=/,$item,2);
 5522:                 $key = &unescape($key);
 5523:                 next if ($key =~ /^error: 2 /);
 5524:                 $returnhash->{$key} = &thaw_unescape($value);
 5525:             }
 5526:         }
 5527:     }
 5528:     return;
 5529: }
 5530: 
 5531: # ---------------------------------------------------------- DC e-mail
 5532: 
 5533: sub dcmailput {
 5534:     my ($domain,$msgid,$message,$server)=@_;
 5535:     my $status = &Apache::lonnet::critical(
 5536:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5537:        &escape($message),$server);
 5538:     return $status;
 5539: }
 5540: 
 5541: sub dcmaildump {
 5542:     my ($dom,$startdate,$enddate,$senders) = @_;
 5543:     my %returnhash=();
 5544: 
 5545:     if (defined(&domain($dom,'primary'))) {
 5546:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5547:                                                          &escape($enddate).':';
 5548: 	my @esc_senders=map { &escape($_)} @$senders;
 5549: 	$cmd.=&escape(join('&',@esc_senders));
 5550: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5551:             my ($key,$value) = split(/\=/,$line,2);
 5552:             if (($key) && ($value)) {
 5553:                 $returnhash{&unescape($key)} = &unescape($value);
 5554:             }
 5555:         }
 5556:     }
 5557:     return %returnhash;
 5558: }
 5559: # ---------------------------------------------------------- Domain roles
 5560: 
 5561: sub get_domain_roles {
 5562:     my ($dom,$roles,$startdate,$enddate)=@_;
 5563:     if ((!defined($startdate)) || ($startdate eq '')) {
 5564:         $startdate = '.';
 5565:     }
 5566:     if ((!defined($enddate)) || ($enddate eq '')) {
 5567:         $enddate = '.';
 5568:     }
 5569:     my $rolelist;
 5570:     if (ref($roles) eq 'ARRAY') {
 5571:         $rolelist = join('&',@{$roles});
 5572:     }
 5573:     my %personnel = ();
 5574: 
 5575:     my %servers = &get_servers($dom,'library');
 5576:     foreach my $tryserver (keys(%servers)) {
 5577: 	%{$personnel{$tryserver}}=();
 5578: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5579: 					    &escape($startdate).':'.
 5580: 					    &escape($enddate).':'.
 5581: 					    &escape($rolelist), $tryserver))) {
 5582: 	    my ($key,$value) = split(/\=/,$line,2);
 5583: 	    if (($key) && ($value)) {
 5584: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5585: 	    }
 5586: 	}
 5587:     }
 5588:     return %personnel;
 5589: }
 5590: 
 5591: sub get_active_domroles {
 5592:     my ($dom,$roles) = @_;
 5593:     return () unless (ref($roles) eq 'ARRAY');
 5594:     my $now = time;
 5595:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5596:     my %domroles;
 5597:     foreach my $server (keys(%dompersonnel)) {
 5598:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5599:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5600:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5601:         }
 5602:     }
 5603:     return %domroles;
 5604: }
 5605: 
 5606: # ----------------------------------------------------------- Interval timing 
 5607: 
 5608: {
 5609: # Caches needed for speedup of navmaps
 5610: # We don't want to cache this for very long at all (5 seconds at most)
 5611: # 
 5612: # The user for whom we cache
 5613: my $cachedkey='';
 5614: # The cached times for this user
 5615: my %cachedtimes=();
 5616: # When this was last done
 5617: my $cachedtime='';
 5618: 
 5619: sub load_all_first_access {
 5620:     my ($uname,$udom,$ignorecache)=@_;
 5621:     if (($cachedkey eq $uname.':'.$udom) &&
 5622:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5623:         (!$ignorecache)) {
 5624:         return;
 5625:     }
 5626:     $cachedtime=time;
 5627:     $cachedkey=$uname.':'.$udom;
 5628:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5629: }
 5630: 
 5631: sub get_first_access {
 5632:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5633:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5634:     if ($argsymb) { $symb=$argsymb; }
 5635:     my ($map,$id,$res)=&decode_symb($symb);
 5636:     if ($argmap) { $map = $argmap; }
 5637:     if ($type eq 'course') {
 5638: 	$res='course';
 5639:     } elsif ($type eq 'map') {
 5640: 	$res=&symbread($map);
 5641:     } else {
 5642: 	$res=$symb;
 5643:     }
 5644:     &load_all_first_access($uname,$udom,$ignorecache);
 5645:     return $cachedtimes{"$courseid\0$res"};
 5646: }
 5647: 
 5648: sub set_first_access {
 5649:     my ($type,$interval)=@_;
 5650:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5651:     my ($map,$id,$res)=&decode_symb($symb);
 5652:     if ($type eq 'course') {
 5653: 	$res='course';
 5654:     } elsif ($type eq 'map') {
 5655: 	$res=&symbread($map);
 5656:     } else {
 5657: 	$res=$symb;
 5658:     }
 5659:     $cachedkey='';
 5660:     my $firstaccess=&get_first_access($type,$symb,$map);
 5661:     if ($firstaccess) {
 5662:         &logthis("First access time already set ($firstaccess) when attempting ".
 5663:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5664:                  "in $courseid");
 5665:         return 'already_set';
 5666:     } else {
 5667:         my $start = time;
 5668: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5669:                           $udom,$uname);
 5670:         if ($putres eq 'ok') {
 5671:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5672:                  $udom,$uname); 
 5673:             &appenv(
 5674:                      {
 5675:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5676:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5677:                      }
 5678:                   );
 5679:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5680:                 $cachedtimes{"$courseid\0$res"} = $start;
 5681:             }
 5682:         } elsif ($putres ne 'refused') {
 5683:             &logthis("Result: $putres when attempting to set first access time ".
 5684:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5685:         }
 5686:         return $putres;
 5687:     }
 5688:     return 'already_set';
 5689: }
 5690: }
 5691: 
 5692: # --------------------------------------------- Set Expire Date for Spreadsheet
 5693: 
 5694: sub expirespread {
 5695:     my ($uname,$udom,$stype,$usymb)=@_;
 5696:     my $cid=$env{'request.course.id'}; 
 5697:     if ($cid) {
 5698:        my $now=time;
 5699:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5700:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5701:                             $env{'course.'.$cid.'.num'}.
 5702: 	        	    ':nohist_expirationdates:'.
 5703:                             &escape($key).'='.$now,
 5704:                             $env{'course.'.$cid.'.home'})
 5705:     }
 5706:     return 'ok';
 5707: }
 5708: 
 5709: # ----------------------------------------------------- Devalidate Spreadsheets
 5710: 
 5711: sub devalidate {
 5712:     my ($symb,$uname,$udom)=@_;
 5713:     my $cid=$env{'request.course.id'}; 
 5714:     if ($cid) {
 5715:         # delete the stored spreadsheets for
 5716:         # - the student level sheet of this user in course's homespace
 5717:         # - the assessment level sheet for this resource 
 5718:         #   for this user in user's homespace
 5719: 	# - current conditional state info
 5720: 	my $key=$uname.':'.$udom.':';
 5721:         my $status=
 5722: 	    &del('nohist_calculatedsheets',
 5723: 		 [$key.'studentcalc:'],
 5724: 		 $env{'course.'.$cid.'.domain'},
 5725: 		 $env{'course.'.$cid.'.num'})
 5726: 		.' '.
 5727: 	    &del('nohist_calculatedsheets_'.$cid,
 5728: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5729:         unless ($status eq 'ok ok') {
 5730:            &logthis('Could not devalidate spreadsheet '.
 5731:                     $uname.' at '.$udom.' for '.
 5732: 		    $symb.': '.$status);
 5733:         }
 5734: 	&delenv('user.state.'.$cid);
 5735:     }
 5736: }
 5737: 
 5738: sub get_scalar {
 5739:     my ($string,$end) = @_;
 5740:     my $value;
 5741:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5742: 	$value = $1;
 5743:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5744: 	$value = $1;
 5745:     }
 5746:     return &unescape($value);
 5747: }
 5748: 
 5749: sub array2str {
 5750:   my (@array) = @_;
 5751:   my $result=&arrayref2str(\@array);
 5752:   $result=~s/^__ARRAY_REF__//;
 5753:   $result=~s/__END_ARRAY_REF__$//;
 5754:   return $result;
 5755: }
 5756: 
 5757: sub arrayref2str {
 5758:   my ($arrayref) = @_;
 5759:   my $result='__ARRAY_REF__';
 5760:   foreach my $elem (@$arrayref) {
 5761:     if(ref($elem) eq 'ARRAY') {
 5762:       $result.=&arrayref2str($elem).'&';
 5763:     } elsif(ref($elem) eq 'HASH') {
 5764:       $result.=&hashref2str($elem).'&';
 5765:     } elsif(ref($elem)) {
 5766:       #print("Got a ref of ".(ref($elem))." skipping.");
 5767:     } else {
 5768:       $result.=&escape($elem).'&';
 5769:     }
 5770:   }
 5771:   $result=~s/\&$//;
 5772:   $result .= '__END_ARRAY_REF__';
 5773:   return $result;
 5774: }
 5775: 
 5776: sub hash2str {
 5777:   my (%hash) = @_;
 5778:   my $result=&hashref2str(\%hash);
 5779:   $result=~s/^__HASH_REF__//;
 5780:   $result=~s/__END_HASH_REF__$//;
 5781:   return $result;
 5782: }
 5783: 
 5784: sub hashref2str {
 5785:   my ($hashref)=@_;
 5786:   my $result='__HASH_REF__';
 5787:   foreach my $key (sort(keys(%$hashref))) {
 5788:     if (ref($key) eq 'ARRAY') {
 5789:       $result.=&arrayref2str($key).'=';
 5790:     } elsif (ref($key) eq 'HASH') {
 5791:       $result.=&hashref2str($key).'=';
 5792:     } elsif (ref($key)) {
 5793:       $result.='=';
 5794:       #print("Got a ref of ".(ref($key))." skipping.");
 5795:     } else {
 5796: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5797:     }
 5798: 
 5799:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5800:       $result.=&arrayref2str($hashref->{$key}).'&';
 5801:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5802:       $result.=&hashref2str($hashref->{$key}).'&';
 5803:     } elsif(ref($hashref->{$key})) {
 5804:        $result.='&';
 5805:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5806:     } else {
 5807:       $result.=&escape($hashref->{$key}).'&';
 5808:     }
 5809:   }
 5810:   $result=~s/\&$//;
 5811:   $result .= '__END_HASH_REF__';
 5812:   return $result;
 5813: }
 5814: 
 5815: sub str2hash {
 5816:     my ($string)=@_;
 5817:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5818:     return %$hash;
 5819: }
 5820: 
 5821: sub str2hashref {
 5822:   my ($string) = @_;
 5823: 
 5824:   my %hash;
 5825: 
 5826:   if($string !~ /^__HASH_REF__/) {
 5827:       if (! ($string eq '' || !defined($string))) {
 5828: 	  $hash{'error'}='Not hash reference';
 5829:       }
 5830:       return (\%hash, $string);
 5831:   }
 5832: 
 5833:   $string =~ s/^__HASH_REF__//;
 5834: 
 5835:   while($string !~ /^__END_HASH_REF__/) {
 5836:       #key
 5837:       my $key='';
 5838:       if($string =~ /^__HASH_REF__/) {
 5839:           ($key, $string)=&str2hashref($string);
 5840:           if(defined($key->{'error'})) {
 5841:               $hash{'error'}='Bad data';
 5842:               return (\%hash, $string);
 5843:           }
 5844:       } elsif($string =~ /^__ARRAY_REF__/) {
 5845:           ($key, $string)=&str2arrayref($string);
 5846:           if($key->[0] eq 'Array reference error') {
 5847:               $hash{'error'}='Bad data';
 5848:               return (\%hash, $string);
 5849:           }
 5850:       } else {
 5851:           $string =~ s/^(.*?)=//;
 5852: 	  $key=&unescape($1);
 5853:       }
 5854:       $string =~ s/^=//;
 5855: 
 5856:       #value
 5857:       my $value='';
 5858:       if($string =~ /^__HASH_REF__/) {
 5859:           ($value, $string)=&str2hashref($string);
 5860:           if(defined($value->{'error'})) {
 5861:               $hash{'error'}='Bad data';
 5862:               return (\%hash, $string);
 5863:           }
 5864:       } elsif($string =~ /^__ARRAY_REF__/) {
 5865:           ($value, $string)=&str2arrayref($string);
 5866:           if($value->[0] eq 'Array reference error') {
 5867:               $hash{'error'}='Bad data';
 5868:               return (\%hash, $string);
 5869:           }
 5870:       } else {
 5871: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5872:       }
 5873:       $string =~ s/^&//;
 5874: 
 5875:       $hash{$key}=$value;
 5876:   }
 5877: 
 5878:   $string =~ s/^__END_HASH_REF__//;
 5879: 
 5880:   return (\%hash, $string);
 5881: }
 5882: 
 5883: sub str2array {
 5884:     my ($string)=@_;
 5885:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5886:     return @$array;
 5887: }
 5888: 
 5889: sub str2arrayref {
 5890:   my ($string) = @_;
 5891:   my @array;
 5892: 
 5893:   if($string !~ /^__ARRAY_REF__/) {
 5894:       if (! ($string eq '' || !defined($string))) {
 5895: 	  $array[0]='Array reference error';
 5896:       }
 5897:       return (\@array, $string);
 5898:   }
 5899: 
 5900:   $string =~ s/^__ARRAY_REF__//;
 5901: 
 5902:   while($string !~ /^__END_ARRAY_REF__/) {
 5903:       my $value='';
 5904:       if($string =~ /^__HASH_REF__/) {
 5905:           ($value, $string)=&str2hashref($string);
 5906:           if(defined($value->{'error'})) {
 5907:               $array[0] ='Array reference error';
 5908:               return (\@array, $string);
 5909:           }
 5910:       } elsif($string =~ /^__ARRAY_REF__/) {
 5911:           ($value, $string)=&str2arrayref($string);
 5912:           if($value->[0] eq 'Array reference error') {
 5913:               $array[0] ='Array reference error';
 5914:               return (\@array, $string);
 5915:           }
 5916:       } else {
 5917: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5918:       }
 5919:       $string =~ s/^&//;
 5920: 
 5921:       push(@array, $value);
 5922:   }
 5923: 
 5924:   $string =~ s/^__END_ARRAY_REF__//;
 5925: 
 5926:   return (\@array, $string);
 5927: }
 5928: 
 5929: # -------------------------------------------------------------------Temp Store
 5930: 
 5931: sub tmpreset {
 5932:   my ($symb,$namespace,$domain,$stuname) = @_;
 5933:   if (!$symb) {
 5934:     $symb=&symbread();
 5935:     if (!$symb) { $symb= $env{'request.url'}; }
 5936:   }
 5937:   $symb=escape($symb);
 5938: 
 5939:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5940:   $namespace=~s/\//\_/g;
 5941:   $namespace=~s/\W//g;
 5942: 
 5943:   if (!$domain) { $domain=$env{'user.domain'}; }
 5944:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5945:   if ($domain eq 'public' && $stuname eq 'public') {
 5946:       $stuname=$ENV{'REMOTE_ADDR'};
 5947:   }
 5948:   my $path=LONCAPA::tempdir();
 5949:   my %hash;
 5950:   if (tie(%hash,'GDBM_File',
 5951: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5952: 	  &GDBM_WRCREAT(),0640)) {
 5953:     foreach my $key (keys(%hash)) {
 5954:       if ($key=~ /:$symb/) {
 5955: 	delete($hash{$key});
 5956:       }
 5957:     }
 5958:   }
 5959: }
 5960: 
 5961: sub tmpstore {
 5962:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5963: 
 5964:   if (!$symb) {
 5965:     $symb=&symbread();
 5966:     if (!$symb) { $symb= $env{'request.url'}; }
 5967:   }
 5968:   $symb=escape($symb);
 5969: 
 5970:   if (!$namespace) {
 5971:     # I don't think we would ever want to store this for a course.
 5972:     # it seems this will only be used if we don't have a course.
 5973:     #$namespace=$env{'request.course.id'};
 5974:     #if (!$namespace) {
 5975:       $namespace=$env{'request.state'};
 5976:     #}
 5977:   }
 5978:   $namespace=~s/\//\_/g;
 5979:   $namespace=~s/\W//g;
 5980:   if (!$domain) { $domain=$env{'user.domain'}; }
 5981:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5982:   if ($domain eq 'public' && $stuname eq 'public') {
 5983:       $stuname=$ENV{'REMOTE_ADDR'};
 5984:   }
 5985:   my $now=time;
 5986:   my %hash;
 5987:   my $path=LONCAPA::tempdir();
 5988:   if (tie(%hash,'GDBM_File',
 5989: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5990: 	  &GDBM_WRCREAT(),0640)) {
 5991:     $hash{"version:$symb"}++;
 5992:     my $version=$hash{"version:$symb"};
 5993:     my $allkeys=''; 
 5994:     foreach my $key (keys(%$storehash)) {
 5995:       $allkeys.=$key.':';
 5996:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5997:     }
 5998:     $hash{"$version:$symb:timestamp"}=$now;
 5999:     $allkeys.='timestamp';
 6000:     $hash{"$version:keys:$symb"}=$allkeys;
 6001:     if (untie(%hash)) {
 6002:       return 'ok';
 6003:     } else {
 6004:       return "error:$!";
 6005:     }
 6006:   } else {
 6007:     return "error:$!";
 6008:   }
 6009: }
 6010: 
 6011: # -----------------------------------------------------------------Temp Restore
 6012: 
 6013: sub tmprestore {
 6014:   my ($symb,$namespace,$domain,$stuname) = @_;
 6015: 
 6016:   if (!$symb) {
 6017:     $symb=&symbread();
 6018:     if (!$symb) { $symb= $env{'request.url'}; }
 6019:   }
 6020:   $symb=escape($symb);
 6021: 
 6022:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6023: 
 6024:   if (!$domain) { $domain=$env{'user.domain'}; }
 6025:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6026:   if ($domain eq 'public' && $stuname eq 'public') {
 6027:       $stuname=$ENV{'REMOTE_ADDR'};
 6028:   }
 6029:   my %returnhash;
 6030:   $namespace=~s/\//\_/g;
 6031:   $namespace=~s/\W//g;
 6032:   my %hash;
 6033:   my $path=LONCAPA::tempdir();
 6034:   if (tie(%hash,'GDBM_File',
 6035: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6036: 	  &GDBM_READER(),0640)) {
 6037:     my $version=$hash{"version:$symb"};
 6038:     $returnhash{'version'}=$version;
 6039:     my $scope;
 6040:     for ($scope=1;$scope<=$version;$scope++) {
 6041:       my $vkeys=$hash{"$scope:keys:$symb"};
 6042:       my @keys=split(/:/,$vkeys);
 6043:       my $key;
 6044:       $returnhash{"$scope:keys"}=$vkeys;
 6045:       foreach $key (@keys) {
 6046: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6047: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6048:       }
 6049:     }
 6050:     if (!(untie(%hash))) {
 6051:       return "error:$!";
 6052:     }
 6053:   } else {
 6054:     return "error:$!";
 6055:   }
 6056:   return %returnhash;
 6057: }
 6058: 
 6059: # ----------------------------------------------------------------------- Store
 6060: 
 6061: sub store {
 6062:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6063:     my $home='';
 6064: 
 6065:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6066: 
 6067:     $symb=&symbclean($symb);
 6068:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6069: 
 6070:     if (!$domain) { $domain=$env{'user.domain'}; }
 6071:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6072: 
 6073:     &devalidate($symb,$stuname,$domain);
 6074: 
 6075:     $symb=escape($symb);
 6076:     if (!$namespace) { 
 6077:        unless ($namespace=$env{'request.course.id'}) { 
 6078:           return ''; 
 6079:        } 
 6080:     }
 6081:     if (!$home) { $home=$env{'user.home'}; }
 6082: 
 6083:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6084:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6085: 
 6086:     my $namevalue='';
 6087:     foreach my $key (keys(%$storehash)) {
 6088:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6089:     }
 6090:     $namevalue=~s/\&$//;
 6091:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6092:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6093: }
 6094: 
 6095: # -------------------------------------------------------------- Critical Store
 6096: 
 6097: sub cstore {
 6098:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6099:     my $home='';
 6100: 
 6101:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6102: 
 6103:     $symb=&symbclean($symb);
 6104:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6105: 
 6106:     if (!$domain) { $domain=$env{'user.domain'}; }
 6107:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6108: 
 6109:     &devalidate($symb,$stuname,$domain);
 6110: 
 6111:     $symb=escape($symb);
 6112:     if (!$namespace) { 
 6113:        unless ($namespace=$env{'request.course.id'}) { 
 6114:           return ''; 
 6115:        } 
 6116:     }
 6117:     if (!$home) { $home=$env{'user.home'}; }
 6118: 
 6119:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6120:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6121: 
 6122:     my $namevalue='';
 6123:     foreach my $key (keys(%$storehash)) {
 6124:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6125:     }
 6126:     $namevalue=~s/\&$//;
 6127:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6128:     return critical
 6129:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6130: }
 6131: 
 6132: # --------------------------------------------------------------------- Restore
 6133: 
 6134: sub restore {
 6135:     my ($symb,$namespace,$domain,$stuname) = @_;
 6136:     my $home='';
 6137: 
 6138:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6139: 
 6140:     if (!$symb) {
 6141:         return if ($namespace eq 'courserequests');
 6142:         unless ($symb=escape(&symbread())) { return ''; }
 6143:     } else {
 6144:         unless ($namespace eq 'courserequests') {
 6145:             $symb=&escape(&symbclean($symb));
 6146:         }
 6147:     }
 6148:     if (!$namespace) { 
 6149:        unless ($namespace=$env{'request.course.id'}) { 
 6150:           return ''; 
 6151:        } 
 6152:     }
 6153:     if (!$domain) { $domain=$env{'user.domain'}; }
 6154:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6155:     if (!$home) { $home=$env{'user.home'}; }
 6156:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6157: 
 6158:     my %returnhash=();
 6159:     foreach my $line (split(/\&/,$answer)) {
 6160: 	my ($name,$value)=split(/\=/,$line);
 6161:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6162:     }
 6163:     my $version;
 6164:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6165:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6166:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6167:        }
 6168:     }
 6169:     return %returnhash;
 6170: }
 6171: 
 6172: # ---------------------------------------------------------- Course Description
 6173: #
 6174: #  
 6175: 
 6176: sub coursedescription {
 6177:     my ($courseid,$args)=@_;
 6178:     $courseid=~s/^\///;
 6179:     $courseid=~s/\_/\//g;
 6180:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6181:     my $chome=&homeserver($cnum,$cdomain);
 6182:     my $normalid=$cdomain.'_'.$cnum;
 6183:     # need to always cache even if we get errors otherwise we keep 
 6184:     # trying and trying and trying to get the course description.
 6185:     my %envhash=();
 6186:     my %returnhash=();
 6187:     
 6188:     my $expiretime=600;
 6189:     if ($env{'request.course.id'} eq $normalid) {
 6190: 	$expiretime=120;
 6191:     }
 6192: 
 6193:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6194:     if (!$args->{'freshen_cache'}
 6195: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6196: 	foreach my $key (keys(%env)) {
 6197: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6198: 	    my ($setting) = $1;
 6199: 	    $returnhash{$setting} = $env{$key};
 6200: 	}
 6201: 	return %returnhash;
 6202:     }
 6203: 
 6204:     # get the data again
 6205: 
 6206:     if (!$args->{'one_time'}) {
 6207: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6208:     }
 6209: 
 6210:     if ($chome ne 'no_host') {
 6211:        %returnhash=&dump('environment',$cdomain,$cnum);
 6212:        if (!exists($returnhash{'con_lost'})) {
 6213: 	   my $username = $env{'user.name'}; # Defult username
 6214: 	   if(defined $args->{'user'}) {
 6215: 	       $username = $args->{'user'};
 6216: 	   }
 6217:            $returnhash{'home'}= $chome;
 6218: 	   $returnhash{'domain'} = $cdomain;
 6219: 	   $returnhash{'num'} = $cnum;
 6220:            if (!defined($returnhash{'type'})) {
 6221:                $returnhash{'type'} = 'Course';
 6222:            }
 6223:            while (my ($name,$value) = each %returnhash) {
 6224:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6225:            }
 6226:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6227:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6228: 	       $username.'_'.$cdomain.'_'.$cnum;
 6229:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6230:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6231:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6232:        }
 6233:     }
 6234:     if (!$args->{'one_time'}) {
 6235: 	&appenv(\%envhash);
 6236:     }
 6237:     return %returnhash;
 6238: }
 6239: 
 6240: sub update_released_required {
 6241:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6242:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6243:         $cid = $env{'request.course.id'};
 6244:         $cdom = $env{'course.'.$cid.'.domain'};
 6245:         $cnum = $env{'course.'.$cid.'.num'};
 6246:         $chome = $env{'course.'.$cid.'.home'};
 6247:     }
 6248:     if ($needsrelease) {
 6249:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6250:         my $needsupdate;
 6251:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6252:             $needsupdate = 1;
 6253:         } else {
 6254:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6255:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6256:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6257:                 $needsupdate = 1;
 6258:             }
 6259:         }
 6260:         if ($needsupdate) {
 6261:             my %needshash = (
 6262:                              'internal.releaserequired' => $needsrelease,
 6263:                             );
 6264:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6265:             if ($putresult eq 'ok') {
 6266:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6267:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6268:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6269:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6270:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6271:                 }
 6272:             }
 6273:         }
 6274:     }
 6275:     return;
 6276: }
 6277: 
 6278: # -------------------------------------------------See if a user is privileged
 6279: 
 6280: sub privileged {
 6281:     my ($username,$domain,$possdomains,$possroles)=@_;
 6282:     my $now = time;
 6283:     my $roles;
 6284:     if (ref($possroles) eq 'ARRAY') {
 6285:         $roles = $possroles; 
 6286:     } else {
 6287:         $roles = ['dc','su'];
 6288:     }
 6289:     if (ref($possdomains) eq 'ARRAY') {
 6290:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6291:         foreach my $dom (@{$possdomains}) {
 6292:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6293:                 (ref($privileged{$dom}) eq 'HASH')) {
 6294:                 foreach my $role (@{$roles}) {
 6295:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6296:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6297:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6298:                             return 1 unless (($end && $end < $now) ||
 6299:                                              ($start && $start > $now));
 6300:                         }
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     } else {
 6306:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6307:         my $now = time;
 6308: 
 6309:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6310:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6311:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6312:                 return 1 unless ($tend && $tend < $now) 
 6313:                         or ($tstart && $tstart > $now);
 6314:             }
 6315:         }
 6316:     }
 6317:     return 0;
 6318: }
 6319: 
 6320: sub privileged_by_domain {
 6321:     my ($domains,$roles) = @_;
 6322:     my %privileged = ();
 6323:     my $cachetime = 60*60*24;
 6324:     my $now = time;
 6325:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6326:         return %privileged;
 6327:     }
 6328:     foreach my $dom (@{$domains}) {
 6329:         next if (ref($privileged{$dom}) eq 'HASH');
 6330:         my $needroles;
 6331:         foreach my $role (@{$roles}) {
 6332:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6333:             if (defined($cached)) {
 6334:                 if (ref($result) eq 'HASH') {
 6335:                     $privileged{$dom}{$role} = $result;
 6336:                 }
 6337:             } else {
 6338:                 $needroles = 1;
 6339:             }
 6340:         }
 6341:         if ($needroles) {
 6342:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6343:             $privileged{$dom} = {};
 6344:             foreach my $server (keys(%dompersonnel)) {
 6345:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6346:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6347:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6348:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6349:                         next if ($end && $end < $now);
 6350:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6351:                             $dompersonnel{$server}{$item};
 6352:                     }
 6353:                 }
 6354:             }
 6355:             if (ref($privileged{$dom}) eq 'HASH') {
 6356:                 foreach my $role (@{$roles}) {
 6357:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6358:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6359:                     } else {
 6360:                         my %hash = ();
 6361:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6362:                     }
 6363:                 }
 6364:             }
 6365:         }
 6366:     }
 6367:     return %privileged;
 6368: }
 6369: 
 6370: # -------------------------------------------------------- Get user privileges
 6371: 
 6372: sub rolesinit {
 6373:     my ($domain, $username) = @_;
 6374:     my %userroles = ('user.login.time' => time);
 6375:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6376: 
 6377:     # firstaccess and timerinterval are related to timed maps/resources. 
 6378:     # also, blocking can be triggered by an activating timer
 6379:     # it's saved in the user's %env.
 6380:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6381:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6382:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6383:         %timerintchk, %timerintenv);
 6384: 
 6385:     foreach my $key (keys(%firstaccess)) {
 6386:         my ($cid, $rest) = split(/\0/, $key);
 6387:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6388:     }
 6389: 
 6390:     foreach my $key (keys(%timerinterval)) {
 6391:         my ($cid,$rest) = split(/\0/,$key);
 6392:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6393:     }
 6394: 
 6395:     my %allroles=();
 6396:     my %allgroups=();
 6397: 
 6398:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6399:         my $role = $rolesdump{$area};
 6400:         $area =~ s/\_\w\w$//;
 6401: 
 6402:         my ($trole, $tend, $tstart, $group_privs);
 6403: 
 6404:         if ($role =~ /^cr/) {
 6405:         # Custom role, defined by a user 
 6406:         # e.g., user.role.cr/msu/smith/mynewrole
 6407:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6408:                 $trole = $1;
 6409:                 ($tend, $tstart) = split('_', $2);
 6410:             } else {
 6411:                 $trole = $role;
 6412:             }
 6413:         } elsif ($role =~ m|^gr/|) {
 6414:         # Role of member in a group, defined within a course/community
 6415:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6416:             ($trole, $tend, $tstart) = split(/_/, $role);
 6417:             next if $tstart eq '-1';
 6418:             ($trole, $group_privs) = split(/\//, $trole);
 6419:             $group_privs = &unescape($group_privs);
 6420:         } else {
 6421:         # Just a normal role, defined in roles.tab
 6422:             ($trole, $tend, $tstart) = split(/_/,$role);
 6423:         }
 6424: 
 6425:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6426:                  $username);
 6427:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6428: 
 6429:         # role expired or not available yet?
 6430:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6431:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6432: 
 6433:         next if $area eq '' or $trole eq '';
 6434: 
 6435:         my $spec = "$trole.$area";
 6436:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6437: 
 6438:         if ($trole =~ /^cr\//) {
 6439:         # Custom role, defined by a user
 6440:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6441:         } elsif ($trole eq 'gr') {
 6442:         # Role of a member in a group, defined within a course/community
 6443:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6444:             next;
 6445:         } else {
 6446:         # Normal role, defined in roles.tab
 6447:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6448:         }
 6449: 
 6450:         my $cid = $tdomain.'_'.$trest;
 6451:         unless ($firstaccchk{$cid}) {
 6452:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6453:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6454:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6455:                         $coursetimerstarts{$cid}{$item}; 
 6456:                 }
 6457:             }
 6458:             $firstaccchk{$cid} = 1;
 6459:         }
 6460:         unless ($timerintchk{$cid}) {
 6461:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6462:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6463:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6464:                        $coursetimerintervals{$cid}{$item};
 6465:                 }
 6466:             }
 6467:             $timerintchk{$cid} = 1;
 6468:         }
 6469:     }
 6470: 
 6471:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6472:                                                           \%allroles, \%allgroups);
 6473:     $env{'user.adv'} = $userroles{'user.adv'};
 6474:     $env{'user.rar'} = $userroles{'user.rar'};
 6475: 
 6476:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6477: }
 6478: 
 6479: sub set_arearole {
 6480:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6481:     unless ($nolog) {
 6482: # log the associated role with the area
 6483:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6484:     }
 6485:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6486: }
 6487: 
 6488: sub custom_roleprivs {
 6489:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6490:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6491:     my $homsvr = &homeserver($rauthor,$rdomain);
 6492:     if (&hostname($homsvr) ne '') {
 6493:         my ($rdummy,$roledef)=
 6494:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6495:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6496:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6497:             if (defined($syspriv)) {
 6498:                 if ($trest =~ /^$match_community$/) {
 6499:                     $syspriv =~ s/bre\&S//; 
 6500:                 }
 6501:                 $$allroles{'cm./'}.=':'.$syspriv;
 6502:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6503:             }
 6504:             if ($tdomain ne '') {
 6505:                 if (defined($dompriv)) {
 6506:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6507:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6508:                 }
 6509:                 if (($trest ne '') && (defined($coursepriv))) {
 6510:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6511:                         my $rolename = $1;
 6512:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6513:                     }
 6514:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6515:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6516:                 }
 6517:             }
 6518:         }
 6519:     }
 6520: }
 6521: 
 6522: sub course_adhocrole_privs {
 6523:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6524:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6525:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6526:         my (%currprivs,%storeprivs);
 6527:         foreach my $item (split(/:/,$coursepriv)) {
 6528:             my ($priv,$restrict) = split(/\&/,$item);
 6529:             $currprivs{$priv} = $restrict;
 6530:         }
 6531:         my (%possadd,%possremove,%full);
 6532:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6533:             my ($priv,$restrict)=split(/\&/,$item);
 6534:             $full{$priv} = $restrict;
 6535:         }
 6536:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6537:              next if ($item eq '');
 6538:              my ($rule,$rest) = split(/=/,$item);
 6539:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6540:              foreach my $priv (split(/:/,$rest)) {
 6541:                  if ($priv ne '') {
 6542:                      if ($rule eq 'off') {
 6543:                          $possremove{$priv} = 1;
 6544:                      } else {
 6545:                          $possadd{$priv} = 1;
 6546:                      }
 6547:                  }
 6548:              }
 6549:          }
 6550:          foreach my $priv (sort(keys(%full))) {
 6551:              if (exists($currprivs{$priv})) {
 6552:                  unless (exists($possremove{$priv})) {
 6553:                      $storeprivs{$priv} = $currprivs{$priv};
 6554:                  }
 6555:              } elsif (exists($possadd{$priv})) {
 6556:                  $storeprivs{$priv} = $full{$priv};
 6557:              }
 6558:          }
 6559:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6560:      }
 6561:      return $coursepriv;
 6562: }
 6563: 
 6564: sub group_roleprivs {
 6565:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6566:     my $access = 1;
 6567:     my $now = time;
 6568:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6569:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6570:     if ($access) {
 6571:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6572:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6573:     }
 6574: }
 6575: 
 6576: sub standard_roleprivs {
 6577:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6578:     if (defined($pr{$trole.':s'})) {
 6579:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6580:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6581:     }
 6582:     if ($tdomain ne '') {
 6583:         if (defined($pr{$trole.':d'})) {
 6584:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6585:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6586:         }
 6587:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6588:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6589:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6590:         }
 6591:     }
 6592: }
 6593: 
 6594: sub set_userprivs {
 6595:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6596:     my $author=0;
 6597:     my $adv=0;
 6598:     my $rar=0;
 6599:     my %grouproles = ();
 6600:     if (keys(%{$allgroups}) > 0) {
 6601:         my @groupkeys; 
 6602:         foreach my $role (keys(%{$allroles})) {
 6603:             push(@groupkeys,$role);
 6604:         }
 6605:         if (ref($groups_roles) eq 'HASH') {
 6606:             foreach my $key (keys(%{$groups_roles})) {
 6607:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6608:                     push(@groupkeys,$key);
 6609:                 }
 6610:             }
 6611:         }
 6612:         if (@groupkeys > 0) {
 6613:             foreach my $role (@groupkeys) {
 6614:                 my ($trole,$area,$sec,$extendedarea);
 6615:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6616:                     $trole = $1;
 6617:                     $area = $2;
 6618:                     $sec = $3;
 6619:                     $extendedarea = $area.$sec;
 6620:                     if (exists($$allgroups{$area})) {
 6621:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6622:                             my $spec = $trole.'.'.$extendedarea;
 6623:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6624:                                                 $$allgroups{$area}{$group};
 6625:                         }
 6626:                     }
 6627:                 }
 6628:             }
 6629:         }
 6630:     }
 6631:     foreach my $group (keys(%grouproles)) {
 6632:         $$allroles{$group} = $grouproles{$group};
 6633:     }
 6634:     foreach my $role (keys(%{$allroles})) {
 6635:         my %thesepriv;
 6636:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6637:         foreach my $item (split(/:/,$$allroles{$role})) {
 6638:             if ($item ne '') {
 6639:                 my ($privilege,$restrictions)=split(/&/,$item);
 6640:                 if ($restrictions eq '') {
 6641:                     $thesepriv{$privilege}='F';
 6642:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6643:                     $thesepriv{$privilege}.=$restrictions;
 6644:                 }
 6645:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6646:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6647:             }
 6648:         }
 6649:         my $thesestr='';
 6650:         foreach my $priv (sort(keys(%thesepriv))) {
 6651: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6652: 	}
 6653:         $userroles->{'user.priv.'.$role} = $thesestr;
 6654:     }
 6655:     return ($author,$adv,$rar);
 6656: }
 6657: 
 6658: sub role_status {
 6659:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6660:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6661:         my ($one,$two) = split(m{\./},$rolekey,2);
 6662:         (undef,undef,$$role) = split(/\./,$one,3);
 6663:         unless (!defined($$role) || $$role eq '') {
 6664:             $$where = '/'.$two;
 6665:             $$trolecode=$$role.'.'.$$where;
 6666:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6667:             $$tstatus='is';
 6668:             if ($$tstart && $$tstart>$update) {
 6669:                 $$tstatus='future';
 6670:                 if ($$tstart<$now) {
 6671:                     if ($$tstart && $$tstart>$refresh) {
 6672:                         if (($$where ne '') && ($$role ne '')) {
 6673:                             my (%allroles,%allgroups,$group_privs,
 6674:                                 %groups_roles,@rolecodes);
 6675:                             my %userroles = (
 6676:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6677:                             );
 6678:                             @rolecodes = ('cm'); 
 6679:                             my $spec=$$role.'.'.$$where;
 6680:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6681:                             if ($$role =~ /^cr\//) {
 6682:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6683:                                 push(@rolecodes,'cr');
 6684:                             } elsif ($$role eq 'gr') {
 6685:                                 push(@rolecodes,$$role);
 6686:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6687:                                                     $env{'user.name'});
 6688:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6689:                                 (undef,my $group_privs) = split(/\//,$trole);
 6690:                                 $group_privs = &unescape($group_privs);
 6691:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6692:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6693:                                 &get_groups_roles($tdomain,$trest,
 6694:                                                   \%course_roles,\@rolecodes,
 6695:                                                   \%groups_roles);
 6696:                             } else {
 6697:                                 push(@rolecodes,$$role);
 6698:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6699:                             }
 6700:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6701:                                                                    \%groups_roles);
 6702:                             &appenv(\%userroles,\@rolecodes);
 6703:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6704:                         }
 6705:                     }
 6706:                     $$tstatus = 'is';
 6707:                 }
 6708:             }
 6709:             if ($$tend) {
 6710:                 if ($$tend<$update) {
 6711:                     $$tstatus='expired';
 6712:                 } elsif ($$tend<$now) {
 6713:                     $$tstatus='will_not';
 6714:                 }
 6715:             }
 6716:         }
 6717:     }
 6718: }
 6719: 
 6720: sub get_groups_roles {
 6721:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6722:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6723:                   (ref($rolecodes) eq 'ARRAY') && 
 6724:                   (ref($groups_roles) eq 'HASH')); 
 6725:     if (keys(%{$cdom_courseroles}) > 0) {
 6726:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6727:         if ($cdom ne '' && $cnum ne '') {
 6728:             foreach my $key (keys(%{$cdom_courseroles})) {
 6729:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6730:                     my $crsrole = $1;
 6731:                     my $crssec = $2;
 6732:                     if ($crsrole =~ /^cr/) {
 6733:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6734:                             push(@{$rolecodes},'cr');
 6735:                         }
 6736:                     } else {
 6737:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6738:                             push(@{$rolecodes},$crsrole);
 6739:                         }
 6740:                     }
 6741:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6742:                     if ($crssec ne '') {
 6743:                         $rolekey .= "/$crssec";
 6744:                     }
 6745:                     $rolekey .= './';
 6746:                     $groups_roles->{$rolekey} = $rolecodes;
 6747:                 }
 6748:             }
 6749:         }
 6750:     }
 6751:     return;
 6752: }
 6753: 
 6754: sub delete_env_groupprivs {
 6755:     my ($where,$courseroles,$possroles) = @_;
 6756:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6757:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6758:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6759:         %{$courseroles->{$udom}} =
 6760:             &get_my_roles('','','userroles',['active'],
 6761:                           $possroles,[$udom],1);
 6762:     }
 6763:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6764:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6765:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6766:             my $area = '/'.$cdom.'/'.$cnum;
 6767:             my $privkey = "user.priv.$crsrole.$area";
 6768:             if ($crssec ne '') {
 6769:                 $privkey .= '/'.$crssec;
 6770:             }
 6771:             $privkey .= ".$area/$group";
 6772:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6773:         }
 6774:     }
 6775:     return;
 6776: }
 6777: 
 6778: sub check_adhoc_privs {
 6779:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6780:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6781:     if ($sec) {
 6782:         $cckey .= '/'.$sec;
 6783:     } 
 6784:     my $setprivs;
 6785:     if ($env{$cckey}) {
 6786:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6787:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6788:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6789:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6790:             $setprivs = 1;
 6791:         }
 6792:     } else {
 6793:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6794:         $setprivs = 1;
 6795:     }
 6796:     return $setprivs;
 6797: }
 6798: 
 6799: sub set_adhoc_privileges {
 6800: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6801:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6802:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6803:     if ($sec ne '') {
 6804:         $area .= '/'.$sec;
 6805:     }
 6806:     my $spec = $role.'.'.$area;
 6807:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6808:                                   $env{'user.name'},1);
 6809:     my %rolehash = ();
 6810:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6811:         my $rolename = $1;
 6812:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6813:         my %domdef = &get_domain_defaults($dcdom);
 6814:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6815:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6816:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6817:             }
 6818:         }
 6819:     } else {
 6820:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6821:     }
 6822:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6823:     &appenv(\%userroles,[$role,'cm']);
 6824:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6825:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6826:             ($caller eq 'tiny')) {
 6827:         &appenv( {'request.role'        => $spec,
 6828:                   'request.role.domain' => $dcdom,
 6829:                   'request.course.sec'  => $sec,
 6830:                  }
 6831:                );
 6832:         my $tadv=0;
 6833:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6834:         &appenv({'request.role.adv'    => $tadv});
 6835:     }
 6836: }
 6837: 
 6838: # --------------------------------------------------------------- get interface
 6839: 
 6840: sub get {
 6841:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6842:    my $items='';
 6843:    foreach my $item (@$storearr) {
 6844:        $items.=&escape($item).'&';
 6845:    }
 6846:    $items=~s/\&$//;
 6847:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6848:    if (!$uname) { $uname=$env{'user.name'}; }
 6849:    my $uhome=&homeserver($uname,$udomain);
 6850: 
 6851:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6852:    my @pairs=split(/\&/,$rep);
 6853:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6854:      return @pairs;
 6855:    }
 6856:    my %returnhash=();
 6857:    my $i=0;
 6858:    foreach my $item (@$storearr) {
 6859:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6860:       $i++;
 6861:    }
 6862:    return %returnhash;
 6863: }
 6864: 
 6865: # --------------------------------------------------------------- del interface
 6866: 
 6867: sub del {
 6868:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6869:    my $items='';
 6870:    foreach my $item (@$storearr) {
 6871:        $items.=&escape($item).'&';
 6872:    }
 6873: 
 6874:    $items=~s/\&$//;
 6875:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6876:    if (!$uname) { $uname=$env{'user.name'}; }
 6877:    my $uhome=&homeserver($uname,$udomain);
 6878:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6879: }
 6880: 
 6881: # -------------------------------------------------------------- dump interface
 6882: 
 6883: sub unserialize {
 6884:     my ($rep, $escapedkeys) = @_;
 6885: 
 6886:     return {} if $rep =~ /^error/;
 6887: 
 6888:     my %returnhash=();
 6889: 	foreach my $item (split(/\&/,$rep)) {
 6890: 	    my ($key, $value) = split(/=/, $item, 2);
 6891: 	    $key = unescape($key) unless $escapedkeys;
 6892: 	    next if $key =~ /^error: 2 /;
 6893: 	    $returnhash{$key} = &thaw_unescape($value);
 6894: 	}
 6895:     #return %returnhash;
 6896:     return \%returnhash;
 6897: }        
 6898: 
 6899: # see Lond::dump_with_regexp
 6900: # if $escapedkeys hash keys won't get unescaped.
 6901: sub dump {
 6902:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6904:     if (!$uname) { $uname=$env{'user.name'}; }
 6905:     my $uhome=&homeserver($uname,$udomain);
 6906: 
 6907:     if ($regexp) {
 6908:         $regexp=&escape($regexp);
 6909:     } else {
 6910:         $regexp='.';
 6911:     }
 6912:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6913:         # user is hosted on this machine
 6914:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6915:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6916:         return %{unserialize($reply, $escapedkeys)};
 6917:     }
 6918:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6919:     my @pairs=split(/\&/,$rep);
 6920:     my %returnhash=();
 6921:     if (!($rep =~ /^error/ )) {
 6922: 	foreach my $item (@pairs) {
 6923: 	    my ($key,$value)=split(/=/,$item,2);
 6924:         $key = unescape($key) unless $escapedkeys;
 6925:         #$key = &unescape($key);
 6926: 	    next if ($key =~ /^error: 2 /);
 6927: 	    $returnhash{$key}=&thaw_unescape($value);
 6928: 	}
 6929:     }
 6930:     return %returnhash;
 6931: }
 6932: 
 6933: 
 6934: # --------------------------------------------------------- dumpstore interface
 6935: 
 6936: sub dumpstore {
 6937:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6938:    # same as dump but keys must be escaped. They may contain colon separated
 6939:    # lists of values that may themself contain colons (e.g. symbs).
 6940:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6941: }
 6942: 
 6943: # -------------------------------------------------------------- keys interface
 6944: 
 6945: sub getkeys {
 6946:    my ($namespace,$udomain,$uname)=@_;
 6947:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6948:    if (!$uname) { $uname=$env{'user.name'}; }
 6949:    my $uhome=&homeserver($uname,$udomain);
 6950:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6951:    my @keyarray=();
 6952:    foreach my $key (split(/\&/,$rep)) {
 6953:       next if ($key =~ /^error: 2 /);
 6954:       push(@keyarray,&unescape($key));
 6955:    }
 6956:    return @keyarray;
 6957: }
 6958: 
 6959: # --------------------------------------------------------------- currentdump
 6960: sub currentdump {
 6961:    my ($courseid,$sdom,$sname)=@_;
 6962:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6963:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6964:    $sname    = $env{'user.name'}         if (! defined($sname));
 6965:    my $uhome = &homeserver($sname,$sdom);
 6966:    my $rep;
 6967: 
 6968:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6969:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6970:                    $courseid)));
 6971:    } else {
 6972:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6973:    }
 6974: 
 6975:    return if ($rep =~ /^(error:|no_such_host)/);
 6976:    #
 6977:    my %returnhash=();
 6978:    #
 6979:    if ($rep eq 'unknown_cmd') {
 6980:        # an old lond will not know currentdump
 6981:        # Do a dump and make it look like a currentdump
 6982:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6983:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6984:        my %hash = @tmp;
 6985:        @tmp=();
 6986:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6987:    } else {
 6988:        my @pairs=split(/\&/,$rep);
 6989:        foreach my $pair (@pairs) {
 6990:            my ($key,$value)=split(/=/,$pair,2);
 6991:            my ($symb,$param) = split(/:/,$key);
 6992:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6993:                                                         &thaw_unescape($value);
 6994:        }
 6995:    }
 6996:    return %returnhash;
 6997: }
 6998: 
 6999: sub convert_dump_to_currentdump{
 7000:     my %hash = %{shift()};
 7001:     my %returnhash;
 7002:     # Code ripped from lond, essentially.  The only difference
 7003:     # here is the unescaping done by lonnet::dump().  Conceivably
 7004:     # we might run in to problems with parameter names =~ /^v\./
 7005:     while (my ($key,$value) = each(%hash)) {
 7006:         my ($v,$symb,$param) = split(/:/,$key);
 7007: 	$symb  = &unescape($symb);
 7008: 	$param = &unescape($param);
 7009:         next if ($v eq 'version' || $symb eq 'keys');
 7010:         next if (exists($returnhash{$symb}) &&
 7011:                  exists($returnhash{$symb}->{$param}) &&
 7012:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7013:         $returnhash{$symb}->{$param}=$value;
 7014:         $returnhash{$symb}->{'v.'.$param}=$v;
 7015:     }
 7016:     #
 7017:     # Remove all of the keys in the hashes which keep track of
 7018:     # the version of the parameter.
 7019:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7020:         # use a foreach because we are going to delete from the hash.
 7021:         foreach my $key (keys(%$param_hash)) {
 7022:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7023:         }
 7024:     }
 7025:     return \%returnhash;
 7026: }
 7027: 
 7028: # ------------------------------------------------------ critical inc interface
 7029: 
 7030: sub cinc {
 7031:     return &inc(@_,'critical');
 7032: }
 7033: 
 7034: # --------------------------------------------------------------- inc interface
 7035: 
 7036: sub inc {
 7037:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7038:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7039:     if (!$uname) { $uname=$env{'user.name'}; }
 7040:     my $uhome=&homeserver($uname,$udomain);
 7041:     my $items='';
 7042:     if (! ref($store)) {
 7043:         # got a single value, so use that instead
 7044:         $items = &escape($store).'=&';
 7045:     } elsif (ref($store) eq 'SCALAR') {
 7046:         $items = &escape($$store).'=&';        
 7047:     } elsif (ref($store) eq 'ARRAY') {
 7048:         $items = join('=&',map {&escape($_);} @{$store});
 7049:     } elsif (ref($store) eq 'HASH') {
 7050:         while (my($key,$value) = each(%{$store})) {
 7051:             $items.= &escape($key).'='.&escape($value).'&';
 7052:         }
 7053:     }
 7054:     $items=~s/\&$//;
 7055:     if ($critical) {
 7056: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7057:     } else {
 7058: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7059:     }
 7060: }
 7061: 
 7062: # --------------------------------------------------------------- put interface
 7063: 
 7064: sub put {
 7065:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7067:    if (!$uname) { $uname=$env{'user.name'}; }
 7068:    my $uhome=&homeserver($uname,$udomain);
 7069:    my $items='';
 7070:    foreach my $item (keys(%$storehash)) {
 7071:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7072:    }
 7073:    $items=~s/\&$//;
 7074:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7075: }
 7076: 
 7077: # ------------------------------------------------------------ newput interface
 7078: 
 7079: sub newput {
 7080:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7081:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7082:    if (!$uname) { $uname=$env{'user.name'}; }
 7083:    my $uhome=&homeserver($uname,$udomain);
 7084:    my $items='';
 7085:    foreach my $key (keys(%$storehash)) {
 7086:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7087:    }
 7088:    $items=~s/\&$//;
 7089:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7090: }
 7091: 
 7092: # ---------------------------------------------------------  putstore interface
 7093: 
 7094: sub putstore {
 7095:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7097:    if (!$uname) { $uname=$env{'user.name'}; }
 7098:    my $uhome=&homeserver($uname,$udomain);
 7099:    my $items='';
 7100:    foreach my $key (keys(%$storehash)) {
 7101:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7102:    }
 7103:    $items=~s/\&$//;
 7104:    my $esc_symb=&escape($symb);
 7105:    my $esc_v=&escape($version);
 7106:    my $reply =
 7107:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7108: 	      $uhome);
 7109:    if (($tolog) && ($reply eq 'ok')) {
 7110:        my $namevalue='';
 7111:        foreach my $key (keys(%{$storehash})) {
 7112:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7113:        }
 7114:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7115:                      '&host='.&escape($perlvar{'lonHostID'}).
 7116:                      '&version='.$esc_v.
 7117:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7118:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7119:    }
 7120:    if ($reply eq 'unknown_cmd') {
 7121:        # gfall back to way things use to be done
 7122:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7123: 			    $uname);
 7124:    }
 7125:    return $reply;
 7126: }
 7127: 
 7128: sub old_putstore {
 7129:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7130:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7131:     if (!$uname) { $uname=$env{'user.name'}; }
 7132:     my $uhome=&homeserver($uname,$udomain);
 7133:     my %newstorehash;
 7134:     foreach my $item (keys(%$storehash)) {
 7135: 	my $key = $version.':'.&escape($symb).':'.$item;
 7136: 	$newstorehash{$key} = $storehash->{$item};
 7137:     }
 7138:     my $items='';
 7139:     my %allitems = ();
 7140:     foreach my $item (keys(%newstorehash)) {
 7141: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7142: 	    my $key = $1.':keys:'.$2;
 7143: 	    $allitems{$key} .= $3.':';
 7144: 	}
 7145: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7146:     }
 7147:     foreach my $item (keys(%allitems)) {
 7148: 	$allitems{$item} =~ s/\:$//;
 7149: 	$items.= $item.'='.$allitems{$item}.'&';
 7150:     }
 7151:     $items=~s/\&$//;
 7152:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7153: }
 7154: 
 7155: # ------------------------------------------------------ critical put interface
 7156: 
 7157: sub cput {
 7158:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7160:    if (!$uname) { $uname=$env{'user.name'}; }
 7161:    my $uhome=&homeserver($uname,$udomain);
 7162:    my $items='';
 7163:    foreach my $item (keys(%$storehash)) {
 7164:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7165:    }
 7166:    $items=~s/\&$//;
 7167:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7168: }
 7169: 
 7170: # -------------------------------------------------------------- eget interface
 7171: 
 7172: sub eget {
 7173:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7174:    my $items='';
 7175:    foreach my $item (@$storearr) {
 7176:        $items.=&escape($item).'&';
 7177:    }
 7178:    $items=~s/\&$//;
 7179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7180:    if (!$uname) { $uname=$env{'user.name'}; }
 7181:    my $uhome=&homeserver($uname,$udomain);
 7182:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7183:    my @pairs=split(/\&/,$rep);
 7184:    my %returnhash=();
 7185:    my $i=0;
 7186:    foreach my $item (@$storearr) {
 7187:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7188:       $i++;
 7189:    }
 7190:    return %returnhash;
 7191: }
 7192: 
 7193: # ------------------------------------------------------------ tmpput interface
 7194: sub tmpput {
 7195:     my ($storehash,$server,$context)=@_;
 7196:     my $items='';
 7197:     foreach my $item (keys(%$storehash)) {
 7198: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7199:     }
 7200:     $items=~s/\&$//;
 7201:     if (defined($context)) {
 7202:         $items .= ':'.&escape($context);
 7203:     }
 7204:     return &reply("tmpput:$items",$server);
 7205: }
 7206: 
 7207: # ------------------------------------------------------------ tmpget interface
 7208: sub tmpget {
 7209:     my ($token,$server)=@_;
 7210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7211:     my $rep=&reply("tmpget:$token",$server);
 7212:     my %returnhash;
 7213:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7214:         return %returnhash;
 7215:     }
 7216:     foreach my $item (split(/\&/,$rep)) {
 7217: 	my ($key,$value)=split(/=/,$item);
 7218: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7219:     }
 7220:     return %returnhash;
 7221: }
 7222: 
 7223: # ------------------------------------------------------------ tmpdel interface
 7224: sub tmpdel {
 7225:     my ($token,$server)=@_;
 7226:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7227:     return &reply("tmpdel:$token",$server);
 7228: }
 7229: 
 7230: # ------------------------------------------------------------ get_timebased_id 
 7231: 
 7232: sub get_timebased_id {
 7233:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7234:         $maxtries) = @_;
 7235:     my ($newid,$error,$dellock);
 7236:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7237:         return ('','ok','invalid call to get suffix');
 7238:     }
 7239: 
 7240: # set defaults for any optional args for which values were not supplied
 7241:     if ($who eq '') {
 7242:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7243:     }
 7244:     if (!$locktries) {
 7245:         $locktries = 3;
 7246:     }
 7247:     if (!$maxtries) {
 7248:         $maxtries = 10;
 7249:     }
 7250:     
 7251:     if (($cdom eq '') || ($cnum eq '')) {
 7252:         if ($env{'request.course.id'}) {
 7253:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7254:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7255:         }
 7256:         if (($cdom eq '') || ($cnum eq '')) {
 7257:             return ('','ok','call to get suffix not in course context');
 7258:         }
 7259:     }
 7260: 
 7261: # construct locking item
 7262:     my $lockhash = {
 7263:                       $prefix."\0".'locked_'.$keyid => $who,
 7264:                    };
 7265:     my $tries = 0;
 7266: 
 7267: # attempt to get lock on nohist_$namespace file
 7268:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7269:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7270:         $tries ++;
 7271:         sleep 1;
 7272:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7273:     }
 7274: 
 7275: # attempt to get unique identifier, based on current timestamp
 7276:     if ($gotlock eq 'ok') {
 7277:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7278:         my $id = time;
 7279:         $newid = $id;
 7280:         if ($idtype eq 'addcode') {
 7281:             $newid .= &sixnum_code();
 7282:         }
 7283:         my $idtries = 0;
 7284:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7285:             if ($idtype eq 'concat') {
 7286:                 $newid = $id.$idtries;
 7287:             } elsif ($idtype eq 'addcode') {
 7288:                 $newid = $newid.&sixnum_code();
 7289:             } else {
 7290:                 $newid ++;
 7291:             }
 7292:             $idtries ++;
 7293:         }
 7294:         if (!exists($inuse{$prefix."\0".$newid})) {
 7295:             my %new_item =  (
 7296:                               $prefix."\0".$newid => $who,
 7297:                             );
 7298:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7299:                                                  $cdom,$cnum);
 7300:             if ($putresult ne 'ok') {
 7301:                 undef($newid);
 7302:                 $error = 'error saving new item: '.$putresult;
 7303:             }
 7304:         } else {
 7305:              undef($newid);
 7306:              $error = ('error: no unique suffix available for the new item ');
 7307:         }
 7308: #  remove lock
 7309:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7310:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7311:     } else {
 7312:         $error = "error: could not obtain lockfile\n";
 7313:         $dellock = 'ok';
 7314:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7315:             $dellock = 'nolock';
 7316:         }
 7317:     }
 7318:     return ($newid,$dellock,$error);
 7319: }
 7320: 
 7321: sub sixnum_code {
 7322:     my $code;
 7323:     for (0..6) {
 7324:         $code .= int( rand(9) );
 7325:     }
 7326:     return $code;
 7327: }
 7328: 
 7329: # -------------------------------------------------- portfolio access checking
 7330: 
 7331: sub portfolio_access {
 7332:     my ($requrl,$clientip) = @_;
 7333:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7334:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7335:     if ($result) {
 7336:         my %setters;
 7337:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7338:             my ($startblock,$endblock) =
 7339:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7340:             if ($startblock && $endblock) {
 7341:                 return 'B';
 7342:             }
 7343:         } else {
 7344:             my ($startblock,$endblock) =
 7345:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7346:             if ($startblock && $endblock) {
 7347:                 return 'B';
 7348:             }
 7349:         }
 7350:     }
 7351:     if ($result eq 'ok') {
 7352:        return 'F';
 7353:     } elsif ($result =~ /^[^:]+:guest_/) {
 7354:        return 'A';
 7355:     }
 7356:     return '';
 7357: }
 7358: 
 7359: sub get_portfolio_access {
 7360:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7361: 
 7362:     if (!ref($access_hash)) {
 7363: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7364: 	my %access_controls = &get_access_controls($current_perms,$group,
 7365: 						   $file_name);
 7366: 	$access_hash = $access_controls{$file_name};
 7367:     }
 7368: 
 7369:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7370:     my $now = time;
 7371:     if (ref($access_hash) eq 'HASH') {
 7372:         foreach my $key (keys(%{$access_hash})) {
 7373:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7374:             if ($start > $now) {
 7375:                 next;
 7376:             }
 7377:             if ($end && $end<$now) {
 7378:                 next;
 7379:             }
 7380:             if ($scope eq 'public') {
 7381:                 $public = $key;
 7382:                 last;
 7383:             } elsif ($scope eq 'guest') {
 7384:                 $guest = $key;
 7385:             } elsif ($scope eq 'domains') {
 7386:                 push(@domains,$key);
 7387:             } elsif ($scope eq 'users') {
 7388:                 push(@users,$key);
 7389:             } elsif ($scope eq 'course') {
 7390:                 push(@courses,$key);
 7391:             } elsif ($scope eq 'group') {
 7392:                 push(@groups,$key);
 7393:             } elsif ($scope eq 'ip') {
 7394:                 push(@ips,$key);
 7395:             }
 7396:         }
 7397:         if ($public) {
 7398:             return 'ok';
 7399:         } elsif (@ips > 0) {
 7400:             my $allowed;
 7401:             foreach my $ipkey (@ips) {
 7402:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7403:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7404:                         $allowed = 1;
 7405:                         last; 
 7406:                     }
 7407:                 }
 7408:             }
 7409:             if ($allowed) {
 7410:                 return 'ok';
 7411:             }
 7412:         }
 7413:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7414:             if ($guest) {
 7415:                 return $guest;
 7416:             }
 7417:         } else {
 7418:             if (@domains > 0) {
 7419:                 foreach my $domkey (@domains) {
 7420:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7421:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7422:                             return 'ok';
 7423:                         }
 7424:                     }
 7425:                 }
 7426:             }
 7427:             if (@users > 0) {
 7428:                 foreach my $userkey (@users) {
 7429:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7430:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7431:                             if (ref($item) eq 'HASH') {
 7432:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7433:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7434:                                     return 'ok';
 7435:                                 }
 7436:                             }
 7437:                         }
 7438:                     } 
 7439:                 }
 7440:             }
 7441:             my %roleshash;
 7442:             my @courses_and_groups = @courses;
 7443:             push(@courses_and_groups,@groups); 
 7444:             if (@courses_and_groups > 0) {
 7445:                 my (%allgroups,%allroles); 
 7446:                 my ($start,$end,$role,$sec,$group);
 7447:                 foreach my $envkey (%env) {
 7448:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7449:                         my $cid = $2.'_'.$3; 
 7450:                         if ($1 eq 'gr') {
 7451:                             $group = $4;
 7452:                             $allgroups{$cid}{$group} = $env{$envkey};
 7453:                         } else {
 7454:                             if ($4 eq '') {
 7455:                                 $sec = 'none';
 7456:                             } else {
 7457:                                 $sec = $4;
 7458:                             }
 7459:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7460:                         }
 7461:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7462:                         my $cid = $2.'_'.$3;
 7463:                         if ($4 eq '') {
 7464:                             $sec = 'none';
 7465:                         } else {
 7466:                             $sec = $4;
 7467:                         }
 7468:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7469:                     }
 7470:                 }
 7471:                 if (keys(%allroles) == 0) {
 7472:                     return;
 7473:                 }
 7474:                 foreach my $key (@courses_and_groups) {
 7475:                     my %content = %{$$access_hash{$key}};
 7476:                     my $cnum = $content{'number'};
 7477:                     my $cdom = $content{'domain'};
 7478:                     my $cid = $cdom.'_'.$cnum;
 7479:                     if (!exists($allroles{$cid})) {
 7480:                         next;
 7481:                     }    
 7482:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7483:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7484:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7485:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7486:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7487:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7488:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7489:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7490:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7491:                                         if (grep/^all$/,@sections) {
 7492:                                             return 'ok';
 7493:                                         } else {
 7494:                                             if (grep/^$sec$/,@sections) {
 7495:                                                 return 'ok';
 7496:                                             }
 7497:                                         }
 7498:                                     }
 7499:                                 }
 7500:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7501:                                     if (grep/^none$/,@groups) {
 7502:                                         return 'ok';
 7503:                                     }
 7504:                                 } else {
 7505:                                     if (grep/^all$/,@groups) {
 7506:                                         return 'ok';
 7507:                                     } 
 7508:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7509:                                         if (grep/^$group$/,@groups) {
 7510:                                             return 'ok';
 7511:                                         }
 7512:                                     }
 7513:                                 } 
 7514:                             }
 7515:                         }
 7516:                     }
 7517:                 }
 7518:             }
 7519:             if ($guest) {
 7520:                 return $guest;
 7521:             }
 7522:         }
 7523:     }
 7524:     return;
 7525: }
 7526: 
 7527: sub course_group_datechecker {
 7528:     my ($dates,$now,$status) = @_;
 7529:     my ($start,$end) = split(/\./,$dates);
 7530:     if (!$start && !$end) {
 7531:         return 'ok';
 7532:     }
 7533:     if (grep/^active$/,@{$status}) {
 7534:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7535:             return 'ok';
 7536:         }
 7537:     }
 7538:     if (grep/^previous$/,@{$status}) {
 7539:         if ($end > $now ) {
 7540:             return 'ok';
 7541:         }
 7542:     }
 7543:     if (grep/^future$/,@{$status}) {
 7544:         if ($start > $now) {
 7545:             return 'ok';
 7546:         }
 7547:     }
 7548:     return; 
 7549: }
 7550: 
 7551: sub parse_portfolio_url {
 7552:     my ($url) = @_;
 7553: 
 7554:     my ($type,$udom,$unum,$group,$file_name);
 7555:     
 7556:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7557: 	$type = 1;
 7558:         $udom = $1;
 7559:         $unum = $2;
 7560:         $file_name = $3;
 7561:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7562: 	$type = 2;
 7563:         $udom = $1;
 7564:         $unum = $2;
 7565:         $group = $3;
 7566:         $file_name = $3.'/'.$4;
 7567:     }
 7568:     if (wantarray) {
 7569: 	return ($type,$udom,$unum,$file_name,$group);
 7570:     }
 7571:     return $type;
 7572: }
 7573: 
 7574: sub is_portfolio_url {
 7575:     my ($url) = @_;
 7576:     return scalar(&parse_portfolio_url($url));
 7577: }
 7578: 
 7579: sub is_portfolio_file {
 7580:     my ($file) = @_;
 7581:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7582:         return 1;
 7583:     }
 7584:     return;
 7585: }
 7586: 
 7587: sub usertools_access {
 7588:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7589:     my ($access,%tools);
 7590:     if ($context eq '') {
 7591:         $context = 'tools';
 7592:     }
 7593:     if ($context eq 'requestcourses') {
 7594:         %tools = (
 7595:                       official   => 1,
 7596:                       unofficial => 1,
 7597:                       community  => 1,
 7598:                       textbook   => 1,
 7599:                       placement  => 1,
 7600:                       lti        => 1,
 7601:                  );
 7602:     } elsif ($context eq 'requestauthor') {
 7603:         %tools = (
 7604:                       requestauthor => 1,
 7605:                  );
 7606:     } else {
 7607:         %tools = (
 7608:                       aboutme   => 1,
 7609:                       blog      => 1,
 7610:                       webdav    => 1,
 7611:                       portfolio => 1,
 7612:                  );
 7613:     }
 7614:     return if (!defined($tools{$tool}));
 7615: 
 7616:     if (($udom eq '') || ($uname eq '')) {
 7617:         $udom = $env{'user.domain'};
 7618:         $uname = $env{'user.name'};
 7619:     }
 7620: 
 7621:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7622:         if ($action ne 'reload') {
 7623:             if ($context eq 'requestcourses') {
 7624:                 return $env{'environment.canrequest.'.$tool};
 7625:             } elsif ($context eq 'requestauthor') {
 7626:                 return $env{'environment.canrequest.author'};
 7627:             } else {
 7628:                 return $env{'environment.availabletools.'.$tool};
 7629:             }
 7630:         }
 7631:     }
 7632: 
 7633:     my ($toolstatus,$inststatus,$envkey);
 7634:     if ($context eq 'requestauthor') {
 7635:         $envkey = $context; 
 7636:     } else {
 7637:         $envkey = $context.'.'.$tool;
 7638:     }
 7639: 
 7640:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7641:          ($action ne 'reload')) {
 7642:         $toolstatus = $env{'environment.'.$envkey};
 7643:         $inststatus = $env{'environment.inststatus'};
 7644:     } else {
 7645:         if (ref($userenvref) eq 'HASH') {
 7646:             $toolstatus = $userenvref->{$envkey};
 7647:             $inststatus = $userenvref->{'inststatus'};
 7648:         } else {
 7649:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7650:             $toolstatus = $userenv{$envkey};
 7651:             $inststatus = $userenv{'inststatus'};
 7652:         }
 7653:     }
 7654: 
 7655:     if ($toolstatus ne '') {
 7656:         if ($toolstatus) {
 7657:             $access = 1;
 7658:         } else {
 7659:             $access = 0;
 7660:         }
 7661:         return $access;
 7662:     }
 7663: 
 7664:     my ($is_adv,%domdef);
 7665:     if (ref($is_advref) eq 'HASH') {
 7666:         $is_adv = $is_advref->{'is_adv'};
 7667:     } else {
 7668:         $is_adv = &is_advanced_user($udom,$uname);
 7669:     }
 7670:     if (ref($domdefref) eq 'HASH') {
 7671:         %domdef = %{$domdefref};
 7672:     } else {
 7673:         %domdef = &get_domain_defaults($udom);
 7674:     }
 7675:     if (ref($domdef{$tool}) eq 'HASH') {
 7676:         if ($is_adv) {
 7677:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7678:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7679:                     $access = 1;
 7680:                 } else {
 7681:                     $access = 0;
 7682:                 }
 7683:                 return $access;
 7684:             }
 7685:         }
 7686:         if ($inststatus ne '') {
 7687:             my ($hasaccess,$hasnoaccess);
 7688:             foreach my $affiliation (split(/:/,$inststatus)) {
 7689:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7690:                     if ($domdef{$tool}{$affiliation}) {
 7691:                         $hasaccess = 1;
 7692:                     } else {
 7693:                         $hasnoaccess = 1;
 7694:                     }
 7695:                 }
 7696:             }
 7697:             if ($hasaccess || $hasnoaccess) {
 7698:                 if ($hasaccess) {
 7699:                     $access = 1;
 7700:                 } elsif ($hasnoaccess) {
 7701:                     $access = 0; 
 7702:                 }
 7703:                 return $access;
 7704:             }
 7705:         } else {
 7706:             if ($domdef{$tool}{'default'} ne '') {
 7707:                 if ($domdef{$tool}{'default'}) {
 7708:                     $access = 1;
 7709:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7710:                     $access = 0;
 7711:                 }
 7712:                 return $access;
 7713:             }
 7714:         }
 7715:     } else {
 7716:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7717:             $access = 1;
 7718:         } else {
 7719:             $access = 0;
 7720:         }
 7721:         return $access;
 7722:     }
 7723: }
 7724: 
 7725: sub is_course_owner {
 7726:     my ($cdom,$cnum,$udom,$uname) = @_;
 7727:     if (($udom eq '') || ($uname eq '')) {
 7728:         $udom = $env{'user.domain'};
 7729:         $uname = $env{'user.name'};
 7730:     }
 7731:     unless (($udom eq '') || ($uname eq '')) {
 7732:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7733:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7734:                 return 1;
 7735:             } else {
 7736:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7737:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7738:                     return 1;
 7739:                 }
 7740:             }
 7741:         }
 7742:     }
 7743:     return;
 7744: }
 7745: 
 7746: sub is_advanced_user {
 7747:     my ($udom,$uname) = @_;
 7748:     if ($udom ne '' && $uname ne '') {
 7749:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7750:             if (wantarray) {
 7751:                 return ($env{'user.adv'},$env{'user.author'});
 7752:             } else {
 7753:                 return $env{'user.adv'};
 7754:             }
 7755:         }
 7756:     }
 7757:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7758:     my %allroles;
 7759:     my ($is_adv,$is_author);
 7760:     foreach my $role (keys(%roleshash)) {
 7761:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7762:         my $area = '/'.$tdomain.'/'.$trest;
 7763:         if ($sec ne '') {
 7764:             $area .= '/'.$sec;
 7765:         }
 7766:         if (($area ne '') && ($trole ne '')) {
 7767:             my $spec=$trole.'.'.$area;
 7768:             if ($trole =~ /^cr\//) {
 7769:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7770:             } elsif ($trole ne 'gr') {
 7771:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7772:             }
 7773:             if ($trole eq 'au') {
 7774:                 $is_author = 1;
 7775:             }
 7776:         }
 7777:     }
 7778:     foreach my $role (keys(%allroles)) {
 7779:         last if ($is_adv);
 7780:         foreach my $item (split(/:/,$allroles{$role})) {
 7781:             if ($item ne '') {
 7782:                 my ($privilege,$restrictions)=split(/&/,$item);
 7783:                 if ($privilege eq 'adv') {
 7784:                     $is_adv = 1;
 7785:                     last;
 7786:                 }
 7787:             }
 7788:         }
 7789:     }
 7790:     if (wantarray) {
 7791:         return ($is_adv,$is_author);
 7792:     }
 7793:     return $is_adv;
 7794: }
 7795: 
 7796: sub check_can_request {
 7797:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7798:     my $canreq = 0;
 7799:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7800:         $uname = $env{'user.name'};
 7801:         $udom = $env{'user.domain'};
 7802:     }
 7803:     my ($types,$typename) = &Apache::loncommon::course_types();
 7804:     my @options = ('approval','validate','autolimit');
 7805:     my $optregex = join('|',@options);
 7806:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7807:         foreach my $type (@{$types}) {
 7808:             if (&usertools_access($uname,$udom,$type,undef,
 7809:                                   'requestcourses')) {
 7810:                 $canreq ++;
 7811:                 if (ref($request_domains) eq 'HASH') {
 7812:                     push(@{$request_domains->{$type}},$udom);
 7813:                 }
 7814:                 if ($dom eq $udom) {
 7815:                     $can_request->{$type} = 1;
 7816:                 }
 7817:             }
 7818:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7819:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7820:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7821:                 if (@curr > 0) {
 7822:                     foreach my $item (@curr) {
 7823:                         if (ref($request_domains) eq 'HASH') {
 7824:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7825:                             if ($otherdom ne '') {
 7826:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7827:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7828:                                         push(@{$request_domains->{$type}},$otherdom);
 7829:                                     }
 7830:                                 } else {
 7831:                                     push(@{$request_domains->{$type}},$otherdom);
 7832:                                 }
 7833:                             }
 7834:                         }
 7835:                     }
 7836:                     unless ($dom eq $env{'user.domain'}) {
 7837:                         $canreq ++;
 7838:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7839:                             $can_request->{$type} = 1;
 7840:                         }
 7841:                     }
 7842:                 }
 7843:             }
 7844:         }
 7845:     }
 7846:     return $canreq;
 7847: }
 7848: 
 7849: # ---------------------------------------------- Custom access rule evaluation
 7850: 
 7851: sub customaccess {
 7852:     my ($priv,$uri)=@_;
 7853:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7854:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7855:     $udom = &LONCAPA::clean_domain($udom);
 7856:     $ucrs = &LONCAPA::clean_username($ucrs);
 7857:     my $access=0;
 7858:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7859: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7860: 	if ($type eq 'user') {
 7861: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7862: 		my ($tdom,$tuname)=split(m{/},$scope);
 7863: 		if ($tdom) {
 7864: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7865: 		}
 7866: 		if ($tuname) {
 7867: 		    if ($tuname ne $env{'user.name'}) { next; }
 7868: 		}
 7869: 		$access=($effect eq 'allow');
 7870: 		last;
 7871: 	    }
 7872: 	} else {
 7873: 	    if ($role) {
 7874: 		if ($role ne $urole) { next; }
 7875: 	    }
 7876: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7877: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7878: 		if ($tdom) {
 7879: 		    if ($tdom ne $udom) { next; }
 7880: 		}
 7881: 		if ($tcrs) {
 7882: 		    if ($tcrs ne $ucrs) { next; }
 7883: 		}
 7884: 		if ($tsec) {
 7885: 		    if ($tsec ne $usec) { next; }
 7886: 		}
 7887: 		$access=($effect eq 'allow');
 7888: 		last;
 7889: 	    }
 7890: 	    if ($realm eq '' && $role eq '') {
 7891: 		$access=($effect eq 'allow');
 7892: 	    }
 7893: 	}
 7894:     }
 7895:     return $access;
 7896: }
 7897: 
 7898: # ------------------------------------------------- Check for a user privilege
 7899: 
 7900: sub allowed {
 7901:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7902:     my $ver_orguri=$uri;
 7903:     $uri=&deversion($uri);
 7904:     my $orguri=$uri;
 7905:     $uri=&declutter($uri);
 7906: 
 7907:     if ($priv eq 'evb') {
 7908: # Evade communication block restrictions for specified role in a course
 7909:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7910:             return $1;
 7911:         } else {
 7912:             return;
 7913:         }
 7914:     }
 7915: 
 7916:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7917: # Free bre access to adm and meta resources
 7918:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7919: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7920: 	&& ($priv eq 'bre')) {
 7921: 	return 'F';
 7922:     }
 7923: 
 7924: # Free bre access to user's own portfolio contents
 7925:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7926:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7927: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7928:         my %setters;
 7929:         my ($startblock,$endblock) = 
 7930:             &Apache::loncommon::blockcheck(\%setters,'port');
 7931:         if ($startblock && $endblock) {
 7932:             return 'B';
 7933:         } else {
 7934:             return 'F';
 7935:         }
 7936:     }
 7937: 
 7938: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7939:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7940:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7941:         if (exists($env{'request.course.id'})) {
 7942:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7943:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7944:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7945:                 my $courseprivid=$env{'request.course.id'};
 7946:                 $courseprivid=~s/\_/\//;
 7947:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7948:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7949:                     return $1; 
 7950:                 } else {
 7951:                     if ($env{'request.course.sec'}) {
 7952:                         $courseprivid.='/'.$env{'request.course.sec'};
 7953:                     }
 7954:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7955:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7956:                         return $2;
 7957:                     }
 7958:                 }
 7959:             }
 7960:         }
 7961:     }
 7962: 
 7963: # Free bre to public access
 7964: 
 7965:     if ($priv eq 'bre') {
 7966:         my $copyright;
 7967:         unless ($uri =~ /ext\.tool/) {
 7968:             $copyright=&metadata($uri,'copyright');
 7969:         }
 7970: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7971:            return 'F'; 
 7972:         }
 7973:         if ($copyright eq 'priv') {
 7974:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7975: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7976: 		return '';
 7977:             }
 7978:         }
 7979:         if ($copyright eq 'domain') {
 7980:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7981: 	    unless (($env{'user.domain'} eq $1) ||
 7982:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7983: 		return '';
 7984:             }
 7985:         }
 7986:         if ($env{'request.role'}=~ /li\.\//) {
 7987:             # Library role, so allow browsing of resources in this domain.
 7988:             return 'F';
 7989:         }
 7990:         if ($copyright eq 'custom') {
 7991: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7992:         }
 7993:     }
 7994:     # Domain coordinator is trying to create a course
 7995:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7996:         # uri is the requested domain in this case.
 7997:         # comparison to 'request.role.domain' shows if the user has selected
 7998:         # a role of dc for the domain in question.
 7999:         return 'F' if ($uri eq $env{'request.role.domain'});
 8000:     }
 8001: 
 8002:     my $thisallowed='';
 8003:     my $statecond=0;
 8004:     my $courseprivid='';
 8005: 
 8006:     my $ownaccess;
 8007:     # Community Coordinator or Assistant Co-author browsing resource space.
 8008:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8009:         if ($uri eq '') {
 8010:             $ownaccess = 1;
 8011:         } else {
 8012:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8013:                 my $udom = $env{'user.domain'};
 8014:                 my $uname = $env{'user.name'};
 8015:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8016:                     $ownaccess = 1;
 8017:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8018:                     unless ($uri =~ m{\.\./}) {
 8019:                         $ownaccess = 1;
 8020:                     }
 8021:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8022:                     my $now = time;
 8023:                     if ($uri =~ m{^([^/]+)/?$}) {
 8024:                         my $adom = $1;
 8025:                         foreach my $key (keys(%env)) {
 8026:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8027:                                 my ($start,$end) = split('.',$env{$key});
 8028:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8029:                                     $ownaccess = 1;
 8030:                                     last;
 8031:                                 }
 8032:                             }
 8033:                         }
 8034:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8035:                         my $adom = $1;
 8036:                         my $aname = $2;
 8037:                         foreach my $role ('ca','aa') { 
 8038:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8039:                                 my ($start,$end) =
 8040:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8041:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8042:                                     $ownaccess = 1;
 8043:                                     last;
 8044:                                 }
 8045:                             }
 8046:                         }
 8047:                     }
 8048:                 }
 8049:             }
 8050:         }
 8051:     }
 8052: 
 8053: # Course
 8054: 
 8055:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8056:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8057:             $thisallowed.=$1;
 8058:         }
 8059:     }
 8060: 
 8061: # Domain
 8062: 
 8063:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8064:        =~/\Q$priv\E\&([^\:]*)/) {
 8065:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8066:             $thisallowed.=$1;
 8067:         }
 8068:     }
 8069: 
 8070: # User who is not author or co-author might still be able to edit
 8071: # resource of an author in the domain (e.g., if Domain Coordinator).
 8072:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8073:         (&allowed('mdc',$env{'request.course.id'}))) {
 8074:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8075:             $thisallowed.=$1;
 8076:         }
 8077:     }
 8078: 
 8079: # Course: uri itself is a course
 8080:     my $courseuri=$uri;
 8081:     $courseuri=~s/\_(\d)/\/$1/;
 8082:     $courseuri=~s/^([^\/])/\/$1/;
 8083: 
 8084:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8085:        =~/\Q$priv\E\&([^\:]*)/) {
 8086:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8087:             $thisallowed.=$1;
 8088:         }
 8089:     }
 8090: 
 8091: # URI is an uploaded document for this course, default permissions don't matter
 8092: # not allowing 'edit' access (editupload) to uploaded course docs
 8093:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8094: 	$thisallowed='';
 8095:         my ($match)=&is_on_map($uri);
 8096:         if ($match) {
 8097:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8098:                   =~/\Q$priv\E\&([^\:]*)/) {
 8099:                 my $value = $1;
 8100:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8101:                 if ($deeplinkblock) {
 8102:                     $thisallowed='D';
 8103:                 } elsif ($noblockcheck) {
 8104:                     $thisallowed.=$value;
 8105:                 } else {
 8106:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8107:                     if (@blockers > 0) {
 8108:                         $thisallowed = 'B';
 8109:                     } else {
 8110:                         $thisallowed.=$value;
 8111:                     }
 8112:                 }
 8113:             }
 8114:         } else {
 8115:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8116:             if ($refuri) {
 8117:                 if ($refuri =~ m|^/adm/|) {
 8118:                     $thisallowed='F';
 8119:                 } else {
 8120:                     $refuri=&declutter($refuri);
 8121:                     my ($match) = &is_on_map($refuri);
 8122:                     if ($match) {
 8123:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8124:                         if ($deeplinkblock) {
 8125:                             $thisallowed='D';
 8126:                         } elsif ($noblockcheck) {
 8127:                             $thisallowed='F';
 8128:                         } else {
 8129:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8130:                             if (@blockers > 0) {
 8131:                                 $thisallowed = 'B';
 8132:                             } else {
 8133:                                 $thisallowed='F';
 8134:                             }
 8135:                         }
 8136:                     }
 8137:                 }
 8138:             }
 8139:         }
 8140:     }
 8141: 
 8142:     if ($priv eq 'bre'
 8143: 	&& $thisallowed ne 'F' 
 8144: 	&& $thisallowed ne '2'
 8145: 	&& &is_portfolio_url($uri)) {
 8146: 	$thisallowed = &portfolio_access($uri,$clientip);
 8147:     }
 8148: 
 8149: # Full access at system, domain or course-wide level? Exit.
 8150:     if ($thisallowed=~/F/) {
 8151: 	return 'F';
 8152:     }
 8153: 
 8154: # If this is generating or modifying users, exit with special codes
 8155: 
 8156:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8157: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8158: 	    my ($audom,$auname)=split('/',$uri);
 8159: # no author name given, so this just checks on the general right to make a co-author in this domain
 8160: 	    unless ($auname) { return $thisallowed; }
 8161: # an author name is given, so we are about to actually make a co-author for a certain account
 8162: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8163: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8164: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8165: 	}
 8166: 	return $thisallowed;
 8167:     }
 8168: #
 8169: # Gathered so far: system, domain and course wide privileges
 8170: #
 8171: # Course: See if uri or referer is an individual resource that is part of 
 8172: # the course
 8173: 
 8174:     if ($env{'request.course.id'}) {
 8175: 
 8176:        $courseprivid=$env{'request.course.id'};
 8177:        if ($env{'request.course.sec'}) {
 8178:           $courseprivid.='/'.$env{'request.course.sec'};
 8179:        }
 8180:        $courseprivid=~s/\_/\//;
 8181:        my $checkreferer=1;
 8182:        my ($match,$cond)=&is_on_map($uri);
 8183:        if ($match) {
 8184:            $statecond=$cond;
 8185:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8186:                =~/\Q$priv\E\&([^\:]*)/) {
 8187:                my $value = $1;
 8188:                if ($priv eq 'bre') {
 8189:                    if ($noblockcheck) {
 8190:                        $thisallowed.=$value;
 8191:                    } else {
 8192:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8193:                        if (@blockers > 0) {
 8194:                            $thisallowed = 'B';
 8195:                        } else {
 8196:                            $thisallowed.=$value;
 8197:                        }
 8198:                    }
 8199:                } else {
 8200:                    $thisallowed.=$value;
 8201:                }
 8202:                $checkreferer=0;
 8203:            }
 8204:        }
 8205:        
 8206:        if ($checkreferer) {
 8207: 	  my $refuri=$env{'httpref.'.$orguri};
 8208:             unless ($refuri) {
 8209:                 foreach my $key (keys(%env)) {
 8210: 		    if ($key=~/^httpref\..*\*/) {
 8211: 			my $pattern=$key;
 8212:                         $pattern=~s/^httpref\.\/res\///;
 8213:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8214:                         $pattern=~s/\//\\\//g;
 8215:                         if ($orguri=~/$pattern/) {
 8216: 			    $refuri=$env{$key};
 8217:                         }
 8218:                     }
 8219:                 }
 8220:             }
 8221: 
 8222:          if ($refuri) { 
 8223: 	  $refuri=&declutter($refuri);
 8224:           my ($match,$cond)=&is_on_map($refuri);
 8225:             if ($match) {
 8226:               my $refstatecond=$cond;
 8227:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8228:                   =~/\Q$priv\E\&([^\:]*)/) {
 8229:                   my $value = $1;
 8230:                   if ($priv eq 'bre') {
 8231:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8232:                       if ($deeplinkblock) {
 8233:                           $thisallowed = 'D';
 8234:                       } elsif ($noblockcheck) {
 8235:                           $thisallowed.=$value;
 8236:                       } else {
 8237:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8238:                           if (@blockers > 0) {
 8239:                               $thisallowed = 'B';
 8240:                           } else {
 8241:                               $thisallowed.=$value;
 8242:                           }
 8243:                       }
 8244:                   } else {
 8245:                       $thisallowed.=$value;
 8246:                   }
 8247:                   $uri=$refuri;
 8248:                   $statecond=$refstatecond;
 8249:               }
 8250:           }
 8251:         }
 8252:        }
 8253:    }
 8254: 
 8255: #
 8256: # Gathered now: all privileges that could apply, and condition number
 8257: # 
 8258: #
 8259: # Full or no access?
 8260: #
 8261: 
 8262:     if ($thisallowed=~/F/) {
 8263: 	return 'F';
 8264:     }
 8265: 
 8266:     unless ($thisallowed) {
 8267:         return '';
 8268:     }
 8269: 
 8270: # Restrictions exist, deal with them
 8271: #
 8272: #   C:according to course preferences
 8273: #   R:according to resource settings
 8274: #   L:unless locked
 8275: #   X:according to user session state
 8276: #
 8277: 
 8278: # Possibly locked functionality, check all courses
 8279: # Locks might take effect only after 10 minutes cache expiration for other
 8280: # courses, and 2 minutes for current course
 8281: 
 8282:     my $envkey;
 8283:     if ($thisallowed=~/L/) {
 8284:         foreach $envkey (keys(%env)) {
 8285:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8286:                my $courseid=$2;
 8287:                my $roleid=$1.'.'.$2;
 8288:                $courseid=~s/^\///;
 8289:                my $expiretime=600;
 8290:                if ($env{'request.role'} eq $roleid) {
 8291: 		  $expiretime=120;
 8292:                }
 8293: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8294:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8295:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8296: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8297:                }
 8298:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8299:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8300: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8301:                        &log($env{'user.domain'},$env{'user.name'},
 8302:                             $env{'user.home'},
 8303:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8304:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8305:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8306: 		       return '';
 8307:                    }
 8308:                }
 8309:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8310:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8311: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8312:                        &log($env{'user.domain'},$env{'user.name'},
 8313:                             $env{'user.home'},
 8314:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8315:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8316:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8317: 		       return '';
 8318:                    }
 8319:                }
 8320: 	   }
 8321:        }
 8322:     }
 8323:    
 8324: #
 8325: # Rest of the restrictions depend on selected course
 8326: #
 8327: 
 8328:     unless ($env{'request.course.id'}) {
 8329: 	if ($thisallowed eq 'A') {
 8330: 	    return 'A';
 8331:         } elsif ($thisallowed eq 'B') {
 8332:             return 'B';
 8333: 	} else {
 8334: 	    return '1';
 8335: 	}
 8336:     }
 8337: 
 8338: #
 8339: # Now user is definitely in a course
 8340: #
 8341: 
 8342: 
 8343: # Course preferences
 8344: 
 8345:    if ($thisallowed=~/C/) {
 8346:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8347:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8348:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8349: 	   =~/\Q$rolecode\E/) {
 8350: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8351: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8352: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8353: 			$env{'request.course.id'});
 8354: 	   }
 8355:            return '';
 8356:        }
 8357: 
 8358:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8359: 	   =~/\Q$unamedom\E/) {
 8360: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8361: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8362: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8363: 			$env{'request.course.id'});
 8364: 	   }
 8365:            return '';
 8366:        }
 8367:    }
 8368: 
 8369: # Resource preferences
 8370: 
 8371:    if ($thisallowed=~/R/) {
 8372:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8373:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8374: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8375: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8376: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8377: 	   }
 8378: 	   return '';
 8379:        }
 8380:    }
 8381: 
 8382: # Restricted by state or randomout?
 8383: 
 8384:    if ($thisallowed=~/X/) {
 8385:       if ($env{'acc.randomout'}) {
 8386: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8387:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8388:             return ''; 
 8389:          }
 8390:       }
 8391:       if (&condval($statecond)) {
 8392: 	 return '2';
 8393:       } else {
 8394:          return '';
 8395:       }
 8396:    }
 8397: 
 8398:     if ($thisallowed eq 'A') {
 8399: 	return 'A';
 8400:     } elsif ($thisallowed eq 'B') {
 8401:         return 'B';
 8402:     } elsif ($thisallowed eq 'D') {
 8403:         return 'D';
 8404:     }
 8405:    return 'F';
 8406: }
 8407: 
 8408: # ------------------------------------------- Check construction space access
 8409: 
 8410: sub constructaccess {
 8411:     my ($url,$setpriv)=@_;
 8412: 
 8413: # We do not allow editing of previous versions of files
 8414:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8415: 
 8416: # Get username and domain from URL
 8417:     my ($ownername,$ownerdomain,$ownerhome);
 8418: 
 8419:     ($ownerdomain,$ownername) =
 8420:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8421: 
 8422: # The URL does not really point to any authorspace, forget it
 8423:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8424: 
 8425: # Now we need to see if the user has access to the authorspace of
 8426: # $ownername at $ownerdomain
 8427: 
 8428:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8429: # Real author for this?
 8430:        $ownerhome = $env{'user.home'};
 8431:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8432:           return ($ownername,$ownerdomain,$ownerhome);
 8433:        }
 8434:     } else {
 8435: # Co-author for this?
 8436:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8437:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8438:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8439:             return ($ownername,$ownerdomain,$ownerhome);
 8440:         }
 8441:         if ($env{'request.course.id'}) {
 8442:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8443:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8444:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8445:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8446:                     return ($ownername,$ownerdomain,$ownerhome);
 8447:                 }
 8448:             }
 8449:         }
 8450:     }
 8451: 
 8452: # We don't have any access right now. If we are not possibly going to do anything about this,
 8453: # we might as well leave
 8454:    unless ($setpriv) { return ''; }
 8455: 
 8456: # Backdoor access?
 8457:     my $allowed=&allowed('eco',$ownerdomain);
 8458: # Nope
 8459:     unless ($allowed) { return ''; }
 8460: # Looks like we may have access, but could be locked by the owner of the construction space
 8461:     if ($allowed eq 'U') {
 8462:         my %blocked=&get('environment',['domcoord.author'],
 8463:                          $ownerdomain,$ownername);
 8464: # Is blocked by owner
 8465:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8466:     }
 8467:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8468: # Grant temporary access
 8469:         my $then=$env{'user.login.time'};
 8470:         my $update=$env{'user.update.time'};
 8471:         if (!$update) { $update = $then; }
 8472:         my $refresh=$env{'user.refresh.time'};
 8473:         if (!$refresh) { $refresh = $update; }
 8474:         my $now = time;
 8475:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8476:                            $now,'ca','constructaccess');
 8477:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8478:         return($ownername,$ownerdomain,$ownerhome);
 8479:     }
 8480: # No business here
 8481:     return '';
 8482: }
 8483: 
 8484: # ----------------------------------------------------------- Content Blocking
 8485: 
 8486: {
 8487: # Caches for faster Course Contents display where content blocking
 8488: # is in operation (i.e., interval param set) for timed quiz.
 8489: #
 8490: # User for whom data are being temporarily cached.
 8491: my $cacheduser='';
 8492: # Cached blockers for this user (a hash of blocking items). 
 8493: my %cachedblockers=();
 8494: # When the data were last cached.
 8495: my $cachedlast='';
 8496: 
 8497: sub load_all_blockers {
 8498:     my ($uname,$udom,$blocks)=@_;
 8499:     if (($uname ne '') && ($udom ne '')) { 
 8500:         if (($cacheduser eq $uname.':'.$udom) &&
 8501:             (abs($cachedlast-time)<5)) {
 8502:             return;
 8503:         }
 8504:     }
 8505:     $cachedlast=time;
 8506:     $cacheduser=$uname.':'.$udom;
 8507:     %cachedblockers = &get_commblock_resources($blocks);
 8508: }
 8509: 
 8510: sub get_comm_blocks {
 8511:     my ($cdom,$cnum) = @_;
 8512:     if ($cdom eq '' || $cnum eq '') {
 8513:         return unless ($env{'request.course.id'});
 8514:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8515:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8516:     }
 8517:     my %commblocks;
 8518:     my $hashid=$cdom.'_'.$cnum;
 8519:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8520:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8521:         %commblocks = %{$blocksref};
 8522:     } else {
 8523:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8524:         my $cachetime = 600;
 8525:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8526:     }
 8527:     return %commblocks;
 8528: }
 8529: 
 8530: sub get_commblock_resources {
 8531:     my ($blocks) = @_;
 8532:     my %blockers = ();
 8533:     return %blockers unless ($env{'request.course.id'});
 8534:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8535:     my %commblocks;
 8536:     if (ref($blocks) eq 'HASH') {
 8537:         %commblocks = %{$blocks};
 8538:     } else {
 8539:         %commblocks = &get_comm_blocks();
 8540:     }
 8541:     return %blockers unless (keys(%commblocks) > 0); 
 8542:     my $navmap = Apache::lonnavmaps::navmap->new();
 8543:     return %blockers unless (ref($navmap));
 8544:     my $now = time;
 8545:     foreach my $block (keys(%commblocks)) {
 8546:         if ($block =~ /^(\d+)____(\d+)$/) {
 8547:             my ($start,$end) = ($1,$2);
 8548:             if ($start <= $now && $end >= $now) {
 8549:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8550:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8551:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8552:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8553:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8554:                             }
 8555:                         }
 8556:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8557:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8558:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8559:                             }
 8560:                         }
 8561:                     }
 8562:                 }
 8563:             }
 8564:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8565:             my $item = $1;
 8566:             my @to_test;
 8567:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8568:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8569:                     my @interval;
 8570:                     my $type = 'map';
 8571:                     if ($item eq 'course') {
 8572:                         $type = 'course';
 8573:                         @interval=&EXT("resource.0.interval");
 8574:                     } else {
 8575:                         if ($item =~ /___\d+___/) {
 8576:                             $type = 'resource';
 8577:                             @interval=&EXT("resource.0.interval",$item);
 8578:                             if (ref($navmap)) {                        
 8579:                                 my $res = $navmap->getBySymb($item); 
 8580:                                 push(@to_test,$res);
 8581:                             }
 8582:                         } else {
 8583:                             my $mapsymb = &symbread($item,1);
 8584:                             if ($mapsymb) {
 8585:                                 if (ref($navmap)) {
 8586:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8587:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8588:                                     foreach my $res (@to_test) {
 8589:                                         my $symb = $res->symb();
 8590:                                         next if ($symb eq $mapsymb);
 8591:                                         if ($symb ne '') {
 8592:                                             @interval=&EXT("resource.0.interval",$symb);
 8593:                                             if ($interval[1] eq 'map') {
 8594:                                                 last;
 8595:                                             }
 8596:                                         }
 8597:                                     }
 8598:                                 }
 8599:                             }
 8600:                         }
 8601:                     }
 8602:                     if ($interval[0] =~ /^(\d+)/) {
 8603:                         my $timelimit = $1; 
 8604:                         my $first_access;
 8605:                         if ($type eq 'resource') {
 8606:                             $first_access=&get_first_access($interval[1],$item);
 8607:                         } elsif ($type eq 'map') {
 8608:                             $first_access=&get_first_access($interval[1],undef,$item);
 8609:                         } else {
 8610:                             $first_access=&get_first_access($interval[1]);
 8611:                         }
 8612:                         if ($first_access) {
 8613:                             my $timesup = $first_access+$timelimit;
 8614:                             if ($timesup > $now) {
 8615:                                 my $activeblock;
 8616:                                 foreach my $res (@to_test) {
 8617:                                     if ($res->answerable()) {
 8618:                                         $activeblock = 1;
 8619:                                         last;
 8620:                                     }
 8621:                                 }
 8622:                                 if ($activeblock) {
 8623:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8624:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8625:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8626:                                          }
 8627:                                     }
 8628:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8629:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8630:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8631:                                         }
 8632:                                     }
 8633:                                 }
 8634:                             }
 8635:                         }
 8636:                     }
 8637:                 }
 8638:             }
 8639:         }
 8640:     }
 8641:     return %blockers;
 8642: }
 8643: 
 8644: sub has_comm_blocking {
 8645:     my ($priv,$symb,$uri,$blocks) = @_;
 8646:     my @blockers;
 8647:     return unless ($env{'request.course.id'});
 8648:     return unless ($priv eq 'bre');
 8649:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8650:     return if ($env{'request.state'} eq 'construct');
 8651:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8652:     return unless (keys(%cachedblockers) > 0);
 8653:     my (%possibles,@symbs);
 8654:     if (!$symb) {
 8655:         $symb = &symbread($uri,1,1,1,\%possibles);
 8656:     }
 8657:     if ($symb) {
 8658:         @symbs = ($symb);
 8659:     } elsif (keys(%possibles)) { 
 8660:         @symbs = keys(%possibles);
 8661:     }
 8662:     my $noblock;
 8663:     foreach my $symb (@symbs) {
 8664:         last if ($noblock);
 8665:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8666:         foreach my $block (keys(%cachedblockers)) {
 8667:             if ($block =~ /^firstaccess____(.+)$/) {
 8668:                 my $item = $1;
 8669:                 if (($item eq $map) || ($item eq $symb)) {
 8670:                     $noblock = 1;
 8671:                     last;
 8672:                 }
 8673:             }
 8674:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8675:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8676:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8677:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8678:                             push(@blockers,$block);
 8679:                         }
 8680:                     }
 8681:                 }
 8682:             }
 8683:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8684:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8685:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8686:                         push(@blockers,$block);
 8687:                     }
 8688:                 }
 8689:             }
 8690:         }
 8691:     }
 8692:     return if ($noblock);
 8693:     return @blockers;
 8694: }
 8695: }
 8696: 
 8697: sub deeplink_check {
 8698:     my ($priv,$symb,$uri) = @_;
 8699:     return unless ($env{'request.course.id'});
 8700:     return unless ($priv eq 'bre');
 8701:     return if ($env{'request.state'} eq 'construct');
 8702:     return if ($env{'request.role.adv'});
 8703:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8704:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8705:     my (%possibles,@symbs);
 8706:     if (!$symb) {
 8707:         $symb = &symbread($uri,1,1,1,\%possibles);
 8708:     }
 8709:     if ($symb) {
 8710:         @symbs = ($symb);
 8711:     } elsif (keys(%possibles)) {
 8712:         @symbs = keys(%possibles);
 8713:     }
 8714: 
 8715:     my ($login,$switchrole,$allow);
 8716:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8717:         my $key = $1;
 8718:         my $tinyurl;
 8719:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8720:         if (defined($cached)) {
 8721:              $tinyurl = $result;
 8722:         } else {
 8723:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8724:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8725:              if ($currtiny{$key} ne '') {
 8726:                  $tinyurl = $currtiny{$key};
 8727:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8728:              }
 8729:         }
 8730:         if ($tinyurl ne '') {
 8731:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8732:             if ($cnumreq eq $cnum) {
 8733:                 $login = $posslogin;
 8734:             } else {
 8735:                 $switchrole = 1;
 8736:             }
 8737:         }
 8738:     }
 8739:     foreach my $symb (@symbs) {
 8740:         last if ($allow);
 8741:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8742:         if ($deeplink eq '') {
 8743:             $allow = 1;
 8744:         } else {
 8745:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8746:             if ($access eq 'any') {
 8747:                 $allow = 1;
 8748:             } elsif ($login) {
 8749:                 if ($access eq 'only') {
 8750:                     if ($scope eq 'res') {
 8751:                         if ($symb eq $login) {
 8752:                             $allow = 1;
 8753:                         }
 8754:                     } elsif ($scope eq 'map') {
 8755: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8756:                     } elsif ($scope eq 'rec') {
 8757: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8758:                     }
 8759:                 } else {
 8760:                     my ($acctype,$item) = split(/:/,$access);
 8761:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8762:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8763:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8764:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8765:                                 $allow = 1;
 8766:                             }
 8767:                         }
 8768:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8769:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8770:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8771:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8772:                                 $allow = 1;
 8773:                             }
 8774:                         }
 8775:                     }
 8776:                 }
 8777:             }
 8778:         }
 8779:     }
 8780:     return if ($allow);
 8781:     return 1;
 8782: }
 8783: 
 8784: # -------------------------------- Deversion and split uri into path an filename   
 8785: 
 8786: #
 8787: #   Removes the version from a URI and
 8788: #   splits it in to its filename and path to the filename.
 8789: #   Seems like File::Basename could have done this more clearly.
 8790: #   Parameters:
 8791: #      $uri   - input URI
 8792: #   Returns:
 8793: #     Two element list consisting of 
 8794: #     $pathname  - the URI up to and excluding the trailing /
 8795: #     $filename  - The part of the URI following the last /
 8796: #  NOTE:
 8797: #    Another realization of this is simply:
 8798: #    use File::Basename;
 8799: #    ...
 8800: #    $uri = shift;
 8801: #    $filename = basename($uri);
 8802: #    $path     = dirname($uri);
 8803: #    return ($filename, $path);
 8804: #
 8805: #     The implementation below is probably faster however.
 8806: #
 8807: sub split_uri_for_cond {
 8808:     my $uri=&deversion(&declutter(shift));
 8809:     my @uriparts=split(/\//,$uri);
 8810:     my $filename=pop(@uriparts);
 8811:     my $pathname=join('/',@uriparts);
 8812:     return ($pathname,$filename);
 8813: }
 8814: # --------------------------------------------------- Is a resource on the map?
 8815: 
 8816: sub is_on_map {
 8817:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8818:     #Trying to find the conditional for the file
 8819:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8820: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8821:     if ($match) {
 8822: 	return (1,$1);
 8823:     } else {
 8824: 	return (0,0);
 8825:     }
 8826: }
 8827: 
 8828: # --------------------------------------------------------- Get symb from alias
 8829: 
 8830: sub get_symb_from_alias {
 8831:     my $symb=shift;
 8832:     my ($map,$resid,$url)=&decode_symb($symb);
 8833: # Already is a symb
 8834:     if ($url) { return $symb; }
 8835: # Must be an alias
 8836:     my $aliassymb='';
 8837:     my %bighash;
 8838:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8839:                             &GDBM_READER(),0640)) {
 8840:         my $rid=$bighash{'mapalias_'.$symb};
 8841: 	if ($rid) {
 8842: 	    my ($mapid,$resid)=split(/\./,$rid);
 8843: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8844: 				    $resid,$bighash{'src_'.$rid});
 8845: 	}
 8846:         untie %bighash;
 8847:     }
 8848:     return $aliassymb;
 8849: }
 8850: 
 8851: # ----------------------------------------------------------------- Define Role
 8852: 
 8853: sub definerole {
 8854:   if (allowed('mcr','/')) {
 8855:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8856:     foreach my $role (split(':',$sysrole)) {
 8857: 	my ($crole,$cqual)=split(/\&/,$role);
 8858:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8859:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8860: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8861:                return "refused:s:$crole&$cqual"; 
 8862:             }
 8863:         }
 8864:     }
 8865:     foreach my $role (split(':',$domrole)) {
 8866: 	my ($crole,$cqual)=split(/\&/,$role);
 8867:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8868:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8869: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8870:                return "refused:d:$crole&$cqual"; 
 8871:             }
 8872:         }
 8873:     }
 8874:     foreach my $role (split(':',$courole)) {
 8875: 	my ($crole,$cqual)=split(/\&/,$role);
 8876:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8877:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8878: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8879:                return "refused:c:$crole&$cqual"; 
 8880:             }
 8881:         }
 8882:     }
 8883:     my $uhome;
 8884:     if (($uname ne '') && ($udom ne '')) {
 8885:         $uhome = &homeserver($uname,$udom);
 8886:         return $uhome if ($uhome eq 'no_host');
 8887:     } else {
 8888:         $uname = $env{'user.name'};
 8889:         $udom = $env{'user.domain'};
 8890:         $uhome = $env{'user.home'};
 8891:     }
 8892:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8893:                 "$udom:$uname:rolesdef_$rolename=".
 8894:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8895:     return reply($command,$uhome);
 8896:   } else {
 8897:     return 'refused';
 8898:   }
 8899: }
 8900: 
 8901: # ---------------- Make a metadata query against the network of library servers
 8902: 
 8903: sub metadata_query {
 8904:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8905:     my %rhash;
 8906:     my %libserv = &all_library();
 8907:     my @server_list = (defined($server_array) ? @$server_array
 8908:                                               : keys(%libserv) );
 8909:     for my $server (@server_list) {
 8910:         my $domains = ''; 
 8911:         if (ref($domains_hash) eq 'HASH') {
 8912:             $domains = $domains_hash->{$server}; 
 8913:         }
 8914: 	unless ($custom or $customshow) {
 8915: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8916: 	    $rhash{$server}=$reply;
 8917: 	}
 8918: 	else {
 8919: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8920: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8921: 			     $server);
 8922: 	    $rhash{$server}=$reply;
 8923: 	}
 8924:     }
 8925:     return \%rhash;
 8926: }
 8927: 
 8928: # ----------------------------------------- Send log queries and wait for reply
 8929: 
 8930: sub log_query {
 8931:     my ($uname,$udom,$query,%filters)=@_;
 8932:     my $uhome=&homeserver($uname,$udom);
 8933:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8934:     my $uhost=&hostname($uhome);
 8935:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8936:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8937:                        $uhome);
 8938:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8939:     return get_query_reply($queryid);
 8940: }
 8941: 
 8942: # -------------------------- Update MySQL table for portfolio file
 8943: 
 8944: sub update_portfolio_table {
 8945:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8946:     if ($group ne '') {
 8947:         $file_name =~s /^\Q$group\E//;
 8948:     }
 8949:     my $homeserver = &homeserver($uname,$udom);
 8950:     my $queryid=
 8951:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8952:                ':'.&escape($file_name).':'.$action,$homeserver);
 8953:     my $reply = &get_query_reply($queryid);
 8954:     return $reply;
 8955: }
 8956: 
 8957: # -------------------------- Update MySQL allusers table
 8958: 
 8959: sub update_allusers_table {
 8960:     my ($uname,$udom,$names) = @_;
 8961:     my $homeserver = &homeserver($uname,$udom);
 8962:     my $queryid=
 8963:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8964:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8965:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8966:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8967:                'generation='.&escape($names->{'generation'}).'%%'.
 8968:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8969:                'id='.&escape($names->{'id'}),$homeserver);
 8970:     return;
 8971: }
 8972: 
 8973: # ------- Request retrieval of institutional classlists for course(s)
 8974: 
 8975: sub fetch_enrollment_query {
 8976:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8977:     my ($homeserver,$sleep,$loopmax);
 8978:     my $maxtries = 1;
 8979:     if ($context eq 'automated') {
 8980:         $homeserver = $perlvar{'lonHostID'};
 8981:         $sleep = 2;
 8982:         $loopmax = 100;
 8983:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8984:     } else {
 8985:         $homeserver = &homeserver($cnum,$dom);
 8986:     }
 8987:     my $host=&hostname($homeserver);
 8988:     my $cmd = '';
 8989:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8990:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8991:     }
 8992:     $cmd =~ s/%%$//;
 8993:     $cmd = &escape($cmd);
 8994:     my $query = 'fetchenrollment';
 8995:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8996:     unless ($queryid=~/^\Q$host\E\_/) { 
 8997:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8998:         return 'error: '.$queryid;
 8999:     }
 9000:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9001:     my $tries = 1;
 9002:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9003:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9004:         $tries ++;
 9005:     }
 9006:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9007:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9008:     } else {
 9009:         my @responses = split(/:/,$reply);
 9010:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9011:             foreach my $line (@responses) {
 9012:                 my ($key,$value) = split(/=/,$line,2);
 9013:                 $$replyref{$key} = $value;
 9014:             }
 9015:         } else {
 9016:             my $pathname = LONCAPA::tempdir();
 9017:             foreach my $line (@responses) {
 9018:                 my ($key,$value) = split(/=/,$line);
 9019:                 $$replyref{$key} = $value;
 9020:                 if ($value > 0) {
 9021:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9022:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9023:                         my $destname = $pathname.'/'.$filename;
 9024:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9025:                         if ($xml_classlist =~ /^error/) {
 9026:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9027:                         } else {
 9028:                             if ( open(FILE,">",$destname) ) {
 9029:                                 print FILE &unescape($xml_classlist);
 9030:                                 close(FILE);
 9031:                             } else {
 9032:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9033:                             }
 9034:                         }
 9035:                     }
 9036:                 }
 9037:             }
 9038:         }
 9039:         return 'ok';
 9040:     }
 9041:     return 'error';
 9042: }
 9043: 
 9044: sub get_query_reply {
 9045:     my ($queryid,$sleep,$loopmax) = @_;;
 9046:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9047:         $sleep = 0.2;
 9048:     }
 9049:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9050:         $loopmax = 100;
 9051:     }
 9052:     my $replyfile=LONCAPA::tempdir().$queryid;
 9053:     my $reply='';
 9054:     for (1..$loopmax) {
 9055: 	sleep($sleep);
 9056:         if (-e $replyfile.'.end') {
 9057: 	    if (open(my $fh,"<",$replyfile)) {
 9058: 		$reply = join('',<$fh>);
 9059: 		close($fh);
 9060: 	   } else { return 'error: reply_file_error'; }
 9061:            return &unescape($reply);
 9062: 	}
 9063:     }
 9064:     return 'timeout:'.$queryid;
 9065: }
 9066: 
 9067: sub courselog_query {
 9068: #
 9069: # possible filters:
 9070: # url: url or symb
 9071: # username
 9072: # domain
 9073: # action: view, submit, grade
 9074: # start: timestamp
 9075: # end: timestamp
 9076: #
 9077:     my (%filters)=@_;
 9078:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9079:     if ($filters{'url'}) {
 9080: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9081:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9082:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9083:     }
 9084:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9085:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9086:     return &log_query($cname,$cdom,'courselog',%filters);
 9087: }
 9088: 
 9089: sub userlog_query {
 9090: #
 9091: # possible filters:
 9092: # action: log check role
 9093: # start: timestamp
 9094: # end: timestamp
 9095: #
 9096:     my ($uname,$udom,%filters)=@_;
 9097:     return &log_query($uname,$udom,'userlog',%filters);
 9098: }
 9099: 
 9100: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9101: 
 9102: sub auto_run {
 9103:     my ($cnum,$cdom) = @_;
 9104:     my $response = 0;
 9105:     my $settings;
 9106:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9107:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9108:         $settings = $domconfig{'autoenroll'};
 9109:         if ($settings->{'run'} eq '1') {
 9110:             $response = 1;
 9111:         }
 9112:     } else {
 9113:         my $homeserver;
 9114:         if (&is_course($cdom,$cnum)) {
 9115:             $homeserver = &homeserver($cnum,$cdom);
 9116:         } else {
 9117:             $homeserver = &domain($cdom,'primary');
 9118:         }
 9119:         if ($homeserver ne 'no_host') {
 9120:             $response = &reply('autorun:'.$cdom,$homeserver);
 9121:         }
 9122:     }
 9123:     return $response;
 9124: }
 9125: 
 9126: sub auto_get_sections {
 9127:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9128:     my $homeserver;
 9129:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9130:         $homeserver = &homeserver($cnum,$cdom);
 9131:     }
 9132:     if (!defined($homeserver)) { 
 9133:         if ($cdom =~ /^$match_domain$/) {
 9134:             $homeserver = &domain($cdom,'primary');
 9135:         }
 9136:     }
 9137:     my @secs;
 9138:     if (defined($homeserver)) {
 9139:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9140:         unless ($response eq 'refused') {
 9141:             @secs = split(/:/,$response);
 9142:         }
 9143:     }
 9144:     return @secs;
 9145: }
 9146: 
 9147: sub auto_new_course {
 9148:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9149:     my $homeserver = &homeserver($cnum,$cdom);
 9150:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9151:     return $response;
 9152: }
 9153: 
 9154: sub auto_validate_courseID {
 9155:     my ($cnum,$cdom,$inst_course_id) = @_;
 9156:     my $homeserver = &homeserver($cnum,$cdom);
 9157:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9158:     return $response;
 9159: }
 9160: 
 9161: sub auto_validate_instcode {
 9162:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9163:     my ($homeserver,$response);
 9164:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9165:         $homeserver = &homeserver($cnum,$cdom);
 9166:     }
 9167:     if (!defined($homeserver)) {
 9168:         if ($cdom =~ /^$match_domain$/) {
 9169:             $homeserver = &domain($cdom,'primary');
 9170:         }
 9171:     }
 9172:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9173:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9174:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9175:     return ($outcome,$description,$defaultcredits);
 9176: }
 9177: 
 9178: sub auto_create_password {
 9179:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9180:     my ($homeserver,$response);
 9181:     my $create_passwd = 0;
 9182:     my $authchk = '';
 9183:     if ($udom =~ /^$match_domain$/) {
 9184:         $homeserver = &domain($udom,'primary');
 9185:     }
 9186:     if ($homeserver eq '') {
 9187:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9188:             $homeserver = &homeserver($cnum,$cdom);
 9189:         }
 9190:     }
 9191:     if ($homeserver eq '') {
 9192:         $authchk = 'nodomain';
 9193:     } else {
 9194:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9195:         if ($response eq 'refused') {
 9196:             $authchk = 'refused';
 9197:         } else {
 9198:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9199:         }
 9200:     }
 9201:     return ($authparam,$create_passwd,$authchk);
 9202: }
 9203: 
 9204: sub auto_photo_permission {
 9205:     my ($cnum,$cdom,$students) = @_;
 9206:     my $homeserver = &homeserver($cnum,$cdom);
 9207:     my ($outcome,$perm_reqd,$conditions) = 
 9208: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9209:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9210: 	return (undef,undef);
 9211:     }
 9212:     return ($outcome,$perm_reqd,$conditions);
 9213: }
 9214: 
 9215: sub auto_checkphotos {
 9216:     my ($uname,$udom,$pid) = @_;
 9217:     my $homeserver = &homeserver($uname,$udom);
 9218:     my ($result,$resulttype);
 9219:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9220: 				   &escape($uname).':'.&escape($pid),
 9221: 				   $homeserver));
 9222:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9223: 	return (undef,undef);
 9224:     }
 9225:     if ($outcome) {
 9226:         ($result,$resulttype) = split(/:/,$outcome);
 9227:     } 
 9228:     return ($result,$resulttype);
 9229: }
 9230: 
 9231: sub auto_photochoice {
 9232:     my ($cnum,$cdom) = @_;
 9233:     my $homeserver = &homeserver($cnum,$cdom);
 9234:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9235: 						       &escape($cdom),
 9236: 						       $homeserver)));
 9237:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9238: 	return (undef,undef);
 9239:     }
 9240:     return ($update,$comment);
 9241: }
 9242: 
 9243: sub auto_photoupdate {
 9244:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9245:     my $homeserver = &homeserver($cnum,$dom);
 9246:     my $host=&hostname($homeserver);
 9247:     my $cmd = '';
 9248:     my $maxtries = 1;
 9249:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9250:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9251:     }
 9252:     $cmd =~ s/%%$//;
 9253:     $cmd = &escape($cmd);
 9254:     my $query = 'institutionalphotos';
 9255:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9256:     unless ($queryid=~/^\Q$host\E\_/) {
 9257:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9258:         return 'error: '.$queryid;
 9259:     }
 9260:     my $reply = &get_query_reply($queryid);
 9261:     my $tries = 1;
 9262:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9263:         $reply = &get_query_reply($queryid);
 9264:         $tries ++;
 9265:     }
 9266:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9267:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9268:     } else {
 9269:         my @responses = split(/:/,$reply);
 9270:         my $outcome = shift(@responses); 
 9271:         foreach my $item (@responses) {
 9272:             my ($key,$value) = split(/=/,$item);
 9273:             $$photo{$key} = $value;
 9274:         }
 9275:         return $outcome;
 9276:     }
 9277:     return 'error';
 9278: }
 9279: 
 9280: sub auto_instcode_format {
 9281:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9282: 	$cat_order) = @_;
 9283:     my $courses = '';
 9284:     my @homeservers;
 9285:     if ($caller eq 'global') {
 9286: 	my %servers = &get_servers($codedom,'library');
 9287: 	foreach my $tryserver (keys(%servers)) {
 9288: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9289: 		push(@homeservers,$tryserver);
 9290: 	    }
 9291:         }
 9292:     } elsif ($caller eq 'requests') {
 9293:         if ($codedom =~ /^$match_domain$/) {
 9294:             my $chome = &domain($codedom,'primary');
 9295:             unless ($chome eq 'no_host') {
 9296:                 push(@homeservers,$chome);
 9297:             }
 9298:         }
 9299:     } else {
 9300:         push(@homeservers,&homeserver($caller,$codedom));
 9301:     }
 9302:     foreach my $code (keys(%{$instcodes})) {
 9303:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9304:     }
 9305:     chop($courses);
 9306:     my $ok_response = 0;
 9307:     my $response;
 9308:     while (@homeservers > 0 && $ok_response == 0) {
 9309:         my $server = shift(@homeservers); 
 9310:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9311:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9312:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9313: 		split(/:/,$response);
 9314:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9315:             push(@{$codetitles},&str2array($codetitles_str));
 9316:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9317:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9318:             $ok_response = 1;
 9319:         }
 9320:     }
 9321:     if ($ok_response) {
 9322:         return 'ok';
 9323:     } else {
 9324:         return $response;
 9325:     }
 9326: }
 9327: 
 9328: sub auto_instcode_defaults {
 9329:     my ($domain,$returnhash,$code_order) = @_;
 9330:     my @homeservers;
 9331: 
 9332:     my %servers = &get_servers($domain,'library');
 9333:     foreach my $tryserver (keys(%servers)) {
 9334: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9335: 	    push(@homeservers,$tryserver);
 9336: 	}
 9337:     }
 9338: 
 9339:     my $response;
 9340:     foreach my $server (@homeservers) {
 9341:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9342:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9343: 	
 9344: 	foreach my $pair (split(/\&/,$response)) {
 9345: 	    my ($name,$value)=split(/\=/,$pair);
 9346: 	    if ($name eq 'code_order') {
 9347: 		@{$code_order} = split(/\&/,&unescape($value));
 9348: 	    } else {
 9349: 		$returnhash->{&unescape($name)}=&unescape($value);
 9350: 	    }
 9351: 	}
 9352: 	return 'ok';
 9353:     }
 9354: 
 9355:     return $response;
 9356: }
 9357: 
 9358: sub auto_possible_instcodes {
 9359:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9360:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9361:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9362:         return;
 9363:     }
 9364:     my (@homeservers,$uhome);
 9365:     if (defined(&domain($domain,'primary'))) {
 9366:         $uhome=&domain($domain,'primary');
 9367:         push(@homeservers,&domain($domain,'primary'));
 9368:     } else {
 9369:         my %servers = &get_servers($domain,'library');
 9370:         foreach my $tryserver (keys(%servers)) {
 9371:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9372:                 push(@homeservers,$tryserver);
 9373:             }
 9374:         }
 9375:     }
 9376:     my $response;
 9377:     foreach my $server (@homeservers) {
 9378:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9379:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9380:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9381:             split(':',$response);
 9382:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9383:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9384:         foreach my $item (split('&',$cat_title)) {   
 9385:             my ($name,$value)=split('=',$item);
 9386:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9387:         }
 9388:         foreach my $item (split('&',$cat_order)) {
 9389:             my ($name,$value)=split('=',$item);
 9390:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9391:         }
 9392:         return 'ok';
 9393:     }
 9394:     return $response;
 9395: }
 9396: 
 9397: sub auto_courserequest_checks {
 9398:     my ($dom) = @_;
 9399:     my ($homeserver,%validations);
 9400:     if ($dom =~ /^$match_domain$/) {
 9401:         $homeserver = &domain($dom,'primary');
 9402:     }
 9403:     unless ($homeserver eq 'no_host') {
 9404:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9405:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9406:             my @items = split(/&/,$response);
 9407:             foreach my $item (@items) {
 9408:                 my ($key,$value) = split('=',$item);
 9409:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9410:             }
 9411:         }
 9412:     }
 9413:     return %validations; 
 9414: }
 9415: 
 9416: sub auto_courserequest_validation {
 9417:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9418:     my ($homeserver,$response);
 9419:     if ($dom =~ /^$match_domain$/) {
 9420:         $homeserver = &domain($dom,'primary');
 9421:     }
 9422:     unless ($homeserver eq 'no_host') {
 9423:         my $customdata;
 9424:         if (ref($custominfo) eq 'HASH') {
 9425:             $customdata = &freeze_escape($custominfo);
 9426:         }
 9427:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9428:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9429:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9430:                                     $customdata,$homeserver));
 9431:     }
 9432:     return $response;
 9433: }
 9434: 
 9435: sub auto_validate_class_sec {
 9436:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9437:     my $homeserver = &homeserver($cnum,$cdom);
 9438:     my $ownerlist;
 9439:     if (ref($owners) eq 'ARRAY') {
 9440:         $ownerlist = join(',',@{$owners});
 9441:     } else {
 9442:         $ownerlist = $owners;
 9443:     }
 9444:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9445:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9446:     return $response;
 9447: }
 9448: 
 9449: sub auto_validate_instclasses {
 9450:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9451:     my ($homeserver,%validations);
 9452:     $homeserver = &homeserver($cnum,$cdom);
 9453:     unless ($homeserver eq 'no_host') {
 9454:         my $ownerlist;
 9455:         if (ref($owners) eq 'ARRAY') {
 9456:             $ownerlist = join(',',@{$owners});
 9457:         } else {
 9458:             $ownerlist = $owners;
 9459:         }
 9460:         if (ref($classesref) eq 'HASH') {
 9461:             my $classes = &freeze_escape($classesref);
 9462:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9463:                                 ':'.$cdom.':'.$classes,$homeserver);
 9464:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9465:                 my @items = split(/&/,$response);
 9466:                 foreach my $item (@items) {
 9467:                     my ($key,$value) = split('=',$item);
 9468:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9469:                 }
 9470:             }
 9471:         }
 9472:     }
 9473:     return %validations;
 9474: }
 9475: 
 9476: sub auto_crsreq_update {
 9477:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9478:         $code,$accessstart,$accessend,$inbound) = @_;
 9479:     my ($homeserver,%crsreqresponse);
 9480:     if ($cdom =~ /^$match_domain$/) {
 9481:         $homeserver = &domain($cdom,'primary');
 9482:     }
 9483:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9484:         my $info;
 9485:         if (ref($inbound) eq 'HASH') {
 9486:             $info = &freeze_escape($inbound);
 9487:         }
 9488:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9489:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9490:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9491:                             &escape($title).':'.&escape($code).':'.
 9492:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9493:                             $homeserver);
 9494:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9495:             my @items = split(/&/,$response);
 9496:             foreach my $item (@items) {
 9497:                 my ($key,$value) = split('=',$item);
 9498:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9499:             }
 9500:         }
 9501:     }
 9502:     return \%crsreqresponse;
 9503: }
 9504: 
 9505: sub auto_export_grades {
 9506:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9507:     my ($homeserver,%exportresponse);
 9508:     if ($cdom =~ /^$match_domain$/) {
 9509:         $homeserver = &domain($cdom,'primary');
 9510:     }
 9511:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9512:         my $info;
 9513:         if (ref($inforef) eq 'HASH') {
 9514:             $info = &freeze_escape($inforef);
 9515:         }
 9516:         if (ref($gradesref) eq 'HASH') {
 9517:             my $grades = &freeze_escape($gradesref);
 9518:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9519:                                 $info.':'.$grades,$homeserver);
 9520:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9521:                 my @items = split(/&/,$response);
 9522:                 foreach my $item (@items) {
 9523:                     my ($key,$value) = split('=',$item);
 9524:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9525:                 }
 9526:             }
 9527:         }
 9528:     }
 9529:     return \%exportresponse;
 9530: }
 9531: 
 9532: sub check_instcode_cloning {
 9533:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9534:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9535:         return;
 9536:     }
 9537:     my $canclone;
 9538:     if (@{$code_order} > 0) {
 9539:         my $instcoderegexp ='^';
 9540:         my @clonecodes = split(/\&/,$cloner);
 9541:         foreach my $item (@{$code_order}) {
 9542:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9543:                 foreach my $pair (@clonecodes) {
 9544:                     my ($key,$val) = split(/\=/,$pair,2);
 9545:                     $val = &unescape($val);
 9546:                     if ($key eq $item) {
 9547:                         $instcoderegexp .= '('.$val.')';
 9548:                         last;
 9549:                     }
 9550:                 }
 9551:             } else {
 9552:                 $instcoderegexp .= $codedefaults->{$item};
 9553:             }
 9554:         }
 9555:         $instcoderegexp .= '$';
 9556:         my (@from,@to);
 9557:         eval {
 9558:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9559:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9560:         };
 9561:         if ((@from > 0) && (@to > 0)) {
 9562:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9563:             if (!@diffs) {
 9564:                 $canclone = 1;
 9565:             }
 9566:         }
 9567:     }
 9568:     return $canclone;
 9569: }
 9570: 
 9571: sub default_instcode_cloning {
 9572:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9573:     my (%codedefaults,@code_order,$canclone);
 9574:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9575:         %codedefaults = %{$codedefaultsref};
 9576:         @code_order = @{$codeorderref};
 9577:     } elsif ($clonedom) {
 9578:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9579:     }
 9580:     if (($domdefclone) && (@code_order)) {
 9581:         my @clonecodes = split(/\+/,$domdefclone);
 9582:         my $instcoderegexp ='^';
 9583:         foreach my $item (@code_order) {
 9584:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9585:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9586:             } else {
 9587:                 $instcoderegexp .= $codedefaults{$item};
 9588:             }
 9589:         }
 9590:         $instcoderegexp .= '$';
 9591:         my (@from,@to);
 9592:         eval {
 9593:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9594:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9595:         };
 9596:         if ((@from > 0) && (@to > 0)) {
 9597:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9598:             if (!@diffs) {
 9599:                 $canclone = 1;
 9600:             }
 9601:         }
 9602:     }
 9603:     return $canclone;
 9604: }
 9605: 
 9606: # ------------------------------------------------------- Course Group routines
 9607: 
 9608: sub get_coursegroups {
 9609:     my ($cdom,$cnum,$group,$namespace) = @_;
 9610:     return(&dump($namespace,$cdom,$cnum,$group));
 9611: }
 9612: 
 9613: sub modify_coursegroup {
 9614:     my ($cdom,$cnum,$groupsettings) = @_;
 9615:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9616: }
 9617: 
 9618: sub toggle_coursegroup_status {
 9619:     my ($cdom,$cnum,$group,$action) = @_;
 9620:     my ($from_namespace,$to_namespace);
 9621:     if ($action eq 'delete') {
 9622:         $from_namespace = 'coursegroups';
 9623:         $to_namespace = 'deleted_groups';
 9624:     } else {
 9625:         $from_namespace = 'deleted_groups';
 9626:         $to_namespace = 'coursegroups';
 9627:     }
 9628:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9629:     if (my $tmp = &error(%curr_group)) {
 9630:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9631:         return ('read error',$tmp);
 9632:     } else {
 9633:         my %savedsettings = %curr_group; 
 9634:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9635:         my $deloutcome;
 9636:         if ($result eq 'ok') {
 9637:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9638:         } else {
 9639:             return ('write error',$result);
 9640:         }
 9641:         if ($deloutcome eq 'ok') {
 9642:             return 'ok';
 9643:         } else {
 9644:             return ('delete error',$deloutcome);
 9645:         }
 9646:     }
 9647: }
 9648: 
 9649: sub modify_group_roles {
 9650:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9651:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9652:     my $role = 'gr/'.&escape($userprivs);
 9653:     my ($uname,$udom) = split(/:/,$user);
 9654:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9655:     if ($result eq 'ok') {
 9656:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9657:     }
 9658:     return $result;
 9659: }
 9660: 
 9661: sub modify_coursegroup_membership {
 9662:     my ($cdom,$cnum,$membership) = @_;
 9663:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9664:     return $result;
 9665: }
 9666: 
 9667: sub get_active_groups {
 9668:     my ($udom,$uname,$cdom,$cnum) = @_;
 9669:     my $now = time;
 9670:     my %groups = ();
 9671:     foreach my $key (keys(%env)) {
 9672:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9673:             my ($start,$end) = split(/\./,$env{$key});
 9674:             if (($end!=0) && ($end<$now)) { next; }
 9675:             if (($start!=0) && ($start>$now)) { next; }
 9676:             if ($1 eq $cdom && $2 eq $cnum) {
 9677:                 $groups{$3} = $env{$key} ;
 9678:             }
 9679:         }
 9680:     }
 9681:     return %groups;
 9682: }
 9683: 
 9684: sub get_group_membership {
 9685:     my ($cdom,$cnum,$group) = @_;
 9686:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9687: }
 9688: 
 9689: sub get_users_groups {
 9690:     my ($udom,$uname,$courseid) = @_;
 9691:     my @usersgroups;
 9692:     my $cachetime=1800;
 9693: 
 9694:     my $hashid="$udom:$uname:$courseid";
 9695:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9696:     if (defined($cached)) {
 9697:         @usersgroups = split(/:/,$grouplist);
 9698:     } else {  
 9699:         $grouplist = '';
 9700:         my $courseurl = &courseid_to_courseurl($courseid);
 9701:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9702:         my $access_end = $env{'course.'.$courseid.
 9703:                               '.default_enrollment_end_date'};
 9704:         my $now = time;
 9705:         foreach my $key (keys(%roleshash)) {
 9706:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9707:                 my $group = $1;
 9708:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9709:                     my $start = $2;
 9710:                     my $end = $1;
 9711:                     if ($start == -1) { next; } # deleted from group
 9712:                     if (($start!=0) && ($start>$now)) { next; }
 9713:                     if (($end!=0) && ($end<$now)) {
 9714:                         if ($access_end && $access_end < $now) {
 9715:                             if ($access_end - $end < 86400) {
 9716:                                 push(@usersgroups,$group);
 9717:                             }
 9718:                         }
 9719:                         next;
 9720:                     }
 9721:                     push(@usersgroups,$group);
 9722:                 }
 9723:             }
 9724:         }
 9725:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9726:         $grouplist = join(':',@usersgroups);
 9727:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9728:     }
 9729:     return @usersgroups;
 9730: }
 9731: 
 9732: sub devalidate_getgroups_cache {
 9733:     my ($udom,$uname,$cdom,$cnum)=@_;
 9734:     my $courseid = $cdom.'_'.$cnum;
 9735: 
 9736:     my $hashid="$udom:$uname:$courseid";
 9737:     &devalidate_cache_new('getgroups',$hashid);
 9738: }
 9739: 
 9740: # ------------------------------------------------------------------ Plain Text
 9741: 
 9742: sub plaintext {
 9743:     my ($short,$type,$cid,$forcedefault) = @_;
 9744:     if ($short =~ m{^cr/}) {
 9745: 	return (split('/',$short))[-1];
 9746:     }
 9747:     if (!defined($cid)) {
 9748:         $cid = $env{'request.course.id'};
 9749:     }
 9750:     my %rolenames = (
 9751:                       Course    => 'std',
 9752:                       Community => 'alt1',
 9753:                       Placement => 'std',
 9754:                     );
 9755:     if ($cid ne '') {
 9756:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9757:             unless ($forcedefault) {
 9758:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9759:                 &Apache::lonlocal::mt_escape(\$roletext);
 9760:                 return &Apache::lonlocal::mt($roletext);
 9761:             }
 9762:         }
 9763:     }
 9764:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9765:         (defined($rolenames{$type})) && 
 9766:         (defined($prp{$short}{$rolenames{$type}}))) {
 9767:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9768:     } elsif ($cid ne '') {
 9769:         my $crstype = $env{'course.'.$cid.'.type'};
 9770:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9771:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9772:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9773:         }
 9774:     }
 9775:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9776: }
 9777: 
 9778: # ----------------------------------------------------------------- Assign Role
 9779: 
 9780: sub assignrole {
 9781:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9782:         $context)=@_;
 9783:     my $mrole;
 9784:     if ($role =~ /^cr\//) {
 9785:         my $cwosec=$url;
 9786:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9787: 	unless (&allowed('ccr',$cwosec)) {
 9788:            my $refused = 1;
 9789:            if ($context eq 'requestcourses') {
 9790:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9791:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9792:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9793:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9794:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9795:                            if ($crsenv{'internal.courseowner'} eq
 9796:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9797:                                $refused = '';
 9798:                            }
 9799:                        }
 9800:                    }
 9801:                }
 9802:            }
 9803:            if ($refused) {
 9804:                &logthis('Refused custom assignrole: '.
 9805:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9806:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9807:                return 'refused';
 9808:            }
 9809:         }
 9810:         $mrole='cr';
 9811:     } elsif ($role =~ /^gr\//) {
 9812:         my $cwogrp=$url;
 9813:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9814:         unless (&allowed('mdg',$cwogrp)) {
 9815:             &logthis('Refused group assignrole: '.
 9816:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9817:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9818:             return 'refused';
 9819:         }
 9820:         $mrole='gr';
 9821:     } else {
 9822:         my $cwosec=$url;
 9823:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9824:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9825:             my $refused;
 9826:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9827:                 if (!(&allowed('c'.$role,$url))) {
 9828:                     $refused = 1;
 9829:                 }
 9830:             } else {
 9831:                 $refused = 1;
 9832:             }
 9833:             if ($refused) {
 9834:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9835:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9836:                     my %crsenv;
 9837:                     if ($role eq 'cc' || $role eq 'co') {
 9838:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9839:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9840:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9841:                                 if ($crsenv{'internal.courseowner'} eq 
 9842:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9843:                                     $refused = '';
 9844:                                 }
 9845:                             }
 9846:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9847:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9848:                                 if ($crsenv{'internal.courseowner'} eq 
 9849:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9850:                                     $refused = '';
 9851:                                 }
 9852:                             }
 9853:                         }
 9854:                     }
 9855:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9856:                     if ($role eq 'st') {
 9857:                         $refused = '';
 9858:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9859:                         $refused = '';
 9860:                     }
 9861:                 } elsif ($context eq 'requestcourses') {
 9862:                     my @possroles = ('st','ta','ep','in','cc','co');
 9863:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9864:                         my $wrongcc;
 9865:                         if ($cnum =~ /^$match_community$/) {
 9866:                             $wrongcc = 1 if ($role eq 'cc');
 9867:                         } else {
 9868:                             $wrongcc = 1 if ($role eq 'co');
 9869:                         }
 9870:                         unless ($wrongcc) {
 9871:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9872:                             if ($crsenv{'internal.courseowner'} eq 
 9873:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9874:                                 $refused = '';
 9875:                             }
 9876:                         }
 9877:                     }
 9878:                 } elsif ($context eq 'requestauthor') {
 9879:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9880:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9881:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9882:                             $refused = '';
 9883:                         } else {
 9884:                             my %domdefaults = &get_domain_defaults($udom);
 9885:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9886:                                 my $checkbystatus;
 9887:                                 if ($env{'user.adv'}) { 
 9888:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9889:                                     if ($disposition eq 'automatic') {
 9890:                                         $refused = '';
 9891:                                     } elsif ($disposition eq '') {
 9892:                                         $checkbystatus = 1;
 9893:                                     } 
 9894:                                 } else {
 9895:                                     $checkbystatus = 1;
 9896:                                 }
 9897:                                 if ($checkbystatus) {
 9898:                                     if ($env{'environment.inststatus'}) {
 9899:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9900:                                         foreach my $type (@inststatuses) {
 9901:                                             if (($type ne '') &&
 9902:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9903:                                                 $refused = '';
 9904:                                             }
 9905:                                         }
 9906:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9907:                                         $refused = '';
 9908:                                     }
 9909:                                 }
 9910:                             }
 9911:                         }
 9912:                     }
 9913:                 }
 9914:                 if ($refused) {
 9915:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9916:                              ' '.$role.' '.$end.' '.$start.' by '.
 9917: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9918:                     return 'refused';
 9919:                 }
 9920:             }
 9921:         } elsif ($role eq 'au') {
 9922:             if ($url ne '/'.$udom.'/') {
 9923:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9924:                          ' to assign author role for '.$uname.':'.$udom.
 9925:                          ' in domain: '.$url.' refused (wrong domain).');
 9926:                 return 'refused';
 9927:             }
 9928:         }
 9929:         $mrole=$role;
 9930:     }
 9931:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9932:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9933:     if ($end) { $command.='_'.$end; }
 9934:     if ($start) {
 9935: 	if ($end) { 
 9936:            $command.='_'.$start; 
 9937:         } else {
 9938:            $command.='_0_'.$start;
 9939:         }
 9940:     }
 9941:     my $origstart = $start;
 9942:     my $origend = $end;
 9943:     my $delflag;
 9944: # actually delete
 9945:     if ($deleteflag) {
 9946: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9947: # modify command to delete the role
 9948:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9949:                 "$udom:$uname:$url".'_'."$mrole";
 9950: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9951: # set start and finish to negative values for userrolelog
 9952:            $start=-1;
 9953:            $end=-1;
 9954:            $delflag = 1;
 9955:         }
 9956:     }
 9957: # send command
 9958:     my $answer=&reply($command,&homeserver($uname,$udom));
 9959: # log new user role if status is ok
 9960:     if ($answer eq 'ok') {
 9961: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9962:         if (($role eq 'cc') || ($role eq 'in') ||
 9963:             ($role eq 'ep') || ($role eq 'ad') ||
 9964:             ($role eq 'ta') || ($role eq 'st') ||
 9965:             ($role=~/^cr/) || ($role eq 'gr') ||
 9966:             ($role eq 'co')) {
 9967: # for course roles, perform group memberships changes triggered by role change.
 9968:             unless ($role =~ /^gr/) {
 9969:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9970:                                                  $origstart,$selfenroll,$context);
 9971:             }
 9972:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9973:                            $selfenroll,$context);
 9974:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9975:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9976:                  ($role eq 'da')) {
 9977:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9978:                            $context);
 9979:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9980:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9981:                              $context); 
 9982:         }
 9983:         if ($role eq 'cc') {
 9984:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9985:         }
 9986:     }
 9987:     return $answer;
 9988: }
 9989: 
 9990: sub autoupdate_coowners {
 9991:     my ($url,$end,$start,$uname,$udom) = @_;
 9992:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9993:     if (($cdom ne '') && ($cnum ne '')) {
 9994:         my $now = time;
 9995:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9996:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9997:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9998:             my $instcode = $coursehash{'internal.coursecode'};
 9999:             if ($instcode ne '') {
10000:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10001:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10002:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10003:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10004:                         if ($result eq 'valid') {
10005:                             if ($coursehash{'internal.co-owners'}) {
10006:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10007:                                     push(@newcoowners,$coowner);
10008:                                 }
10009:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10010:                                     push(@newcoowners,$uname.':'.$udom);
10011:                                 }
10012:                                 @newcoowners = sort(@newcoowners);
10013:                             } else {
10014:                                 push(@newcoowners,$uname.':'.$udom);
10015:                             }
10016:                         } else {
10017:                             if ($coursehash{'internal.co-owners'}) {
10018:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10019:                                     unless ($coowner eq $uname.':'.$udom) {
10020:                                         push(@newcoowners,$coowner);
10021:                                     }
10022:                                 }
10023:                                 unless (@newcoowners > 0) {
10024:                                     $delcoowners = 1;
10025:                                     $coowners = '';
10026:                                 }
10027:                             }
10028:                         }
10029:                         if (@newcoowners || $delcoowners) {
10030:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10031:                                             $delcoowners,@newcoowners);
10032:                         }
10033:                     }
10034:                 }
10035:             }
10036:         }
10037:     }
10038: }
10039: 
10040: sub store_coowners {
10041:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10042:     my $cid = $cdom.'_'.$cnum;
10043:     my ($coowners,$delresult,$putresult);
10044:     if (@newcoowners) {
10045:         $coowners = join(',',@newcoowners);
10046:         my %coownershash = (
10047:                             'internal.co-owners' => $coowners,
10048:                            );
10049:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10050:         if ($putresult eq 'ok') {
10051:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10052:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10053:             }
10054:         }
10055:     }
10056:     if ($delcoowners) {
10057:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10058:         if ($delresult eq 'ok') {
10059:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10060:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10061:             }
10062:         }
10063:     }
10064:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10065:         my %crsinfo =
10066:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10067:         if (ref($crsinfo{$cid}) eq 'HASH') {
10068:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10069:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10070:         }
10071:     }
10072: }
10073: 
10074: # -------------------------------------------------- Modify user authentication
10075: # Overrides without validation
10076: 
10077: sub modifyuserauth {
10078:     my ($udom,$uname,$umode,$upass)=@_;
10079:     my $uhome=&homeserver($uname,$udom);
10080:     unless (&allowed('mau',$udom)) { return 'refused'; }
10081:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10082:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10083:              ' in domain '.$env{'request.role.domain'});  
10084:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10085: 		     &escape($upass),$uhome);
10086:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10087:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10088:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10089:     &log($udom,,$uname,$uhome,
10090:         'Authentication changed by '.$env{'user.domain'}.', '.
10091:                                      $env{'user.name'}.', '.$umode.
10092:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10093:     unless ($reply eq 'ok') {
10094:         &logthis('Authentication mode error: '.$reply);
10095: 	return 'error: '.$reply;
10096:     }   
10097:     return 'ok';
10098: }
10099: 
10100: # --------------------------------------------------------------- Modify a user
10101: 
10102: sub modifyuser {
10103:     my ($udom,    $uname, $uid,
10104:         $umode,   $upass, $first,
10105:         $middle,  $last,  $gene,
10106:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10107:     $udom= &LONCAPA::clean_domain($udom);
10108:     $uname=&LONCAPA::clean_username($uname);
10109:     my $showcandelete = 'none';
10110:     if (ref($candelete) eq 'ARRAY') {
10111:         if (@{$candelete} > 0) {
10112:             $showcandelete = join(', ',@{$candelete});
10113:         }
10114:     }
10115:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10116:              $umode.', '.$first.', '.$middle.', '.
10117: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10118:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10119:                                      ' desiredhome not specified'). 
10120:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10121:              ' in domain '.$env{'request.role.domain'});
10122:     my $uhome=&homeserver($uname,$udom,'true');
10123:     my $newuser;
10124:     if ($uhome eq 'no_host') {
10125:         $newuser = 1;
10126:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10127:                 ($umode eq 'lti')) {
10128:             return 'error: more information needed to create new user';
10129:         }
10130:     }
10131: # ----------------------------------------------------------------- Create User
10132:     if (($uhome eq 'no_host') && 
10133: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10134:         my $unhome='';
10135:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10136:             $unhome = $desiredhome;
10137: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10138: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10139:         } else { # load balancing routine for determining $unhome
10140:             my $loadm=10000000;
10141: 	    my %servers = &get_servers($udom,'library');
10142: 	    foreach my $tryserver (keys(%servers)) {
10143: 		my $answer=reply('load',$tryserver);
10144: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10145: 		    $loadm=$answer;
10146: 		    $unhome=$tryserver;
10147: 		}
10148: 	    }
10149:         }
10150:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10151: 	    return 'error: unable to find a home server for '.$uname.
10152:                    ' in domain '.$udom;
10153:         }
10154:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10155:                          &escape($upass),$unhome);
10156: 	unless ($reply eq 'ok') {
10157:             return 'error: '.$reply;
10158:         }   
10159:         $uhome=&homeserver($uname,$udom,'true');
10160:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10161: 	    return 'error: unable verify users home machine.';
10162:         }
10163:     }   # End of creation of new user
10164: # ---------------------------------------------------------------------- Add ID
10165:     if ($uid) {
10166:        $uid=~tr/A-Z/a-z/;
10167:        my %uidhash=&idrget($udom,$uname);
10168:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10169:          && (!$forceid)) {
10170: 	  unless ($uid eq $uidhash{$uname}) {
10171: 	      return 'error: user id "'.$uid.'" does not match '.
10172:                   'current user id "'.$uidhash{$uname}.'".';
10173:           }
10174:        } else {
10175: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10176:        }
10177:     }
10178: # -------------------------------------------------------------- Add names, etc
10179:     my @tmp=&get('environment',
10180: 		   ['firstname','middlename','lastname','generation','id',
10181:                     'permanentemail','inststatus'],
10182: 		   $udom,$uname);
10183:     my (%names,%oldnames);
10184:     if ($tmp[0] =~ m/^error:.*/) { 
10185:         %names=(); 
10186:     } else {
10187:         %names = @tmp;
10188:         %oldnames = %names;
10189:     }
10190: #
10191: # If name, email and/or uid are blank (e.g., because an uploaded file
10192: # of users did not contain them), do not overwrite existing values
10193: # unless field is in $candelete array ref.  
10194: #
10195: 
10196:     my @fields = ('firstname','middlename','lastname','generation',
10197:                   'permanentemail','id');
10198:     my %newvalues;
10199:     if (ref($candelete) eq 'ARRAY') {
10200:         foreach my $field (@fields) {
10201:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10202:                 if ($field eq 'firstname') {
10203:                     $names{$field} = $first;
10204:                 } elsif ($field eq 'middlename') {
10205:                     $names{$field} = $middle;
10206:                 } elsif ($field eq 'lastname') {
10207:                     $names{$field} = $last;
10208:                 } elsif ($field eq 'generation') { 
10209:                     $names{$field} = $gene;
10210:                 } elsif ($field eq 'permanentemail') {
10211:                     $names{$field} = $email;
10212:                 } elsif ($field eq 'id') {
10213:                     $names{$field}  = $uid;
10214:                 }
10215:             }
10216:         }
10217:     }
10218:     if ($first)  { $names{'firstname'}  = $first; }
10219:     if (defined($middle)) { $names{'middlename'} = $middle; }
10220:     if ($last)   { $names{'lastname'}   = $last; }
10221:     if (defined($gene))   { $names{'generation'} = $gene; }
10222:     if ($email) {
10223:        $email=~s/[^\w\@\.\-\,]//gs;
10224:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10225:     }
10226:     if ($uid) { $names{'id'}  = $uid; }
10227:     if (defined($inststatus)) {
10228:         $names{'inststatus'} = '';
10229:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10230:         if (ref($usertypes) eq 'HASH') {
10231:             my @okstatuses; 
10232:             foreach my $item (split(/:/,$inststatus)) {
10233:                 if (defined($usertypes->{$item})) {
10234:                     push(@okstatuses,$item);  
10235:                 }
10236:             }
10237:             if (@okstatuses) {
10238:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10239:             }
10240:         }
10241:     }
10242:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10243:                  $umode.', '.$first.', '.$middle.', '.
10244:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10245:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10246:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10247:     } else {
10248:         $logmsg .= ' during self creation';
10249:     }
10250:     my $changed;
10251:     if ($newuser) {
10252:         $changed = 1;
10253:     } else {
10254:         foreach my $field (@fields) {
10255:             if ($names{$field} ne $oldnames{$field}) {
10256:                 $changed = 1;
10257:                 last;
10258:             }
10259:         }
10260:     }
10261:     unless ($changed) {
10262:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10263:         &logthis($logmsg);
10264:         return 'ok';
10265:     }
10266:     my $reply = &put('environment', \%names, $udom,$uname);
10267:     if ($reply ne 'ok') { 
10268:         return 'error: '.$reply;
10269:     }
10270:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10271:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10272:     }
10273:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10274:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10275:     $logmsg = 'Success modifying user '.$logmsg;
10276:     &logthis($logmsg);
10277:     return 'ok';
10278: }
10279: 
10280: # -------------------------------------------------------------- Modify student
10281: 
10282: sub modifystudent {
10283:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10284:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10285:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10286:     if (!$cid) {
10287: 	unless ($cid=$env{'request.course.id'}) {
10288: 	    return 'not_in_class';
10289: 	}
10290:     }
10291: # --------------------------------------------------------------- Make the user
10292:     my $reply=&modifyuser
10293: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10294:          $desiredhome,$email,$inststatus);
10295:     unless ($reply eq 'ok') { return $reply; }
10296:     # This will cause &modify_student_enrollment to get the uid from the
10297:     # student's environment
10298:     $uid = undef if (!$forceid);
10299:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10300:                                         $gene,$usec,$end,$start,$type,$locktype,
10301:                                         $cid,$selfenroll,$context,$credits,$instsec);
10302:     return $reply;
10303: }
10304: 
10305: sub modify_student_enrollment {
10306:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10307:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10308:     my ($cdom,$cnum,$chome);
10309:     if (!$cid) {
10310: 	unless ($cid=$env{'request.course.id'}) {
10311: 	    return 'not_in_class';
10312: 	}
10313: 	$cdom=$env{'course.'.$cid.'.domain'};
10314: 	$cnum=$env{'course.'.$cid.'.num'};
10315:     } else {
10316: 	($cdom,$cnum)=split(/_/,$cid);
10317:     }
10318:     $chome=$env{'course.'.$cid.'.home'};
10319:     if (!$chome) {
10320: 	$chome=&homeserver($cnum,$cdom);
10321:     }
10322:     if (!$chome) { return 'unknown_course'; }
10323:     # Make sure the user exists
10324:     my $uhome=&homeserver($uname,$udom);
10325:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10326: 	return 'error: no such user';
10327:     }
10328:     # Get student data if we were not given enough information
10329:     if (!defined($first)  || $first  eq '' || 
10330:         !defined($last)   || $last   eq '' || 
10331:         !defined($uid)    || $uid    eq '' || 
10332:         !defined($middle) || $middle eq '' || 
10333:         !defined($gene)   || $gene   eq '') {
10334:         # They did not supply us with enough data to enroll the student, so
10335:         # we need to pick up more information.
10336:         my %tmp = &get('environment',
10337:                        ['firstname','middlename','lastname', 'generation','id']
10338:                        ,$udom,$uname);
10339: 
10340:         #foreach my $key (keys(%tmp)) {
10341:         #    &logthis("key $key = ".$tmp{$key});
10342:         #}
10343:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10344:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10345:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10346:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10347:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10348:     }
10349:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10350:     my $user = "$uname:$udom";
10351:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10352:     my $reply=cput('classlist',
10353: 		   {$user => 
10354: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10355: 		   $cdom,$cnum);
10356:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10357:         &devalidate_getsection_cache($udom,$uname,$cid);
10358:     } else { 
10359: 	return 'error: '.$reply;
10360:     }
10361:     # Add student role to user
10362:     my $uurl='/'.$cid;
10363:     $uurl=~s/\_/\//g;
10364:     if ($usec) {
10365: 	$uurl.='/'.$usec;
10366:     }
10367:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10368:                              $selfenroll,$context);
10369:     if ($result ne 'ok') {
10370:         if ($old_entry{$user} ne '') {
10371:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10372:         } else {
10373:             $reply = &del('classlist',[$user],$cdom,$cnum);
10374:         }
10375:     }
10376:     return $result; 
10377: }
10378: 
10379: sub format_name {
10380:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10381:     my $name;
10382:     if ($first ne 'lastname') {
10383: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10384:     } else {
10385: 	if ($lastname=~/\S/) {
10386: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10387: 	    $name=~s/\s+,/,/;
10388: 	} else {
10389: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10390: 	}
10391:     }
10392:     $name=~s/^\s+//;
10393:     $name=~s/\s+$//;
10394:     $name=~s/\s+/ /g;
10395:     return $name;
10396: }
10397: 
10398: # ------------------------------------------------- Write to course preferences
10399: 
10400: sub writecoursepref {
10401:     my ($courseid,%prefs)=@_;
10402:     $courseid=~s/^\///;
10403:     $courseid=~s/\_/\//g;
10404:     my ($cdomain,$cnum)=split(/\//,$courseid);
10405:     my $chome=homeserver($cnum,$cdomain);
10406:     if (($chome eq '') || ($chome eq 'no_host')) { 
10407: 	return 'error: no such course';
10408:     }
10409:     my $cstring='';
10410:     foreach my $pref (keys(%prefs)) {
10411: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10412:     }
10413:     $cstring=~s/\&$//;
10414:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10415: }
10416: 
10417: # ---------------------------------------------------------- Make/modify course
10418: 
10419: sub createcourse {
10420:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10421:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10422:     $url=&declutter($url);
10423:     my $cid='';
10424:     if ($context eq 'requestcourses') {
10425:         my $can_create = 0;
10426:         my ($ownername,$ownerdom) = split(':',$course_owner);
10427:         if ($udom eq $ownerdom) {
10428:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10429:                                   $context)) {
10430:                 $can_create = 1;
10431:             }
10432:         } else {
10433:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10434:                                            $category);
10435:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10436:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10437:                 if (@curr > 0) {
10438:                     my @options = qw(approval validate autolimit);
10439:                     my $optregex = join('|',@options);
10440:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10441:                         $can_create = 1;
10442:                     }
10443:                 }
10444:             }
10445:         }
10446:         if ($can_create) {
10447:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10448:                 unless (&allowed('ccc',$udom)) {
10449:                     return 'refused'; 
10450:                 }
10451:             }
10452:         } else {
10453:             return 'refused';
10454:         }
10455:     } elsif (!&allowed('ccc',$udom)) {
10456:         return 'refused';
10457:     }
10458: # --------------------------------------------------------------- Get Unique ID
10459:     my $uname;
10460:     if ($cnum =~ /^$match_courseid$/) {
10461:         my $chome=&homeserver($cnum,$udom,'true');
10462:         if (($chome eq '') || ($chome eq 'no_host')) {
10463:             $uname = $cnum;
10464:         } else {
10465:             $uname = &generate_coursenum($udom,$crstype);
10466:         }
10467:     } else {
10468:         $uname = &generate_coursenum($udom,$crstype);
10469:     }
10470:     return $uname if ($uname =~ /^error/);
10471: # -------------------------------------------------- Check supplied server name
10472:     if (!defined($course_server)) {
10473:         if (defined(&domain($udom,'primary'))) {
10474:             $course_server = &domain($udom,'primary');
10475:         } else {
10476:             $course_server = $env{'user.home'}; 
10477:         }
10478:     }
10479:     my %host_servers =
10480:         &Apache::lonnet::get_servers($udom,'library');
10481:     unless ($host_servers{$course_server}) {
10482:         return 'error: invalid home server for course: '.$course_server;
10483:     }
10484: # ------------------------------------------------------------- Make the course
10485:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10486:                       $course_server);
10487:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10488:     my $uhome=&homeserver($uname,$udom,'true');
10489:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10490: 	return 'error: no such course';
10491:     }
10492: # ----------------------------------------------------------------- Course made
10493: # log existence
10494:     my $now = time;
10495:     my $newcourse = {
10496:                     $udom.'_'.$uname => {
10497:                                      description => $description,
10498:                                      inst_code   => $inst_code,
10499:                                      owner       => $course_owner,
10500:                                      type        => $crstype,
10501:                                      creator     => $env{'user.name'}.':'.
10502:                                                     $env{'user.domain'},
10503:                                      created     => $now,
10504:                                      context     => $context,
10505:                                                 },
10506:                     };
10507:     &courseidput($udom,$newcourse,$uhome,'notime');
10508: # set toplevel url
10509:     my $topurl=$url;
10510:     unless ($nonstandard) {
10511: # ------------------------------------------ For standard courses, make top url
10512:         my $mapurl=&clutter($url);
10513:         if ($mapurl eq '/res/') { $mapurl=''; }
10514:         $env{'form.initmap'}=(<<ENDINITMAP);
10515: <map>
10516: <resource id="1" type="start"></resource>
10517: <resource id="2" src="$mapurl"></resource>
10518: <resource id="3" type="finish"></resource>
10519: <link index="1" from="1" to="2"></link>
10520: <link index="2" from="2" to="3"></link>
10521: </map>
10522: ENDINITMAP
10523:         $topurl=&declutter(
10524:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10525:                           );
10526:     }
10527: # ----------------------------------------------------------- Write preferences
10528:     &writecoursepref($udom.'_'.$uname,
10529:                      ('description'              => $description,
10530:                       'url'                      => $topurl,
10531:                       'internal.creator'         => $env{'user.name'}.':'.
10532:                                                     $env{'user.domain'},
10533:                       'internal.created'         => $now,
10534:                       'internal.creationcontext' => $context)
10535:                     );
10536:     return '/'.$udom.'/'.$uname;
10537: }
10538: 
10539: # ------------------------------------------------------------------- Create ID
10540: sub generate_coursenum {
10541:     my ($udom,$crstype) = @_;
10542:     my $domdesc = &domain($udom);
10543:     return 'error: invalid domain' if ($domdesc eq '');
10544:     my $first;
10545:     if ($crstype eq 'Community') {
10546:         $first = '0';
10547:     } else {
10548:         $first = int(1+rand(9)); 
10549:     } 
10550:     my $uname=$first.
10551:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10552:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10553:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10554: # ----------------------------------------------- Make sure that does not exist
10555:     my $uhome=&homeserver($uname,$udom,'true');
10556:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10557:         if ($crstype eq 'Community') {
10558:             $first = '0';
10559:         } else {
10560:             $first = int(1+rand(9));
10561:         }
10562:         $uname=$first.
10563:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10564:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10565:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10566:         $uhome=&homeserver($uname,$udom,'true');
10567:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10568:             return 'error: unable to generate unique course-ID';
10569:         }
10570:     }
10571:     return $uname;
10572: }
10573: 
10574: sub is_course {
10575:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10576:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10577: 
10578:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10579:     my $uhome=&homeserver($cnum,$cdom);
10580:     my $iscourse;
10581:     if (grep { $_ eq $uhome } current_machine_ids()) {
10582:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10583:     } else {
10584:         my $hashid = $cdom.':'.$cnum;
10585:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10586:         unless (defined($cached)) {
10587:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10588:                                         $cnum,undef,undef,'.');
10589:             $iscourse = 0;
10590:             if (exists($courses{$cdom.'_'.$cnum})) {
10591:                 $iscourse = 1;
10592:             }
10593:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10594:         }
10595:     }
10596:     return unless ($iscourse);
10597:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10598: }
10599: 
10600: sub store_userdata {
10601:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10602:     my $result;
10603:     if ($datakey ne '') {
10604:         if (ref($storehash) eq 'HASH') {
10605:             if ($udom eq '' || $uname eq '') {
10606:                 $udom = $env{'user.domain'};
10607:                 $uname = $env{'user.name'};
10608:             }
10609:             my $uhome=&homeserver($uname,$udom);
10610:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10611:                 $result = 'error: no_host';
10612:             } else {
10613:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10614:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10615: 
10616:                 my $namevalue='';
10617:                 foreach my $key (keys(%{$storehash})) {
10618:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10619:                 }
10620:                 $namevalue=~s/\&$//;
10621:                 unless ($namespace eq 'courserequests') {
10622:                     $datakey = &escape($datakey);
10623:                 }
10624:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10625:                                   $namevalue,$uhome);
10626:             }
10627:         } else {
10628:             $result = 'error: data to store was not a hash reference'; 
10629:         }
10630:     } else {
10631:         $result= 'error: invalid requestkey'; 
10632:     }
10633:     return $result;
10634: }
10635: 
10636: # ---------------------------------------------------------- Assign Custom Role
10637: 
10638: sub assigncustomrole {
10639:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10640:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10641:                        $end,$start,$deleteflag,$selfenroll,$context);
10642: }
10643: 
10644: # ----------------------------------------------------------------- Revoke Role
10645: 
10646: sub revokerole {
10647:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10648:     my $now=time;
10649:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10650: }
10651: 
10652: # ---------------------------------------------------------- Revoke Custom Role
10653: 
10654: sub revokecustomrole {
10655:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10656:     my $now=time;
10657:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10658:            $deleteflag,$selfenroll,$context);
10659: }
10660: 
10661: # ------------------------------------------------------------ Disk usage
10662: sub diskusage {
10663:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10664:     $directorypath =~ s/\/$//;
10665:     my $listing=&reply('du2:'.&escape($directorypath).':'
10666:                        .&escape($getpropath).':'.&escape($uname).':'
10667:                        .&escape($udom),homeserver($uname,$udom));
10668:     if ($listing eq 'unknown_cmd') {
10669:         if ($getpropath) {
10670:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10671:         }
10672:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10673:     }
10674:     return $listing;
10675: }
10676: 
10677: sub is_locked {
10678:     my ($file_name, $domain, $user, $which) = @_;
10679:     my @check;
10680:     my $is_locked;
10681:     push (@check,$file_name);
10682:     my %locked = &get('file_permissions',\@check,
10683: 		      $env{'user.domain'},$env{'user.name'});
10684:     my ($tmp)=keys(%locked);
10685:     if ($tmp=~/^error:/) { undef(%locked); }
10686:     
10687:     if (ref($locked{$file_name}) eq 'ARRAY') {
10688:         $is_locked = 'false';
10689:         foreach my $entry (@{$locked{$file_name}}) {
10690:            if (ref($entry) eq 'ARRAY') {
10691:                $is_locked = 'true';
10692:                if (ref($which) eq 'ARRAY') {
10693:                    push(@{$which},$entry);
10694:                } else {
10695:                    last;
10696:                }
10697:            }
10698:        }
10699:     } else {
10700:         $is_locked = 'false';
10701:     }
10702:     return $is_locked;
10703: }
10704: 
10705: sub declutter_portfile {
10706:     my ($file) = @_;
10707:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10708:     return $file;
10709: }
10710: 
10711: # ------------------------------------------------------------- Mark as Read Only
10712: 
10713: sub mark_as_readonly {
10714:     my ($domain,$user,$files,$what) = @_;
10715:     my %current_permissions = &dump('file_permissions',$domain,$user);
10716:     my ($tmp)=keys(%current_permissions);
10717:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10718:     foreach my $file (@{$files}) {
10719: 	$file = &declutter_portfile($file);
10720:         push(@{$current_permissions{$file}},$what);
10721:     }
10722:     &put('file_permissions',\%current_permissions,$domain,$user);
10723:     return;
10724: }
10725: 
10726: # ------------------------------------------------------------Save Selected Files
10727: 
10728: sub save_selected_files {
10729:     my ($user, $path, @files) = @_;
10730:     my $filename = $user."savedfiles";
10731:     my @other_files = &files_not_in_path($user, $path);
10732:     open (OUT,'>',LONCAPA::tempdir().$filename);
10733:     foreach my $file (@files) {
10734:         print (OUT $env{'form.currentpath'}.$file."\n");
10735:     }
10736:     foreach my $file (@other_files) {
10737:         print (OUT $file."\n");
10738:     }
10739:     close (OUT);
10740:     return 'ok';
10741: }
10742: 
10743: sub clear_selected_files {
10744:     my ($user) = @_;
10745:     my $filename = $user."savedfiles";
10746:     open (OUT,'>',LONCAPA::tempdir().$filename);
10747:     print (OUT undef);
10748:     close (OUT);
10749:     return ("ok");    
10750: }
10751: 
10752: sub files_in_path {
10753:     my ($user, $path) = @_;
10754:     my $filename = $user."savedfiles";
10755:     my %return_files;
10756:     open (IN,'<',LONCAPA::tempdir().$filename);
10757:     while (my $line_in = <IN>) {
10758:         chomp ($line_in);
10759:         my @paths_and_file = split (m!/!, $line_in);
10760:         my $file_part = pop (@paths_and_file);
10761:         my $path_part = join ('/', @paths_and_file);
10762:         $path_part.='/';
10763:         my $path_and_file = $path_part.$file_part;
10764:         if ($path_part eq $path) {
10765:             $return_files{$file_part}= 'selected';
10766:         }
10767:     }
10768:     close (IN);
10769:     return (\%return_files);
10770: }
10771: 
10772: # called in portfolio select mode, to show files selected NOT in current directory
10773: sub files_not_in_path {
10774:     my ($user, $path) = @_;
10775:     my $filename = $user."savedfiles";
10776:     my @return_files;
10777:     my $path_part;
10778:     open(IN, '<',LONCAPA::tempdir().$filename);
10779:     while (my $line = <IN>) {
10780:         #ok, I know it's clunky, but I want it to work
10781:         my @paths_and_file = split(m|/|, $line);
10782:         my $file_part = pop(@paths_and_file);
10783:         chomp($file_part);
10784:         my $path_part = join('/', @paths_and_file);
10785:         $path_part .= '/';
10786:         my $path_and_file = $path_part.$file_part;
10787:         if ($path_part ne $path) {
10788:             push(@return_files, ($path_and_file));
10789:         }
10790:     }
10791:     close(OUT);
10792:     return (@return_files);
10793: }
10794: 
10795: #------------------------------Submitted/Handedback Portfolio Files Versioning
10796:  
10797: sub portfiles_versioning {
10798:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10799:     my $portfolio_root = '/userfiles/portfolio';
10800:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10801:     foreach my $file (@{$portfiles}) {
10802:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10803:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10804:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10805:         my $getpropath = 1;
10806:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10807:                                              $stu_name,$getpropath);
10808:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10809:         my $new_answer = 
10810:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10811:         if ($new_answer ne 'problem getting file') {
10812:             push(@{$versioned_portfiles}, $directory.$new_answer);
10813:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10814:                               [$symb,$env{'request.course.id'},'graded']);
10815:         }
10816:     }
10817: }
10818: 
10819: sub get_next_version {
10820:     my ($answer_name, $answer_ext, $dir_list) = @_;
10821:     my $version;
10822:     if (ref($dir_list) eq 'ARRAY') {
10823:         foreach my $row (@{$dir_list}) {
10824:             my ($file) = split(/\&/,$row,2);
10825:             my ($file_name,$file_version,$file_ext) =
10826:                 &file_name_version_ext($file);
10827:             if (($file_name eq $answer_name) &&
10828:                 ($file_ext eq $answer_ext)) {
10829:                      # gets here if filename and extension match,
10830:                      # regardless of version
10831:                 if ($file_version ne '') {
10832:                     # a versioned file is found  so save it for later
10833:                     if ($file_version > $version) {
10834:                         $version = $file_version;
10835:                     }
10836:                 }
10837:             }
10838:         }
10839:     }
10840:     $version ++;
10841:     return($version);
10842: }
10843: 
10844: sub version_selected_portfile {
10845:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10846:     my ($answer_name,$answer_ver,$answer_ext) =
10847:         &file_name_version_ext($file_name);
10848:     my $new_answer;
10849:     $env{'form.copy'} =
10850:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10851:     if($env{'form.copy'} eq '-1') {
10852:         $new_answer = 'problem getting file';
10853:     } else {
10854:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10855:         my $copy_result = 
10856:             &finishuserfileupload($stu_name,$domain,'copy',
10857:                                   '/portfolio'.$directory.$new_answer);
10858:     }
10859:     undef($env{'form.copy'});
10860:     return ($new_answer);
10861: }
10862: 
10863: sub file_name_version_ext {
10864:     my ($file)=@_;
10865:     my @file_parts = split(/\./, $file);
10866:     my ($name,$version,$ext);
10867:     if (@file_parts > 1) {
10868:         $ext=pop(@file_parts);
10869:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10870:             $version=pop(@file_parts);
10871:         }
10872:         $name=join('.',@file_parts);
10873:     } else {
10874:         $name=join('.',@file_parts);
10875:     }
10876:     return($name,$version,$ext);
10877: }
10878: 
10879: #----------------------------------------------Get portfolio file permissions
10880: 
10881: sub get_portfile_permissions {
10882:     my ($domain,$user) = @_;
10883:     my %current_permissions = &dump('file_permissions',$domain,$user);
10884:     my ($tmp)=keys(%current_permissions);
10885:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10886:     return \%current_permissions;
10887: }
10888: 
10889: #---------------------------------------------Get portfolio file access controls
10890: 
10891: sub get_access_controls {
10892:     my ($current_permissions,$group,$file) = @_;
10893:     my %access;
10894:     my $real_file = $file;
10895:     $file =~ s/\.meta$//;
10896:     if (defined($file)) {
10897:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10898:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10899:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10900:             }
10901:         }
10902:     } else {
10903:         foreach my $key (keys(%{$current_permissions})) {
10904:             if ($key =~ /\0accesscontrol$/) {
10905:                 if (defined($group)) {
10906:                     if ($key !~ m-^\Q$group\E/-) {
10907:                         next;
10908:                     }
10909:                 }
10910:                 my ($fullpath) = split(/\0/,$key);
10911:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10912:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10913:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10914:                     }
10915:                 }
10916:             }
10917:         }
10918:     }
10919:     return %access;
10920: }
10921: 
10922: sub modify_access_controls {
10923:     my ($file_name,$changes,$domain,$user)=@_;
10924:     my ($outcome,$deloutcome);
10925:     my %store_permissions;
10926:     my %new_values;
10927:     my %new_control;
10928:     my %translation;
10929:     my @deletions = ();
10930:     my $now = time;
10931:     if (exists($$changes{'activate'})) {
10932:         if (ref($$changes{'activate'}) eq 'HASH') {
10933:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10934:             my $numnew = scalar(@newitems);
10935:             for (my $i=0; $i<$numnew; $i++) {
10936:                 my $newkey = $newitems[$i];
10937:                 my $newid = &Apache::loncommon::get_cgi_id();
10938:                 if ($newkey =~ /^\d+:/) { 
10939:                     $newkey =~ s/^(\d+)/$newid/;
10940:                     $translation{$1} = $newid;
10941:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10942:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10943:                     $translation{$1} = $newid;
10944:                 }
10945:                 $new_values{$file_name."\0".$newkey} = 
10946:                                           $$changes{'activate'}{$newitems[$i]};
10947:                 $new_control{$newkey} = $now;
10948:             }
10949:         }
10950:     }
10951:     my %todelete;
10952:     my %changed_items;
10953:     foreach my $action ('delete','update') {
10954:         if (exists($$changes{$action})) {
10955:             if (ref($$changes{$action}) eq 'HASH') {
10956:                 foreach my $key (keys(%{$$changes{$action}})) {
10957:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10958:                     if ($action eq 'delete') { 
10959:                         $todelete{$itemnum} = 1;
10960:                     } else {
10961:                         $changed_items{$itemnum} = $key;
10962:                     }
10963:                 }
10964:             }
10965:         }
10966:     }
10967:     # get lock on access controls for file.
10968:     my $lockhash = {
10969:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10970:                                                        ':'.$env{'user.domain'},
10971:                    }; 
10972:     my $tries = 0;
10973:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10974:    
10975:     while (($gotlock ne 'ok') && $tries < 10) {
10976:         $tries ++;
10977:         sleep(0.1);
10978:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10979:     }
10980:     if ($gotlock eq 'ok') {
10981:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10982:         my ($tmp)=keys(%curr_permissions);
10983:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10984:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10985:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10986:             if (ref($curr_controls) eq 'HASH') {
10987:                 foreach my $control_item (keys(%{$curr_controls})) {
10988:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10989:                     if (defined($todelete{$itemnum})) {
10990:                         push(@deletions,$file_name."\0".$control_item);
10991:                     } else {
10992:                         if (defined($changed_items{$itemnum})) {
10993:                             $new_control{$changed_items{$itemnum}} = $now;
10994:                             push(@deletions,$file_name."\0".$control_item);
10995:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10996:                         } else {
10997:                             $new_control{$control_item} = $$curr_controls{$control_item};
10998:                         }
10999:                     }
11000:                 }
11001:             }
11002:         }
11003:         my ($group);
11004:         if (&is_course($domain,$user)) {
11005:             ($group,my $file) = split(/\//,$file_name,2);
11006:         }
11007:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11008:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11009:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11010:         #  remove lock
11011:         my @del_lock = ($file_name."\0".'locked_access_records');
11012:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11013:         my $sqlresult =
11014:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11015:                                     $group);
11016:     } else {
11017:         $outcome = "error: could not obtain lockfile\n";  
11018:     }
11019:     return ($outcome,$deloutcome,\%new_values,\%translation);
11020: }
11021: 
11022: sub make_public_indefinitely {
11023:     my (@requrl) = @_;
11024:     return &automated_portfile_access('public',\@requrl);
11025: }
11026: 
11027: sub automated_portfile_access {
11028:     my ($accesstype,$addsref,$delsref,$info) = @_;
11029:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11030:         return 'invalid';
11031:     }
11032:     my %urls;
11033:     if (ref($addsref) eq 'ARRAY') {
11034:         foreach my $requrl (@{$addsref}) {
11035:             if (&is_portfolio_url($requrl)) {
11036:                 unless (exists($urls{$requrl})) {
11037:                     $urls{$requrl} = 'add';
11038:                 }
11039:             }
11040:         }
11041:     }
11042:     if (ref($delsref) eq 'ARRAY') {
11043:         foreach my $requrl (@{$delsref}) { 
11044:             if (&is_portfolio_url($requrl)) {
11045:                 unless (exists($urls{$requrl})) {
11046:                     $urls{$requrl} = 'delete'; 
11047:                 }
11048:             }
11049:         }
11050:     }
11051:     unless (keys(%urls)) {
11052:         return 'invalid';
11053:     }
11054:     my $ip;
11055:     if ($accesstype eq 'ip') {
11056:         if (ref($info) eq 'HASH') {
11057:             if ($info->{'ip'} ne '') {
11058:                 $ip = $info->{'ip'};
11059:             }
11060:         }
11061:         if ($ip eq '') {
11062:             return 'invalid';
11063:         }
11064:     }
11065:     my $errors;
11066:     my $now = time;
11067:     my %current_perms;
11068:     foreach my $requrl (sort(keys(%urls))) {
11069:         my $action;
11070:         if ($urls{$requrl} eq 'add') {
11071:             $action = 'activate';
11072:         } else {
11073:             $action = 'none';
11074:         }
11075:         my $aclnum = 0;
11076:         my (undef,$udom,$unum,$file_name,$group) =
11077:             &parse_portfolio_url($requrl);
11078:         unless (exists($current_perms{$unum.':'.$udom})) {
11079:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11080:         }
11081:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11082:                                                    $group,$file_name);
11083:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11084:             my ($num,$scope,$end,$start) = 
11085:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11086:             if ($scope eq $accesstype) {
11087:                 if (($start <= $now) && ($end == 0)) {
11088:                     if ($accesstype eq 'ip') {
11089:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11090:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11091:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11092:                                     if ($urls{$requrl} eq 'add') {
11093:                                         $action = 'none';
11094:                                         last;
11095:                                     } else {
11096:                                         $action = 'delete';
11097:                                         $aclnum = $num;
11098:                                         last;
11099:                                     }
11100:                                 }
11101:                             }
11102:                         }
11103:                     } elsif ($accesstype eq 'public') {
11104:                         if ($urls{$requrl} eq 'add') {
11105:                             $action = 'none';
11106:                             last;
11107:                         } else {
11108:                             $action = 'delete';
11109:                             $aclnum = $num;
11110:                             last;
11111:                         }
11112:                     }
11113:                 } elsif ($accesstype eq 'public') {
11114:                     $action = 'update';
11115:                     $aclnum = $num;
11116:                     last;
11117:                 }
11118:             }
11119:         }
11120:         if ($action eq 'none') {
11121:             next;
11122:         } else {
11123:             my %changes;
11124:             my $newend = 0;
11125:             my $newstart = $now;
11126:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11127:             $changes{$action}{$newkey} = {
11128:                 type => $accesstype,
11129:                 time => {
11130:                     start => $newstart,
11131:                     end   => $newend,
11132:                 },
11133:             };
11134:             if ($accesstype eq 'ip') {
11135:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11136:             }
11137:             my ($outcome,$deloutcome,$new_values,$translation) =
11138:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11139:             unless ($outcome eq 'ok') {
11140:                 $errors .= $outcome.' ';
11141:             }
11142:         }
11143:     }
11144:     if ($errors) {
11145:         $errors =~ s/\s$//;
11146:         return $errors;
11147:     } else {
11148:         return 'ok';
11149:     }
11150: }
11151: 
11152: #------------------------------------------------------Get Marked as Read Only
11153: 
11154: sub get_marked_as_readonly {
11155:     my ($domain,$user,$what,$group) = @_;
11156:     my $current_permissions = &get_portfile_permissions($domain,$user);
11157:     my @readonly_files;
11158:     my $cmp1=$what;
11159:     if (ref($what)) { $cmp1=join('',@{$what}) };
11160:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11161:         if (defined($group)) {
11162:             if ($file_name !~ m-^\Q$group\E/-) {
11163:                 next;
11164:             }
11165:         }
11166:         if (ref($value) eq "ARRAY"){
11167:             foreach my $stored_what (@{$value}) {
11168:                 my $cmp2=$stored_what;
11169:                 if (ref($stored_what) eq 'ARRAY') {
11170:                     $cmp2=join('',@{$stored_what});
11171:                 }
11172:                 if ($cmp1 eq $cmp2) {
11173:                     push(@readonly_files, $file_name);
11174:                     last;
11175:                 } elsif (!defined($what)) {
11176:                     push(@readonly_files, $file_name);
11177:                     last;
11178:                 }
11179:             }
11180:         }
11181:     }
11182:     return @readonly_files;
11183: }
11184: #-----------------------------------------------------------Get Marked as Read Only Hash
11185: 
11186: sub get_marked_as_readonly_hash {
11187:     my ($current_permissions,$group,$what) = @_;
11188:     my %readonly_files;
11189:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11190:         if (defined($group)) {
11191:             if ($file_name !~ m-^\Q$group\E/-) {
11192:                 next;
11193:             }
11194:         }
11195:         if (ref($value) eq "ARRAY"){
11196:             foreach my $stored_what (@{$value}) {
11197:                 if (ref($stored_what) eq 'ARRAY') {
11198:                     foreach my $lock_descriptor(@{$stored_what}) {
11199:                         if ($lock_descriptor eq 'graded') {
11200:                             $readonly_files{$file_name} = 'graded';
11201:                         } elsif ($lock_descriptor eq 'handback') {
11202:                             $readonly_files{$file_name} = 'handback';
11203:                         } else {
11204:                             if (!exists($readonly_files{$file_name})) {
11205:                                 $readonly_files{$file_name} = 'locked';
11206:                             }
11207:                         }
11208:                     }
11209:                 } 
11210:             }
11211:         } 
11212:     }
11213:     return %readonly_files;
11214: }
11215: # ------------------------------------------------------------ Unmark as Read Only
11216: 
11217: sub unmark_as_readonly {
11218:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11219:     # for portfolio submissions, $what contains [$symb,$crsid] 
11220:     my ($domain,$user,$what,$file_name,$group) = @_;
11221:     $file_name = &declutter_portfile($file_name);
11222:     my $symb_crs = $what;
11223:     if (ref($what)) { $symb_crs=join('',@$what); }
11224:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11225:     my ($tmp)=keys(%current_permissions);
11226:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11227:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11228:     foreach my $file (@readonly_files) {
11229: 	my $clean_file = &declutter_portfile($file);
11230: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11231: 	my $current_locks = $current_permissions{$file};
11232:         my @new_locks;
11233:         my @del_keys;
11234:         if (ref($current_locks) eq "ARRAY"){
11235:             foreach my $locker (@{$current_locks}) {
11236:                 my $compare=$locker;
11237:                 if (ref($locker) eq 'ARRAY') {
11238:                     $compare=join('',@{$locker});
11239:                     if ($compare ne $symb_crs) {
11240:                         push(@new_locks, $locker);
11241:                     }
11242:                 }
11243:             }
11244:             if (scalar(@new_locks) > 0) {
11245:                 $current_permissions{$file} = \@new_locks;
11246:             } else {
11247:                 push(@del_keys, $file);
11248:                 &del('file_permissions',\@del_keys, $domain, $user);
11249:                 delete($current_permissions{$file});
11250:             }
11251:         }
11252:     }
11253:     &put('file_permissions',\%current_permissions,$domain,$user);
11254:     return;
11255: }
11256: 
11257: # ------------------------------------------------------------ Directory lister
11258: 
11259: sub dirlist {
11260:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11261:     $uri=~s/^\///;
11262:     $uri=~s/\/$//;
11263:     my ($udom, $uname);
11264:     if ($getuserdir) {
11265:         $udom = $userdomain;
11266:         $uname = $username;
11267:     } else {
11268:         (undef,$udom,$uname)=split(/\//,$uri);
11269:         if(defined($userdomain)) {
11270:             $udom = $userdomain;
11271:         }
11272:         if(defined($username)) {
11273:             $uname = $username;
11274:         }
11275:     }
11276:     my ($dirRoot,$listing,@listing_results);
11277: 
11278:     $dirRoot = $perlvar{'lonDocRoot'};
11279:     if (defined($getpropath)) {
11280:         $dirRoot = &propath($udom,$uname);
11281:         $dirRoot =~ s/\/$//;
11282:     } elsif (defined($getuserdir)) {
11283:         my $subdir=$uname.'__';
11284:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11285:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11286:                    ."/$udom/$subdir/$uname";
11287:     } elsif (defined($alternateRoot)) {
11288:         $dirRoot = $alternateRoot;
11289:     }
11290: 
11291:     if($udom) {
11292:         if($uname) {
11293:             my $uhome = &homeserver($uname,$udom);
11294:             if ($uhome eq 'no_host') {
11295:                 return ([],'no_host');
11296:             }
11297:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11298:                               .$getuserdir.':'.&escape($dirRoot)
11299:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11300:             if ($listing eq 'unknown_cmd') {
11301:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11302:             } else {
11303:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11304:             }
11305:             if ($listing eq 'unknown_cmd') {
11306:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11307:                 @listing_results = split(/:/,$listing);
11308:             } else {
11309:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11310:             }
11311:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11312:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11313:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11314:                 return ([],$listing);
11315:             } else {
11316:                 return (\@listing_results);
11317:             }
11318:         } elsif(!$alternateRoot) {
11319:             my (%allusers,%listerror);
11320: 	    my %servers = &get_servers($udom,'library');
11321:  	    foreach my $tryserver (keys(%servers)) {
11322:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11323:                                   &escape($udom),$tryserver);
11324:                 if ($listing eq 'unknown_cmd') {
11325: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11326: 				      $udom, $tryserver);
11327:                 } else {
11328:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11329:                 }
11330: 		if ($listing eq 'unknown_cmd') {
11331: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11332: 				      $udom, $tryserver);
11333: 		    @listing_results = split(/:/,$listing);
11334: 		} else {
11335: 		    @listing_results =
11336: 			map { &unescape($_); } split(/:/,$listing);
11337: 		}
11338:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11339:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11340:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11341:                     $listerror{$tryserver} = $listing;
11342:                 } else {
11343: 		    foreach my $line (@listing_results) {
11344: 			my ($entry) = split(/&/,$line,2);
11345: 			$allusers{$entry} = 1;
11346: 		    }
11347: 		}
11348:             }
11349:             my @alluserslist=();
11350:             foreach my $user (sort(keys(%allusers))) {
11351:                 push(@alluserslist,$user.'&user');
11352:             }
11353: 
11354:             if (!%listerror) {
11355:                 # no errors
11356:                 return (\@alluserslist);
11357:             } elsif (scalar(keys(%servers)) == 1) {
11358:                 # one library server, one error 
11359:                 my ($key) = keys(%listerror);
11360:                 return (\@alluserslist, $listerror{$key});
11361:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11362:                 # con_lost indicates that we might miss data from at least one
11363:                 # library server
11364:                 return (\@alluserslist, 'con_lost');
11365:             } else {
11366:                 # multiple library servers and no con_lost -> data should be
11367:                 # complete. 
11368:                 return (\@alluserslist);
11369:             }
11370: 
11371:         } else {
11372:             return ([],'missing username');
11373:         }
11374:     } elsif(!defined($getpropath)) {
11375:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11376:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11377:         return (\@all_domains);
11378:     } else {
11379:         return ([],'missing domain');
11380:     }
11381: }
11382: 
11383: # --------------------------------------------- GetFileTimestamp
11384: # This function utilizes dirlist and returns the date stamp for
11385: # when it was last modified.  It will also return an error of -1
11386: # if an error occurs
11387: 
11388: sub GetFileTimestamp {
11389:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11390:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11391:     $studentName   = &LONCAPA::clean_username($studentName);
11392:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11393:                                     undef,$getuserdir);
11394:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11395:         return -1;
11396:     }
11397:     if (ref($fileref) eq 'ARRAY') {
11398:         my @stats = split('&',$fileref->[0]);
11399:         # @stats contains first the filename, then the stat output
11400:         return $stats[10]; # so this is 10 instead of 9.
11401:     } else {
11402:         return -1;
11403:     }
11404: }
11405: 
11406: sub stat_file {
11407:     my ($uri) = @_;
11408:     $uri = &clutter_with_no_wrapper($uri);
11409: 
11410:     my ($udom,$uname,$file);
11411:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11412: 	($udom,$uname,$file) =
11413: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11414: 	$file = 'userfiles/'.$file;
11415:     }
11416:     if ($uri =~ m-^/res/-) {
11417: 	($udom,$uname) = 
11418: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11419: 	$file = $uri;
11420:     }
11421: 
11422:     if (!$udom || !$uname || !$file) {
11423: 	# unable to handle the uri
11424: 	return ();
11425:     }
11426:     my $getpropath;
11427:     if ($file =~ /^userfiles\//) {
11428:         $getpropath = 1;
11429:     }
11430:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11431:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11432:         return ();
11433:     } else {
11434:         if (ref($listref) eq 'ARRAY') {
11435:             my @stats = split('&',$listref->[0]);
11436: 	    shift(@stats); #filename is first
11437: 	    return @stats;
11438:         }
11439:     }
11440:     return ();
11441: }
11442: 
11443: # --------------------------------------------------------- recursedirs
11444: # Recursive function to traverse either a specific user's Authoring Space
11445: # or corresponding Published Resource Space, and populate the hash ref:
11446: # $dirhashref with URLs of all directories, and if $filehashref hash
11447: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11448: # or .rights files in resource space, and .meta, .save, .log, and .bak
11449: # files in Authoring Space.
11450: #
11451: # Inputs:
11452: #
11453: # $is_home - true if current server is home server for user's space
11454: # $context - either: priv, or res respectively for Authoring or Resource Space.
11455: # $docroot - Document root (i.e., /home/httpd/html
11456: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11457: # $relpath - Current path (relative to top level).
11458: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11459: # $filehashref - reference to hash to populate with URLs of files (Optional)
11460: #
11461: # Returns: nothing
11462: #
11463: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11464: #
11465: # Currently used by interface/londocs.pm to create linked select boxes for
11466: # directory and filename to import a Course "Author" resource into a course, and
11467: # also to create linked select boxes for Authoring Space and Directory to choose
11468: # save location for creation of a new "standard" problem from the Course Editor.
11469: #
11470: 
11471: sub recursedirs {
11472:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11473:     return unless (ref($dirhashref) eq 'HASH');
11474:     my $currpath = $docroot.$toppath;
11475:     if ($relpath) {
11476:         $currpath .= "/$relpath";
11477:     }
11478:     my $savefile;
11479:     if (ref($filehashref)) {
11480:         $savefile = 1;
11481:     }
11482:     if ($is_home) {
11483:         if (opendir(my $dirh,$currpath)) {
11484:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11485:                 next if ($item eq '');
11486:                 if (-d "$currpath/$item") {
11487:                     my $newpath;
11488:                     if ($relpath) {
11489:                         $newpath = "$relpath/$item";
11490:                     } else {
11491:                         $newpath = $item;
11492:                     }
11493:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11494:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11495:                 } elsif ($savefile) {
11496:                     if ($context eq 'priv') {
11497:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11498:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11499:                         }
11500:                     } else {
11501:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11502:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11503:                         }
11504:                     }
11505:                 }
11506:             }
11507:             closedir($dirh);
11508:         }
11509:     } else {
11510:         my ($dirlistref,$listerror) =
11511:             &dirlist($toppath.$relpath);
11512:         my @dir_lines;
11513:         my $dirptr=16384;
11514:         if (ref($dirlistref) eq 'ARRAY') {
11515:             foreach my $dir_line (sort
11516:                               {
11517:                                   my ($afile)=split('&',$a,2);
11518:                                   my ($bfile)=split('&',$b,2);
11519:                                   return (lc($afile) cmp lc($bfile));
11520:                               } (@{$dirlistref})) {
11521:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11522:                     split(/\&/,$dir_line,16);
11523:                 $item =~ s/\s+$//;
11524:                 next if (($item =~ /^\.\.?$/) || ($obs));
11525:                 if ($dirptr&$testdir) {
11526:                     my $newpath;
11527:                     if ($relpath) {
11528:                         $newpath = "$relpath/$item";
11529:                     } else {
11530:                         $relpath = '/';
11531:                         $newpath = $item;
11532:                     }
11533:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11534:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11535:                 } elsif ($savefile) {
11536:                     if ($context eq 'priv') {
11537:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11538:                             $filehashref->{$relpath}{$item} = 1;
11539:                         }
11540:                     } else {
11541:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11542:                             $filehashref->{$relpath}{$item} = 1;
11543:                         }
11544:                     }
11545:                 }
11546:             }
11547:         }
11548:     }
11549:     return;
11550: }
11551: 
11552: # -------------------------------------------------------- Value of a Condition
11553: 
11554: # gets the value of a specific preevaluated condition
11555: #    stored in the string  $env{user.state.<cid>}
11556: # or looks up a condition reference in the bighash and if if hasn't
11557: # already been evaluated recurses into docondval to get the value of
11558: # the condition, then memoizing it to 
11559: #   $env{user.state.<cid>.<condition>}
11560: sub directcondval {
11561:     my $number=shift;
11562:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11563: 	&Apache::lonuserstate::evalstate();
11564:     }
11565:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11566: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11567:     } elsif ($number =~ /^_/) {
11568: 	my $sub_condition;
11569: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11570: 		&GDBM_READER(),0640)) {
11571: 	    $sub_condition=$bighash{'conditions'.$number};
11572: 	    untie(%bighash);
11573: 	}
11574: 	my $value = &docondval($sub_condition);
11575: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11576: 	return $value;
11577:     }
11578:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11579:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11580:     } else {
11581:        return 2;
11582:     }
11583: }
11584: 
11585: # get the collection of conditions for this resource
11586: sub condval {
11587:     my $condidx=shift;
11588:     my $allpathcond='';
11589:     foreach my $cond (split(/\|/,$condidx)) {
11590: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11591: 	    $allpathcond.=
11592: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11593: 	}
11594:     }
11595:     $allpathcond=~s/\|$//;
11596:     return &docondval($allpathcond);
11597: }
11598: 
11599: #evaluates an expression of conditions
11600: sub docondval {
11601:     my ($allpathcond) = @_;
11602:     my $result=0;
11603:     if ($env{'request.course.id'}
11604: 	&& defined($allpathcond)) {
11605: 	my $operand='|';
11606: 	my @stack;
11607: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11608: 	    if ($chunk eq '(') {
11609: 		push @stack,($operand,$result);
11610: 	    } elsif ($chunk eq ')') {
11611: 		my $before=pop @stack;
11612: 		if (pop @stack eq '&') {
11613: 		    $result=$result>$before?$before:$result;
11614: 		} else {
11615: 		    $result=$result>$before?$result:$before;
11616: 		}
11617: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11618: 		$operand=$chunk;
11619: 	    } else {
11620: 		my $new=directcondval($chunk);
11621: 		if ($operand eq '&') {
11622: 		    $result=$result>$new?$new:$result;
11623: 		} else {
11624: 		    $result=$result>$new?$result:$new;
11625: 		}
11626: 	    }
11627: 	}
11628:     }
11629:     return $result;
11630: }
11631: 
11632: # ---------------------------------------------------- Devalidate courseresdata
11633: 
11634: sub devalidatecourseresdata {
11635:     my ($coursenum,$coursedomain)=@_;
11636:     my $hashid=$coursenum.':'.$coursedomain;
11637:     &devalidate_cache_new('courseres',$hashid);
11638: }
11639: 
11640: 
11641: # --------------------------------------------------- Course Resourcedata Query
11642: #
11643: #  Parameters:
11644: #      $coursenum    - Number of the course.
11645: #      $coursedomain - Domain at which the course was created.
11646: #  Returns:
11647: #     A hash of the course parameters along (I think) with timestamps
11648: #     and version info.
11649: 
11650: sub get_courseresdata {
11651:     my ($coursenum,$coursedomain)=@_;
11652:     my $coursehom=&homeserver($coursenum,$coursedomain);
11653:     my $hashid=$coursenum.':'.$coursedomain;
11654:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11655:     my %dumpreply;
11656:     unless (defined($cached)) {
11657: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11658: 	$result=\%dumpreply;
11659: 	my ($tmp) = keys(%dumpreply);
11660: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11661: 	    &do_cache_new('courseres',$hashid,$result,600);
11662: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11663: 	    return $tmp;
11664: 	} elsif ($tmp =~ /^(error)/) {
11665: 	    $result=undef;
11666: 	    &do_cache_new('courseres',$hashid,$result,600);
11667: 	}
11668:     }
11669:     return $result;
11670: }
11671: 
11672: sub devalidateuserresdata {
11673:     my ($uname,$udom)=@_;
11674:     my $hashid="$udom:$uname";
11675:     &devalidate_cache_new('userres',$hashid);
11676: }
11677: 
11678: sub get_userresdata {
11679:     my ($uname,$udom)=@_;
11680:     #most student don\'t have any data set, check if there is some data
11681:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11682: 
11683:     my $hashid="$udom:$uname";
11684:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11685:     if (!defined($cached)) {
11686: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11687: 	$result=\%resourcedata;
11688: 	&do_cache_new('userres',$hashid,$result,600);
11689:     }
11690:     my ($tmp)=keys(%$result);
11691:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11692: 	return $result;
11693:     }
11694:     #error 2 occurs when the .db doesn't exist
11695:     if ($tmp!~/error: 2 /) {
11696:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11697: 	    &logthis("<font color=\"blue\">WARNING:".
11698: 		     " Trying to get resource data for ".
11699: 		     $uname." at ".$udom.": ".
11700: 		     $tmp."</font>");
11701:         }
11702:     } elsif ($tmp=~/error: 2 /) {
11703: 	#&EXT_cache_set($udom,$uname);
11704: 	&do_cache_new('userres',$hashid,undef,600);
11705: 	undef($tmp); # not really an error so don't send it back
11706:     }
11707:     return $tmp;
11708: }
11709: #----------------------------------------------- resdata - return resource data
11710: #  Purpose:
11711: #    Return resource data for either users or for a course.
11712: #  Parameters:
11713: #     $name      - Course/user name.
11714: #     $domain    - Name of the domain the user/course is registered on.
11715: #     $type      - Type of thing $name is (must be 'course' or 'user')
11716: #     $mapp      - decluttered URL of enclosing map  
11717: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11718: #     $recurseup - Ref to array of map URLs, starting with map containing
11719: #                  $mapp up through hierarchy of nested maps to top level map.  
11720: #     $courseid  - CourseID (first part of param identifier).
11721: #     $modifier  - Middle part of param identifier.
11722: #     $what      - Last part of param identifier.
11723: #     @which     - Array of names of resources desired.
11724: #  Returns:
11725: #     The value of the first reasource in @which that is found in the
11726: #     resource hash.
11727: #  Exceptional Conditions:
11728: #     If the $type passed in is not valid (not the string 'course' or 
11729: #     'user', an undefined  reference is returned.
11730: #     If none of the resources are found, an undef is returned
11731: sub resdata {
11732:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11733:         $modifier,$what,@which)=@_;
11734:     my $result;
11735:     if ($type eq 'course') {
11736: 	$result=&get_courseresdata($name,$domain);
11737:     } elsif ($type eq 'user') {
11738: 	$result=&get_userresdata($name,$domain);
11739:     }
11740:     if (!ref($result)) { return $result; }    
11741:     foreach my $item (@which) {
11742:         if ($item->[1] eq 'course') {
11743:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11744:                 unless ($$recursed) {
11745:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11746:                     $$recursed = 1;
11747:                 }
11748:                 foreach my $item (@${recurseup}) {
11749:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11750:                     last if (defined($result->{$norecursechk}));
11751:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11752:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11753:                 }
11754:             }
11755:         }
11756:         if (defined($result->{$item->[0]})) {
11757: 	    return [$result->{$item->[0]},$item->[1]];
11758: 	}
11759:     }
11760:     return undef;
11761: }
11762: 
11763: sub get_domain_lti {
11764:     my ($cdom,$context) = @_;
11765:     my ($name,%lti);
11766:     if ($context eq 'consumer') {
11767:         $name = 'ltitools';
11768:     } elsif ($context eq 'provider') {
11769:         $name = 'lti';
11770:     } else {
11771:         return %lti;
11772:     }
11773:     my ($result,$cached)=&is_cached_new($name,$cdom);
11774:     if (defined($cached)) {
11775:         if (ref($result) eq 'HASH') {
11776:             %lti = %{$result};
11777:         }
11778:     } else {
11779:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11780:         if (ref($domconfig{$name}) eq 'HASH') {
11781:             %lti = %{$domconfig{$name}};
11782:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11783:             if (ref($encdomconfig{$name}) eq 'HASH') {
11784:                 foreach my $id (keys(%lti)) {
11785:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11786:                         foreach my $item ('key','secret') {
11787:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11788:                         }
11789:                     }
11790:                 }
11791:             }
11792:         }
11793:         my $cachetime = 24*60*60;
11794:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11795:     }
11796:     return %lti;
11797: }
11798: 
11799: sub get_numsuppfiles {
11800:     my ($cnum,$cdom,$ignorecache)=@_;
11801:     my $hashid=$cnum.':'.$cdom;
11802:     my ($suppcount,$cached);
11803:     unless ($ignorecache) {
11804:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11805:     }
11806:     unless (defined($cached)) {
11807:         my $chome=&homeserver($cnum,$cdom);
11808:         unless ($chome eq 'no_host') {
11809:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11810:             my $suppmap = 'supplemental.sequence';
11811:             ($suppcount,$supptools,$errors) =
11812:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11813:                                                          $supptools,$errors);
11814:         }
11815:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11816:     }
11817:     return $suppcount;
11818: }
11819: 
11820: #
11821: # EXT resource caching routines
11822: #
11823: 
11824: {
11825: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11826: #
11827: # The course for which we cache
11828: my $cachedmapkey='';
11829: # The cached recursive maps for this course
11830: my %cachedmaps=();
11831: # When this was last done
11832: my $cachedmaptime='';
11833: 
11834: sub clear_EXT_cache_status {
11835:     &delenv('cache.EXT.');
11836: }
11837: 
11838: sub EXT_cache_status {
11839:     my ($target_domain,$target_user) = @_;
11840:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11841:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11842:         # We know already the user has no data
11843:         return 1;
11844:     } else {
11845:         return 0;
11846:     }
11847: }
11848: 
11849: sub EXT_cache_set {
11850:     my ($target_domain,$target_user) = @_;
11851:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11852:     #&appenv({$cachename => time});
11853: }
11854: 
11855: # --------------------------------------------------------- Value of a Variable
11856: sub EXT {
11857: 
11858:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11859:     unless ($varname) { return ''; }
11860:     #get real user name/domain, courseid and symb
11861:     my $courseid;
11862:     my $publicuser;
11863:     if ($symbparm) {
11864: 	$symbparm=&get_symb_from_alias($symbparm);
11865:     }
11866:     if (!($uname && $udom)) {
11867:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11868:       if (!$symbparm) {	$symbparm=$cursymb; }
11869:     } else {
11870: 	$courseid=$env{'request.course.id'};
11871:     }
11872:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11873:     my $rest;
11874:     if (defined($therest[0])) {
11875:        $rest=join('.',@therest);
11876:     } else {
11877:        $rest='';
11878:     }
11879: 
11880:     my $qualifierrest=$qualifier;
11881:     if ($rest) { $qualifierrest.='.'.$rest; }
11882:     my $spacequalifierrest=$space;
11883:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11884:     if ($realm eq 'user') {
11885: # --------------------------------------------------------------- user.resource
11886: 	if ($space eq 'resource') {
11887: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11888: 		  || defined($Apache::lonhomework::parsing_a_task))
11889: 		 &&
11890: 		 ($symbparm eq &symbread()) ) {	
11891: 		# if we are in the middle of processing the resource the
11892: 		# get the value we are planning on committing
11893:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11894:                     return $Apache::lonhomework::results{$qualifierrest};
11895:                 } else {
11896:                     return $Apache::lonhomework::history{$qualifierrest};
11897:                 }
11898: 	    } else {
11899: 		my %restored;
11900: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11901: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11902: 		} else {
11903: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11904: 		}
11905: 		return $restored{$qualifierrest};
11906: 	    }
11907: # ----------------------------------------------------------------- user.access
11908:         } elsif ($space eq 'access') {
11909: 	    # FIXME - not supporting calls for a specific user
11910:             return &allowed($qualifier,$rest);
11911: # ------------------------------------------ user.preferences, user.environment
11912:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11913: 	    if (($uname eq $env{'user.name'}) &&
11914: 		($udom eq $env{'user.domain'})) {
11915: 		return $env{join('.',('environment',$qualifierrest))};
11916: 	    } else {
11917: 		my %returnhash;
11918: 		if (!$publicuser) {
11919: 		    %returnhash=&userenvironment($udom,$uname,
11920: 						 $qualifierrest);
11921: 		}
11922: 		return $returnhash{$qualifierrest};
11923: 	    }
11924: # ----------------------------------------------------------------- user.course
11925:         } elsif ($space eq 'course') {
11926: 	    # FIXME - not supporting calls for a specific user
11927:             return $env{join('.',('request.course',$qualifier))};
11928: # ------------------------------------------------------------------- user.role
11929:         } elsif ($space eq 'role') {
11930: 	    # FIXME - not supporting calls for a specific user
11931:             my ($role,$where)=split(/\./,$env{'request.role'});
11932:             if ($qualifier eq 'value') {
11933: 		return $role;
11934:             } elsif ($qualifier eq 'extent') {
11935:                 return $where;
11936:             }
11937: # ----------------------------------------------------------------- user.domain
11938:         } elsif ($space eq 'domain') {
11939:             return $udom;
11940: # ------------------------------------------------------------------- user.name
11941:         } elsif ($space eq 'name') {
11942:             return $uname;
11943: # ---------------------------------------------------- Any other user namespace
11944:         } else {
11945: 	    my %reply;
11946: 	    if (!$publicuser) {
11947: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11948: 	    }
11949: 	    return $reply{$qualifierrest};
11950:         }
11951:     } elsif ($realm eq 'query') {
11952: # ---------------------------------------------- pull stuff out of query string
11953:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11954: 						[$spacequalifierrest]);
11955: 	return $env{'form.'.$spacequalifierrest}; 
11956:    } elsif ($realm eq 'request') {
11957: # ------------------------------------------------------------- request.browser
11958:         if ($space eq 'browser') {
11959:             return $env{'browser.'.$qualifier};
11960: # ------------------------------------------------------------ request.filename
11961:         } else {
11962:             return $env{'request.'.$spacequalifierrest};
11963:         }
11964:     } elsif ($realm eq 'course') {
11965: # ---------------------------------------------------------- course.description
11966:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11967:     } elsif ($realm eq 'resource') {
11968: 
11969: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11970: 	    if (!$symbparm) { $symbparm=&symbread(); }
11971: 	}
11972: 
11973:         if ($qualifier eq '') {
11974: 	    if ($space eq 'title') {
11975: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11976: 	        return &gettitle($symbparm);
11977: 	    }
11978: 	
11979: 	    if ($space eq 'map') {
11980: 	        my ($map) = &decode_symb($symbparm);
11981: 	        return &symbread($map);
11982: 	    }
11983:             if ($space eq 'maptitle') {
11984:                 my ($map) = &decode_symb($symbparm);
11985:                 return &gettitle($map);
11986:             }
11987: 	    if ($space eq 'filename') {
11988: 	        if ($symbparm) {
11989: 		    return &clutter((&decode_symb($symbparm))[2]);
11990: 	        }
11991: 	        return &hreflocation('',$env{'request.filename'});
11992: 	    }
11993: 
11994:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11995:                 if ($space eq 'visibleparts') {
11996:                     my $navmap = Apache::lonnavmaps::navmap->new();
11997:                     my $item;
11998:                     if (ref($navmap)) {
11999:                         my $res = $navmap->getBySymb($symbparm);
12000:                         my $parts = $res->parts();
12001:                         if (ref($parts) eq 'ARRAY') {
12002:                             $item = join(',',@{$parts});
12003:                         }
12004:                         undef($navmap);
12005:                     }
12006:                     return $item;
12007:                 }
12008:             }
12009:         }
12010: 
12011: 	my ($section, $group, @groups, @recurseup, $recursed);
12012: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12013:         if (($courseid eq '') && ($cid)) {
12014:             $courseid = $cid;
12015:         }
12016: 	if (($symbparm && $courseid) && 
12017: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12018: 
12019: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12020: 
12021: # ----------------------------------------------------- Cascading lookup scheme
12022: 	    my $symbp=$symbparm;
12023: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12024: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12025:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12026: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12027: 	    if (($env{'user.name'} eq $uname) &&
12028: 		($env{'user.domain'} eq $udom)) {
12029: 		$section=$env{'request.course.sec'};
12030:                 @groups = split(/:/,$env{'request.course.groups'});  
12031:                 @groups=&sort_course_groups($courseid,@groups); 
12032: 	    } else {
12033: 		if (! defined($usection)) {
12034: 		    $section=&getsection($udom,$uname,$courseid);
12035: 		} else {
12036: 		    $section = $usection;
12037: 		}
12038:                 @groups = &get_users_groups($udom,$uname,$courseid);
12039: 	    }
12040: 
12041: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12042: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12043:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12044: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12045: 
12046: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12047: 	    my $courselevelr=$courseid.'.'.$symbparm;
12048:             $courseleveli=$courseid.'.'.$recurseparm;
12049: 	    $courselevelm=$courseid.'.'.$mapparm;
12050: 
12051: # ----------------------------------------------------------- first, check user
12052: 
12053: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12054:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12055: 				       ([$courselevelr,'resource'],
12056: 					[$courselevelm,'map'     ],
12057:                                         [$courseleveli,'map'     ],
12058: 					[$courselevel, 'course'  ]));
12059: 	    if (defined($userreply)) { return &get_reply($userreply); }
12060: 
12061: # ------------------------------------------------ second, check some of course
12062:             my $coursereply;
12063:             if (@groups > 0) {
12064:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12065:                                        $recurseparm,$mapparm,$spacequalifierrest,
12066:                                        $mapp,\$recursed,\@recurseup);
12067:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12068:             }
12069: 
12070: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12071: 				  $env{'course.'.$courseid.'.domain'},
12072: 				  'course',$mapp,\$recursed,\@recurseup,
12073:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12074: 				  ([$seclevelr,   'resource'],
12075: 				   [$seclevelm,   'map'     ],
12076:                                    [$secleveli,   'map'     ],
12077: 				   [$seclevel,    'course'  ],
12078: 				   [$courselevelr,'resource']));
12079: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12080: 
12081: # ------------------------------------------------------ third, check map parms
12082: 	    my %parmhash=();
12083: 	    my $thisparm='';
12084: 	    if (tie(%parmhash,'GDBM_File',
12085: 		    $env{'request.course.fn'}.'_parms.db',
12086: 		    &GDBM_READER(),0640)) {
12087: 		$thisparm=$parmhash{$symbparm};
12088: 		untie(%parmhash);
12089: 	    }
12090: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12091: 	}
12092: # ------------------------------------------ fourth, look in resource metadata
12093:  
12094:         my $what = $spacequalifierrest;
12095: 	$what=~s/\./\_/;
12096: 	my $filename;
12097: 	if (!$symbparm) { $symbparm=&symbread(); }
12098: 	if ($symbparm) {
12099: 	    $filename=(&decode_symb($symbparm))[2];
12100: 	} else {
12101: 	    $filename=$env{'request.filename'};
12102: 	}
12103:         my $toolsymb;
12104:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12105:             $toolsymb = $symbparm;
12106:         }
12107: 	my $metadata=&metadata($filename,$what,$toolsymb);
12108: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12109: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12110: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12111: 
12112: # ----------------------------------------------- fifth, look in rest of course
12113: 	if ($symbparm && defined($courseid) && 
12114: 	    $courseid eq $env{'request.course.id'}) {
12115: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12116: 				     $env{'course.'.$courseid.'.domain'},
12117: 				     'course',$mapp,\$recursed,\@recurseup,
12118:                                      $courseid,'.',$spacequalifierrest,
12119: 				     ([$courselevelm,'map'   ],
12120:                                       [$courseleveli,'map'   ],
12121: 				      [$courselevel, 'course']));
12122: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12123: 	}
12124: # ------------------------------------------------------------------ Cascade up
12125: 	unless ($space eq '0') {
12126: 	    my @parts=split(/_/,$space);
12127: 	    my $id=pop(@parts);
12128: 	    my $part=join('_',@parts);
12129: 	    if ($part eq '') { $part='0'; }
12130: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12131: 				 $symbparm,$udom,$uname,$section,1);
12132: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12133: 	}
12134: 	if ($recurse) { return undef; }
12135: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12136: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12137: # ---------------------------------------------------- Any other user namespace
12138:     } elsif ($realm eq 'environment') {
12139: # ----------------------------------------------------------------- environment
12140: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12141: 	    return $env{'environment.'.$spacequalifierrest};
12142: 	} else {
12143: 	    if ($uname eq 'anonymous' && $udom eq '') {
12144: 		return '';
12145: 	    }
12146: 	    my %returnhash=&userenvironment($udom,$uname,
12147: 					    $spacequalifierrest);
12148: 	    return $returnhash{$spacequalifierrest};
12149: 	}
12150:     } elsif ($realm eq 'system') {
12151: # ----------------------------------------------------------------- system.time
12152: 	if ($space eq 'time') {
12153: 	    return time;
12154:         }
12155:     } elsif ($realm eq 'server') {
12156: # ----------------------------------------------------------------- system.time
12157: 	if ($space eq 'name') {
12158: 	    return $ENV{'SERVER_NAME'};
12159:         }
12160:     }
12161:     return '';
12162: }
12163: 
12164: sub get_reply {
12165:     my ($reply_value) = @_;
12166:     if (ref($reply_value) eq 'ARRAY') {
12167:         if (wantarray) {
12168: 	    return @$reply_value;
12169:         }
12170:         return $reply_value->[0];
12171:     } else {
12172:         return $reply_value;
12173:     }
12174: }
12175: 
12176: sub check_group_parms {
12177:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12178:         $recursed,$recurseupref) = @_;
12179:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12180:                   [$what,'course']);
12181:     my $coursereply;
12182:     foreach my $group (@{$groups}) {
12183:         my @groupitems = ();
12184:         foreach my $level (@levels) {
12185:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12186:              push(@groupitems,[$item,$level->[1]]);
12187:         }
12188:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12189:                                    $env{'course.'.$courseid.'.domain'},
12190:                                    'course',$mapp,$recursed,$recurseupref,
12191:                                    $courseid,'.['.$group.'].',$what,
12192:                                    @groupitems);
12193:         last if (defined($coursereply));
12194:     }
12195:     return $coursereply;
12196: }
12197: 
12198: sub get_map_hierarchy {
12199:     my ($mapname,$courseid) = @_;
12200:     my @recurseup = ();
12201:     if ($mapname) {
12202:         if (($cachedmapkey eq $courseid) &&
12203:             (abs($cachedmaptime-time)<5)) {
12204:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12205:                 return @{$cachedmaps{$mapname}};
12206:             }
12207:         }
12208:         my $navmap = Apache::lonnavmaps::navmap->new();
12209:         if (ref($navmap)) {
12210:             @recurseup = $navmap->recurseup_maps($mapname);
12211:             undef($navmap);
12212:             $cachedmaps{$mapname} = \@recurseup;
12213:             $cachedmaptime=time;
12214:             $cachedmapkey=$courseid;
12215:         }
12216:     }
12217:     return @recurseup;
12218: }
12219: 
12220: }
12221: 
12222: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12223:     my ($courseid,@groups) = @_;
12224:     @groups = sort(@groups);
12225:     return @groups;
12226: }
12227: 
12228: sub packages_tab_default {
12229:     my ($uri,$varname,$toolsymb)=@_;
12230:     my (undef,$part,$name)=split(/\./,$varname);
12231: 
12232:     my (@extension,@specifics,$do_default);
12233:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12234: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12235: 	if ($pack_type eq 'default') {
12236: 	    $do_default=1;
12237: 	} elsif ($pack_type eq 'extension') {
12238: 	    push(@extension,[$package,$pack_type,$pack_part]);
12239: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12240: 	    # only look at packages defaults for packages that this id is
12241: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12242: 	}
12243:     }
12244:     # first look for a package that matches the requested part id
12245:     foreach my $package (@specifics) {
12246: 	my (undef,$pack_type,$pack_part)=@{$package};
12247: 	next if ($pack_part ne $part);
12248: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12249: 	    return $packagetab{"$pack_type&$name&default"};
12250: 	}
12251:     }
12252:     # look for any possible matching non extension_ package
12253:     foreach my $package (@specifics) {
12254: 	my (undef,$pack_type,$pack_part)=@{$package};
12255: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12256: 	    return $packagetab{"$pack_type&$name&default"};
12257: 	}
12258: 	if ($pack_type eq 'part') { $pack_part='0'; }
12259: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12260: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12261: 	}
12262:     }
12263:     # look for any posible extension_ match
12264:     foreach my $package (@extension) {
12265: 	my ($package,$pack_type)=@{$package};
12266: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12267: 	    return $packagetab{"$pack_type&$name&default"};
12268: 	}
12269: 	if (defined($packagetab{$package."&$name&default"})) {
12270: 	    return $packagetab{$package."&$name&default"};
12271: 	}
12272:     }
12273:     # look for a global default setting
12274:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12275: 	return $packagetab{"default&$name&default"};
12276:     }
12277:     return undef;
12278: }
12279: 
12280: sub add_prefix_and_part {
12281:     my ($prefix,$part)=@_;
12282:     my $keyroot;
12283:     if (defined($prefix) && $prefix !~ /^__/) {
12284: 	# prefix that has a part already
12285: 	$keyroot=$prefix;
12286:     } elsif (defined($prefix)) {
12287: 	# prefix that is missing a part
12288: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12289:     } else {
12290: 	# no prefix at all
12291: 	if (defined($part)) { $keyroot='_'.$part; }
12292:     }
12293:     return $keyroot;
12294: }
12295: 
12296: # ---------------------------------------------------------------- Get metadata
12297: 
12298: my %metaentry;
12299: my %importedpartids;
12300: my %importedrespids;
12301: sub metadata {
12302:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12303:     $uri=&declutter($uri);
12304:     # if it is a non metadata possible uri return quickly
12305:     if (($uri eq '') || 
12306: 	(($uri =~ m|^/*adm/|) && 
12307: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12308:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12309: 	return undef;
12310:     }
12311:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12312: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12313: 	return undef;
12314:     }
12315:     my $filename=$uri;
12316:     $uri=~s/\.meta$//;
12317: #
12318: # Is the metadata already cached?
12319: # Look at timestamp of caching
12320: # Everything is cached by the main uri, libraries are never directly cached
12321: #
12322:     if (!defined($liburi)) {
12323: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12324: 	if (defined($cached)) { return $result->{':'.$what}; }
12325:     }
12326: 
12327: #
12328: # If the uri is for an external tool the file from
12329: # which metadata should be retrieved depends on whether
12330: # the tool had been configured to be gradable (set in the Course
12331: # Editor or Resource Editor).
12332: #
12333: # If a valid symb has been included as the third arg in the call
12334: # to &metadata() that can be used to retrieve the value of
12335: # parameter_0_gradable set for the resource, and included in the
12336: # uploaded map containing the tool. The value is retrieved via
12337: # &EXT(), if a valid symb is available.  Otherwise the value of
12338: # gradable in the exttool_$marker.db file for the tool instance
12339: # is retrieved via &get().
12340: #
12341: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12342: # hiddenresource and encrypturl (during course initialization)
12343: # the map-level parameter for resource.0.gradable included in the 
12344: # uploaded map containing the tool will not yet have been stored
12345: # in the user_course_parms.db file for the user's session, so in 
12346: # this case fall back to retrieving gradable status from the
12347: # exttool_$marker.db file.
12348: #
12349: # In order to avoid an infinite loop, &metadata() will return
12350: # before a call to &EXT(), if the uri is for an external tool
12351: # and the $what for which metadata is being requested is
12352: # parameter_0_gradable or 0_gradable.
12353: #
12354: 
12355:     if ($uri =~ /ext\.tool$/) {
12356:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12357:             return;
12358:         } else {
12359:             my ($checked,$use_passback);
12360:             if ($toolsymb ne '') {
12361:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12362:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12363:                     $checked = 1;
12364:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12365:                         $use_passback = 1;
12366:                     }
12367:                 }
12368:             }
12369:             unless ($checked) {
12370:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12371:                 $marker=~s/\D//g;
12372:                 if ($marker) {
12373:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12374:                     $use_passback = $toolsettings{'gradable'};
12375:                 }
12376:             }
12377:             if ($use_passback) {
12378:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12379:             } else {
12380:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12381:             }
12382:         }
12383:     }
12384: 
12385:     {
12386: # Imported parts would go here
12387:         my @origfiletagids=();
12388:         my $importedparts=0;
12389: 
12390: # Imported responseids would go here
12391:         my $importedresponses=0;
12392: #
12393: # Is this a recursive call for a library?
12394: #
12395: #	if (! exists($metacache{$uri})) {
12396: #	    $metacache{$uri}={};
12397: #	}
12398: 	my $cachetime = 60*60;
12399:         if ($liburi) {
12400: 	    $liburi=&declutter($liburi);
12401:             $filename=$liburi;
12402:         } else {
12403: 	    &devalidate_cache_new('meta',$uri);
12404: 	    undef(%metaentry);
12405: 	}
12406:         my %metathesekeys=();
12407:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12408: 	my $metastring;
12409: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12410: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12411: 	    $metastring = 
12412: 		&Apache::lonnet::ssi_body($which,
12413: 					  ('grade_target' => 'meta'));
12414: 	    $cachetime = 1; # only want this cached in the child not long term
12415: 	} elsif (($uri !~ m -^(editupload)/-) && 
12416:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12417: 	    my $file=&filelocation('',&clutter($filename));
12418: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12419: 	    $metastring=&getfile($file);
12420: 	}
12421:         my $parser=HTML::LCParser->new(\$metastring);
12422:         my $token;
12423:         undef %metathesekeys;
12424:         while ($token=$parser->get_token) {
12425: 	    if ($token->[0] eq 'S') {
12426: 		if (defined($token->[2]->{'package'})) {
12427: #
12428: # This is a package - get package info
12429: #
12430: 		    my $package=$token->[2]->{'package'};
12431: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12432: 		    if (defined($token->[2]->{'id'})) { 
12433: 			$keyroot.='_'.$token->[2]->{'id'}; 
12434: 		    }
12435: 		    if ($metaentry{':packages'}) {
12436: 			$metaentry{':packages'}.=','.$package.$keyroot;
12437: 		    } else {
12438: 			$metaentry{':packages'}=$package.$keyroot;
12439: 		    }
12440: 		    foreach my $pack_entry (keys(%packagetab)) {
12441: 			my $part=$keyroot;
12442: 			$part=~s/^\_//;
12443: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12444: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12445: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12446: 			    # ignore package.tab specified default values
12447:                             # here &package_tab_default() will fetch those
12448: 			    if ($subp eq 'default') { next; }
12449: 			    my $value=$packagetab{$pack_entry};
12450: 			    my $unikey;
12451: 			    if ($pack =~ /_0$/) {
12452: 				$unikey='parameter_0_'.$name;
12453: 				$part=0;
12454: 			    } else {
12455: 				$unikey='parameter'.$keyroot.'_'.$name;
12456: 			    }
12457: 			    if ($subp eq 'display') {
12458: 				$value.=' [Part: '.$part.']';
12459: 			    }
12460: 			    $metaentry{':'.$unikey.'.part'}=$part;
12461: 			    $metathesekeys{$unikey}=1;
12462: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12463: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12464: 			    }
12465: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12466: 				$metaentry{':'.$unikey}=
12467: 				    $metaentry{':'.$unikey.'.default'};
12468: 			    }
12469: 			}
12470: 		    }
12471: 		} else {
12472: #
12473: # This is not a package - some other kind of start tag
12474: #
12475: 		    my $entry=$token->[1];
12476: 		    my $unikey='';
12477: 
12478: 		    if ($entry eq 'import') {
12479: #
12480: # Importing a library here
12481: #
12482:                         my $location=$parser->get_text('/import');
12483:                         my $dir=$filename;
12484:                         $dir=~s|[^/]*$||;
12485:                         $location=&filelocation($dir,$location);
12486: 
12487:                         my $importid=$token->[2]->{'id'};
12488:                         my $importmode=$token->[2]->{'importmode'};
12489: #
12490: # Check metadata for imported file to
12491: # see if it contained response items
12492: #
12493:                         my ($origfile,@libfilekeys);
12494:                         my %currmetaentry = %metaentry;
12495:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12496:                                                            $depthcount+1));
12497:                         if (grep(/^responseorder$/,@libfilekeys)) {
12498:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12499:                                                              undef,$depthcount+1);
12500:                             if ($libresponseorder ne '') {
12501:                                 if ($#origfiletagids<0) {
12502:                                     undef(%importedrespids);
12503:                                     undef(%importedpartids);
12504:                                 }
12505:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12506:                                 if (@respids) {
12507:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12508:                                 }
12509:                                 if ($importedrespids{$importid} ne '') {
12510:                                     $importedresponses = 1;
12511: # We need to get the original file and the imported file to get the response order correct
12512: # Load and inspect original file
12513:                                     if ($#origfiletagids<0) {
12514:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12515:                                         $origfile=&getfile($origfilelocation);
12516:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12517:                                     }
12518:                                 }
12519:                             }
12520:                         }
12521: # Do not overwrite contents of %metaentry hash for resource itself with 
12522: # hash populated for imported library file
12523:                         %metaentry = %currmetaentry;
12524:                         undef(%currmetaentry);
12525:                         if ($importmode eq 'part') {
12526: # Import as part(s)
12527:                            $importedparts=1;
12528: # We need to get the original file and the imported file to get the part order correct
12529: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12530: # Load and inspect original file if we didn't do that already
12531:                            if ($#origfiletagids<0) {
12532:                                undef(%importedrespids);
12533:                                undef(%importedpartids);
12534:                                if ($origfile eq '') {
12535:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12536:                                    $origfile=&getfile($origfilelocation);
12537:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12538:                                }
12539:                            }
12540:                            my @impfilepartids;
12541: # If <partorder> tag is included in metadata for the imported file
12542: # get the parts in the imported file from that.
12543:                            if (grep(/^partorder$/,@libfilekeys)) {
12544:                                %currmetaentry = %metaentry;
12545:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12546:                                                             $depthcount+1);
12547:                                %metaentry = %currmetaentry;
12548:                                undef(%currmetaentry);
12549:                                if ($libpartorder ne '') {
12550:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12551:                                }
12552:                            } else {
12553: # If no <partorder> tag available, load and inspect imported file
12554:                                my $impfile=&getfile($location);
12555:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12556:                            }
12557:                            if ($#impfilepartids>=0) {
12558: # This problem had parts
12559:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12560:                            } else {
12561: # Importing by turning a single problem into a problem part
12562: # It gets the import-tags ID as part-ID
12563:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12564:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12565:                            }
12566:                         } else {
12567: # Import as problem or as normal import
12568:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12569:                             unless ($importmode eq 'problem') {
12570: # Normal import
12571:                                 if (defined($token->[2]->{'id'})) {
12572:                                     $unikey.='_'.$token->[2]->{'id'};
12573:                                 }
12574:                             }
12575: # Check metadata for imported file to
12576: # see if it contained parts
12577:                             if (grep(/^partorder$/,@libfilekeys)) {
12578:                                 %currmetaentry = %metaentry;
12579:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12580:                                                              $depthcount+1);
12581:                                 %metaentry = %currmetaentry;
12582:                                 undef(%currmetaentry);
12583:                                 if ($libpartorder ne '') {
12584:                                     $importedparts = 1;
12585:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12586:                                 }
12587:                             }
12588:                         }
12589: 			if ($depthcount<20) {
12590: 			    my $metadata = 
12591: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12592: 					  $depthcount+1);
12593: 			    foreach my $meta (split(',',$metadata)) {
12594: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12595: 				$metathesekeys{$meta}=1;
12596: 			    }
12597:                         }
12598: 		    } else {
12599: #
12600: # Not importing, some other kind of non-package, non-library start tag
12601: # 
12602:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12603:                         if (defined($token->[2]->{'id'})) {
12604:                             $unikey.='_'.$token->[2]->{'id'};
12605:                         }
12606: 			if (defined($token->[2]->{'name'})) { 
12607: 			    $unikey.='_'.$token->[2]->{'name'}; 
12608: 			}
12609: 			$metathesekeys{$unikey}=1;
12610: 			foreach my $param (@{$token->[3]}) {
12611: 			    $metaentry{':'.$unikey.'.'.$param} =
12612: 				$token->[2]->{$param};
12613: 			}
12614: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12615: 			my $default=$metaentry{':'.$unikey.'.default'};
12616: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12617: 		 # only ws inside the tag, and not in default, so use default
12618: 		 # as value
12619: 			    $metaentry{':'.$unikey}=$default;
12620: 			} elsif ( $internaltext =~ /\S/ ) {
12621: 		  # something interesting inside the tag
12622: 			    $metaentry{':'.$unikey}=$internaltext;
12623: 			} else {
12624: 		  # no interesting values, don't set a default
12625: 			}
12626: # end of not-a-package not-a-library import
12627: 		    }
12628: # end of not-a-package start tag
12629: 		}
12630: # the next is the end of "start tag"
12631: 	    }
12632: 	}
12633: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12634: 	$extension = lc($extension);
12635: 	if ($extension eq 'htm') { $extension='html'; }
12636: 
12637: 	foreach my $key (keys(%packagetab)) {
12638: 	    #no specific packages #how's our extension
12639: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12640: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12641: 					 \%metathesekeys);
12642: 	}
12643: 
12644: 	if (!exists($metaentry{':packages'})
12645: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12646: 	    foreach my $key (keys(%packagetab)) {
12647: 		#no specific packages well let's get default then
12648: 		if ($key!~/^default&/) { next; }
12649: 		&metadata_create_package_def($uri,$key,'default',
12650: 					     \%metathesekeys);
12651: 	    }
12652: 	}
12653: # are there custom rights to evaluate
12654: 	if ($metaentry{':copyright'} eq 'custom') {
12655: 
12656:     #
12657:     # Importing a rights file here
12658:     #
12659: 	    unless ($depthcount) {
12660: 		my $location=$metaentry{':customdistributionfile'};
12661: 		my $dir=$filename;
12662: 		$dir=~s|[^/]*$||;
12663: 		$location=&filelocation($dir,$location);
12664: 		my $rights_metadata =
12665: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12666: 			      $depthcount+1);
12667: 		foreach my $rights (split(',',$rights_metadata)) {
12668: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12669: 		    $metathesekeys{$rights}=1;
12670: 		}
12671: 	    }
12672: 	}
12673: 	# uniqifiy package listing
12674: 	my %seen;
12675: 	my @uniq_packages =
12676: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12677: 	$metaentry{':packages'} = join(',',@uniq_packages);
12678: 
12679:         if (($importedresponses) || ($importedparts)) {
12680:             if ($importedparts) {
12681: # We had imported parts and need to rebuild partorder
12682:                 $metaentry{':partorder'}='';
12683:                 $metathesekeys{'partorder'}=1;
12684:             }
12685:             if ($importedresponses) {
12686: # We had imported responses and need to rebuil responseorder
12687:                 $metaentry{':responseorder'}='';
12688:                 $metathesekeys{'responseorder'}=1;
12689:             }
12690:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12691:                 my $origid = $origfiletagids[$index+1];
12692:                 if ($origfiletagids[$index] eq 'part') {
12693: # Original part, part of the problem
12694:                     if ($importedparts) {
12695:                         $metaentry{':partorder'}.=','.$origid;
12696:                     }
12697:                 } elsif ($origfiletagids[$index] eq 'import') {
12698:                     if ($importedparts) {
12699: # We have imported parts at this position
12700:                         if ($importedpartids{$origid} ne '') {
12701:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12702:                         }
12703:                     }
12704:                     if ($importedresponses) {
12705: # We have imported responses at this position
12706:                         if ($importedrespids{$origid} ne '') {
12707:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12708:                         }
12709:                     }
12710:                 } else {
12711: # Original response item, part of the problem
12712:                     if ($importedresponses) {
12713:                         $metaentry{':responseorder'}.=','.$origid;
12714:                     }
12715:                 }
12716:             }
12717:             if ($importedparts) {
12718:                 $metaentry{':partorder'}=~s/^\,//;
12719:             }
12720:             if ($importedresponses) {
12721:                 $metaentry{':responseorder'}=~s/^\,//;
12722:             }
12723:         }
12724: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12725: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12726: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12727:         unless ($liburi) {
12728: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12729:         }
12730: # this is the end of "was not already recently cached
12731:     }
12732:     return $metaentry{':'.$what};
12733: }
12734: 
12735: sub metadata_create_package_def {
12736:     my ($uri,$key,$package,$metathesekeys)=@_;
12737:     my ($pack,$name,$subp)=split(/\&/,$key);
12738:     if ($subp eq 'default') { next; }
12739:     
12740:     if (defined($metaentry{':packages'})) {
12741: 	$metaentry{':packages'}.=','.$package;
12742:     } else {
12743: 	$metaentry{':packages'}=$package;
12744:     }
12745:     my $value=$packagetab{$key};
12746:     my $unikey;
12747:     $unikey='parameter_0_'.$name;
12748:     $metaentry{':'.$unikey.'.part'}=0;
12749:     $$metathesekeys{$unikey}=1;
12750:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12751: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12752:     }
12753:     if (defined($metaentry{':'.$unikey.'.default'})) {
12754: 	$metaentry{':'.$unikey}=
12755: 	    $metaentry{':'.$unikey.'.default'};
12756:     }
12757: }
12758: 
12759: sub metadata_generate_part0 {
12760:     my ($metadata,$metacache,$uri) = @_;
12761:     my %allnames;
12762:     foreach my $metakey (keys(%$metadata)) {
12763: 	if ($metakey=~/^parameter\_(.*)/) {
12764: 	  my $part=$$metacache{':'.$metakey.'.part'};
12765: 	  my $name=$$metacache{':'.$metakey.'.name'};
12766: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12767: 	    $allnames{$name}=$part;
12768: 	  }
12769: 	}
12770:     }
12771:     foreach my $name (keys(%allnames)) {
12772:       $$metadata{"parameter_0_$name"}=1;
12773:       my $key=":parameter_0_$name";
12774:       $$metacache{"$key.part"}='0';
12775:       $$metacache{"$key.name"}=$name;
12776:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12777: 					   $allnames{$name}.'_'.$name.
12778: 					   '.type'};
12779:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12780: 			     '.display'};
12781:       my $expr='[Part: '.$allnames{$name}.']';
12782:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12783:       $$metacache{"$key.display"}=$olddis;
12784:     }
12785: }
12786: 
12787: # ------------------------------------------------------ Devalidate title cache
12788: 
12789: sub devalidate_title_cache {
12790:     my ($url)=@_;
12791:     if (!$env{'request.course.id'}) { return; }
12792:     my $symb=&symbread($url);
12793:     if (!$symb) { return; }
12794:     my $key=$env{'request.course.id'}."\0".$symb;
12795:     &devalidate_cache_new('title',$key);
12796: }
12797: 
12798: # ------------------------------------------------- Get the title of a course
12799: 
12800: sub current_course_title {
12801:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12802: }
12803: # ------------------------------------------------- Get the title of a resource
12804: 
12805: sub gettitle {
12806:     my $urlsymb=shift;
12807:     my $symb=&symbread($urlsymb);
12808:     if ($symb) {
12809: 	my $key=$env{'request.course.id'}."\0".$symb;
12810: 	my ($result,$cached)=&is_cached_new('title',$key);
12811: 	if (defined($cached)) { 
12812: 	    return $result;
12813: 	}
12814: 	my ($map,$resid,$url)=&decode_symb($symb);
12815: 	my $title='';
12816: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12817: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12818: 	} else {
12819: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12820: 		    &GDBM_READER(),0640)) {
12821: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12822: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12823: 		untie(%bighash);
12824: 	    }
12825: 	}
12826: 	$title=~s/\&colon\;/\:/gs;
12827: 	if ($title) {
12828: # Remember both $symb and $title for dynamic metadata
12829:             $accesshash{$symb.'___crstitle'}=$title;
12830:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12831: # Cache this title and then return it
12832: 	    return &do_cache_new('title',$key,$title,600);
12833: 	}
12834: 	$urlsymb=$url;
12835:     }
12836:     my $title=&metadata($urlsymb,'title');
12837:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12838:     return $title;
12839: }
12840: 
12841: sub get_slot {
12842:     my ($which,$cnum,$cdom)=@_;
12843:     if (!$cnum || !$cdom) {
12844: 	(undef,my $courseid)=&whichuser();
12845: 	$cdom=$env{'course.'.$courseid.'.domain'};
12846: 	$cnum=$env{'course.'.$courseid.'.num'};
12847:     }
12848:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12849:     my %slotinfo;
12850:     if (exists($remembered{$key})) {
12851: 	$slotinfo{$which} = $remembered{$key};
12852:     } else {
12853: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12854: 	&Apache::lonhomework::showhash(%slotinfo);
12855: 	my ($tmp)=keys(%slotinfo);
12856: 	if ($tmp=~/^error:/) { return (); }
12857: 	$remembered{$key} = $slotinfo{$which};
12858:     }
12859:     if (ref($slotinfo{$which}) eq 'HASH') {
12860: 	return %{$slotinfo{$which}};
12861:     }
12862:     return $slotinfo{$which};
12863: }
12864: 
12865: sub get_reservable_slots {
12866:     my ($cnum,$cdom,$uname,$udom) = @_;
12867:     my $now = time;
12868:     my $reservable_info;
12869:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12870:     if (exists($remembered{$key})) {
12871:         $reservable_info = $remembered{$key};
12872:     } else {
12873:         my %resv;
12874:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12875:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12876:         $reservable_info = \%resv;
12877:         $remembered{$key} = $reservable_info;
12878:     }
12879:     return $reservable_info;
12880: }
12881: 
12882: sub get_course_slots {
12883:     my ($cnum,$cdom) = @_;
12884:     my $hashid=$cnum.':'.$cdom;
12885:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12886:     if (defined($cached)) {
12887:         if (ref($result) eq 'HASH') {
12888:             return %{$result};
12889:         }
12890:     } else {
12891:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12892:         my ($tmp) = keys(%slots);
12893:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12894:             &do_cache_new('allslots',$hashid,\%slots,600);
12895:             return %slots;
12896:         }
12897:     }
12898:     return;
12899: }
12900: 
12901: sub devalidate_slots_cache {
12902:     my ($cnum,$cdom)=@_;
12903:     my $hashid=$cnum.':'.$cdom;
12904:     &devalidate_cache_new('allslots',$hashid);
12905: }
12906: 
12907: sub get_coursechange {
12908:     my ($cdom,$cnum) = @_;
12909:     if ($cdom eq '' || $cnum eq '') {
12910:         return unless ($env{'request.course.id'});
12911:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12912:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12913:     }
12914:     my $hashid=$cdom.'_'.$cnum;
12915:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12916:     if ((defined($cached)) && ($change ne '')) {
12917:         return $change;
12918:     } else {
12919:         my %crshash;
12920:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12921:         if ($crshash{'internal.contentchange'} eq '') {
12922:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12923:             if ($change eq '') {
12924:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12925:                 $change = $crshash{'internal.created'};
12926:             }
12927:         } else {
12928:             $change = $crshash{'internal.contentchange'};
12929:         }
12930:         my $cachetime = 600;
12931:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12932:     }
12933:     return $change;
12934: }
12935: 
12936: sub devalidate_coursechange_cache {
12937:     my ($cnum,$cdom)=@_;
12938:     my $hashid=$cnum.':'.$cdom;
12939:     &devalidate_cache_new('crschange',$hashid);
12940: }
12941: 
12942: # ------------------------------------------------- Update symbolic store links
12943: 
12944: sub symblist {
12945:     my ($mapname,%newhash)=@_;
12946:     $mapname=&deversion(&declutter($mapname));
12947:     my %hash;
12948:     if (($env{'request.course.fn'}) && (%newhash)) {
12949:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12950:                       &GDBM_WRCREAT(),0640)) {
12951: 	    foreach my $url (keys(%newhash)) {
12952: 		next if ($url eq 'last_known'
12953: 			 && $env{'form.no_update_last_known'});
12954: 		$hash{declutter($url)}=&encode_symb($mapname,
12955: 						    $newhash{$url}->[1],
12956: 						    $newhash{$url}->[0]);
12957:             }
12958:             if (untie(%hash)) {
12959: 		return 'ok';
12960:             }
12961:         }
12962:     }
12963:     return 'error';
12964: }
12965: 
12966: # --------------------------------------------------------------- Verify a symb
12967: 
12968: sub symbverify {
12969:     my ($symb,$thisurl,$encstate)=@_;
12970:     my $thisfn=$thisurl;
12971:     $thisfn=&declutter($thisfn);
12972: # direct jump to resource in page or to a sequence - will construct own symbs
12973:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12974: # check URL part
12975:     my ($map,$resid,$url)=&decode_symb($symb);
12976: 
12977:     unless ($url eq $thisfn) { return 0; }
12978: 
12979:     $symb=&symbclean($symb);
12980:     $thisurl=&deversion($thisurl);
12981:     $thisfn=&deversion($thisfn);
12982: 
12983:     my %bighash;
12984:     my $okay=0;
12985: 
12986:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12987:                             &GDBM_READER(),0640)) {
12988:         my $noclutter;
12989:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12990:             $thisurl =~ s/\?.+$//;
12991:             if ($map =~ m{^uploaded/.+\.page$}) {
12992:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12993:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12994:                 $noclutter = 1;
12995:             }
12996:         }
12997:         my $ids;
12998:         if ($noclutter) {
12999:             $ids=$bighash{'ids_'.$thisurl};
13000:         } else {
13001:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13002:         }
13003:         unless ($ids) {
13004:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13005:             $ids=$bighash{$idkey};
13006:         }
13007:         if ($ids) {
13008: # ------------------------------------------------------------------- Has ID(s)
13009:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13010:                 $symb =~ s/\?.+$//;
13011:             }
13012: 	    foreach my $id (split(/\,/,$ids)) {
13013: 	       my ($mapid,$resid)=split(/\./,$id);
13014:                if (
13015:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13016:    eq $symb) {
13017:                    if (ref($encstate)) {
13018:                        $$encstate = $bighash{'encrypted_'.$id};
13019:                    }
13020: 		   if (($env{'request.role.adv'}) ||
13021: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13022:                        ($thisurl eq '/adm/navmaps')) {
13023: 		       $okay=1;
13024:                        last;
13025: 		   }
13026: 	       }
13027: 	   }
13028:         }
13029: 	untie(%bighash);
13030:     }
13031:     return $okay;
13032: }
13033: 
13034: # --------------------------------------------------------------- Clean-up symb
13035: 
13036: sub symbclean {
13037:     my $symb=shift;
13038:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13039: # remove version from map
13040:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13041: 
13042: # remove version from URL
13043:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13044: 
13045: # remove wrapper
13046: 
13047:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13048:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13049:     return $symb;
13050: }
13051: 
13052: # ---------------------------------------------- Split symb to find map and url
13053: 
13054: sub encode_symb {
13055:     my ($map,$resid,$url)=@_;
13056:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13057: }
13058: 
13059: sub decode_symb {
13060:     my $symb=shift;
13061:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13062:     my ($map,$resid,$url)=split(/___/,$symb);
13063:     return (&fixversion($map),$resid,&fixversion($url));
13064: }
13065: 
13066: sub fixversion {
13067:     my $fn=shift;
13068:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13069:     my %bighash;
13070:     my $uri=&clutter($fn);
13071:     my $key=$env{'request.course.id'}.'_'.$uri;
13072: # is this cached?
13073:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13074:     if (defined($cached)) { return $result; }
13075: # unfortunately not cached, or expired
13076:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13077: 	    &GDBM_READER(),0640)) {
13078:  	if ($bighash{'version_'.$uri}) {
13079:  	    my $version=$bighash{'version_'.$uri};
13080:  	    unless (($version eq 'mostrecent') || 
13081: 		    ($version==&getversion($uri))) {
13082:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13083:  	    }
13084:  	}
13085:  	untie %bighash;
13086:     }
13087:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13088: }
13089: 
13090: sub deversion {
13091:     my $url=shift;
13092:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13093:     return $url;
13094: }
13095: 
13096: # ------------------------------------------------------ Return symb list entry
13097: 
13098: sub symbread {
13099:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13100:     my $cache_str='request.symbread.cached.'.$thisfn;
13101:     if (defined($env{$cache_str})) {
13102:         if ($ignorecachednull) {
13103:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13104:         } else {
13105:             return $env{$cache_str};
13106:         }
13107:     }
13108: # no filename provided? try from environment
13109:     unless ($thisfn) {
13110:         if ($env{'request.symb'}) {
13111: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13112: 	}
13113: 	$thisfn=$env{'request.filename'};
13114:     }
13115:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13116: # is that filename actually a symb? Verify, clean, and return
13117:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13118: 	if (&symbverify($thisfn,$1)) {
13119: 	    return $env{$cache_str}=&symbclean($thisfn);
13120: 	}
13121:     }
13122:     $thisfn=declutter($thisfn);
13123:     my %hash;
13124:     my %bighash;
13125:     my $syval='';
13126:     if (($env{'request.course.fn'}) && ($thisfn)) {
13127:         my $targetfn = $thisfn;
13128:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13129:             $targetfn = 'adm/wrapper/'.$thisfn;
13130:         }
13131: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13132: 	    $targetfn=$1;
13133: 	}
13134:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13135:                       &GDBM_READER(),0640)) {
13136: 	    $syval=$hash{$targetfn};
13137:             untie(%hash);
13138:         }
13139: # ---------------------------------------------------------- There was an entry
13140:         if ($syval) {
13141: 	    #unless ($syval=~/\_\d+$/) {
13142: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13143: 		    #&appenv({'request.ambiguous' => $thisfn});
13144: 		    #return $env{$cache_str}='';
13145: 		#}    
13146: 		#$syval.=$1;
13147: 	    #}
13148:         } else {
13149: # ------------------------------------------------------- Was not in symb table
13150:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13151:                             &GDBM_READER(),0640)) {
13152: # ---------------------------------------------- Get ID(s) for current resource
13153:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13154:               unless ($ids) { 
13155:                  $ids=$bighash{'ids_/'.$thisfn};
13156:               }
13157:               unless ($ids) {
13158: # alias?
13159: 		  $ids=$bighash{'mapalias_'.$thisfn};
13160:               }
13161:               if ($ids) {
13162: # ------------------------------------------------------------------- Has ID(s)
13163:                  my @possibilities=split(/\,/,$ids);
13164:                  if ($#possibilities==0) {
13165: # ----------------------------------------------- There is only one possibility
13166: 		     my ($mapid,$resid)=split(/\./,$ids);
13167: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13168: 						    $resid,$thisfn);
13169:                      if (ref($possibles) eq 'HASH') {
13170:                          $possibles->{$syval} = 1;    
13171:                      }
13172:                      if ($checkforblock) {
13173:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13174:                          if (@blockers) {
13175:                              $syval = '';
13176:                              return;
13177:                          }
13178:                      }
13179:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13180: # ------------------------------------------ There is more than one possibility
13181:                      my $realpossible=0;
13182:                      foreach my $id (@possibilities) {
13183: 			 my $file=$bighash{'src_'.$id};
13184:                          my $canaccess;
13185:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13186:                              $canaccess = 1;
13187:                          } else { 
13188:                              $canaccess = &allowed('bre',$file);
13189:                          }
13190:                          if ($canaccess) {
13191:          		     my ($mapid,$resid)=split(/\./,$id);
13192:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13193:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13194: 						             $resid,$thisfn);
13195:                                  if (ref($possibles) eq 'HASH') {
13196:                                      $possibles->{$syval} = 1;
13197:                                  }
13198:                                  if ($checkforblock) {
13199:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13200:                                      unless (@blockers > 0) {
13201:                                          $syval = $poss_syval;
13202:                                          $realpossible++;
13203:                                      }
13204:                                  } else {
13205:                                      $syval = $poss_syval;
13206:                                      $realpossible++;
13207:                                  }
13208:                              }
13209: 			 }
13210:                      }
13211: 		     if ($realpossible!=1) { $syval=''; }
13212:                  } else {
13213:                      $syval='';
13214:                  }
13215: 	      }
13216:               untie(%bighash);
13217:            }
13218:         }
13219:         if ($syval) {
13220: 	    return $env{$cache_str}=$syval;
13221:         }
13222:     }
13223:     &appenv({'request.ambiguous' => $thisfn});
13224:     return $env{$cache_str}='';
13225: }
13226: 
13227: # ---------------------------------------------------------- Return random seed
13228: 
13229: sub numval {
13230:     my $txt=shift;
13231:     $txt=~tr/A-J/0-9/;
13232:     $txt=~tr/a-j/0-9/;
13233:     $txt=~tr/K-T/0-9/;
13234:     $txt=~tr/k-t/0-9/;
13235:     $txt=~tr/U-Z/0-5/;
13236:     $txt=~tr/u-z/0-5/;
13237:     $txt=~s/\D//g;
13238:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13239:     return int($txt);
13240: }
13241: 
13242: sub numval2 {
13243:     my $txt=shift;
13244:     $txt=~tr/A-J/0-9/;
13245:     $txt=~tr/a-j/0-9/;
13246:     $txt=~tr/K-T/0-9/;
13247:     $txt=~tr/k-t/0-9/;
13248:     $txt=~tr/U-Z/0-5/;
13249:     $txt=~tr/u-z/0-5/;
13250:     $txt=~s/\D//g;
13251:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13252:     my $total;
13253:     foreach my $val (@txts) { $total+=$val; }
13254:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13255:     return int($total);
13256: }
13257: 
13258: sub numval3 {
13259:     use integer;
13260:     my $txt=shift;
13261:     $txt=~tr/A-J/0-9/;
13262:     $txt=~tr/a-j/0-9/;
13263:     $txt=~tr/K-T/0-9/;
13264:     $txt=~tr/k-t/0-9/;
13265:     $txt=~tr/U-Z/0-5/;
13266:     $txt=~tr/u-z/0-5/;
13267:     $txt=~s/\D//g;
13268:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13269:     my $total;
13270:     foreach my $val (@txts) { $total+=$val; }
13271:     if ($_64bit) { $total=(($total<<32)>>32); }
13272:     return $total;
13273: }
13274: 
13275: sub digest {
13276:     my ($data)=@_;
13277:     my $digest=&Digest::MD5::md5($data);
13278:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13279:     my ($e,$f);
13280:     {
13281:         use integer;
13282:         $e=($a+$b);
13283:         $f=($c+$d);
13284:         if ($_64bit) {
13285:             $e=(($e<<32)>>32);
13286:             $f=(($f<<32)>>32);
13287:         }
13288:     }
13289:     if (wantarray) {
13290: 	return ($e,$f);
13291:     } else {
13292: 	my $g;
13293: 	{
13294: 	    use integer;
13295: 	    $g=($e+$f);
13296: 	    if ($_64bit) {
13297: 		$g=(($g<<32)>>32);
13298: 	    }
13299: 	}
13300: 	return $g;
13301:     }
13302: }
13303: 
13304: sub latest_rnd_algorithm_id {
13305:     return '64bit5';
13306: }
13307: 
13308: sub get_rand_alg {
13309:     my ($courseid)=@_;
13310:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13311:     if ($courseid) {
13312: 	return $env{"course.$courseid.rndseed"};
13313:     }
13314:     return &latest_rnd_algorithm_id();
13315: }
13316: 
13317: sub validCODE {
13318:     my ($CODE)=@_;
13319:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13320:     return 0;
13321: }
13322: 
13323: sub getCODE {
13324:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13325:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13326: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13327: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13328: 	return $Apache::lonhomework::history{'resource.CODE'};
13329:     }
13330:     return undef;
13331: }
13332: #
13333: #  Determines the random seed for a specific context:
13334: #
13335: # parameters:
13336: #   symb      - in course context the symb for the seed.
13337: #   course_id - The course id of the form domain_coursenum.
13338: #   domain    - Domain for the user.
13339: #   course    - Course for the user.
13340: #   cenv      - environment of the course.
13341: #
13342: # NOTE:
13343: #   All parameters are picked out of the environment if missing
13344: #   or not defined.
13345: #   If a symb cannot be determined the current time is used instead.
13346: #
13347: #  For a given well defined symb, courside, domain, username,
13348: #  and course environment, the seed is reproducible.
13349: #
13350: sub rndseed {
13351:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13352:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13353:     if (!defined($symb)) {
13354: 	unless ($symb=$wsymb) { return time; }
13355:     }
13356:     if (!defined $courseid) { 
13357: 	$courseid=$wcourseid; 
13358:     }
13359:     if (!defined $domain) { $domain=$wdomain; }
13360:     if (!defined $username) { $username=$wusername }
13361: 
13362:     my $which;
13363:     if (defined($cenv->{'rndseed'})) {
13364: 	$which = $cenv->{'rndseed'};
13365:     } else {
13366: 	$which =&get_rand_alg($courseid);
13367:     }
13368:     if (defined(&getCODE())) {
13369: 
13370: 	if ($which eq '64bit5') {
13371: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13372: 	} elsif ($which eq '64bit4') {
13373: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13374: 	} else {
13375: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13376: 	}
13377:     } elsif ($which eq '64bit5') {
13378: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13379:     } elsif ($which eq '64bit4') {
13380: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13381:     } elsif ($which eq '64bit3') {
13382: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13383:     } elsif ($which eq '64bit2') {
13384: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13385:     } elsif ($which eq '64bit') {
13386: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13387:     }
13388:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13389: }
13390: 
13391: sub rndseed_32bit {
13392:     my ($symb,$courseid,$domain,$username)=@_;
13393:     {
13394: 	use integer;
13395: 	my $symbchck=unpack("%32C*",$symb) << 27;
13396: 	my $symbseed=numval($symb) << 22;
13397: 	my $namechck=unpack("%32C*",$username) << 17;
13398: 	my $nameseed=numval($username) << 12;
13399: 	my $domainseed=unpack("%32C*",$domain) << 7;
13400: 	my $courseseed=unpack("%32C*",$courseid);
13401: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13402: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13403: 	#&logthis("rndseed :$num:$symb");
13404: 	if ($_64bit) { $num=(($num<<32)>>32); }
13405: 	return $num;
13406:     }
13407: }
13408: 
13409: sub rndseed_64bit {
13410:     my ($symb,$courseid,$domain,$username)=@_;
13411:     {
13412: 	use integer;
13413: 	my $symbchck=unpack("%32S*",$symb) << 21;
13414: 	my $symbseed=numval($symb) << 10;
13415: 	my $namechck=unpack("%32S*",$username);
13416: 	
13417: 	my $nameseed=numval($username) << 21;
13418: 	my $domainseed=unpack("%32S*",$domain) << 10;
13419: 	my $courseseed=unpack("%32S*",$courseid);
13420: 	
13421: 	my $num1=$symbchck+$symbseed+$namechck;
13422: 	my $num2=$nameseed+$domainseed+$courseseed;
13423: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13424: 	#&logthis("rndseed :$num:$symb");
13425: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13426: 	return "$num1,$num2";
13427:     }
13428: }
13429: 
13430: sub rndseed_64bit2 {
13431:     my ($symb,$courseid,$domain,$username)=@_;
13432:     {
13433: 	use integer;
13434: 	# strings need to be an even # of cahracters long, it it is odd the
13435:         # last characters gets thrown away
13436: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13437: 	my $symbseed=numval($symb) << 10;
13438: 	my $namechck=unpack("%32S*",$username.' ');
13439: 	
13440: 	my $nameseed=numval($username) << 21;
13441: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13442: 	my $courseseed=unpack("%32S*",$courseid.' ');
13443: 	
13444: 	my $num1=$symbchck+$symbseed+$namechck;
13445: 	my $num2=$nameseed+$domainseed+$courseseed;
13446: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13447: 	#&logthis("rndseed :$num:$symb");
13448: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13449: 	return "$num1,$num2";
13450:     }
13451: }
13452: 
13453: sub rndseed_64bit3 {
13454:     my ($symb,$courseid,$domain,$username)=@_;
13455:     {
13456: 	use integer;
13457: 	# strings need to be an even # of cahracters long, it it is odd the
13458:         # last characters gets thrown away
13459: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13460: 	my $symbseed=numval2($symb) << 10;
13461: 	my $namechck=unpack("%32S*",$username.' ');
13462: 	
13463: 	my $nameseed=numval2($username) << 21;
13464: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13465: 	my $courseseed=unpack("%32S*",$courseid.' ');
13466: 	
13467: 	my $num1=$symbchck+$symbseed+$namechck;
13468: 	my $num2=$nameseed+$domainseed+$courseseed;
13469: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13470: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13471: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13472: 	
13473: 	return "$num1:$num2";
13474:     }
13475: }
13476: 
13477: sub rndseed_64bit4 {
13478:     my ($symb,$courseid,$domain,$username)=@_;
13479:     {
13480: 	use integer;
13481: 	# strings need to be an even # of cahracters long, it it is odd the
13482:         # last characters gets thrown away
13483: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13484: 	my $symbseed=numval3($symb) << 10;
13485: 	my $namechck=unpack("%32S*",$username.' ');
13486: 	
13487: 	my $nameseed=numval3($username) << 21;
13488: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13489: 	my $courseseed=unpack("%32S*",$courseid.' ');
13490: 	
13491: 	my $num1=$symbchck+$symbseed+$namechck;
13492: 	my $num2=$nameseed+$domainseed+$courseseed;
13493: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13494: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13495: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13496: 	
13497: 	return "$num1:$num2";
13498:     }
13499: }
13500: 
13501: sub rndseed_64bit5 {
13502:     my ($symb,$courseid,$domain,$username)=@_;
13503:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13504:     return "$num1:$num2";
13505: }
13506: 
13507: sub rndseed_CODE_64bit {
13508:     my ($symb,$courseid,$domain,$username)=@_;
13509:     {
13510: 	use integer;
13511: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13512: 	my $symbseed=numval2($symb);
13513: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13514: 	my $CODEseed=numval(&getCODE());
13515: 	my $courseseed=unpack("%32S*",$courseid.' ');
13516: 	my $num1=$symbseed+$CODEchck;
13517: 	my $num2=$CODEseed+$courseseed+$symbchck;
13518: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13519: 	#&logthis("rndseed :$num1:$num2:$symb");
13520: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13521: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13522: 	return "$num1:$num2";
13523:     }
13524: }
13525: 
13526: sub rndseed_CODE_64bit4 {
13527:     my ($symb,$courseid,$domain,$username)=@_;
13528:     {
13529: 	use integer;
13530: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13531: 	my $symbseed=numval3($symb);
13532: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13533: 	my $CODEseed=numval3(&getCODE());
13534: 	my $courseseed=unpack("%32S*",$courseid.' ');
13535: 	my $num1=$symbseed+$CODEchck;
13536: 	my $num2=$CODEseed+$courseseed+$symbchck;
13537: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13538: 	#&logthis("rndseed :$num1:$num2:$symb");
13539: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13540: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13541: 	return "$num1:$num2";
13542:     }
13543: }
13544: 
13545: sub rndseed_CODE_64bit5 {
13546:     my ($symb,$courseid,$domain,$username)=@_;
13547:     my $code = &getCODE();
13548:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13549:     return "$num1:$num2";
13550: }
13551: 
13552: sub setup_random_from_rndseed {
13553:     my ($rndseed)=@_;
13554:     if ($rndseed =~/([,:])/) {
13555:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13556:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13557:             &Math::Random::random_set_seed_from_phrase($rndseed);
13558:         } else {
13559:             &Math::Random::random_set_seed($num1,$num2);
13560:         }
13561:     } else {
13562: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13563:     }
13564: }
13565: 
13566: sub latest_receipt_algorithm_id {
13567:     return 'receipt3';
13568: }
13569: 
13570: sub recunique {
13571:     my $fucourseid=shift;
13572:     my $unique;
13573:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13574: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13575: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13576:     } else {
13577: 	$unique=$perlvar{'lonReceipt'};
13578:     }
13579:     return unpack("%32C*",$unique);
13580: }
13581: 
13582: sub recprefix {
13583:     my $fucourseid=shift;
13584:     my $prefix;
13585:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13586: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13587: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13588:     } else {
13589: 	$prefix=$perlvar{'lonHostID'};
13590:     }
13591:     return unpack("%32C*",$prefix);
13592: }
13593: 
13594: sub ireceipt {
13595:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13596: 
13597:     my $return =&recprefix($fucourseid).'-';
13598: 
13599:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13600: 	$env{'request.state'} eq 'construct') {
13601: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13602: 	return $return;
13603:     }
13604: 
13605:     my $cuname=unpack("%32C*",$funame);
13606:     my $cudom=unpack("%32C*",$fudom);
13607:     my $cucourseid=unpack("%32C*",$fucourseid);
13608:     my $cusymb=unpack("%32C*",$fusymb);
13609:     my $cunique=&recunique($fucourseid);
13610:     my $cpart=unpack("%32S*",$part);
13611:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13612: 
13613: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13614: 			       
13615: 	$return.= ($cunique%$cuname+
13616: 		   $cunique%$cudom+
13617: 		   $cusymb%$cuname+
13618: 		   $cusymb%$cudom+
13619: 		   $cucourseid%$cuname+
13620: 		   $cucourseid%$cudom+
13621: 		   $cpart%$cuname+
13622: 		   $cpart%$cudom);
13623:     } else {
13624: 	$return.= ($cunique%$cuname+
13625: 		   $cunique%$cudom+
13626: 		   $cusymb%$cuname+
13627: 		   $cusymb%$cudom+
13628: 		   $cucourseid%$cuname+
13629: 		   $cucourseid%$cudom);
13630:     }
13631:     return $return;
13632: }
13633: 
13634: sub receipt {
13635:     my ($part)=@_;
13636:     my ($symb,$courseid,$domain,$name) = &whichuser();
13637:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13638: }
13639: 
13640: sub whichuser {
13641:     my ($passedsymb)=@_;
13642:     my ($symb,$courseid,$domain,$name,$publicuser);
13643:     if (defined($env{'form.grade_symb'})) {
13644: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13645: 	my $allowed=&allowed('vgr',$tmp_courseid);
13646: 	if (!$allowed &&
13647: 	    exists($env{'request.course.sec'}) &&
13648: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13649: 	    $allowed=&allowed('vgr',$tmp_courseid.
13650: 			      '/'.$env{'request.course.sec'});
13651: 	}
13652: 	if ($allowed) {
13653: 	    ($symb)=&get_env_multiple('form.grade_symb');
13654: 	    $courseid=$tmp_courseid;
13655: 	    ($domain)=&get_env_multiple('form.grade_domain');
13656: 	    ($name)=&get_env_multiple('form.grade_username');
13657: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13658: 	}
13659:     }
13660:     if (!$passedsymb) {
13661: 	$symb=&symbread();
13662:     } else {
13663: 	$symb=$passedsymb;
13664:     }
13665:     $courseid=$env{'request.course.id'};
13666:     $domain=$env{'user.domain'};
13667:     $name=$env{'user.name'};
13668:     if ($name eq 'public' && $domain eq 'public') {
13669: 	if (!defined($env{'form.username'})) {
13670: 	    $env{'form.username'}.=time.rand(10000000);
13671: 	}
13672: 	$name.=$env{'form.username'};
13673:     }
13674:     return ($symb,$courseid,$domain,$name,$publicuser);
13675: 
13676: }
13677: 
13678: # ------------------------------------------------------------ Serves up a file
13679: # returns either the contents of the file or 
13680: # -1 if the file doesn't exist
13681: #
13682: # if the target is a file that was uploaded via DOCS, 
13683: # a check will be made to see if a current copy exists on the local server,
13684: # if it does this will be served, otherwise a copy will be retrieved from
13685: # the home server for the course and stored in /home/httpd/html/userfiles on
13686: # the local server.   
13687: 
13688: sub getfile {
13689:     my ($file) = @_;
13690:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13691:     &repcopy($file);
13692:     return &readfile($file);
13693: }
13694: 
13695: sub repcopy_userfile {
13696:     my ($file)=@_;
13697:     my $londocroot = $perlvar{'lonDocRoot'};
13698:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13699:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13700:     my ($cdom,$cnum,$filename) = 
13701: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13702:     my $uri="/uploaded/$cdom/$cnum/$filename";
13703:     if (-e "$file") {
13704: # we already have a local copy, check it out
13705: 	my @fileinfo = stat($file);
13706: 	my $rtncode;
13707: 	my $info;
13708: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13709: 	if ($lwpresp ne 'ok') {
13710: # there is no such file anymore, even though we had a local copy
13711: 	    if ($rtncode eq '404') {
13712: 		unlink($file);
13713: 	    }
13714: 	    return -1;
13715: 	}
13716: 	if ($info < $fileinfo[9]) {
13717: # nice, the file we have is up-to-date, just say okay
13718: 	    return 'ok';
13719: 	} else {
13720: # the file is outdated, get rid of it
13721: 	    unlink($file);
13722: 	}
13723:     }
13724: # one way or the other, at this point, we don't have the file
13725: # construct the correct path for the file
13726:     my @parts = ($cdom,$cnum); 
13727:     if ($filename =~ m|^(.+)/[^/]+$|) {
13728: 	push @parts, split(/\//,$1);
13729:     }
13730:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13731:     foreach my $part (@parts) {
13732: 	$path .= '/'.$part;
13733: 	if (!-e $path) {
13734: 	    mkdir($path,0770);
13735: 	}
13736:     }
13737: # now the path exists for sure
13738: # get a user agent
13739:     my $transferfile=$file.'.in.transfer';
13740: # FIXME: this should flock
13741:     if (-e $transferfile) { return 'ok'; }
13742:     my $request;
13743:     $uri=~s/^\///;
13744:     my $homeserver = &homeserver($cnum,$cdom);
13745:     my $hostname = &hostname($homeserver);
13746:     my $protocol = $protocol{$homeserver};
13747:     $protocol = 'http' if ($protocol ne 'https');
13748:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13749:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13750: # did it work?
13751:     if ($response->is_error()) {
13752: 	unlink($transferfile);
13753: 	&logthis("Userfile repcopy failed for $uri");
13754: 	return -1;
13755:     }
13756: # worked, rename the transfer file
13757:     rename($transferfile,$file);
13758:     return 'ok';
13759: }
13760: 
13761: sub tokenwrapper {
13762:     my $uri=shift;
13763:     $uri=~s|^https?\://([^/]+)||;
13764:     $uri=~s|^/||;
13765:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13766:     my $token=$1;
13767:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13768:     if ($udom && $uname && $file) {
13769: 	$file=~s|(\?\.*)*$||;
13770:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13771:         my $homeserver = &homeserver($uname,$udom);
13772:         my $hostname = &hostname($homeserver);
13773:         my $protocol = $protocol{$homeserver};
13774:         $protocol = 'http' if ($protocol ne 'https');
13775:         return $protocol.'://'.$hostname.'/'.$uri.
13776:                (($uri=~/\?/)?'&':'?').'token='.$token.
13777:                                '&tokenissued='.$perlvar{'lonHostID'};
13778:     } else {
13779:         return '/adm/notfound.html';
13780:     }
13781: }
13782: 
13783: # call with reqtype HEAD: get last modification time
13784: # call with reqtype GET: get the file contents
13785: # Do not call this with reqtype GET for large files! It loads everything into memory
13786: #
13787: sub getuploaded {
13788:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13789:     $uri=~s/^\///;
13790:     my $homeserver = &homeserver($cnum,$cdom);
13791:     my $hostname = &hostname($homeserver);
13792:     my $protocol = $protocol{$homeserver};
13793:     $protocol = 'http' if ($protocol ne 'https');
13794:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13795:     my $request=new HTTP::Request($reqtype,$uri);
13796:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13797:     $$rtncode = $response->code;
13798:     if (! $response->is_success()) {
13799: 	return 'failed';
13800:     }      
13801:     if ($reqtype eq 'HEAD') {
13802: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13803:     } elsif ($reqtype eq 'GET') {
13804: 	$$info = $response->content;
13805:     }
13806:     return 'ok';
13807: }
13808: 
13809: sub readfile {
13810:     my $file = shift;
13811:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13812:     my $fh;
13813:     open($fh,"<",$file);
13814:     my $a='';
13815:     while (my $line = <$fh>) { $a .= $line; }
13816:     return $a;
13817: }
13818: 
13819: sub filelocation {
13820:     my ($dir,$file) = @_;
13821:     my $location;
13822:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13823: 
13824:     if ($file =~ m-^/adm/-) {
13825: 	$file=~s-^/adm/wrapper/-/-;
13826: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13827:     }
13828: 
13829:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13830:         $location = $file;
13831:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13832:         my ($udom,$uname,$filename)=
13833:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13834:         my $home=&homeserver($uname,$udom);
13835:         my $is_me=0;
13836:         my @ids=&current_machine_ids();
13837:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13838:         if ($is_me) {
13839:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13840:         } else {
13841:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13842:   	      $udom.'/'.$uname.'/'.$filename;
13843:         }
13844:     } elsif ($file =~ m-^/adm/-) {
13845: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13846:     } else {
13847:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13848:         $file=~s:^/(res|priv)/:/:;
13849:         my $space=$1;
13850:         if ( !( $file =~ m:^/:) ) {
13851:             $location = $dir. '/'.$file;
13852:         } else {
13853:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13854:         }
13855:     }
13856:     $location=~s://+:/:g; # remove duplicate /
13857:     while ($location=~m{/\.\./}) {
13858: 	if ($location =~ m{/[^/]+/\.\./}) {
13859: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13860: 	} else {
13861: 	    $location=~ s{/\.\./}{/}g;
13862: 	}
13863:     } #remove dir/..
13864:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13865:     return $location;
13866: }
13867: 
13868: sub hreflocation {
13869:     my ($dir,$file)=@_;
13870:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13871: 	$file=filelocation($dir,$file);
13872:     } elsif ($file=~m-^/adm/-) {
13873: 	$file=~s-^/adm/wrapper/-/-;
13874: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13875:     }
13876:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13877: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13878:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13879: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13880: 	        {/uploaded/$1/$2/}x;
13881:     }
13882:     if ($file=~ m{^/userfiles/}) {
13883: 	$file =~ s{^/userfiles/}{/uploaded/};
13884:     }
13885:     return $file;
13886: }
13887: 
13888: 
13889: 
13890: 
13891: 
13892: sub current_machine_domains {
13893:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13894: }
13895: 
13896: sub machine_domains {
13897:     my ($hostname) = @_;
13898:     my @domains;
13899:     my %hostname = &all_hostnames();
13900:     while( my($id, $name) = each(%hostname)) {
13901: #	&logthis("-$id-$name-$hostname-");
13902: 	if ($hostname eq $name) {
13903: 	    push(@domains,&host_domain($id));
13904: 	}
13905:     }
13906:     return @domains;
13907: }
13908: 
13909: sub current_machine_ids {
13910:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13911: }
13912: 
13913: sub machine_ids {
13914:     my ($hostname) = @_;
13915:     $hostname ||= &hostname($perlvar{'lonHostID'});
13916:     my @ids;
13917:     my %name_to_host = &all_names();
13918:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13919: 	return @{ $name_to_host{$hostname} };
13920:     }
13921:     return;
13922: }
13923: 
13924: sub additional_machine_domains {
13925:     my @domains;
13926:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13927:     while( my $line = <$fh>) {
13928:         $line =~ s/\s//g;
13929:         push(@domains,$line);
13930:     }
13931:     return @domains;
13932: }
13933: 
13934: sub default_login_domain {
13935:     my $domain = $perlvar{'lonDefDomain'};
13936:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13937:     foreach my $posdom (&current_machine_domains(),
13938:                         &additional_machine_domains()) {
13939:         if (lc($posdom) eq lc($testdomain)) {
13940:             $domain=$posdom;
13941:             last;
13942:         }
13943:     }
13944:     return $domain;
13945: }
13946: 
13947: sub uses_sts {
13948:     my ($ignore_cache) = @_;
13949:     my $lonhost = $perlvar{'lonHostID'};
13950:     my $hostname = &hostname($lonhost);
13951:     my $sts_on;
13952:     if ($protocol{$lonhost} eq 'https') {
13953:         my $cachetime = 12*3600;
13954:         if (!$ignore_cache) {
13955:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13956:             if (defined($cached)) {
13957:                 return $sts_on;
13958:             }
13959:         }
13960:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13961:         my $request=new HTTP::Request('HEAD',$url);
13962:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
13963:         if ($response->is_success) {
13964:             my $has_sts = $response->header('Strict-Transport-Security');
13965:             if ($has_sts eq '') {
13966:                 $sts_on = 0;
13967:             } else {
13968:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13969:                     my $maxage = $1;
13970:                     if ($maxage) {
13971:                         $sts_on = 1;
13972:                     } else {
13973:                         $sts_on = 0;
13974:                     }
13975:                 } else {
13976:                     $sts_on = 0;
13977:                 }
13978:             }
13979:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13980:         }
13981:     }
13982:     return;
13983: }
13984: 
13985: # ------------------------------------------------------------- Declutters URLs
13986: 
13987: sub declutter {
13988:     my $thisfn=shift;
13989:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13990:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13991:         $thisfn=~s{^/home/httpd/html}{};
13992:     }
13993:     $thisfn=~s/^\///;
13994:     $thisfn=~s|^adm/wrapper/||;
13995:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13996:     $thisfn=~s/^res\///;
13997:     $thisfn=~s/^priv\///;
13998:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13999:         $thisfn=~s/\?.+$//;
14000:     }
14001:     return $thisfn;
14002: }
14003: 
14004: # ------------------------------------------------------------- Clutter up URLs
14005: 
14006: sub clutter {
14007:     my $thisfn='/'.&declutter(shift);
14008:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14009: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14010:        $thisfn='/res'.$thisfn; 
14011:     }
14012:     if ($thisfn !~m|^/adm|) {
14013: 	if ($thisfn =~ m|^/ext/|) {
14014: 	    $thisfn='/adm/wrapper'.$thisfn;
14015: 	} else {
14016: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14017: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14018: 	    if ($embstyle eq 'ssi'
14019: 		|| ($embstyle eq 'hdn')
14020: 		|| ($embstyle eq 'rat')
14021: 		|| ($embstyle eq 'prv')
14022: 		|| ($embstyle eq 'ign')) {
14023: 		#do nothing with these
14024: 	    } elsif (($embstyle eq 'img') 
14025: 		|| ($embstyle eq 'emb')
14026: 		|| ($embstyle eq 'wrp')) {
14027: 		$thisfn='/adm/wrapper'.$thisfn;
14028: 	    } elsif ($embstyle eq 'unk'
14029: 		     && $thisfn!~/\.(sequence|page)$/) {
14030: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14031: 	    } else {
14032: #		&logthis("Got a blank emb style");
14033: 	    }
14034: 	}
14035:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14036:         $thisfn='/adm/wrapper'.$thisfn;
14037:     }
14038:     return $thisfn;
14039: }
14040: 
14041: sub clutter_with_no_wrapper {
14042:     my $uri = &clutter(shift);
14043:     if ($uri =~ m-^/adm/-) {
14044: 	$uri =~ s-^/adm/wrapper/-/-;
14045: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14046:     }
14047:     return $uri;
14048: }
14049: 
14050: sub freeze_escape {
14051:     my ($value)=@_;
14052:     if (ref($value)) {
14053: 	$value=&nfreeze($value);
14054: 	return '__FROZEN__'.&escape($value);
14055:     }
14056:     return &escape($value);
14057: }
14058: 
14059: 
14060: sub thaw_unescape {
14061:     my ($value)=@_;
14062:     if ($value =~ /^__FROZEN__/) {
14063: 	substr($value,0,10,undef);
14064: 	$value=&unescape($value);
14065: 	return &thaw($value);
14066:     }
14067:     return &unescape($value);
14068: }
14069: 
14070: sub correct_line_ends {
14071:     my ($result)=@_;
14072:     $$result =~s/\r\n/\n/mg;
14073:     $$result =~s/\r/\n/mg;
14074: }
14075: # ================================================================ Main Program
14076: 
14077: sub goodbye {
14078:    &logthis("Starting Shut down");
14079: #not converted to using infrastruture and probably shouldn't be
14080:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14081: #converted
14082: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14083:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14084: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14085: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14086: #1.1 only
14087: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14088: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14089: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14090: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14091:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14092:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14093:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14094:    &flushcourselogs();
14095:    &logthis("Shutting down");
14096: }
14097: 
14098: sub get_dns {
14099:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14100:     if (!$ignore_cache) {
14101: 	my ($content,$cached)=
14102: 	    &Apache::lonnet::is_cached_new('dns',$url);
14103: 	if ($cached) {
14104: 	    &$func($content,$hashref);
14105: 	    return;
14106: 	}
14107:     }
14108: 
14109:     my %alldns;
14110:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14111:         foreach my $dns (<$config>) {
14112: 	    next if ($dns !~ /^\^(\S*)/x);
14113:             my $line = $1;
14114:             my ($host,$protocol) = split(/:/,$line);
14115:             if ($protocol ne 'https') {
14116:                 $protocol = 'http';
14117:             }
14118: 	    $alldns{$host} = $protocol;
14119:         }
14120:         close($config);
14121:     }
14122:     while (%alldns) {
14123: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14124: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14125:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14126:         delete($alldns{$dns});
14127: 	next if ($response->is_error());
14128:         if ($url eq '/adm/dns/loncapaCRL') {
14129:             return &$func($response);
14130:         } else {
14131: 	    my @content = split("\n",$response->content);
14132: 	    unless ($nocache) {
14133: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14134: 	    }
14135: 	    &$func(\@content,$hashref);
14136:             return;
14137:         }
14138:     }
14139:     my $which = (split('/',$url,4))[3];
14140:     if ($which eq 'loncapaCRL') {
14141:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14142:         if (-e $diskfile) {
14143:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14144:         } else {
14145:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14146:         }
14147:     } else {
14148:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14149:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14150:             my @content = <$config>;
14151:             close($config);
14152:             &$func(\@content,$hashref);
14153:         }
14154:     }
14155:     return;
14156: }
14157: 
14158: # ------------------------------------------------------Get DNS checksums file
14159: sub parse_dns_checksums_tab {
14160:     my ($lines,$hashref) = @_;
14161:     my $lonhost = $perlvar{'lonHostID'};
14162:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14163:     my $loncaparev = &get_server_loncaparev($machine_dom);
14164:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14165:     my $webconfdir = '/etc/httpd/conf';
14166:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14167:         $webconfdir = '/etc/apache2';
14168:     } elsif ($distro =~ /^sles(\d+)$/) {
14169:         if ($1 >= 10) {
14170:             $webconfdir = '/etc/apache2';
14171:         }
14172:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14173:         if ($1 >= 10.0) {
14174:             $webconfdir = '/etc/apache2';
14175:         }
14176:     }
14177:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14178:     my (%chksum,%revnum);
14179:     if (ref($lines) eq 'ARRAY') {
14180:         chomp(@{$lines});
14181:         my $version = shift(@{$lines});
14182:         if ($version eq $release) {  
14183:             foreach my $line (@{$lines}) {
14184:                 my ($file,$version,$shasum) = split(/,/,$line);
14185:                 if ($file =~ m{^/etc/httpd/conf}) {
14186:                     if ($webconfdir eq '/etc/apache2') {
14187:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14188:                     }
14189:                 }
14190:                 $chksum{$file} = $shasum;
14191:                 $revnum{$file} = $version;
14192:             }
14193:             if (ref($hashref) eq 'HASH') {
14194:                 %{$hashref} = (
14195:                                 sums     => \%chksum,
14196:                                 versions => \%revnum,
14197:                               );
14198:             }
14199:         }
14200:     }
14201:     return;
14202: }
14203: 
14204: sub fetch_dns_checksums {
14205:     my %checksums;
14206:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14207:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14208:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14209:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14210:              \%checksums);
14211:     return \%checksums;
14212: }
14213: 
14214: sub fetch_crl_pemfile {
14215:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14216: }
14217: 
14218: sub save_crl_pem {
14219:     my ($response) = @_;
14220:     my ($msg,$hadchanges);
14221:     if (ref($response)) {
14222:         my $now = time;
14223:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14224:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14225:         if (open(my $fh,'>',"$tmpcrl")) {
14226:             print $fh $response->content;
14227:             close($fh);
14228:             if (-e $lonca) {
14229:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14230:                     my $check = <PIPE>;
14231:                     close(PIPE);
14232:                     chomp($check);
14233:                     if ($check eq 'verify OK') {
14234:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14235:                         my $backup;
14236:                         if (-e $dest) {
14237:                             if (&File::Copy::move($dest,"$dest.bak")) {
14238:                                 $backup = 'ok';
14239:                             }
14240:                         }
14241:                         if (&File::Copy::move($tmpcrl,$dest)) {
14242:                             $msg = 'ok';
14243:                             if ($backup) {
14244:                                 my (%oldnums,%newnums);
14245:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14246:                                     while (<PIPE>) {
14247:                                         $oldnums{(split(/:/))[1]} = 1;
14248:                                     }
14249:                                     close(PIPE);
14250:                                 }
14251:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14252:                                     while(<PIPE>) {
14253:                                         $newnums{(split(/:/))[1]} = 1;
14254:                                     }
14255:                                     close(PIPE);
14256:                                 }
14257:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14258:                                     unless (exists($oldnums{$key})) {
14259:                                         $hadchanges = 1;
14260:                                         last;
14261:                                     }
14262:                                 }
14263:                                 unless ($hadchanges) {
14264:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14265:                                         unless (exists($newnums{$key})) {
14266:                                             $hadchanges = 1;
14267:                                             last;
14268:                                         }
14269:                                     }
14270:                                 }
14271:                             }
14272:                         }
14273:                     } else {
14274:                         unlink($tmpcrl);
14275:                     }
14276:                 } else {
14277:                     unlink($tmpcrl);
14278:                 }
14279:             } else {
14280:                 unlink($tmpcrl);
14281:             }
14282:         }
14283:     }
14284:     return ($msg,$hadchanges);
14285: }
14286: 
14287: # ------------------------------------------------------------ Read domain file
14288: {
14289:     my $loaded;
14290:     my %domain;
14291: 
14292:     sub parse_domain_tab {
14293: 	my ($lines) = @_;
14294: 	foreach my $line (@$lines) {
14295: 	    next if ($line =~ /^(\#|\s*$ )/x);
14296: 
14297: 	    chomp($line);
14298: 	    my ($name,@elements) = split(/:/,$line,9);
14299: 	    my %this_domain;
14300: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14301: 			       'lang_def', 'city', 'longi', 'lati',
14302: 			       'primary') {
14303: 		$this_domain{$field} = shift(@elements);
14304: 	    }
14305: 	    $domain{$name} = \%this_domain;
14306: 	}
14307:     }
14308: 
14309:     sub reset_domain_info {
14310: 	undef($loaded);
14311: 	undef(%domain);
14312:     }
14313: 
14314:     sub load_domain_tab {
14315: 	my ($ignore_cache,$nocache) = @_;
14316: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14317: 	my $fh;
14318: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14319: 	    my @lines = <$fh>;
14320: 	    &parse_domain_tab(\@lines);
14321: 	}
14322: 	close($fh);
14323: 	$loaded = 1;
14324:     }
14325: 
14326:     sub domain {
14327: 	&load_domain_tab() if (!$loaded);
14328: 
14329: 	my ($name,$what) = @_;
14330: 	return if ( !exists($domain{$name}) );
14331: 
14332: 	if (!$what) {
14333: 	    return $domain{$name}{'description'};
14334: 	}
14335: 	return $domain{$name}{$what};
14336:     }
14337: 
14338:     sub domain_info {
14339:         &load_domain_tab() if (!$loaded);
14340:         return %domain;
14341:     }
14342: 
14343: }
14344: 
14345: 
14346: # ------------------------------------------------------------- Read hosts file
14347: {
14348:     my %hostname;
14349:     my %hostdom;
14350:     my %libserv;
14351:     my $loaded;
14352:     my %name_to_host;
14353:     my %internetdom;
14354:     my %LC_dns_serv;
14355: 
14356:     sub parse_hosts_tab {
14357: 	my ($file) = @_;
14358: 	foreach my $configline (@$file) {
14359: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14360:             chomp($configline);
14361: 	    if ($configline =~ /^\^/) {
14362:                 if ($configline =~ /^\^([\w.\-]+)/) {
14363:                     $LC_dns_serv{$1} = 1;
14364:                 }
14365:                 next;
14366:             }
14367: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14368: 	    $name=~s/\s//g;
14369: 	    if ($id && $domain && $role && $name) {
14370:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14371:                     my $curr = $hostname{$id};
14372:                     my $skip;
14373:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14374:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14375:                             $skip = 1;
14376:                         } else {
14377:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14378:                         }
14379:                     }
14380:                     unless ($skip) {
14381:                         push(@{$name_to_host{$name}},$id);
14382:                     }
14383:                 } else {
14384:                     push(@{$name_to_host{$name}},$id);
14385:                 }
14386: 		$hostname{$id}=$name;
14387: 		$hostdom{$id}=$domain;
14388: 		if ($role eq 'library') { $libserv{$id}=$name; }
14389:                 if (defined($protocol)) {
14390:                     if ($protocol eq 'https') {
14391:                         $protocol{$id} = $protocol;
14392:                     } else {
14393:                         $protocol{$id} = 'http'; 
14394:                     }
14395:                 } else {
14396:                     $protocol{$id} = 'http';
14397:                 }
14398:                 if (defined($intdom)) {
14399:                     $internetdom{$id} = $intdom;
14400:                 }
14401: 	    }
14402: 	}
14403:     }
14404:     
14405:     sub reset_hosts_info {
14406: 	&purge_remembered();
14407: 	&reset_domain_info();
14408: 	&reset_hosts_ip_info();
14409:         undef(%internetdom);
14410: 	undef(%name_to_host);
14411: 	undef(%hostname);
14412: 	undef(%hostdom);
14413: 	undef(%libserv);
14414: 	undef($loaded);
14415:     }
14416: 
14417:     sub load_hosts_tab {
14418: 	my ($ignore_cache,$nocache) = @_;
14419: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14420: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14421: 	my @config = <$config>;
14422: 	&parse_hosts_tab(\@config);
14423: 	close($config);
14424: 	$loaded=1;
14425:     }
14426: 
14427:     sub hostname {
14428: 	&load_hosts_tab() if (!$loaded);
14429: 
14430: 	my ($lonid) = @_;
14431: 	return $hostname{$lonid};
14432:     }
14433: 
14434:     sub all_hostnames {
14435: 	&load_hosts_tab() if (!$loaded);
14436: 
14437: 	return %hostname;
14438:     }
14439: 
14440:     sub all_names {
14441:         my ($ignore_cache,$nocache) = @_;
14442: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14443: 
14444: 	return %name_to_host;
14445:     }
14446: 
14447:     sub all_host_domain {
14448:         &load_hosts_tab() if (!$loaded);
14449:         return %hostdom;
14450:     }
14451: 
14452:     sub all_host_intdom {
14453:         &load_hosts_tab() if (!$loaded);
14454:         return %internetdom;
14455:     }
14456: 
14457:     sub is_library {
14458: 	&load_hosts_tab() if (!$loaded);
14459: 
14460: 	return exists($libserv{$_[0]});
14461:     }
14462: 
14463:     sub all_library {
14464: 	&load_hosts_tab() if (!$loaded);
14465: 
14466: 	return %libserv;
14467:     }
14468: 
14469:     sub unique_library {
14470: 	#2x reverse removes all hostnames that appear more than once
14471:         my %unique = reverse &all_library();
14472:         return reverse %unique;
14473:     }
14474: 
14475:     sub get_servers {
14476: 	&load_hosts_tab() if (!$loaded);
14477: 
14478: 	my ($domain,$type) = @_;
14479: 	my %possible_hosts = ($type eq 'library') ? %libserv
14480: 	                                          : %hostname;
14481: 	my %result;
14482: 	if (ref($domain) eq 'ARRAY') {
14483: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14484: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14485: 		    $result{$host} = $hostname;
14486: 		}
14487: 	    }
14488: 	} else {
14489: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14490: 		if ($hostdom{$host} eq $domain) {
14491: 		    $result{$host} = $hostname;
14492: 		}
14493: 	    }
14494: 	}
14495: 	return %result;
14496:     }
14497: 
14498:     sub get_unique_servers {
14499:         my %unique = reverse &get_servers(@_);
14500: 	return reverse %unique;
14501:     }
14502: 
14503:     sub host_domain {
14504: 	&load_hosts_tab() if (!$loaded);
14505: 
14506: 	my ($lonid) = @_;
14507: 	return $hostdom{$lonid};
14508:     }
14509: 
14510:     sub all_domains {
14511: 	&load_hosts_tab() if (!$loaded);
14512: 
14513: 	my %seen;
14514: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14515: 	return @uniq;
14516:     }
14517: 
14518:     sub internet_dom {
14519:         &load_hosts_tab() if (!$loaded);
14520: 
14521:         my ($lonid) = @_;
14522:         return $internetdom{$lonid};
14523:     }
14524: 
14525:     sub is_LC_dns {
14526:         &load_hosts_tab() if (!$loaded);
14527: 
14528:         my ($hostname) = @_;
14529:         return exists($LC_dns_serv{$hostname});
14530:     }
14531: 
14532: }
14533: 
14534: { 
14535:     my %iphost;
14536:     my %name_to_ip;
14537:     my %lonid_to_ip;
14538: 
14539:     sub get_hosts_from_ip {
14540: 	my ($ip) = @_;
14541: 	my %iphosts = &get_iphost();
14542: 	if (ref($iphosts{$ip})) {
14543: 	    return @{$iphosts{$ip}};
14544: 	}
14545: 	return;
14546:     }
14547:     
14548:     sub reset_hosts_ip_info {
14549: 	undef(%iphost);
14550: 	undef(%name_to_ip);
14551: 	undef(%lonid_to_ip);
14552:     }
14553: 
14554:     sub get_host_ip {
14555: 	my ($lonid) = @_;
14556: 	if (exists($lonid_to_ip{$lonid})) {
14557: 	    return $lonid_to_ip{$lonid};
14558: 	}
14559: 	my $name=&hostname($lonid);
14560:    	my $ip = gethostbyname($name);
14561: 	return if (!$ip || length($ip) ne 4);
14562: 	$ip=inet_ntoa($ip);
14563: 	$name_to_ip{$name}   = $ip;
14564: 	$lonid_to_ip{$lonid} = $ip;
14565: 	return $ip;
14566:     }
14567:     
14568:     sub get_iphost {
14569: 	my ($ignore_cache,$nocache) = @_;
14570: 
14571: 	if (!$ignore_cache) {
14572: 	    if (%iphost) {
14573: 		return %iphost;
14574: 	    }
14575: 	    my ($ip_info,$cached)=
14576: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14577: 	    if ($cached) {
14578: 		%iphost      = %{$ip_info->[0]};
14579: 		%name_to_ip  = %{$ip_info->[1]};
14580: 		%lonid_to_ip = %{$ip_info->[2]};
14581: 		return %iphost;
14582: 	    }
14583: 	}
14584: 
14585: 	# get yesterday's info for fallback
14586: 	my %old_name_to_ip;
14587: 	my ($ip_info,$cached)=
14588: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14589: 	if ($cached) {
14590: 	    %old_name_to_ip = %{$ip_info->[1]};
14591: 	}
14592: 
14593: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14594: 	foreach my $name (keys(%name_to_host)) {
14595: 	    my $ip;
14596: 	    if (!exists($name_to_ip{$name})) {
14597: 		$ip = gethostbyname($name);
14598: 		if (!$ip || length($ip) ne 4) {
14599: 		    if (defined($old_name_to_ip{$name})) {
14600: 			$ip = $old_name_to_ip{$name};
14601: 			&logthis("Can't find $name defaulting to old $ip");
14602: 		    } else {
14603: 			&logthis("Name $name no IP found");
14604: 			next;
14605: 		    }
14606: 		} else {
14607: 		    $ip=inet_ntoa($ip);
14608: 		}
14609: 		$name_to_ip{$name} = $ip;
14610: 	    } else {
14611: 		$ip = $name_to_ip{$name};
14612: 	    }
14613: 	    foreach my $id (@{ $name_to_host{$name} }) {
14614: 		$lonid_to_ip{$id} = $ip;
14615: 	    }
14616: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14617: 	}
14618:         unless ($nocache) {
14619: 	    &do_cache_new('iphost','iphost',
14620: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14621: 		          48*60*60);
14622:         }
14623: 
14624: 	return %iphost;
14625:     }
14626: 
14627:     #
14628:     #  Given a DNS returns the loncapa host name for that DNS 
14629:     # 
14630:     sub host_from_dns {
14631:         my ($dns) = @_;
14632:         my @hosts;
14633:         my $ip;
14634: 
14635:         if (exists($name_to_ip{$dns})) {
14636:             $ip = $name_to_ip{$dns};
14637:         }
14638:         if (!$ip) {
14639:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14640:             if (length($ip) == 4) { 
14641: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14642:             }
14643:         }
14644:         if ($ip) {
14645: 	    @hosts = get_hosts_from_ip($ip);
14646: 	    return $hosts[0];
14647:         }
14648:         return undef;
14649:     }
14650: 
14651:     sub get_internet_names {
14652:         my ($lonid) = @_;
14653:         return if ($lonid eq '');
14654:         my ($idnref,$cached)=
14655:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14656:         if ($cached) {
14657:             return $idnref;
14658:         }
14659:         my $ip = &get_host_ip($lonid);
14660:         my @hosts = &get_hosts_from_ip($ip);
14661:         my %iphost = &get_iphost();
14662:         my (@idns,%seen);
14663:         foreach my $id (@hosts) {
14664:             my $dom = &host_domain($id);
14665:             my $prim_id = &domain($dom,'primary');
14666:             my $prim_ip = &get_host_ip($prim_id);
14667:             next if ($seen{$prim_ip});
14668:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14669:                 foreach my $id (@{$iphost{$prim_ip}}) {
14670:                     my $intdom = &internet_dom($id);
14671:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14672:                         push(@idns,$intdom);
14673:                     }
14674:                 }
14675:             }
14676:             $seen{$prim_ip} = 1;
14677:         }
14678:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14679:     }
14680: 
14681: }
14682: 
14683: sub all_loncaparevs {
14684:     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);
14685: }
14686: 
14687: # ---------------------------------------------------------- Read loncaparev table
14688: {
14689:     sub load_loncaparevs { 
14690:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14691:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14692:                 while (my $configline=<$config>) {
14693:                     chomp($configline);
14694:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14695:                     $loncaparevs{$hostid}=$loncaparev;
14696:                 }
14697:                 close($config);
14698:             }
14699:         }
14700:     }
14701: }
14702: 
14703: # ---------------------------------------------------------- Read serverhostID table
14704: {
14705:     sub load_serverhomeIDs {
14706:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14707:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14708:                 while (my $configline=<$config>) {
14709:                     chomp($configline);
14710:                     my ($name,$id)=split(/:/,$configline);
14711:                     $serverhomeIDs{$name}=$id;
14712:                 }
14713:                 close($config);
14714:             }
14715:         }
14716:     }
14717: }
14718: 
14719: 
14720: BEGIN {
14721: 
14722: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14723:     unless ($readit) {
14724: {
14725:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14726:     %perlvar = (%perlvar,%{$configvars});
14727: }
14728: 
14729: 
14730: # ------------------------------------------------------ Read spare server file
14731: {
14732:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14733: 
14734:     while (my $configline=<$config>) {
14735:        chomp($configline);
14736:        if ($configline) {
14737: 	   my ($host,$type) = split(':',$configline,2);
14738: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14739: 	   push(@{ $spareid{$type} }, $host);
14740:        }
14741:     }
14742:     close($config);
14743: }
14744: # ------------------------------------------------------------ Read permissions
14745: {
14746:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14747: 
14748:     while (my $configline=<$config>) {
14749: 	chomp($configline);
14750: 	if ($configline) {
14751: 	    my ($role,$perm)=split(/ /,$configline);
14752: 	    if ($perm ne '') { $pr{$role}=$perm; }
14753: 	}
14754:     }
14755:     close($config);
14756: }
14757: 
14758: # -------------------------------------------- Read plain texts for permissions
14759: {
14760:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14761: 
14762:     while (my $configline=<$config>) {
14763: 	chomp($configline);
14764: 	if ($configline) {
14765: 	    my ($short,@plain)=split(/:/,$configline);
14766:             %{$prp{$short}} = ();
14767: 	    if (@plain > 0) {
14768:                 $prp{$short}{'std'} = $plain[0];
14769:                 for (my $i=1; $i<@plain; $i++) {
14770:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14771:                 }
14772:             }
14773: 	}
14774:     }
14775:     close($config);
14776: }
14777: 
14778: # ---------------------------------------------------------- Read package table
14779: {
14780:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14781: 
14782:     while (my $configline=<$config>) {
14783: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14784: 	chomp($configline);
14785: 	my ($short,$plain)=split(/:/,$configline);
14786: 	my ($pack,$name)=split(/\&/,$short);
14787: 	if ($plain ne '') {
14788: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14789: 	    $packagetab{$short}=$plain; 
14790: 	}
14791:     }
14792:     close($config);
14793: }
14794: 
14795: # ---------------------------------------------------------- Read loncaparev table
14796: 
14797: &load_loncaparevs();
14798: 
14799: # ---------------------------------------------------------- Read serverhostID table
14800: 
14801: &load_serverhomeIDs();
14802: 
14803: # ---------------------------------------------------------- Read releaseslist XML
14804: {
14805:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14806:     if (-e $file) {
14807:         my $parser = HTML::LCParser->new($file);
14808:         while (my $token = $parser->get_token()) {
14809:             if ($token->[0] eq 'S') {
14810:                 my $item = $token->[1];
14811:                 my $name = $token->[2]{'name'};
14812:                 my $value = $token->[2]{'value'};
14813:                 my $valuematch = $token->[2]{'valuematch'};
14814:                 my $namematch = $token->[2]{'namematch'};
14815:                 if ($item eq 'parameter') {
14816:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14817:                         my $release = $parser->get_text();
14818:                         $release =~ s/(^\s*|\s*$ )//gx;
14819:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14820:                     }
14821:                 } elsif ($item ne '' && $name ne '') {
14822:                     my $release = $parser->get_text();
14823:                     $release =~ s/(^\s*|\s*$ )//gx;
14824:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14825:                 }
14826:             }
14827:         }
14828:     }
14829: }
14830: 
14831: # ---------------------------------------------------------- Read managers table
14832: {
14833:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14834:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14835:             while (my $configline=<$config>) {
14836:                 chomp($configline);
14837:                 next if ($configline =~ /^\#/);
14838:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14839:                     $managerstab{$configline} = 1;
14840:                 }
14841:             }
14842:             close($config);
14843:         }
14844:     }
14845: }
14846: 
14847: # ------------- set up temporary directory
14848: {
14849:     $tmpdir = LONCAPA::tempdir();
14850: 
14851: }
14852: 
14853: # ------------- set default texengine (domain default overrides this)
14854: {
14855:     $deftex = LONCAPA::texengine();
14856: }
14857: 
14858: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14859: 				'compress_threshold'=> 20_000,
14860:  			        });
14861: 
14862: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14863: $dumpcount=0;
14864: $locknum=0;
14865: 
14866: &logtouch();
14867: &logthis('<font color="yellow">INFO: Read configuration</font>');
14868: $readit=1;
14869:     {
14870: 	use integer;
14871: 	my $test=(2**32)+1;
14872: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14873: 	&logthis(" Detected 64bit platform ($_64bit)");
14874:     }
14875: }
14876: }
14877: 
14878: 1;
14879: __END__
14880: 
14881: =pod
14882: 
14883: =head1 NAME
14884: 
14885: Apache::lonnet - Subroutines to ask questions about things in the network.
14886: 
14887: =head1 SYNOPSIS
14888: 
14889: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14890: 
14891:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14892: 
14893: Common parameters:
14894: 
14895: =over 4
14896: 
14897: =item *
14898: 
14899: $uname : an internal username (if $cname expecting a course Id specifically)
14900: 
14901: =item *
14902: 
14903: $udom : a domain (if $cdom expecting a course's domain specifically)
14904: 
14905: =item *
14906: 
14907: $symb : a resource instance identifier
14908: 
14909: =item *
14910: 
14911: $namespace : the name of a .db file that contains the data needed or
14912: being set.
14913: 
14914: =back
14915: 
14916: =head1 OVERVIEW
14917: 
14918: lonnet provides subroutines which interact with the
14919: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14920: about classes, users, and resources.
14921: 
14922: For many of these objects you can also use this to store data about
14923: them or modify them in various ways.
14924: 
14925: =head2 Symbs
14926: 
14927: To identify a specific instance of a resource, LON-CAPA uses symbols
14928: or "symbs"X<symb>. These identifiers are built from the URL of the
14929: map, the resource number of the resource in the map, and the URL of
14930: the resource itself. The latter is somewhat redundant, but might help
14931: if maps change.
14932: 
14933: An example is
14934: 
14935:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14936: 
14937: The respective map entry is
14938: 
14939:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14940:   title="Problem 2">
14941:  </resource>
14942: 
14943: Symbs are used by the random number generator, as well as to store and
14944: restore data specific to a certain instance of for example a problem.
14945: 
14946: =head2 Storing And Retrieving Data
14947: 
14948: X<store()>X<cstore()>X<restore()>Three of the most important functions
14949: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14950: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14951: is is the non-critical message twin of cstore. These functions are for
14952: handlers to store a perl hash to a user's permanent data space in an
14953: easy manner, and to retrieve it again on another call. It is expected
14954: that a handler would use this once at the beginning to retrieve data,
14955: and then again once at the end to send only the new data back.
14956: 
14957: The data is stored in the user's data directory on the user's
14958: homeserver under the ID of the course.
14959: 
14960: The hash that is returned by restore will have all of the previous
14961: value for all of the elements of the hash.
14962: 
14963: Example:
14964: 
14965:  #creating a hash
14966:  my %hash;
14967:  $hash{'foo'}='bar';
14968: 
14969:  #storing it
14970:  &Apache::lonnet::cstore(\%hash);
14971: 
14972:  #changing a value
14973:  $hash{'foo'}='notbar';
14974: 
14975:  #adding a new value
14976:  $hash{'bar'}='foo';
14977:  &Apache::lonnet::cstore(\%hash);
14978: 
14979:  #retrieving the hash
14980:  my %history=&Apache::lonnet::restore();
14981: 
14982:  #print the hash
14983:  foreach my $key (sort(keys(%history))) {
14984:    print("\%history{$key} = $history{$key}");
14985:  }
14986: 
14987: Will print out:
14988: 
14989:  %history{1:foo} = bar
14990:  %history{1:keys} = foo:timestamp
14991:  %history{1:timestamp} = 990455579
14992:  %history{2:bar} = foo
14993:  %history{2:foo} = notbar
14994:  %history{2:keys} = foo:bar:timestamp
14995:  %history{2:timestamp} = 990455580
14996:  %history{bar} = foo
14997:  %history{foo} = notbar
14998:  %history{timestamp} = 990455580
14999:  %history{version} = 2
15000: 
15001: Note that the special hash entries C<keys>, C<version> and
15002: C<timestamp> were added to the hash. C<version> will be equal to the
15003: total number of versions of the data that have been stored. The
15004: C<timestamp> attribute will be the UNIX time the hash was
15005: stored. C<keys> is available in every historical section to list which
15006: keys were added or changed at a specific historical revision of a
15007: hash.
15008: 
15009: B<Warning>: do not store the hash that restore returns directly. This
15010: will cause a mess since it will restore the historical keys as if the
15011: were new keys. I.E. 1:foo will become 1:1:foo etc.
15012: 
15013: Calling convention:
15014: 
15015:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15016:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15017: 
15018: For more detailed information, see lonnet specific documentation.
15019: 
15020: =head1 RETURN MESSAGES
15021: 
15022: =over 4
15023: 
15024: =item * B<con_lost>: unable to contact remote host
15025: 
15026: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15027: when the connection is brought back up
15028: 
15029: =item * B<con_failed>: unable to contact remote host and unable to save message
15030: for later delivery
15031: 
15032: =item * B<error:>: an error a occurred, a description of the error follows the :
15033: 
15034: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15035: that was requested
15036: 
15037: =back
15038: 
15039: =head1 PUBLIC SUBROUTINES
15040: 
15041: =head2 Session Environment Functions
15042: 
15043: =over 4
15044: 
15045: =item * 
15046: X<appenv()>
15047: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15048: the user envirnoment file, and will be restored for each access this
15049: user makes during this session, also modifies the %env for the current
15050: process. Optional rolesarrayref - if defined contains a reference to an array
15051: of roles which are exempt from the restriction on modifying user.role entries 
15052: in the user's environment.db and in %env.    
15053: 
15054: =item *
15055: X<delenv()>
15056: B<delenv($delthis,$regexp)>: removes all items from the session
15057: environment file that begin with $delthis. If the 
15058: optional second arg - $regexp - is true, $delthis is treated as a 
15059: regular expression, otherwise \Q$delthis\E is used. 
15060: The values are also deleted from the current processes %env.
15061: 
15062: =item * get_env_multiple($name) 
15063: 
15064: gets $name from the %env hash, it seemlessly handles the cases where multiple
15065: values may be defined and end up as an array ref.
15066: 
15067: returns an array of values
15068: 
15069: =back
15070: 
15071: =head2 User Information
15072: 
15073: =over 4
15074: 
15075: =item *
15076: X<queryauthenticate()>
15077: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15078: authentication scheme
15079: 
15080: =item *
15081: X<authenticate()>
15082: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15083: authenticate user from domain's lib servers (first use the current
15084: one). C<$upass> should be the users password.
15085: $checkdefauth is optional (value is 1 if a check should be made to
15086:    authenticate user using default authentication method, and allow
15087:    account creation if username does not have account in the domain).
15088: $clientcancheckhost is optional (value is 1 if checking whether the
15089:    server can host will occur on the client side in lonauth.pm).   
15090: 
15091: =item *
15092: X<homeserver()>
15093: B<homeserver($uname,$udom)>: find the server which has
15094: the user's directory and files (there must be only one), this caches
15095: the answer, and also caches if there is a borken connection.
15096: 
15097: =item *
15098: X<idget()>
15099: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15100: a list of student/employee IDs or clicker IDs
15101: (student/employee IDs are a unique resource in a domain, there must be 
15102: only 1 ID per username, and only 1 username per ID in a specific domain).
15103: clickerIDs are not necessarily unique, as students might share clickers.
15104: (returns hash: id=>name,id=>name)
15105: 
15106: =item *
15107: X<idrget()>
15108: B<idrget($udom,@unames)>: find the IDs behind a list of
15109: usernames (returns hash: name=>id,name=>id)
15110: 
15111: =item *
15112: X<idput()>
15113: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15114: names and associated student/employee IDs or clicker IDs.
15115: 
15116: =item *
15117: X<iddel()>
15118: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15119: student/employee ID or clicker ID username look-ups from domain.
15120: The homeserver ($uhome) and namespace ($namespace) are optional.
15121: If no $uhome is provided, it will be determined usig &homeserver()
15122: for each user.  If no $namespace is provided, the default is ids.
15123: 
15124: =item *
15125: X<updateclickers()>
15126: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15127: clicker ID-to-username look-ups in clickers.db on library server.
15128: Permitted actions are add or del (i.e., add or delete). The 
15129: clickers.db contains clickerID as keys (escaped), and each corresponding
15130: value is an escaped comma-separated list of usernames (for whom the
15131: library server is the homeserver), who registered that particular ID.
15132: If $critical is true, the update will be sent via &critical, otherwise
15133: &reply() will be used.
15134: 
15135: =item *
15136: X<rolesinit()>
15137: B<rolesinit($udom,$username)>: get user privileges.
15138: returns user role, first access and timer interval hashes
15139: 
15140: =item *
15141: X<privileged()>
15142: B<privileged($username,$domain)>: returns a true if user has a
15143: privileged and active role (i.e. su or dc), false otherwise.
15144: 
15145: =item *
15146: X<getsection()>
15147: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15148: course $cname, return section name/number or '' for "not in course"
15149: and '-1' for "no section"
15150: 
15151: =item *
15152: X<userenvironment()>
15153: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15154: passed in @what from the requested user's environment, returns a hash
15155: 
15156: =item * 
15157: X<userlog_query()>
15158: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15159: activity.log file. %filters defines filters applied when parsing the
15160: log file. These can be start or end timestamps, or the type of action
15161: - log to look for Login or Logout events, check for Checkin or
15162: Checkout, role for role selection. The response is in the form
15163: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15164: escaped strings of the action recorded in the activity.log file.
15165: 
15166: =back
15167: 
15168: =head2 User Roles
15169: 
15170: =over 4
15171: 
15172: =item *
15173: 
15174: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15175: returns codes for allowed actions.
15176: 
15177: The first argument is required, all others are optional.
15178: 
15179: $priv is the privilege being checked.
15180: $uri contains additional information about what is being checked for access (e.g.,
15181: URL, course ID etc.). 
15182: $symb is the unique resource instance identifier in a course; if needed,
15183: but not provided, it will be retrieved via a call to &symbread(). 
15184: $role is the role for which a priv is being checked (only used if priv is evb). 
15185: $clientip is the user's IP address (only used when checking for access to portfolio 
15186: files).
15187: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15188: prevents recursive calls to &allowed.
15189: 
15190:  F: full access
15191:  U,I,K: authentication modes (cxx only)
15192:  '': forbidden
15193:  1: user needs to choose course
15194:  2: browse allowed
15195:  A: passphrase authentication needed
15196:  B: access temporarily blocked because of a blocking event in a course.
15197:  D: access blocked because access is required via session initiated via deep-link 
15198: 
15199: =item *
15200: 
15201: constructaccess($url,$setpriv) : check for access to construction space URL
15202: 
15203: See if the owner domain and name in the URL match those in the
15204: expected environment.  If so, return three element list
15205: ($ownername,$ownerdomain,$ownerhome).
15206: 
15207: Otherwise return the null string.
15208: 
15209: If second argument 'setpriv' is true, it assigns the privileges,
15210: and returns the same three element list, unless the owner has
15211: blocked "ad hoc" Domain Coordinator access to the Author Space,
15212: in which case the null string is returned.
15213: 
15214: =item *
15215: 
15216: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15217: define a custom role rolename set privileges in format of lonTabs/roles.tab
15218: for system, domain, and course level. $uname and $udom are optional (current
15219: user's username and domain will be used when either of $uname or $udom are absent.
15220: 
15221: =item *
15222: 
15223: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15224: (rolesplain.tab); plain text explanation of a user role term.
15225: $type is Course (default) or Community.
15226: If $forcedefault evaluates to true, text returned will be default 
15227: text for $type. Otherwise, if this is a course, the text returned 
15228: will be a custom name for the role (if defined in the course's 
15229: environment).  If no custom name is defined the default is returned.
15230:    
15231: =item *
15232: 
15233: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15234: All arguments are optional. Returns a hash of a roles, either for
15235: co-author/assistant author roles for a user's Construction Space
15236: (default), or if $context is 'userroles', roles for the user himself,
15237: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15238: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15239: For each key, value is set to colon-separated start and end times for
15240: the role.  If no username and domain are specified, will default to
15241: current user/domain. Types, roles, and roledoms are references to arrays
15242: of role statuses (active, future or previous), roles 
15243: (e.g., cc,in, st etc.) and domains of the roles which can be used
15244: to restrict the list of roles reported. If no array ref is 
15245: provided for types, will default to return only active roles.
15246: 
15247: =item *
15248: 
15249: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15250: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15251: 
15252: Additional optional arguments are: $type (if role checking is to be restricted 
15253: to certain user status types -- previous (expired roles), active (currently
15254: available roles) or future (roles available in the future), and
15255: $hideprivileged -- if true will not report course roles for users who
15256: have active Domain Coordinator role in course's domain or in additional
15257: domains (specified in 'Domains to check for privileged users' in course
15258: environment -- set via:  Course Settings -> Classlists and staff listing).
15259: 
15260: =item *
15261: 
15262: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15263: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15264: $possdomains and $possroles are optional array refs -- to domains to check and
15265: roles to check.  If $possdomains is not specified, a dump will be done of the
15266: users' roles.db to check for a dc or su role in any domain. This can be
15267: time consuming if &privileged is called repeatedly (e.g., when displaying a
15268: classlist), so in such cases, supplying a $possdomains array is preferred, as
15269: this then allows &privileged_by_domain() to be used, which caches the identity
15270: of privileged users, eliminating the need for repeated calls to &dump().
15271: 
15272: =item *
15273: 
15274: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15275: where the outer hash keys are domains specified in the $possdomains array ref,
15276: next inner hash keys are privileged roles specified in the $roles array ref,
15277: and the innermost hash contains key = value pairs for username:domain = end:start
15278: for active or future "privileged" users with that role in that domain. To avoid
15279: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15280: innerhash are cached using priv_$role and $dom as the identifiers.
15281: 
15282: =back
15283: 
15284: =head2 User Modification
15285: 
15286: =over 4
15287: 
15288: =item *
15289: 
15290: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15291: user for the level given by URL.  Optional start and end dates (leave empty
15292: string or zero for "no date")
15293: 
15294: =item *
15295: 
15296: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15297: change a users, password, possible return values are: ok,
15298: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15299: refused
15300: 
15301: =item *
15302: 
15303: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15304: 
15305: =item *
15306: 
15307: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15308:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15309: 
15310: will update user information (firstname,middlename,lastname,generation,
15311: permanentemail), and if forceid is true, student/employee ID also.
15312: A user's institutional affiliation(s) can also be updated.
15313: User information fields will not be overwritten with empty entries 
15314: unless the field is included in the $candelete array reference.
15315: This array is included when a single user is modified via "Manage Users",
15316: or when Autoupdate.pl is run by cron in a domain.
15317: 
15318: =item *
15319: 
15320: modifystudent
15321: 
15322: modify a student's enrollment and identification information.
15323: The course id is resolved based on the current user's environment.  
15324: This means the invoking user must be a course coordinator or otherwise
15325: associated with a course.
15326: 
15327: This call is essentially a wrapper for lonnet::modifyuser and
15328: lonnet::modify_student_enrollment
15329: 
15330: Inputs: 
15331: 
15332: =over 4
15333: 
15334: =item B<$udom> Student's loncapa domain
15335: 
15336: =item B<$uname> Student's loncapa login name
15337: 
15338: =item B<$uid> Student/Employee ID
15339: 
15340: =item B<$umode> Student's authentication mode
15341: 
15342: =item B<$upass> Student's password
15343: 
15344: =item B<$first> Student's first name
15345: 
15346: =item B<$middle> Student's middle name
15347: 
15348: =item B<$last> Student's last name
15349: 
15350: =item B<$gene> Student's generation
15351: 
15352: =item B<$usec> Student's section in course
15353: 
15354: =item B<$end> Unix time of the roles expiration
15355: 
15356: =item B<$start> Unix time of the roles start date
15357: 
15358: =item B<$forceid> If defined, allow $uid to be changed
15359: 
15360: =item B<$desiredhome> server to use as home server for student
15361: 
15362: =item B<$email> Student's permanent e-mail address
15363: 
15364: =item B<$type> Type of enrollment (auto or manual)
15365: 
15366: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15367: 
15368: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15369: 
15370: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15371: 
15372: =item B<$context> role change context (shown in User Management Logs display in a course)
15373: 
15374: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15375: 
15376: =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.
15377: 
15378: =back
15379: 
15380: =item *
15381: 
15382: modify_student_enrollment
15383: 
15384: Change a student's enrollment status in a class.  The environment variable
15385: 'role.request.course' must be defined for this function to proceed.
15386: 
15387: Inputs:
15388: 
15389: =over 4
15390: 
15391: =item $udom, student's domain
15392: 
15393: =item $uname, student's name
15394: 
15395: =item $uid, student's user id
15396: 
15397: =item $first, student's first name
15398: 
15399: =item $middle
15400: 
15401: =item $last
15402: 
15403: =item $gene
15404: 
15405: =item $usec
15406: 
15407: =item $end
15408: 
15409: =item $start
15410: 
15411: =item $type
15412: 
15413: =item $locktype
15414: 
15415: =item $cid
15416: 
15417: =item $selfenroll
15418: 
15419: =item $context
15420: 
15421: =item $credits, number of credits student will earn from this class
15422: 
15423: =item $instsec, institutional course section code for student
15424: 
15425: =back
15426: 
15427: 
15428: =item *
15429: 
15430: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15431: custom role; give a custom role to a user for the level given by URL.  Specify
15432: name and domain of role author, and role name
15433: 
15434: =item *
15435: 
15436: revokerole($udom,$uname,$url,$role) : revoke a role for url
15437: 
15438: =item *
15439: 
15440: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15441: 
15442: =back
15443: 
15444: =head2 Course Infomation
15445: 
15446: =over 4
15447: 
15448: =item *
15449: 
15450: coursedescription($courseid,$options) : returns a hash of information about the
15451: specified course id, including all environment settings for the
15452: course, the description of the course will be in the hash under the
15453: key 'description'
15454: 
15455: $options is an optional parameter that if supplied is a hash reference that controls
15456: what how this function works.  It has the following key/values:
15457: 
15458: =over 4
15459: 
15460: =item freshen_cache
15461: 
15462: If defined, and the environment cache for the course is valid, it is 
15463: returned in the returned hash.
15464: 
15465: =item one_time
15466: 
15467: If defined, the last cache time is set to _now_
15468: 
15469: =item user
15470: 
15471: If defined, the supplied username is used instead of the current user.
15472: 
15473: 
15474: =back
15475: 
15476: =item *
15477: 
15478: resdata($name,$domain,$type,@which) : request for current parameter
15479: setting for a specific $type, where $type is either 'course' or 'user',
15480: @what should be a list of parameters to ask about. This routine caches
15481: answers for 10 minutes.
15482: 
15483: =item *
15484: 
15485: get_courseresdata($courseid, $domain) : dump the entire course resource
15486: data base, returning a hash that is keyed by the resource name and has
15487: values that are the resource value.  I believe that the timestamps and
15488: versions are also returned.
15489: 
15490: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15491: supplemental content area. This routine caches the number of files for 
15492: 10 minutes.
15493: 
15494: =back
15495: 
15496: =head2 Course Modification
15497: 
15498: =over 4
15499: 
15500: =item *
15501: 
15502: writecoursepref($courseid,%prefs) : write preferences (environment
15503: database) for a course
15504: 
15505: =item *
15506: 
15507: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15508: 
15509: =item *
15510: 
15511: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15512: 
15513: =item *
15514: 
15515: is_course($courseid), is_course($cdom, $cnum)
15516: 
15517: Accepts either a combined $courseid (in the form of domain_courseid) or the
15518: two component version $cdom, $cnum. It checks if the specified course exists.
15519: 
15520: Returns:
15521:     undef if the course doesn't exist, otherwise
15522:     in scalar context the combined courseid.
15523:     in list context the two components of the course identifier, domain and 
15524:     courseid.    
15525: 
15526: =back
15527: 
15528: =head2 Bubblesheet Configuration
15529: 
15530: =over 4
15531: 
15532: =item *
15533: 
15534: get_scantron_config($which)
15535: 
15536: $which - the name of the configuration to parse from the file.
15537: 
15538: Parses and returns the bubblesheet configuration line selected as a
15539: hash of configuration file fields.
15540: 
15541: 
15542: Returns:
15543:     If the named configuration is not in the file, an empty
15544:     hash is returned.
15545: 
15546:     a hash with the fields
15547:       name         - internal name for the this configuration setup
15548:       description  - text to display to operator that describes this config
15549:       CODElocation - if 0 or the string 'none'
15550:                           - no CODE exists for this config
15551:                      if -1 || the string 'letter'
15552:                           - a CODE exists for this config and is
15553:                             a string of letters
15554:                      Unsupported value (but planned for future support)
15555:                           if a positive integer
15556:                                - The CODE exists as the first n items from
15557:                                  the question section of the form
15558:                           if the string 'number'
15559:                                - The CODE exists for this config and is
15560:                                  a string of numbers
15561:       CODEstart   - (only matter if a CODE exists) column in the line where
15562:                      the CODE starts
15563:       CODElength  - length of the CODE
15564:       IDstart     - column where the student/employee ID starts
15565:       IDlength    - length of the student/employee ID info
15566:       Qstart      - column where the information from the bubbled
15567:                     'questions' start
15568:       Qlength     - number of columns comprising a single bubble line from
15569:                     the sheet. (usually either 1 or 10)
15570:       Qon         - either a single character representing the character used
15571:                     to signal a bubble was chosen in the positional setup, or
15572:                     the string 'letter' if the letter of the chosen bubble is
15573:                     in the final, or 'number' if a number representing the
15574:                     chosen bubble is in the file (1->A 0->J)
15575:       Qoff        - the character used to represent that a bubble was
15576:                     left blank
15577:       PaperID     - if the scanning process generates a unique number for each
15578:                     sheet scanned the column that this ID number starts in
15579:       PaperIDlength - number of columns that comprise the unique ID number
15580:                       for the sheet of paper
15581:       FirstName   - column that the first name starts in
15582:       FirstNameLength - number of columns that the first name spans
15583:       LastName    - column that the last name starts in
15584:       LastNameLength - number of columns that the last name spans
15585:       BubblesPerRow - number of bubbles available in each row used to
15586:                       bubble an answer. (If not specified, 10 assumed).
15587: 
15588: 
15589: =item *
15590: 
15591: get_scantronformat_file($cdom)
15592: 
15593: $cdom - the course's domain (optional); if not supplied, uses
15594: domain for current $env{'request.course.id'}.
15595: 
15596: Returns an array containing lines from the scantron format file for
15597: the domain of the course.
15598: 
15599: If a url for a custom.tab file is listed in domain's configuration.db,
15600: lines are from this file.
15601: 
15602: Otherwise, if a default.tab has been published in RES space by the
15603: domainconfig user, lines are from this file.
15604: 
15605: Otherwise, fall back to getting lines from the legacy file on the
15606: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15607: 
15608: =back
15609: 
15610: =head2 Resource Subroutines
15611: 
15612: =over 4
15613: 
15614: =item *
15615: 
15616: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15617: 
15618: =item *
15619: 
15620: repcopy($filename) : subscribes to the requested file, and attempts to
15621: replicate from the owning library server, Might return
15622: 'unavailable', 'not_found', 'forbidden', 'ok', or
15623: 'bad_request', also attempts to grab the metadata for the
15624: resource. Expects the local filesystem pathname
15625: (/home/httpd/html/res/....)
15626: 
15627: =back
15628: 
15629: =head2 Resource Information
15630: 
15631: =over 4
15632: 
15633: =item *
15634: 
15635: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15636: and returns the value of a variety of different possible values,
15637: $varname should be a request string, and the other parameters can be
15638: used to specify who and what one is asking about. Ordinarily, $cid 
15639: does not need to be specified, as it is retrived from 
15640: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15641: within lonuserstate::loadmap() when initializing a course, before
15642: $env{'request.course.id'} has been set, so it needs to be provided
15643: in that one case.
15644: 
15645: Possible values for $varname are environment.lastname (or other item
15646: from the envirnment hash), user.name (or someother aspect about the
15647: user), resource.0.maxtries (or some other part and parameter of a
15648: resource)
15649: 
15650: =item *
15651: 
15652: directcondval($number) : get current value of a condition; reads from a state
15653: string
15654: 
15655: =item *
15656: 
15657: condval($condidx) : value of condition index based on state
15658: 
15659: =item *
15660: 
15661: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15662: resource's metadata, $what should be either a specific key, or either
15663: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15664: packages that this resource currently uses, the last 3 arguments are 
15665: only used internally for recursive metadata.
15666: 
15667: the toolsymb is only used where the uri is for an external tool (for which
15668: the uri as well as the symb are guaranteed to be unique).
15669: 
15670: this function automatically caches all requests except any made recursively
15671: to retrieve a list of metadata keys for an imported library file ($liburi is 
15672: defined).
15673: 
15674: =item *
15675: 
15676: metadata_query($query,$custom,$customshow) : make a metadata query against the
15677: network of library servers; returns file handle of where SQL and regex results
15678: will be stored for query
15679: 
15680: =item *
15681: 
15682: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15683: return symbolic list entry (all arguments optional). 
15684: 
15685: Args: filename is the filename (including path) for the file for which a symb 
15686: is required; donotrecurse, if true will prevent calls to allowed() being made 
15687: to check access status if more than one resource was found in the bighash 
15688: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15689: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15690: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15691: cause possible symbs to be checked to determine if they are subject to content
15692: blocking, if so they will not be included as possible symbs; possibles is a
15693: ref to a hash, which, as a side effect, will be populated with all possible 
15694: symbs (content blocking not tested).
15695:  
15696: returns the data handle
15697: 
15698: =item *
15699: 
15700: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15701: and is a possible symb for the URL in $thisfn, and if is an encrypted
15702: resource that the user accessed using /enc/ returns a 1 on success, 0
15703: on failure, user must be in a course, as it assumes the existence of
15704: the course initial hash, and uses $env('request.course.id'}.  The third
15705: arg is an optional reference to a scalar.  If this arg is passed in the 
15706: call to symbverify, it will be set to 1 if the symb has been set to be 
15707: encrypted; otherwise it will be null.  
15708: 
15709: =item *
15710: 
15711: symbclean($symb) : removes versions numbers from a symb, returns the
15712: cleaned symb
15713: 
15714: =item *
15715: 
15716: is_on_map($uri) : checks if the $uri is somewhere on the current
15717: course map, user must be in a course for it to work.
15718: 
15719: =item *
15720: 
15721: numval($salt) : return random seed value (addend for rndseed)
15722: 
15723: =item *
15724: 
15725: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15726: a random seed, all arguments are optional, if they aren't sent it uses the
15727: environment to derive them. Note: if symb isn't sent and it can't get one
15728: from &symbread it will use the current time as its return value
15729: 
15730: =item *
15731: 
15732: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15733: unfakeable, receipt
15734: 
15735: =item *
15736: 
15737: receipt() : API to ireceipt working off of env values; given out to users
15738: 
15739: =item *
15740: 
15741: countacc($url) : count the number of accesses to a given URL
15742: 
15743: =item *
15744: 
15745: 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
15746: 
15747: =item *
15748: 
15749: 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)
15750: 
15751: =item *
15752: 
15753: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15754: 
15755: =item *
15756: 
15757: devalidate($symb) : devalidate temporary spreadsheet calculations,
15758: forcing spreadsheet to reevaluate the resource scores next time.
15759: 
15760: =item * 
15761: 
15762: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15763: when viewing in course context.
15764: 
15765:  input: six args -- filename (decluttered), course number, course domain,
15766:                     url, symb (if registered) and group (if this is a 
15767:                     group item -- e.g., bulletin board, group page etc.).
15768: 
15769:  output: array of five scalars --
15770:          $cfile -- url for file editing if editable on current server
15771:          $home -- homeserver of resource (i.e., for author if published,
15772:                                           or course if uploaded.).
15773:          $switchserver --  1 if server switch will be needed.
15774:          $forceedit -- 1 if icon/link should be to go to edit mode 
15775:          $forceview -- 1 if icon/link should be to go to view mode
15776: 
15777: =item *
15778: 
15779: is_course_upload($file,$cnum,$cdom)
15780: 
15781: Used in course context to determine if current file was uploaded to 
15782: the course (i.e., would be found in /userfiles/docs on the course's 
15783: homeserver.
15784: 
15785:   input: 3 args -- filename (decluttered), course number and course domain.
15786:   output: boolean -- 1 if file was uploaded.
15787: 
15788: =back
15789: 
15790: =head2 Storing/Retreiving Data
15791: 
15792: =over 4
15793: 
15794: =item *
15795: 
15796: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15797: permanently for this url; hashref needs to be given and should be a \%hashname;
15798: the remaining args aren't required and if they aren't passed or are '' they will
15799: be derived from the env (with the exception of $laststore, which is an 
15800: optional arg used when a user's submission is stored in grading).
15801: $laststore is $version=$timestamp, where $version is the most recent version
15802: number retrieved for the corresponding $symb in the $namespace db file, and
15803: $timestamp is the timestamp for that transaction (UNIX time).
15804: $laststore is currently only passed when cstore() is called by 
15805: structuretags::finalize_storage().
15806: 
15807: =item *
15808: 
15809: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15810: but uses critical subroutine
15811: 
15812: =item *
15813: 
15814: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15815: all args are optional
15816: 
15817: =item *
15818: 
15819: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15820: dumps the complete (or key matching regexp) namespace into a hash
15821: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15822: normally &store()ed into
15823: 
15824: $range should be either an integer '100' (give me the first 100
15825:                                            matching records)
15826:               or be  two integers sperated by a - with no spaces
15827:                  '30-50' (give me the 30th through the 50th matching
15828:                           records)
15829: 
15830: 
15831: =item *
15832: 
15833: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15834: replaces a &store() version of data with a replacement set of data
15835: for a particular resource in a namespace passed in the $storehash hash 
15836: reference. If $tolog is true, the transaction is logged in the courselog
15837: with an action=PUTSTORE.
15838: 
15839: =item *
15840: 
15841: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15842: works very similar to store/cstore, but all data is stored in a
15843: temporary location and can be reset using tmpreset, $storehash should
15844: be a hash reference, returns nothing on success
15845: 
15846: =item *
15847: 
15848: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15849: similar to restore, but all data is stored in a temporary location and
15850: can be reset using tmpreset. Returns a hash of values on success,
15851: error string otherwise.
15852: 
15853: =item *
15854: 
15855: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15856: deltes all keys for $symb form the temporary storage hash.
15857: 
15858: =item *
15859: 
15860: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15861: reference filled in from namesp ($udom and $uname are optional)
15862: 
15863: =item *
15864: 
15865: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15866: namesp ($udom and $uname are optional)
15867: 
15868: =item *
15869: 
15870: dump($namespace,$udom,$uname,$regexp,$range) : 
15871: dumps the complete (or key matching regexp) namespace into a hash
15872: ($udom, $uname, $regexp, $range are optional)
15873: 
15874: $range should be either an integer '100' (give me the first 100
15875:                                            matching records)
15876:               or be  two integers sperated by a - with no spaces
15877:                  '30-50' (give me the 30th through the 50th matching
15878:                           records)
15879: =item *
15880: 
15881: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15882: $store can be a scalar, an array reference, or if the amount to be 
15883: incremented is > 1, a hash reference.
15884: 
15885: ($udom and $uname are optional)
15886: 
15887: =item *
15888: 
15889: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15890: ($udom and $uname are optional)
15891: 
15892: =item *
15893: 
15894: cput($namespace,$storehash,$udom,$uname) : critical put
15895: ($udom and $uname are optional)
15896: 
15897: =item *
15898: 
15899: newput($namespace,$storehash,$udom,$uname) :
15900: 
15901: Attempts to store the items in the $storehash, but only if they don't
15902: currently exist, if this succeeds you can be certain that you have 
15903: successfully created a new key value pair in the $namespace db.
15904: 
15905: 
15906: Args:
15907:  $namespace: name of database to store values to
15908:  $storehash: hashref to store to the db
15909:  $udom: (optional) domain of user containing the db
15910:  $uname: (optional) name of user caontaining the db
15911: 
15912: Returns:
15913:  'ok' -> succeeded in storing all keys of $storehash
15914:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15915:                         least <key> already existed in the db (other
15916:                         requested keys may also already exist)
15917:  'error: <msg>' -> unable to tie the DB or other error occurred
15918:  'con_lost' -> unable to contact request server
15919:  'refused' -> action was not allowed by remote machine
15920: 
15921: 
15922: =item *
15923: 
15924: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15925: reference filled in from namesp (encrypts the return communication)
15926: ($udom and $uname are optional)
15927: 
15928: =item *
15929: 
15930: log($udom,$name,$home,$message) : write to permanent log for user; use
15931: critical subroutine
15932: 
15933: =item *
15934: 
15935: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15936: array reference filled in from namespace found in domain level on either
15937: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15938: 
15939: =item *
15940: 
15941: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15942: domain level either on specified domain server ($uhome) or primary domain 
15943: server ($udom and $uhome are optional)
15944: 
15945: =item * 
15946: 
15947: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15948: for: authentication, language, quotas, timezone, date locale, and portal URL in
15949: the target domain.
15950: 
15951: May also include additional key => value pairs for the following groups:
15952: 
15953: =over
15954: 
15955: =item
15956: disk quotas (MB allocated by default to portfolios and authoring spaces).
15957: 
15958: =over
15959: 
15960: =item defaultquota, authorquota
15961: 
15962: =back
15963: 
15964: =item
15965: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15966: portfolio for users).
15967: 
15968: =over
15969: 
15970: =item
15971: aboutme, blog, webdav, portfolio
15972: 
15973: =back
15974: 
15975: =item
15976: requestcourses: ability to request courses, and how requests are processed.
15977: 
15978: =over
15979: 
15980: =item
15981: official, unofficial, community, textbook, placement
15982: 
15983: =back
15984: 
15985: =item
15986: inststatus: types of institutional affiliation, and order in which they are displayed.
15987: 
15988: =over
15989: 
15990: =item
15991: inststatustypes, inststatusorder, inststatusguest
15992: 
15993: =back
15994: 
15995: =item
15996: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15997: for course's uploaded content.
15998: 
15999: =over
16000: 
16001: =item
16002: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16003: communityquota, textbookquota, placementquota
16004: 
16005: =back
16006: 
16007: =item
16008: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16009: on your servers.
16010: 
16011: =over
16012: 
16013: =item 
16014: remotesessions, hostedsessions
16015: 
16016: =back
16017: 
16018: =back
16019: 
16020: In cases where a domain coordinator has never used the "Set Domain Configuration"
16021: utility to create a configuration.db file on a domain's primary library server 
16022: only the following domain defaults: auth_def, auth_arg_def, lang_def
16023: -- corresponding values are authentication type (internal, krb4, krb5,
16024: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16025: will be available. Values are retrieved from cache (if current), unless the
16026: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16027: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16028: 
16029: Typical usage:
16030: 
16031: %domdefaults = &get_domain_defaults($target_domain);
16032: 
16033: =back
16034: 
16035: =head2 Network Status Functions
16036: 
16037: =over 4
16038: 
16039: =item *
16040: 
16041: dirlist() : return directory list based on URI (first arg).
16042: 
16043: Inputs: 1 required, 5 optional.
16044: 
16045: =over
16046: 
16047: =item 
16048: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16049: 
16050: =item
16051: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16052: 
16053: =item
16054: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16055: 
16056: =item
16057: $getpropath - boolean: 1 if prepend path using &propath(). 
16058: 
16059: =item
16060: $getuserdir - boolean: 1 if prepend path for "userfiles".
16061: 
16062: =item 
16063: $alternateRoot - path to prepend in place of path from $uri.
16064: 
16065: =back
16066: 
16067: Returns: Array of up to two items.
16068: 
16069: =over
16070: 
16071: a reference to an array of files/subdirectories
16072: 
16073: =over
16074: 
16075: Each element in the array of files/subdirectories is a & separated list of
16076: item name and the result of running stat on the item.  If dirlist was requested
16077: for a file instead of a directory, the item name will be ''. For a directory 
16078: listing, if the item is a metadata file, the element will end &N&M 
16079: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16080: default copyright set (1).  
16081: 
16082: =back
16083: 
16084: a scalar containing error condition (if encountered).
16085: 
16086: =over
16087: 
16088: =item 
16089: no_host (no homeserver identified for $username:$domain).
16090: 
16091: =item 
16092: no_such_host (server contacted for listing not identified as valid host).
16093: 
16094: =item 
16095: con_lost (connection to remote server failed).
16096: 
16097: =item 
16098: refused (invalid $username:$domain received on lond side).
16099: 
16100: =item 
16101: no_such_dir (directory at specified path on lond side does not exist). 
16102: 
16103: =item 
16104: empty (directory at specified path on lond side is empty).
16105: 
16106: =over
16107: 
16108: This is currently not encountered because the &ls3, &ls2, 
16109: &ls (_handler) routines on the lond side do not filter out
16110: . and .. from a directory listing. 
16111: 
16112: =back
16113: 
16114: =back
16115: 
16116: =back
16117: 
16118: =item *
16119: 
16120: spareserver() : find server with least workload from spare.tab
16121: 
16122: 
16123: =item *
16124: 
16125: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16126: if there is no corresponding loncapa host.
16127: 
16128: =back
16129: 
16130: 
16131: =head2 Apache Request
16132: 
16133: =over 4
16134: 
16135: =item *
16136: 
16137: ssi($url,%hash) : server side include, does a complete request cycle on url to
16138: localhost, posts hash
16139: 
16140: =back
16141: 
16142: =head2 Data to String to Data
16143: 
16144: =over 4
16145: 
16146: =item *
16147: 
16148: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16149: and '&' separators, supports elements that are arrayrefs and hashrefs
16150: 
16151: =item *
16152: 
16153: hashref2str($hashref) : convert a hashref into a string complete with
16154: escaping and '=' and '&' separators, supports elements that are
16155: arrayrefs and hashrefs
16156: 
16157: =item *
16158: 
16159: arrayref2str($arrayref) : convert an arrayref into a string complete
16160: with escaping and '&' separators, supports elements that are arrayrefs
16161: and hashrefs
16162: 
16163: =item *
16164: 
16165: str2hash($string) : convert string to hash using unescaping and
16166: splitting on '=' and '&', supports elements that are arrayrefs and
16167: hashrefs
16168: 
16169: =item *
16170: 
16171: str2array($string) : convert string to hash using unescaping and
16172: splitting on '&', supports elements that are arrayrefs and hashrefs
16173: 
16174: =back
16175: 
16176: =head2 Logging Routines
16177: 
16178: 
16179: These routines allow one to make log messages in the lonnet.log and
16180: lonnet.perm logfiles.
16181: 
16182: =over 4
16183: 
16184: =item *
16185: 
16186: logtouch() : make sure the logfile, lonnet.log, exists
16187: 
16188: =item *
16189: 
16190: logthis() : append message to the normal lonnet.log file, it gets
16191: preiodically rolled over and deleted.
16192: 
16193: =item *
16194: 
16195: logperm() : append a permanent message to lonnet.perm.log, this log
16196: file never gets deleted by any automated portion of the system, only
16197: messages of critical importance should go in here.
16198: 
16199: 
16200: =back
16201: 
16202: =head2 General File Helper Routines
16203: 
16204: =over 4
16205: 
16206: =item *
16207: 
16208: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16209: (a) files in /uploaded
16210:   (i) If a local copy of the file exists - 
16211:       compares modification date of local copy with last-modified date for 
16212:       definitive version stored on home server for course. If local copy is 
16213:       stale, requests a new version from the home server and stores it. 
16214:       If the original has been removed from the home server, then local copy 
16215:       is unlinked.
16216:   (ii) If local copy does not exist -
16217:       requests the file from the home server and stores it. 
16218:   
16219:   If $caller is 'uploadrep':  
16220:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16221:     for request for files originally uploaded via DOCS. 
16222:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16223:   
16224:   Otherwise:
16225:      This indicates a call from the content generation phase of the request.
16226:      -  returns the entire contents of the file or -1.
16227:      
16228: (b) files in /res
16229:    - returns the entire contents of a file or -1; 
16230:    it properly subscribes to and replicates the file if neccessary.
16231: 
16232: 
16233: =item *
16234: 
16235: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16236:                   reference
16237: 
16238: returns either a stat() list of data about the file or an empty list
16239: if the file doesn't exist or couldn't find out about it (connection
16240: problems or user unknown)
16241: 
16242: =item *
16243: 
16244: filelocation($dir,$file) : returns file system location of a file
16245: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16246: directory that relative $file lookups are to looked in ($dir of /a/dir
16247: and a file of ../bob will become /a/bob)
16248: 
16249: =item *
16250: 
16251: hreflocation($dir,$file) : returns file system location or a URL; same as
16252: filelocation except for hrefs
16253: 
16254: =item *
16255: 
16256: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16257: also removes beginning /home/httpd/html unless /priv/ follows it.
16258: 
16259: =back
16260: 
16261: =head2 Usererfile file routines (/uploaded*)
16262: 
16263: =over 4
16264: 
16265: =item *
16266: 
16267: userfileupload(): main rotine for putting a file in a user or course's
16268:                   filespace, arguments are,
16269: 
16270:  formname - required - this is the name of the element in $env where the
16271:            filename, and the contents of the file to create/modifed exist
16272:            the filename is in $env{'form.'.$formname.'.filename'} and the
16273:            contents of the file is located in $env{'form.'.$formname}
16274:  context - if coursedoc, store the file in the course of the active role
16275:              of the current user; 
16276:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16277:            if 'canceloverwrite': delete file in tmp/overwrites directory
16278:  subdir - required - subdirectory to put the file in under ../userfiles/
16279:          if undefined, it will be placed in "unknown"
16280: 
16281:  (This routine calls clean_filename() to remove any dangerous
16282:  characters from the filename, and then calls finuserfileupload() to
16283:  complete the transaction)
16284: 
16285:  returns either the url of the uploaded file (/uploaded/....) if successful
16286:  and /adm/notfound.html if unsuccessful
16287: 
16288: =item *
16289: 
16290: clean_filename(): routine for cleaing a filename up for storage in
16291:                  userfile space, argument is:
16292: 
16293:  filename - proposed filename
16294: 
16295: returns: the new clean filename
16296: 
16297: =item *
16298: 
16299: finishuserfileupload(): routine that creates and sends the file to
16300: userspace, probably shouldn't be called directly
16301: 
16302:   docuname: username or courseid of destination for the file
16303:   docudom: domain of user/course of destination for the file
16304:   formname: same as for userfileupload()
16305:   fname: filename (including subdirectories) for the file
16306:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16307:           if hashref, and context is scantron, will convert csv format to standard format
16308:   allfiles: reference to hash used to store objects found by parser
16309:   codebase: reference to hash used for codebases of java objects found by parser
16310:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16311:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16312:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16313:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16314:   context: if 'overwrite', will move the uploaded file from its temporary location to
16315:             userfiles to facilitate overwriting a previously uploaded file with same name.
16316:   mimetype: reference to scalar to accommodate mime type determined
16317:             from File::MMagic if $parser = parse.
16318: 
16319:  returns either the url of the uploaded file (/uploaded/....) if successful
16320:  and /adm/notfound.html if unsuccessful (or an error message if context 
16321:  was 'overwrite').
16322:  
16323: 
16324: =item *
16325: 
16326: renameuserfile(): renames an existing userfile to a new name
16327: 
16328:   Args:
16329:    docuname: username or courseid of destination for the file
16330:    docudom: domain of user/course of destination for the file
16331:    old: current file name (including any subdirs under userfiles)
16332:    new: desired file name (including any subdirs under userfiles)
16333: 
16334: =item *
16335: 
16336: mkdiruserfile(): creates a directory is a userfiles dir
16337: 
16338:   Args:
16339:    docuname: username or courseid of destination for the file
16340:    docudom: domain of user/course of destination for the file
16341:    dir: dir to create (including any subdirs under userfiles)
16342: 
16343: =item *
16344: 
16345: removeuserfile(): removes a file that exists in userfiles
16346: 
16347:   Args:
16348:    docuname: username or courseid of destination for the file
16349:    docudom: domain of user/course of destination for the file
16350:    fname: filname to delete (including any subdirs under userfiles)
16351: 
16352: =item *
16353: 
16354: removeuploadedurl(): convience function for removeuserfile()
16355: 
16356:   Args:
16357:    url:  a full /uploaded/... url to delete
16358: 
16359: =item * 
16360: 
16361: get_portfile_permissions():
16362:   Args:
16363:     domain: domain of user or course contain the portfolio files
16364:     user: name of user or num of course contain the portfolio files
16365:   Returns:
16366:     hashref of a dump of the proper file_permissions.db
16367:    
16368: 
16369: =item * 
16370: 
16371: get_access_controls():
16372: 
16373: Args:
16374:   current_permissions: the hash ref returned from get_portfile_permissions()
16375:   group: (optional) the group you want the files associated with
16376:   file: (optional) the file you want access info on
16377: 
16378: Returns:
16379:     a hash (keys are file names) of hashes containing
16380:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16381:         values are XML containing access control settings (see below) 
16382: 
16383: Internal notes:
16384: 
16385:  access controls are stored in file_permissions.db as key=value pairs.
16386:     key -> path to file/file_name\0uniqueID:scope_end_start
16387:         where scope -> public,guest,course,group,domains or users.
16388:               end -> UNIX time for end of access (0 -> no end date)
16389:               start -> UNIX time for start of access
16390: 
16391:     value -> XML description of access control
16392:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16393:             <start></start>
16394:             <end></end>
16395: 
16396:             <password></password>  for scope type = guest
16397: 
16398:             <domain></domain>     for scope type = course or group
16399:             <number></number>
16400:             <roles id="">
16401:              <role></role>
16402:              <access></access>
16403:              <section></section>
16404:              <group></group>
16405:             </roles>
16406: 
16407:             <dom></dom>         for scope type = domains
16408: 
16409:             <users>             for scope type = users
16410:              <user>
16411:               <uname></uname>
16412:               <udom></udom>
16413:              </user>
16414:             </users>
16415:            </scope> 
16416:               
16417:  Access data is also aggregated for each file in an additional key=value pair:
16418:  key -> path to file/file_name\0accesscontrol 
16419:  value -> reference to hash
16420:           hash contains key = value pairs
16421:           where key = uniqueID:scope_end_start
16422:                 value = UNIX time record was last updated
16423: 
16424:           Used to improve speed of look-ups of access controls for each file.  
16425:  
16426:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16427: 
16428: =item *
16429: 
16430: modify_access_controls():
16431: 
16432: Modifies access controls for a portfolio file
16433: Args
16434: 1. file name
16435: 2. reference to hash of required changes,
16436: 3. domain
16437: 4. username
16438:   where domain,username are the domain of the portfolio owner 
16439:   (either a user or a course) 
16440: 
16441: Returns:
16442: 1. result of additions or updates ('ok' or 'error', with error message). 
16443: 2. result of deletions ('ok' or 'error', with error message).
16444: 3. reference to hash of any new or updated access controls.
16445: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16446:    key = integer (inbound ID)
16447:    value = uniqueID
16448: 
16449: =item *
16450: 
16451: get_timebased_id():
16452: 
16453: Attempts to get a unique timestamp-based suffix for use with items added to a 
16454: course via the Course Editor (e.g., folders, composite pages, 
16455: group bulletin boards).
16456: 
16457: Args: (first three required; six others optional)
16458: 
16459: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16460:    docssequence, or name of group
16461: 
16462: 2. keyid (alphanumeric): name of temporary locking key in hash,
16463:    e.g., num, boardids
16464: 
16465: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16466:    file will be named nohist_namespace.db
16467: 
16468: 4. cdom: domain of course; default is current course domain from %env
16469: 
16470: 5. cnum: course number; default is current course number from %env
16471: 
16472: 6. idtype: set to concat if an additional digit is to be appended to the 
16473:    unix timestamp to form the suffix, if the plain timestamp is already
16474:    in use.  Default is to not do this, but simply increment the unix 
16475:    timestamp by 1 until a unique key is obtained.
16476: 
16477: 7. who: holder of locking key; defaults to user:domain for user.
16478: 
16479: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16480:    retrying); default is 3.
16481: 
16482: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16483: 
16484: Returns:
16485: 
16486: 1. suffix obtained (numeric)
16487: 
16488: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16489: 
16490: 3. error: contains (localized) error message if an error occurred.
16491: 
16492: 
16493: =back
16494: 
16495: =head2 HTTP Helper Routines
16496: 
16497: =over 4
16498: 
16499: =item *
16500: 
16501: escape() : unpack non-word characters into CGI-compatible hex codes
16502: 
16503: =item *
16504: 
16505: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16506: 
16507: =back
16508: 
16509: =head1 PRIVATE SUBROUTINES
16510: 
16511: =head2 Underlying communication routines (Shouldn't call)
16512: 
16513: =over 4
16514: 
16515: =item *
16516: 
16517: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16518: 
16519: =item *
16520: 
16521: reply() : uses subreply to send a message to remote machine, logs all failures
16522: 
16523: =item *
16524: 
16525: critical() : passes a critical message to another server; if cannot
16526: get through then place message in connection buffer directory and
16527: returns con_delayed, if incapable of saving message, returns
16528: con_failed
16529: 
16530: =item *
16531: 
16532: reconlonc() : tries to reconnect lonc client processes.
16533: 
16534: =back
16535: 
16536: =head2 Resource Access Logging
16537: 
16538: =over 4
16539: 
16540: =item *
16541: 
16542: flushcourselogs() : flush (save) buffer logs and access logs
16543: 
16544: =item *
16545: 
16546: courselog($what) : save message for course in hash
16547: 
16548: =item *
16549: 
16550: courseacclog($what) : save message for course using &courselog().  Perform
16551: special processing for specific resource types (problems, exams, quizzes, etc).
16552: 
16553: =item *
16554: 
16555: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16556: as a PerlChildExitHandler
16557: 
16558: =back
16559: 
16560: =head2 Other
16561: 
16562: =over 4
16563: 
16564: =item *
16565: 
16566: symblist($mapname,%newhash) : update symbolic storage links
16567: 
16568: =back
16569: 
16570: =cut
16571: 

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