File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1406: download - view: text, annotated - select for diffs
Tue Feb 26 14:42:27 2019 UTC (5 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6792
  - Replace a non-ascii character in the filename of uploaded file with an
    appropriate ascii character (if available).
  - If lonnet::clean_filename() reduces filename to .extension, prepend
    timestamp_milliseconds.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1406 2019/02/26 14:42: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:     }
 1256:     return $answer;
 1257: }
 1258: 
 1259: # ----------------------- Try to determine user's current authentication scheme
 1260: 
 1261: sub queryauthenticate {
 1262:     my ($uname,$udom)=@_;
 1263:     my $uhome=&homeserver($uname,$udom);
 1264:     if (!$uhome) {
 1265: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1266: 	return 'no_host';
 1267:     }
 1268:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1269:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1270: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1271:     }
 1272:     return $answer;
 1273: }
 1274: 
 1275: # --------- Try to authenticate user from domain's lib servers (first this one)
 1276: 
 1277: sub authenticate {
 1278:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1279:     $upass=&escape($upass);
 1280:     $uname= &LONCAPA::clean_username($uname);
 1281:     my $uhome=&homeserver($uname,$udom,1);
 1282:     my $newhome;
 1283:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1284: # Maybe the machine was offline and only re-appeared again recently?
 1285:         &reconlonc();
 1286: # One more
 1287: 	$uhome=&homeserver($uname,$udom,1);
 1288:         if (($uhome eq 'no_host') && $checkdefauth) {
 1289:             if (defined(&domain($udom,'primary'))) {
 1290:                 $newhome=&domain($udom,'primary');
 1291:             }
 1292:             if ($newhome ne '') {
 1293:                 $uhome = $newhome;
 1294:             }
 1295:         }
 1296: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1297: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1298: 	    return 'no_host';
 1299:         }
 1300:     }
 1301:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1302:     if ($answer eq 'authorized') {
 1303:         if ($newhome) {
 1304:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1305:             return 'no_account_on_host'; 
 1306:         } else {
 1307:             &logthis("User $uname at $udom authorized by $uhome");
 1308:             return $uhome;
 1309:         }
 1310:     }
 1311:     if ($answer eq 'non_authorized') {
 1312: 	&logthis("User $uname at $udom rejected by $uhome");
 1313: 	return 'no_host'; 
 1314:     }
 1315:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1316:     return 'no_host';
 1317: }
 1318: 
 1319: sub can_host_session {
 1320:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1321:     my $canhost = 1;
 1322:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1323:     if (ref($remotesessions) eq 'HASH') {
 1324:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1325:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1326:                 $canhost = 0;
 1327:             } else {
 1328:                 $canhost = 1;
 1329:             }
 1330:         }
 1331:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1332:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1333:                 $canhost = 1;
 1334:             } else {
 1335:                 $canhost = 0;
 1336:             }
 1337:         }
 1338:         if ($canhost) {
 1339:             if ($remotesessions->{'version'} ne '') {
 1340:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1341:                 if ($reqmajor ne '' && $reqminor ne '') {
 1342:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1343:                         my $major = $1;
 1344:                         my $minor = $2;
 1345:                         if (($major < $reqmajor ) ||
 1346:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1347:                             $canhost = 0;
 1348:                         }
 1349:                     } else {
 1350:                         $canhost = 0;
 1351:                     }
 1352:                 }
 1353:             }
 1354:         }
 1355:     }
 1356:     if ($canhost) {
 1357:         if (ref($hostedsessions) eq 'HASH') {
 1358:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1359:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1360:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1361:                 if (($uint_dom ne '') && 
 1362:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1363:                     $canhost = 0;
 1364:                 } else {
 1365:                     $canhost = 1;
 1366:                 }
 1367:             }
 1368:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1369:                 if (($uint_dom ne '') && 
 1370:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1371:                     $canhost = 1;
 1372:                 } else {
 1373:                     $canhost = 0;
 1374:                 }
 1375:             }
 1376:         }
 1377:     }
 1378:     return $canhost;
 1379: }
 1380: 
 1381: sub spare_can_host {
 1382:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1383:     my $canhost=1;
 1384:     my $try_server_hostname = &hostname($try_server);
 1385:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1386:     my $serverhomedom = &host_domain($serverhomeID);
 1387:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1388:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1389:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1390:             $canhost = 0;
 1391:         }
 1392:     }
 1393:     if (($canhost) && ($uint_dom)) {
 1394:         my @intdoms;
 1395:         my $internet_names = &get_internet_names($try_server);
 1396:         if (ref($internet_names) eq 'ARRAY') {
 1397:             @intdoms = @{$internet_names};
 1398:         }
 1399:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1400:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1401:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1402:                                          $remotesessions,
 1403:                                          $defdomdefaults{'hostedsessions'});
 1404:         }
 1405:     }
 1406:     return $canhost;
 1407: }
 1408: 
 1409: sub this_host_spares {
 1410:     my ($dom) = @_;
 1411:     my ($dom_in_use,$lonhost_in_use,$result);
 1412:     my @hosts = &current_machine_ids();
 1413:     foreach my $lonhost (@hosts) {
 1414:         if (&host_domain($lonhost) eq $dom) {
 1415:             $dom_in_use = $dom;
 1416:             $lonhost_in_use = $lonhost;
 1417:             last;
 1418:         }
 1419:     }
 1420:     if ($dom_in_use ne '') {
 1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1422:     }
 1423:     if (ref($result) ne 'HASH') {
 1424:         $lonhost_in_use = $perlvar{'lonHostID'};
 1425:         $dom_in_use = &host_domain($lonhost_in_use);
 1426:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1427:         if (ref($result) ne 'HASH') {
 1428:             $result = \%spareid;
 1429:         }
 1430:     }
 1431:     return $result;
 1432: }
 1433: 
 1434: sub spares_for_offload  {
 1435:     my ($dom_in_use,$lonhost_in_use) = @_;
 1436:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1437:     if (defined($cached)) {
 1438:         return $result;
 1439:     } else {
 1440:         my $cachetime = 60*60*24;
 1441:         my %domconfig =
 1442:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1443:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1444:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1445:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1446:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1447:                 }
 1448:             }
 1449:         }
 1450:     }
 1451:     return;
 1452: }
 1453: 
 1454: sub get_lonbalancer_config {
 1455:     my ($servers) = @_;
 1456:     my ($currbalancer,$currtargets);
 1457:     if (ref($servers) eq 'HASH') {
 1458:         foreach my $server (keys(%{$servers})) {
 1459:             my %what = (
 1460:                          spareid => 1,
 1461:                          perlvar => 1,
 1462:                        );
 1463:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1464:             if ($result eq 'ok') {
 1465:                 if (ref($returnhash) eq 'HASH') {
 1466:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1467:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1468:                             $currbalancer = $server;
 1469:                             $currtargets = {};
 1470:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1471:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1472:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1473:                                 }
 1474:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1475:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1476:                                 }
 1477:                             }
 1478:                             last;
 1479:                         }
 1480:                     }
 1481:                 }
 1482:             }
 1483:         }
 1484:     }
 1485:     return ($currbalancer,$currtargets);
 1486: }
 1487: 
 1488: sub check_loadbalancing {
 1489:     my ($uname,$udom,$caller) = @_;
 1490:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1491:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1492:     my $lonhost = $perlvar{'lonHostID'};
 1493:     my @hosts = &current_machine_ids();
 1494:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1495:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1496:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1497:     my $serverhomedom = &host_domain($lonhost);
 1498:     my $domneedscache;
 1499:     my $cachetime = 60*60*24;
 1500: 
 1501:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1502:         $dom_in_use = $udom;
 1503:         $homeintdom = 1;
 1504:     } else {
 1505:         $dom_in_use = $serverhomedom;
 1506:     }
 1507:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1508:     unless (defined($cached)) {
 1509:         my %domconfig =
 1510:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1511:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1512:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1513:         } else {
 1514:             $domneedscache = $dom_in_use;
 1515:         }
 1516:     }
 1517:     if (ref($result) eq 'HASH') {
 1518:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1519:             &check_balancer_result($result,@hosts);
 1520:         if ($is_balancer) {
 1521:             if (ref($currrules) eq 'HASH') {
 1522:                 if ($homeintdom) {
 1523:                     if ($uname ne '') {
 1524:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1525:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1526:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1527:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1528:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1529:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1530:                             }
 1531:                         }
 1532:                         if ($rule_in_effect eq '') {
 1533:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1534:                             if ($userenv{'inststatus'} ne '') {
 1535:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1536:                                 my ($othertitle,$usertypes,$types) =
 1537:                                     &Apache::loncommon::sorted_inst_types($udom);
 1538:                                 if (ref($types) eq 'ARRAY') {
 1539:                                     foreach my $type (@{$types}) {
 1540:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1541:                                             if (exists($currrules->{$type})) {
 1542:                                                 $rule_in_effect = $currrules->{$type};
 1543:                                             }
 1544:                                         }
 1545:                                     }
 1546:                                 }
 1547:                             } else {
 1548:                                 if (exists($currrules->{'default'})) {
 1549:                                     $rule_in_effect = $currrules->{'default'};
 1550:                                 }
 1551:                             }
 1552:                         }
 1553:                     } else {
 1554:                         if (exists($currrules->{'default'})) {
 1555:                             $rule_in_effect = $currrules->{'default'};
 1556:                         }
 1557:                     }
 1558:                 } else {
 1559:                     if ($currrules->{'_LC_external'} ne '') {
 1560:                         $rule_in_effect = $currrules->{'_LC_external'};
 1561:                     }
 1562:                 }
 1563:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1564:                                                        $uname,$udom);
 1565:             }
 1566:         }
 1567:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1568:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1569:         unless (defined($cached)) {
 1570:             my %domconfig =
 1571:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1572:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1573:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1574:             } else {
 1575:                 $domneedscache = $serverhomedom;
 1576:             }
 1577:         }
 1578:         if (ref($result) eq 'HASH') {
 1579:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1580:                 &check_balancer_result($result,@hosts);
 1581:             if ($is_balancer) {
 1582:                 if (ref($currrules) eq 'HASH') {
 1583:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1584:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1585:                     }
 1586:                 }
 1587:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1588:                                                        $uname,$udom);
 1589:             }
 1590:         } else {
 1591:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1592:                 $is_balancer = 1;
 1593:                 $offloadto = &this_host_spares($dom_in_use);
 1594:             }
 1595:             unless (defined($cached)) {
 1596:                 $domneedscache = $serverhomedom;
 1597:             }
 1598:         }
 1599:     } else {
 1600:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1601:             $is_balancer = 1;
 1602:             $offloadto = &this_host_spares($dom_in_use);
 1603:         }
 1604:         unless (defined($cached)) {
 1605:             $domneedscache = $serverhomedom;
 1606:         }
 1607:     }
 1608:     if ($domneedscache) {
 1609:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1610:     }
 1611:     if ($is_balancer) {
 1612:         my $lowest_load = 30000;
 1613:         if (ref($offloadto) eq 'HASH') {
 1614:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1615:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1616:                     ($otherserver,$lowest_load) =
 1617:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1618:                 }
 1619:             }
 1620:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1621: 
 1622:             if (!$found_server) {
 1623:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1624:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1625:                         ($otherserver,$lowest_load) =
 1626:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1627:                     }
 1628:                 }
 1629:             }
 1630:         } elsif (ref($offloadto) eq 'ARRAY') {
 1631:             if (@{$offloadto} == 1) {
 1632:                 $otherserver = $offloadto->[0];
 1633:             } elsif (@{$offloadto} > 1) {
 1634:                 foreach my $try_server (@{$offloadto}) {
 1635:                     ($otherserver,$lowest_load) =
 1636:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1637:                 }
 1638:             }
 1639:         }
 1640:         unless ($caller eq 'login') {
 1641:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1642:                 $is_balancer = 0;
 1643:                 if ($uname ne '' && $udom ne '') {
 1644:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1645:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1646:                                  'user.loadbalcheck.time' => time});
 1647:                     }
 1648:                 }
 1649:             }
 1650:         }
 1651:         unless ($homeintdom) {
 1652:             undef($setcookie);
 1653:         }
 1654:     }
 1655:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1656: }
 1657: 
 1658: sub check_balancer_result {
 1659:     my ($result,@hosts) = @_;
 1660:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1661:     if (ref($result) eq 'HASH') {
 1662:         if ($result->{'lonhost'} ne '') {
 1663:             my $currbalancer = $result->{'lonhost'};
 1664:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1665:                 $is_balancer = 1;
 1666:                 $currtargets = $result->{'targets'};
 1667:                 $currrules = $result->{'rules'};
 1668:             }
 1669:             $dom_balancers = $currbalancer;
 1670:         } else {
 1671:             if (keys(%{$result})) {
 1672:                 foreach my $key (keys(%{$result})) {
 1673:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1674:                         (ref($result->{$key}) eq 'HASH')) {
 1675:                         $is_balancer = 1;
 1676:                         $currrules = $result->{$key}{'rules'};
 1677:                         $currtargets = $result->{$key}{'targets'};
 1678:                         $setcookie = $result->{$key}{'cookie'};
 1679:                         last;
 1680:                     }
 1681:                 }
 1682:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1683:             }
 1684:         }
 1685:     }
 1686:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1687: }
 1688: 
 1689: sub get_loadbalancer_targets {
 1690:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1691:     my $offloadto;
 1692:     if ($rule_in_effect eq 'none') {
 1693:         return [$perlvar{'lonHostID'}];
 1694:     } elsif ($rule_in_effect eq '') {
 1695:         $offloadto = $currtargets;
 1696:     } else {
 1697:         if ($rule_in_effect eq 'homeserver') {
 1698:             my $homeserver = &homeserver($uname,$udom);
 1699:             if ($homeserver ne 'no_host') {
 1700:                 $offloadto = [$homeserver];
 1701:             }
 1702:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1703:             my %domconfig =
 1704:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1705:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1706:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1707:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1708:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1709:                     }
 1710:                 }
 1711:             } else {
 1712:                 my %servers = &internet_dom_servers($udom);
 1713:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1714:                 if (&hostname($remotebalancer) ne '') {
 1715:                     $offloadto = [$remotebalancer];
 1716:                 }
 1717:             }
 1718:         } elsif (&hostname($rule_in_effect) ne '') {
 1719:             $offloadto = [$rule_in_effect];
 1720:         }
 1721:     }
 1722:     return $offloadto;
 1723: }
 1724: 
 1725: sub internet_dom_servers {
 1726:     my ($dom) = @_;
 1727:     my (%uniqservers,%servers);
 1728:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1729:     my @machinedoms = &machine_domains($primaryserver);
 1730:     foreach my $mdom (@machinedoms) {
 1731:         my %currservers = %servers;
 1732:         my %server = &get_servers($mdom);
 1733:         %servers = (%currservers,%server);
 1734:     }
 1735:     my %by_hostname;
 1736:     foreach my $id (keys(%servers)) {
 1737:         push(@{$by_hostname{$servers{$id}}},$id);
 1738:     }
 1739:     foreach my $hostname (sort(keys(%by_hostname))) {
 1740:         if (@{$by_hostname{$hostname}} > 1) {
 1741:             my $match = 0;
 1742:             foreach my $id (@{$by_hostname{$hostname}}) {
 1743:                 if (&host_domain($id) eq $dom) {
 1744:                     $uniqservers{$id} = $hostname;
 1745:                     $match = 1;
 1746:                 }
 1747:             }
 1748:             unless ($match) {
 1749:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1750:             }
 1751:         } else {
 1752:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1753:         }
 1754:     }
 1755:     return %uniqservers;
 1756: }
 1757: 
 1758: sub trusted_domains {
 1759:     my ($cmdtype,$calldom) = @_;
 1760:     my ($trusted,$untrusted);
 1761:     if (&domain($calldom) eq '') {
 1762:         return ($trusted,$untrusted);
 1763:     }
 1764:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1765:         return ($trusted,$untrusted);
 1766:     }
 1767:     my $callprimary = &domain($calldom,'primary');
 1768:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1769:     if ($intcalldom eq '') {
 1770:         return ($trusted,$untrusted);
 1771:     }
 1772: 
 1773:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1774:     unless (defined($cached)) {
 1775:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1776:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1777:         $trustconfig = $domconfig{'trust'};
 1778:     }
 1779:     if (ref($trustconfig)) {
 1780:         my (%possexc,%possinc,@allexc,@allinc); 
 1781:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1782:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1783:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1784:             }
 1785:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1786:                 $possinc{$intcalldom} = 1;
 1787:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1788:             }
 1789:         }
 1790:         if (keys(%possexc)) {
 1791:             if (keys(%possinc)) {
 1792:                 foreach my $key (sort(keys(%possexc))) {
 1793:                     next if ($key eq $intcalldom);
 1794:                     unless ($possinc{$key}) {
 1795:                         push(@allexc,$key);
 1796:                     }
 1797:                 }
 1798:             } else {
 1799:                 @allexc = sort(keys(%possexc));
 1800:             }
 1801:         }
 1802:         if (keys(%possinc)) {
 1803:             $possinc{$intcalldom} = 1;
 1804:             @allinc = sort(keys(%possinc));
 1805:         }
 1806:         if ((@allexc > 0) || (@allinc > 0)) {
 1807:             my %doms_by_intdom;
 1808:             my %allintdoms = &all_host_intdom();
 1809:             my %alldoms = &all_host_domain();
 1810:             foreach my $key (%allintdoms) {
 1811:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1812:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1813:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1814:                     }
 1815:                 } else {
 1816:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1817:                 }
 1818:             }
 1819:             foreach my $exc (@allexc) {
 1820:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1821:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1822:                 }
 1823:             }
 1824:             foreach my $inc (@allinc) {
 1825:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1826:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1827:                 }
 1828:             }
 1829:         }
 1830:     }
 1831:     return ($trusted,$untrusted);
 1832: }
 1833: 
 1834: sub will_trust {
 1835:     my ($cmdtype,$domain,$possdom) = @_;
 1836:     return 1 if ($domain eq $possdom);
 1837:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1838:     my $willtrust; 
 1839:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1840:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1841:             $willtrust = 1;
 1842:         }
 1843:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1844:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1845:             $willtrust = 1;
 1846:         }
 1847:     } else {
 1848:         $willtrust = 1;
 1849:     }
 1850:     return $willtrust;
 1851: }
 1852: 
 1853: # ---------------------- Find the homebase for a user from domain's lib servers
 1854: 
 1855: my %homecache;
 1856: sub homeserver {
 1857:     my ($uname,$udom,$ignoreBadCache)=@_;
 1858:     my $index="$uname:$udom";
 1859: 
 1860:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1861: 
 1862:     my %servers = &get_servers($udom,'library');
 1863:     foreach my $tryserver (keys(%servers)) {
 1864:         next if ($ignoreBadCache ne 'true' && 
 1865: 		 exists($badServerCache{$tryserver}));
 1866: 
 1867: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1868: 	if ($answer eq 'found') {
 1869: 	    delete($badServerCache{$tryserver}); 
 1870: 	    return $homecache{$index}=$tryserver;
 1871: 	} elsif ($answer eq 'no_host') {
 1872: 	    $badServerCache{$tryserver}=1;
 1873: 	}
 1874:     }    
 1875:     return 'no_host';
 1876: }
 1877: 
 1878: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1879: 
 1880: sub idget {
 1881:     my ($udom,$idsref,$namespace)=@_;
 1882:     my %returnhash=();
 1883:     my @ids=(); 
 1884:     if (ref($idsref) eq 'ARRAY') {
 1885:         @ids = @{$idsref};
 1886:     } else {
 1887:         return %returnhash; 
 1888:     }
 1889:     if ($namespace eq '') {
 1890:         $namespace = 'ids';
 1891:     }
 1892:     
 1893:     my %servers = &get_servers($udom,'library');
 1894:     foreach my $tryserver (keys(%servers)) {
 1895: 	my $idlist=join('&', map { &escape($_); } @ids);
 1896: 	if ($namespace eq 'ids') {
 1897: 	    $idlist=~tr/A-Z/a-z/;
 1898: 	}
 1899: 	my $reply;
 1900: 	if ($namespace eq 'ids') {
 1901: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1902: 	} else {
 1903: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1904: 	}
 1905: 	my @answer=();
 1906: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1907: 	    @answer=split(/\&/,$reply);
 1908: 	}                    ;
 1909: 	my $i;
 1910: 	for ($i=0;$i<=$#ids;$i++) {
 1911: 	    if ($answer[$i]) {
 1912: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1913: 	    }
 1914: 	}
 1915:     }
 1916:     return %returnhash;
 1917: }
 1918: 
 1919: # ------------------------------------- Find the IDs behind a list of usernames
 1920: 
 1921: sub idrget {
 1922:     my ($udom,@unames)=@_;
 1923:     my %returnhash=();
 1924:     foreach my $uname (@unames) {
 1925:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1926:     }
 1927:     return %returnhash;
 1928: }
 1929: 
 1930: # Store away a list of names and associated student/employee IDs or clicker IDs
 1931: 
 1932: sub idput {
 1933:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1934:     my %servers=();
 1935:     my %ids=();
 1936:     my %byid = ();
 1937:     if (ref($idsref) eq 'HASH') {
 1938:         %ids=%{$idsref};
 1939:     }
 1940:     if ($namespace eq '') {
 1941:         $namespace = 'ids'; 
 1942:     }
 1943:     foreach my $uname (keys(%ids)) {
 1944: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1945:         if ($uhom eq '') {
 1946:             $uhom=&homeserver($uname,$udom);
 1947:         }
 1948:         if ($uhom ne 'no_host') {
 1949:             my $esc_unam=&escape($uname);
 1950:             if ($namespace eq 'ids') {
 1951:                 my $id=&escape($ids{$uname});
 1952:                 $id=~tr/A-Z/a-z/;
 1953:                 my $esc_unam=&escape($uname);
 1954:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1955:             } else {
 1956:                 my @currids = split(/,/,$ids{$uname});
 1957:                 foreach my $id (@currids) {
 1958:                     $byid{$uhom}{$id} .= $uname.',';
 1959:                 }
 1960:             }
 1961:         }
 1962:     }
 1963:     if ($namespace eq 'clickers') {
 1964:         foreach my $server (keys(%byid)) {
 1965:             if (ref($byid{$server}) eq 'HASH') {
 1966:                 foreach my $id (keys(%{$byid{$server}})) {
 1967:                     $byid{$server} =~ s/,$//;
 1968:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1969:                 }
 1970:             }
 1971:         }
 1972:     }
 1973:     foreach my $server (keys(%servers)) {
 1974:         $servers{$server} =~ s/\&$//;
 1975:         if ($namespace eq 'ids') {     
 1976:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1977:         } else {
 1978:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1979:         }
 1980:     }
 1981: }
 1982: 
 1983: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1984: 
 1985: sub iddel {
 1986:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1987:     my %result=();
 1988:     my %ids=();
 1989:     my %byid = ();
 1990:     if (ref($idshashref) eq 'HASH') {
 1991:         %ids=%{$idshashref};
 1992:     } else {
 1993:         return %result;
 1994:     }
 1995:     if ($namespace eq '') {
 1996:         $namespace = 'ids';
 1997:     }
 1998:     my %servers=();
 1999:     while (my ($id,$unamestr) = each(%ids)) {
 2000:         if ($namespace eq 'ids') {
 2001:             my $uhom = $uhome;
 2002:             if ($uhom eq '') { 
 2003:                 $uhom=&homeserver($unamestr,$udom);
 2004:             }
 2005:             if ($uhom ne 'no_host') {
 2006:                 $servers{$uhom}.='&'.&escape($id);
 2007:             }
 2008:          } else {
 2009:             my @curritems = split(/,/,$ids{$id});
 2010:             foreach my $uname (@curritems) {
 2011:                 my $uhom = $uhome;
 2012:                 if ($uhom eq '') {
 2013:                     $uhom=&homeserver($uname,$udom);
 2014:                 }
 2015:                 if ($uhom ne 'no_host') { 
 2016:                     $byid{$uhom}{$id} .= $uname.',';
 2017:                 }
 2018:             }
 2019:         }
 2020:     }
 2021:     if ($namespace eq 'clickers') {
 2022:         foreach my $server (keys(%byid)) {
 2023:             if (ref($byid{$server}) eq 'HASH') {
 2024:                 foreach my $id (keys(%{$byid{$server}})) {
 2025:                     $byid{$server}{$id} =~ s/,$//;
 2026:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2027:                 }
 2028:             }
 2029:         }
 2030:     }
 2031:     foreach my $server (keys(%servers)) {
 2032:         $servers{$server} =~ s/\&$//;
 2033:         if ($namespace eq 'ids') {
 2034:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2035:         } elsif ($namespace eq 'clickers') {
 2036:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2037:         }
 2038:     }
 2039:     return %result;
 2040: }
 2041: 
 2042: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2043: 
 2044: sub updateclickers {
 2045:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2046:     my %clickers;
 2047:     if (ref($idshashref) eq 'HASH') {
 2048:         %clickers=%{$idshashref};
 2049:     } else {
 2050:         return;
 2051:     }
 2052:     my $items='';
 2053:     foreach my $item (keys(%clickers)) {
 2054:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2055:     }
 2056:     $items=~s/\&$//;
 2057:     my $request = "updateclickers:$udom:$action:$items";
 2058:     if ($critical) {
 2059:         return &critical($request,$uhome);
 2060:     } else {
 2061:         return &reply($request,$uhome);
 2062:     }
 2063: }
 2064: 
 2065: # ------------------------------dump from db file owned by domainconfig user
 2066: sub dump_dom {
 2067:     my ($namespace, $udom, $regexp) = @_;
 2068: 
 2069:     $udom ||= $env{'user.domain'};
 2070: 
 2071:     return () unless $udom;
 2072: 
 2073:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2074: }
 2075: 
 2076: # ------------------------------------------ get items from domain db files   
 2077: 
 2078: sub get_dom {
 2079:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2080:     return if ($udom eq 'public');
 2081:     my $items='';
 2082:     foreach my $item (@$storearr) {
 2083:         $items.=&escape($item).'&';
 2084:     }
 2085:     $items=~s/\&$//;
 2086:     if (!$udom) {
 2087:         $udom=$env{'user.domain'};
 2088:         return if ($udom eq 'public');
 2089:         if (defined(&domain($udom,'primary'))) {
 2090:             $uhome=&domain($udom,'primary');
 2091:         } else {
 2092:             undef($uhome);
 2093:         }
 2094:     } else {
 2095:         if (!$uhome) {
 2096:             if (defined(&domain($udom,'primary'))) {
 2097:                 $uhome=&domain($udom,'primary');
 2098:             }
 2099:         }
 2100:     }
 2101:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2102:         my $rep;
 2103:         if ($namespace =~ /^enc/) {
 2104:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2105:         } else {
 2106:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2107:         }
 2108:         my %returnhash;
 2109:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2110:             return %returnhash;
 2111:         }
 2112:         my @pairs=split(/\&/,$rep);
 2113:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2114:             return @pairs;
 2115:         }
 2116:         my $i=0;
 2117:         foreach my $item (@$storearr) {
 2118:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2119:             $i++;
 2120:         }
 2121:         return %returnhash;
 2122:     } else {
 2123:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2124:     }
 2125: }
 2126: 
 2127: # -------------------------------------------- put items in domain db files 
 2128: 
 2129: sub put_dom {
 2130:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2131:     if (!$udom) {
 2132:         $udom=$env{'user.domain'};
 2133:         if (defined(&domain($udom,'primary'))) {
 2134:             $uhome=&domain($udom,'primary');
 2135:         } else {
 2136:             undef($uhome);
 2137:         }
 2138:     } else {
 2139:         if (!$uhome) {
 2140:             if (defined(&domain($udom,'primary'))) {
 2141:                 $uhome=&domain($udom,'primary');
 2142:             }
 2143:         }
 2144:     } 
 2145:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2146:         my $items='';
 2147:         foreach my $item (keys(%$storehash)) {
 2148:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2149:         }
 2150:         $items=~s/\&$//;
 2151:         if ($namespace =~ /^enc/) {
 2152:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2153:         } else {
 2154:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2155:         }
 2156:     } else {
 2157:         &logthis("put_dom failed - no homeserver and/or domain");
 2158:     }
 2159: }
 2160: 
 2161: # --------------------- newput for items in db file owned by domainconfig user
 2162: sub newput_dom {
 2163:     my ($namespace,$storehash,$udom) = @_;
 2164:     my $result;
 2165:     if (!$udom) {
 2166:         $udom=$env{'user.domain'};
 2167:     }
 2168:     if ($udom) {
 2169:         my $uname = &get_domainconfiguser($udom);
 2170:         $result = &newput($namespace,$storehash,$udom,$uname);
 2171:     }
 2172:     return $result;
 2173: }
 2174: 
 2175: # --------------------- delete for items in db file owned by domainconfig user
 2176: sub del_dom {
 2177:     my ($namespace,$storearr,$udom)=@_;
 2178:     if (ref($storearr) eq 'ARRAY') {
 2179:         if (!$udom) {
 2180:             $udom=$env{'user.domain'};
 2181:         }
 2182:         if ($udom) {
 2183:             my $uname = &get_domainconfiguser($udom); 
 2184:             return &del($namespace,$storearr,$udom,$uname);
 2185:         }
 2186:     }
 2187: }
 2188: 
 2189: # ----------------------------------construct domainconfig user for a domain 
 2190: sub get_domainconfiguser {
 2191:     my ($udom) = @_;
 2192:     return $udom.'-domainconfig';
 2193: }
 2194: 
 2195: sub retrieve_inst_usertypes {
 2196:     my ($udom) = @_;
 2197:     my (%returnhash,@order);
 2198:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2199:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2200:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2201:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2202:     } else {
 2203:         if (defined(&domain($udom,'primary'))) {
 2204:             my $uhome=&domain($udom,'primary');
 2205:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2206:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2207:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2208:                 return (\%returnhash,\@order);
 2209:             }
 2210:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2211:             my @pairs=split(/\&/,$hashitems);
 2212:             foreach my $item (@pairs) {
 2213:                 my ($key,$value)=split(/=/,$item,2);
 2214:                 $key = &unescape($key);
 2215:                 next if ($key =~ /^error: 2 /);
 2216:                 $returnhash{$key}=&thaw_unescape($value);
 2217:             }
 2218:             my @esc_order = split(/\&/,$orderitems);
 2219:             foreach my $item (@esc_order) {
 2220:                 push(@order,&unescape($item));
 2221:             }
 2222:         } else {
 2223:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2224:         }
 2225:         return (\%returnhash,\@order);
 2226:     }
 2227: }
 2228: 
 2229: sub is_domainimage {
 2230:     my ($url) = @_;
 2231:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2232:         if (&domain($1) ne '') {
 2233:             return '1';
 2234:         }
 2235:     }
 2236:     return;
 2237: }
 2238: 
 2239: sub inst_directory_query {
 2240:     my ($srch) = @_;
 2241:     my $udom = $srch->{'srchdomain'};
 2242:     my %results;
 2243:     my $homeserver = &domain($udom,'primary');
 2244:     my $outcome;
 2245:     if ($homeserver ne '') {
 2246:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2247:             if ($srch->{'srchby'} eq 'email') {
 2248:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2249:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2250:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2251:                     (($major == 2) && ($minor < 12))) {
 2252:                     return;
 2253:                 }
 2254:             }
 2255:         }
 2256: 	my $queryid=&reply("querysend:instdirsearch:".
 2257: 			   &escape($srch->{'srchby'}).':'.
 2258: 			   &escape($srch->{'srchterm'}).':'.
 2259: 			   &escape($srch->{'srchtype'}),$homeserver);
 2260: 	my $host=&hostname($homeserver);
 2261: 	if ($queryid !~/^\Q$host\E\_/) {
 2262: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2263: 	    return;
 2264: 	}
 2265: 	my $response = &get_query_reply($queryid);
 2266: 	my $maxtries = 5;
 2267: 	my $tries = 1;
 2268: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2269: 	    $response = &get_query_reply($queryid);
 2270: 	    $tries ++;
 2271: 	}
 2272: 
 2273:         if (!&error($response) && $response ne 'refused') {
 2274:             if ($response eq 'unavailable') {
 2275:                 $outcome = $response;
 2276:             } else {
 2277:                 $outcome = 'ok';
 2278:                 my @matches = split(/\n/,$response);
 2279:                 foreach my $match (@matches) {
 2280:                     my ($key,$value) = split(/=/,$match);
 2281:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2282:                 }
 2283:             }
 2284:         }
 2285:     }
 2286:     return ($outcome,%results);
 2287: }
 2288: 
 2289: sub usersearch {
 2290:     my ($srch) = @_;
 2291:     my $dom = $srch->{'srchdomain'};
 2292:     my %results;
 2293:     my %libserv = &all_library();
 2294:     my $query = 'usersearch';
 2295:     foreach my $tryserver (keys(%libserv)) {
 2296:         if (&host_domain($tryserver) eq $dom) {
 2297:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2298:                 if ($srch->{'srchby'} eq 'email') {
 2299:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2300:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2301:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2302:                              (($major == 2) && ($minor < 12)));
 2303:                 }
 2304:             }
 2305:             my $host=&hostname($tryserver);
 2306:             my $queryid=
 2307:                 &reply("querysend:".&escape($query).':'.
 2308:                        &escape($srch->{'srchby'}).':'.
 2309:                        &escape($srch->{'srchtype'}).':'.
 2310:                        &escape($srch->{'srchterm'}),$tryserver);
 2311:             if ($queryid !~/^\Q$host\E\_/) {
 2312:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2313:                 next;
 2314:             }
 2315:             my $reply = &get_query_reply($queryid);
 2316:             my $maxtries = 1;
 2317:             my $tries = 1;
 2318:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2319:                 $reply = &get_query_reply($queryid);
 2320:                 $tries ++;
 2321:             }
 2322:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2323:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2324:             } else {
 2325:                 my @matches;
 2326:                 if ($reply =~ /\n/) {
 2327:                     @matches = split(/\n/,$reply);
 2328:                 } else {
 2329:                     @matches = split(/\&/,$reply);
 2330:                 }
 2331:                 foreach my $match (@matches) {
 2332:                     my ($uname,$udom,%userhash);
 2333:                     foreach my $entry (split(/:/,$match)) {
 2334:                         my ($key,$value) =
 2335:                             map {&unescape($_);} split(/=/,$entry);
 2336:                         $userhash{$key} = $value;
 2337:                         if ($key eq 'username') {
 2338:                             $uname = $value;
 2339:                         } elsif ($key eq 'domain') {
 2340:                             $udom = $value;
 2341:                         }
 2342:                     }
 2343:                     $results{$uname.':'.$udom} = \%userhash;
 2344:                 }
 2345:             }
 2346:         }
 2347:     }
 2348:     return %results;
 2349: }
 2350: 
 2351: sub get_instuser {
 2352:     my ($udom,$uname,$id) = @_;
 2353:     my $homeserver = &domain($udom,'primary');
 2354:     my ($outcome,%results);
 2355:     if ($homeserver ne '') {
 2356:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2357:                            &escape($id).':'.&escape($udom),$homeserver);
 2358:         my $host=&hostname($homeserver);
 2359:         if ($queryid !~/^\Q$host\E\_/) {
 2360:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2361:             return;
 2362:         }
 2363:         my $response = &get_query_reply($queryid);
 2364:         my $maxtries = 5;
 2365:         my $tries = 1;
 2366:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2367:             $response = &get_query_reply($queryid);
 2368:             $tries ++;
 2369:         }
 2370:         if (!&error($response) && $response ne 'refused') {
 2371:             if ($response eq 'unavailable') {
 2372:                 $outcome = $response;
 2373:             } else {
 2374:                 $outcome = 'ok';
 2375:                 my @matches = split(/\n/,$response);
 2376:                 foreach my $match (@matches) {
 2377:                     my ($key,$value) = split(/=/,$match);
 2378:                     $results{&unescape($key)} = &thaw_unescape($value);
 2379:                 }
 2380:             }
 2381:         }
 2382:     }
 2383:     my %userinfo;
 2384:     if (ref($results{$uname}) eq 'HASH') {
 2385:         %userinfo = %{$results{$uname}};
 2386:     } 
 2387:     return ($outcome,%userinfo);
 2388: }
 2389: 
 2390: sub get_multiple_instusers {
 2391:     my ($udom,$users,$caller) = @_;
 2392:     my ($outcome,$results);
 2393:     if (ref($users) eq 'HASH') {
 2394:         my $count = keys(%{$users}); 
 2395:         my $requested = &freeze_escape($users);
 2396:         my $homeserver = &domain($udom,'primary');
 2397:         if ($homeserver ne '') {
 2398:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2399:             my $host=&hostname($homeserver);
 2400:             if ($queryid !~/^\Q$host\E\_/) {
 2401:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2402:                          ' for host: '.$homeserver.'in domain '.$udom);
 2403:                 return ($outcome,$results);
 2404:             }
 2405:             my $response = &get_query_reply($queryid);
 2406:             my $maxtries = 5;
 2407:             if ($count > 100) {
 2408:                 $maxtries = 1+int($count/20);
 2409:             }
 2410:             my $tries = 1;
 2411:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2412:                 $response = &get_query_reply($queryid);
 2413:                 $tries ++;
 2414:             }
 2415:             if ($response eq '') {
 2416:                 $results = {};
 2417:                 foreach my $key (keys(%{$users})) {
 2418:                     my ($uname,$id);
 2419:                     if ($caller eq 'id') {
 2420:                         $id = $key;
 2421:                     } else {
 2422:                         $uname = $key;
 2423:                     }
 2424:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2425:                     $outcome = $resp;
 2426:                     if ($resp eq 'ok') {
 2427:                         %{$results} = (%{$results}, %info);
 2428:                     } else {
 2429:                         last;
 2430:                     }
 2431:                 }
 2432:             } elsif(!&error($response) && ($response ne 'refused')) {
 2433:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2434:                     $outcome = $response;
 2435:                 } else {
 2436:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2437:                     if ($outcome eq 'ok') {
 2438:                         $results = &thaw_unescape($userdata); 
 2439:                     }
 2440:                 }
 2441:             }
 2442:         }
 2443:     }
 2444:     return ($outcome,$results);
 2445: }
 2446: 
 2447: sub inst_rulecheck {
 2448:     my ($udom,$uname,$id,$item,$rules) = @_;
 2449:     my %returnhash;
 2450:     if ($udom ne '') {
 2451:         if (ref($rules) eq 'ARRAY') {
 2452:             @{$rules} = map {&escape($_);} (@{$rules});
 2453:             my $rulestr = join(':',@{$rules});
 2454:             my $homeserver=&domain($udom,'primary');
 2455:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2456:                 my $response;
 2457:                 if ($item eq 'username') {                
 2458:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2459:                                               ':'.&escape($uname).':'.$rulestr,
 2460:                                               $homeserver));
 2461:                 } elsif ($item eq 'id') {
 2462:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2463:                                               ':'.&escape($id).':'.$rulestr,
 2464:                                               $homeserver));
 2465:                 } elsif ($item eq 'selfcreate') {
 2466:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2467:                                                &escape($udom).':'.&escape($uname).
 2468:                                               ':'.$rulestr,$homeserver));
 2469:                 }
 2470:                 if ($response ne 'refused') {
 2471:                     my @pairs=split(/\&/,$response);
 2472:                     foreach my $item (@pairs) {
 2473:                         my ($key,$value)=split(/=/,$item,2);
 2474:                         $key = &unescape($key);
 2475:                         next if ($key =~ /^error: 2 /);
 2476:                         $returnhash{$key}=&thaw_unescape($value);
 2477:                     }
 2478:                 }
 2479:             }
 2480:         }
 2481:     }
 2482:     return %returnhash;
 2483: }
 2484: 
 2485: sub inst_userrules {
 2486:     my ($udom,$check) = @_;
 2487:     my (%ruleshash,@ruleorder);
 2488:     if ($udom ne '') {
 2489:         my $homeserver=&domain($udom,'primary');
 2490:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2491:             my $response;
 2492:             if ($check eq 'id') {
 2493:                 $response=&reply('instidrules:'.&escape($udom),
 2494:                                  $homeserver);
 2495:             } elsif ($check eq 'email') {
 2496:                 $response=&reply('instemailrules:'.&escape($udom),
 2497:                                  $homeserver);
 2498:             } else {
 2499:                 $response=&reply('instuserrules:'.&escape($udom),
 2500:                                  $homeserver);
 2501:             }
 2502:             if (($response ne 'refused') && ($response ne 'error') && 
 2503:                 ($response ne 'unknown_cmd') && 
 2504:                 ($response ne 'no_such_host')) {
 2505:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2506:                 my @pairs=split(/\&/,$hashitems);
 2507:                 foreach my $item (@pairs) {
 2508:                     my ($key,$value)=split(/=/,$item,2);
 2509:                     $key = &unescape($key);
 2510:                     next if ($key =~ /^error: 2 /);
 2511:                     $ruleshash{$key}=&thaw_unescape($value);
 2512:                 }
 2513:                 my @esc_order = split(/\&/,$orderitems);
 2514:                 foreach my $item (@esc_order) {
 2515:                     push(@ruleorder,&unescape($item));
 2516:                 }
 2517:             }
 2518:         }
 2519:     }
 2520:     return (\%ruleshash,\@ruleorder);
 2521: }
 2522: 
 2523: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2524: 
 2525: sub get_domain_defaults {
 2526:     my ($domain,$ignore_cache) = @_;
 2527:     return if (($domain eq '') || ($domain eq 'public'));
 2528:     my $cachetime = 60*60*24;
 2529:     unless ($ignore_cache) {
 2530:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2531:         if (defined($cached)) {
 2532:             if (ref($result) eq 'HASH') {
 2533:                 return %{$result};
 2534:             }
 2535:         }
 2536:     }
 2537:     my %domdefaults;
 2538:     my %domconfig =
 2539:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2540:                                   'requestcourses','inststatus',
 2541:                                   'coursedefaults','usersessions',
 2542:                                   'requestauthor','selfenrollment',
 2543:                                   'coursecategories','ssl','autoenroll',
 2544:                                   'trust','helpsettings'],$domain);
 2545:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2546:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2547:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2548:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2549:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2550:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2551:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2552:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2553:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2554:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2555:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2556:     } else {
 2557:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2558:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2559:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2560:     }
 2561:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2562:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2563:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2564:         } else {
 2565:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2566:         }
 2567:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2568:         foreach my $item (@usertools) {
 2569:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2570:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2571:             }
 2572:         }
 2573:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2574:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2575:         }
 2576:     }
 2577:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2578:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2579:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2580:         }
 2581:     }
 2582:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2583:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2584:     }
 2585:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2586:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2587:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2588:         }
 2589:     }
 2590:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2591:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2592:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2593:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2594:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2595:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2596:         }
 2597:         foreach my $type (@coursetypes) {
 2598:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2599:                 unless ($type eq 'community') {
 2600:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2601:                 }
 2602:             }
 2603:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2604:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2605:             }
 2606:             if ($domdefaults{'postsubmit'} eq 'on') {
 2607:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2608:                     $domdefaults{$type.'postsubtimeout'} = 
 2609:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2610:                 }
 2611:             }
 2612:         }
 2613:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2614:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2615:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2616:                 if (@clonecodes) {
 2617:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2618:                 }
 2619:             }
 2620:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2621:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2622:         }
 2623:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2624:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2625:         } 
 2626:     }
 2627:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2628:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2629:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2630:         }
 2631:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2632:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2633:         }
 2634:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2635:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2636:         }
 2637:     }
 2638:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2639:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2640:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2641:                             'approval','limit');
 2642:             foreach my $type (@coursetypes) {
 2643:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2644:                     my @mgrdc = ();
 2645:                     foreach my $item (@settings) {
 2646:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2647:                             push(@mgrdc,$item);
 2648:                         }
 2649:                     }
 2650:                     if (@mgrdc) {
 2651:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2652:                     }
 2653:                 }
 2654:             }
 2655:         }
 2656:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2657:             foreach my $type (@coursetypes) {
 2658:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2659:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2660:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2661:                     }
 2662:                 }
 2663:             }
 2664:         }
 2665:     }
 2666:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2667:         $domdefaults{'catauth'} = 'std';
 2668:         $domdefaults{'catunauth'} = 'std';
 2669:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2670:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2671:         }
 2672:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2673:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2674:         }
 2675:     }
 2676:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2677:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2678:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2679:         }
 2680:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2681:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2682:         }
 2683:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2684:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2685:         }
 2686:     }
 2687:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2688:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2689:         foreach my $prefix (@prefixes) {
 2690:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2691:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2692:             }
 2693:         }
 2694:     }
 2695:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2696:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2697:     }
 2698:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2699:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2700:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2701:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2702:         }
 2703:     }
 2704:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2705:     return %domdefaults;
 2706: }
 2707: 
 2708: sub course_portal_url {
 2709:     my ($cnum,$cdom) = @_;
 2710:     my $chome = &homeserver($cnum,$cdom);
 2711:     my $hostname = &hostname($chome);
 2712:     my $protocol = $protocol{$chome};
 2713:     $protocol = 'http' if ($protocol ne 'https');
 2714:     my %domdefaults = &get_domain_defaults($cdom);
 2715:     my $firsturl;
 2716:     if ($domdefaults{'portal_def'}) {
 2717:         $firsturl = $domdefaults{'portal_def'};
 2718:     } else {
 2719:         $firsturl = $protocol.'://'.$hostname;
 2720:     }
 2721:     return $firsturl;
 2722: }
 2723: 
 2724: # --------------------------------------------------- Assign a key to a student
 2725: 
 2726: sub assign_access_key {
 2727: #
 2728: # a valid key looks like uname:udom#comments
 2729: # comments are being appended
 2730: #
 2731:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2732:     $kdom=
 2733:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2734:     $knum=
 2735:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2736:     $cdom=
 2737:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2738:     $cnum=
 2739:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2740:     $udom=$env{'user.name'} unless (defined($udom));
 2741:     $uname=$env{'user.domain'} unless (defined($uname));
 2742:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2743:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2744:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2745:                                                   # assigned to this person
 2746:                                                   # - this should not happen,
 2747:                                                   # unless something went wrong
 2748:                                                   # the first time around
 2749: # ready to assign
 2750:         $logentry=$1.'; '.$logentry;
 2751:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2752:                                                  $kdom,$knum) eq 'ok') {
 2753: # key now belongs to user
 2754: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2755:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2756:                 &appenv({'environment.'.$envkey => $ckey});
 2757:                 return 'ok';
 2758:             } else {
 2759:                 return 
 2760:   'error: Count not permanently assign key, will need to be re-entered later.';
 2761: 	    }
 2762:         } else {
 2763:             return 'error: Could not assign key, try again later.';
 2764:         }
 2765:     } elsif (!$existing{$ckey}) {
 2766: # the key does not exist
 2767: 	return 'error: The key does not exist';
 2768:     } else {
 2769: # the key is somebody else's
 2770: 	return 'error: The key is already in use';
 2771:     }
 2772: }
 2773: 
 2774: # ------------------------------------------ put an additional comment on a key
 2775: 
 2776: sub comment_access_key {
 2777: #
 2778: # a valid key looks like uname:udom#comments
 2779: # comments are being appended
 2780: #
 2781:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2782:     $cdom=
 2783:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2784:     $cnum=
 2785:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2786:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2787:     if ($existing{$ckey}) {
 2788:         $existing{$ckey}.='; '.$logentry;
 2789: # ready to assign
 2790:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2791:                                                  $cdom,$cnum) eq 'ok') {
 2792: 	    return 'ok';
 2793:         } else {
 2794: 	    return 'error: Count not store comment.';
 2795:         }
 2796:     } else {
 2797: # the key does not exist
 2798: 	return 'error: The key does not exist';
 2799:     }
 2800: }
 2801: 
 2802: # ------------------------------------------------------ Generate a set of keys
 2803: 
 2804: sub generate_access_keys {
 2805:     my ($number,$cdom,$cnum,$logentry)=@_;
 2806:     $cdom=
 2807:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2808:     $cnum=
 2809:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2810:     unless (&allowed('mky',$cdom)) { return 0; }
 2811:     unless (($cdom) && ($cnum)) { return 0; }
 2812:     if ($number>10000) { return 0; }
 2813:     sleep(2); # make sure don't get same seed twice
 2814:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2815:     my $total=0;
 2816:     for (my $i=1;$i<=$number;$i++) {
 2817:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2818:                   sprintf("%lx",int(100000*rand)).'-'.
 2819:                   sprintf("%lx",int(100000*rand));
 2820:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2821:        $newkey=~s/0/h/g; # and also 0 and O
 2822:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2823:        if ($existing{$newkey}) {
 2824:            $i--;
 2825:        } else {
 2826: 	  if (&put('accesskeys',
 2827:               { $newkey => '# generated '.localtime().
 2828:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2829:                            '; '.$logentry },
 2830: 		   $cdom,$cnum) eq 'ok') {
 2831:               $total++;
 2832: 	  }
 2833:        }
 2834:     }
 2835:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2836:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2837:     return $total;
 2838: }
 2839: 
 2840: # ------------------------------------------------------- Validate an accesskey
 2841: 
 2842: sub validate_access_key {
 2843:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2844:     $cdom=
 2845:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2846:     $cnum=
 2847:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2848:     $udom=$env{'user.domain'} unless (defined($udom));
 2849:     $uname=$env{'user.name'} unless (defined($uname));
 2850:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2851:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2852: }
 2853: 
 2854: # ------------------------------------- Find the section of student in a course
 2855: sub devalidate_getsection_cache {
 2856:     my ($udom,$unam,$courseid)=@_;
 2857:     my $hashid="$udom:$unam:$courseid";
 2858:     &devalidate_cache_new('getsection',$hashid);
 2859: }
 2860: 
 2861: sub courseid_to_courseurl {
 2862:     my ($courseid) = @_;
 2863:     #already url style courseid
 2864:     return $courseid if ($courseid =~ m{^/});
 2865: 
 2866:     if (exists($env{'course.'.$courseid.'.num'})) {
 2867: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2868: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2869: 	return "/$cdom/$cnum";
 2870:     }
 2871: 
 2872:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2873:     if (exists($courseinfo{'num'})) {
 2874: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2875:     }
 2876: 
 2877:     return undef;
 2878: }
 2879: 
 2880: sub getsection {
 2881:     my ($udom,$unam,$courseid)=@_;
 2882:     my $cachetime=1800;
 2883: 
 2884:     my $hashid="$udom:$unam:$courseid";
 2885:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2886:     if (defined($cached)) { return $result; }
 2887: 
 2888:     my %Pending; 
 2889:     my %Expired;
 2890:     #
 2891:     # Each role can either have not started yet (pending), be active, 
 2892:     #    or have expired.
 2893:     #
 2894:     # If there is an active role, we are done.
 2895:     #
 2896:     # If there is more than one role which has not started yet, 
 2897:     #     choose the one which will start sooner
 2898:     # If there is one role which has not started yet, return it.
 2899:     #
 2900:     # If there is more than one expired role, choose the one which ended last.
 2901:     # If there is a role which has expired, return it.
 2902:     #
 2903:     $courseid = &courseid_to_courseurl($courseid);
 2904:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2905:     foreach my $key (keys(%roleshash)) {
 2906:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2907:         my $section=$1;
 2908:         if ($key eq $courseid.'_st') { $section=''; }
 2909:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2910:         my $now=time;
 2911:         if (defined($end) && $end && ($now > $end)) {
 2912:             $Expired{$end}=$section;
 2913:             next;
 2914:         }
 2915:         if (defined($start) && $start && ($now < $start)) {
 2916:             $Pending{$start}=$section;
 2917:             next;
 2918:         }
 2919:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2920:     }
 2921:     #
 2922:     # Presumedly there will be few matching roles from the above
 2923:     # loop and the sorting time will be negligible.
 2924:     if (scalar(keys(%Pending))) {
 2925:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2926:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2927:     } 
 2928:     if (scalar(keys(%Expired))) {
 2929:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2930:         my $time = pop(@sorted);
 2931:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2932:     }
 2933:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2934: }
 2935: 
 2936: sub save_cache {
 2937:     &purge_remembered();
 2938:     #&Apache::loncommon::validate_page();
 2939:     undef(%env);
 2940:     undef($env_loaded);
 2941: }
 2942: 
 2943: my $to_remember=-1;
 2944: my %remembered;
 2945: my %accessed;
 2946: my $kicks=0;
 2947: my $hits=0;
 2948: sub make_key {
 2949:     my ($name,$id) = @_;
 2950:     if (length($id) > 65 
 2951: 	&& length(&escape($id)) > 200) {
 2952: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2953:     }
 2954:     return &escape($name.':'.$id);
 2955: }
 2956: 
 2957: sub devalidate_cache_new {
 2958:     my ($name,$id,$debug) = @_;
 2959:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2960:     my $remembered_id=$name.':'.$id;
 2961:     $id=&make_key($name,$id);
 2962:     $memcache->delete($id);
 2963:     delete($remembered{$remembered_id});
 2964:     delete($accessed{$remembered_id});
 2965: }
 2966: 
 2967: sub is_cached_new {
 2968:     my ($name,$id,$debug) = @_;
 2969:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2970:     if (exists($remembered{$remembered_id})) {
 2971: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2972: 	$accessed{$remembered_id}=[&gettimeofday()];
 2973: 	$hits++;
 2974: 	return ($remembered{$remembered_id},1);
 2975:     }
 2976:     $id=&make_key($name,$id);
 2977:     my $value = $memcache->get($id);
 2978:     if (!(defined($value))) {
 2979: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2980: 	return (undef,undef);
 2981:     }
 2982:     if ($value eq '__undef__') {
 2983: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2984: 	$value=undef;
 2985:     }
 2986:     &make_room($remembered_id,$value,$debug);
 2987:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2988:     return ($value,1);
 2989: }
 2990: 
 2991: sub do_cache_new {
 2992:     my ($name,$id,$value,$time,$debug) = @_;
 2993:     my $remembered_id=$name.':'.$id;
 2994:     $id=&make_key($name,$id);
 2995:     my $setvalue=$value;
 2996:     if (!defined($setvalue)) {
 2997: 	$setvalue='__undef__';
 2998:     }
 2999:     if (!defined($time) ) {
 3000: 	$time=600;
 3001:     }
 3002:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3003:     my $result = $memcache->set($id,$setvalue,$time);
 3004:     if (! $result) {
 3005: 	&logthis("caching of id -> $id  failed");
 3006: 	$memcache->disconnect_all();
 3007:     }
 3008:     # need to make a copy of $value
 3009:     &make_room($remembered_id,$value,$debug);
 3010:     return $value;
 3011: }
 3012: 
 3013: sub make_room {
 3014:     my ($remembered_id,$value,$debug)=@_;
 3015: 
 3016:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3017:                                     : $value;
 3018:     if ($to_remember<0) { return; }
 3019:     $accessed{$remembered_id}=[&gettimeofday()];
 3020:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3021:     my $to_kick;
 3022:     my $max_time=0;
 3023:     foreach my $other (keys(%accessed)) {
 3024: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3025: 	    $to_kick=$other;
 3026: 	    $max_time=&tv_interval($accessed{$other});
 3027: 	}
 3028:     }
 3029:     delete($remembered{$to_kick});
 3030:     delete($accessed{$to_kick});
 3031:     $kicks++;
 3032:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3033:     return;
 3034: }
 3035: 
 3036: sub purge_remembered {
 3037:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3038:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3039:     undef(%remembered);
 3040:     undef(%accessed);
 3041: }
 3042: # ------------------------------------- Read an entry from a user's environment
 3043: 
 3044: sub userenvironment {
 3045:     my ($udom,$unam,@what)=@_;
 3046:     my $items;
 3047:     foreach my $item (@what) {
 3048:         $items.=&escape($item).'&';
 3049:     }
 3050:     $items=~s/\&$//;
 3051:     my %returnhash=();
 3052:     my $uhome = &homeserver($unam,$udom);
 3053:     unless ($uhome eq 'no_host') {
 3054:         my @answer=split(/\&/, 
 3055:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3056:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3057:             return %returnhash;
 3058:         }
 3059:         my $i;
 3060:         for ($i=0;$i<=$#what;$i++) {
 3061: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3062:         }
 3063:     }
 3064:     return %returnhash;
 3065: }
 3066: 
 3067: # ---------------------------------------------------------- Get a studentphoto
 3068: sub studentphoto {
 3069:     my ($udom,$unam,$ext) = @_;
 3070:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3071:     if (defined($env{'request.course.id'})) {
 3072:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3073:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3074:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3075:             } else {
 3076:                 my ($result,$perm_reqd)=
 3077: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3078:                 if ($result eq 'ok') {
 3079:                     if (!($perm_reqd eq 'yes')) {
 3080:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3081:                     }
 3082:                 }
 3083:             }
 3084:         }
 3085:     } else {
 3086:         my ($result,$perm_reqd) = 
 3087: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3088:         if ($result eq 'ok') {
 3089:             if (!($perm_reqd eq 'yes')) {
 3090:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3091:             }
 3092:         }
 3093:     }
 3094:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3095: }
 3096: 
 3097: sub retrievestudentphoto {
 3098:     my ($udom,$unam,$ext,$type) = @_;
 3099:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3100:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3101:     if ($ret eq 'ok') {
 3102:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3103:         if ($type eq 'thumbnail') {
 3104:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3105:         }
 3106:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3107:         return $tokenurl;
 3108:     } else {
 3109:         if ($type eq 'thumbnail') {
 3110:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3111:         } else { 
 3112:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3113:         }
 3114:     }
 3115: }
 3116: 
 3117: # -------------------------------------------------------------------- New chat
 3118: 
 3119: sub chatsend {
 3120:     my ($newentry,$anon,$group)=@_;
 3121:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3122:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3123:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3124:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3125: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3126: 		   &escape($newentry)).':'.$group,$chome);
 3127: }
 3128: 
 3129: # ------------------------------------------ Find current version of a resource
 3130: 
 3131: sub getversion {
 3132:     my $fname=&clutter(shift);
 3133:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3134:     return &currentversion(&filelocation('',$fname));
 3135: }
 3136: 
 3137: sub currentversion {
 3138:     my $fname=shift;
 3139:     my $author=$fname;
 3140:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3141:     my ($udom,$uname)=split(/\//,$author);
 3142:     my $home=&homeserver($uname,$udom);
 3143:     if ($home eq 'no_host') { 
 3144:         return -1; 
 3145:     }
 3146:     my $answer=&reply("currentversion:$fname",$home);
 3147:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3148: 	return -1;
 3149:     }
 3150:     return $answer;
 3151: }
 3152: 
 3153: #
 3154: # Return special version number of resource if set by override, empty otherwise
 3155: #
 3156: sub usedversion {
 3157:     my $fname=shift;
 3158:     unless ($fname) { $fname=$env{'request.uri'}; }
 3159:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3160:     if ($urlversion) { return $urlversion; }
 3161:     return '';
 3162: }
 3163: 
 3164: # ----------------------------- Subscribe to a resource, return URL if possible
 3165: 
 3166: sub subscribe {
 3167:     my $fname=shift;
 3168:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3169:     $fname=~s/[\n\r]//g;
 3170:     my $author=$fname;
 3171:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3172:     my ($udom,$uname)=split(/\//,$author);
 3173:     my $home=homeserver($uname,$udom);
 3174:     if ($home eq 'no_host') {
 3175:         return 'not_found';
 3176:     }
 3177:     my $answer=reply("sub:$fname",$home);
 3178:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3179: 	$answer.=' by '.$home;
 3180:     }
 3181:     return $answer;
 3182: }
 3183:     
 3184: # -------------------------------------------------------------- Replicate file
 3185: 
 3186: sub repcopy {
 3187:     my $filename=shift;
 3188:     $filename=~s/\/+/\//g;
 3189:     my $londocroot = $perlvar{'lonDocRoot'};
 3190:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3191:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3192:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3193: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3194: 	return &repcopy_userfile($filename);
 3195:     }
 3196:     $filename=~s/[\n\r]//g;
 3197:     my $transname="$filename.in.transfer";
 3198: # FIXME: this should flock
 3199:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3200:     my $remoteurl=subscribe($filename);
 3201:     if ($remoteurl =~ /^con_lost by/) {
 3202: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3203:            return 'unavailable';
 3204:     } elsif ($remoteurl eq 'not_found') {
 3205: 	   #&logthis("Subscribe returned not_found: $filename");
 3206: 	   return 'not_found';
 3207:     } elsif ($remoteurl =~ /^rejected by/) {
 3208: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3209:            return 'forbidden';
 3210:     } elsif ($remoteurl eq 'directory') {
 3211:            return 'ok';
 3212:     } else {
 3213:         my $author=$filename;
 3214:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3215:         my ($udom,$uname)=split(/\//,$author);
 3216:         my $home=homeserver($uname,$udom);
 3217:         unless ($home eq $perlvar{'lonHostID'}) {
 3218:            my @parts=split(/\//,$filename);
 3219:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3220:            if ($path ne "$londocroot/res") {
 3221:                &logthis("Malconfiguration for replication: $filename");
 3222: 	       return 'bad_request';
 3223:            }
 3224:            my $count;
 3225:            for ($count=5;$count<$#parts;$count++) {
 3226:                $path.="/$parts[$count]";
 3227:                if ((-e $path)!=1) {
 3228: 		   mkdir($path,0777);
 3229:                }
 3230:            }
 3231:            my $request=new HTTP::Request('GET',"$remoteurl");
 3232:            my $response;
 3233:            if ($remoteurl =~ m{/raw/}) {
 3234:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3235:            } else {
 3236:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3237:            }
 3238:            if ($response->is_error()) {
 3239: 	       unlink($transname);
 3240:                my $message=$response->status_line;
 3241:                &logthis("<font color=\"blue\">WARNING:"
 3242:                        ." LWP get: $message: $filename</font>");
 3243:                return 'unavailable';
 3244:            } else {
 3245: 	       if ($remoteurl!~/\.meta$/) {
 3246:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3247:                   my $mresponse;
 3248:                   if ($remoteurl =~ m{/raw/}) {
 3249:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3250:                   } else {
 3251:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3252:                   }
 3253:                   if ($mresponse->is_error()) {
 3254: 		      unlink($filename.'.meta');
 3255:                       &logthis(
 3256:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3257:                   }
 3258: 	       }
 3259:                rename($transname,$filename);
 3260:                return 'ok';
 3261:            }
 3262:        }
 3263:     }
 3264: }
 3265: 
 3266: # ------------------------------------------------ Get server side include body
 3267: sub ssi_body {
 3268:     my ($filelink,%form)=@_;
 3269:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3270:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3271:     }
 3272:     my $output='';
 3273:     my $response;
 3274:     if ($filelink=~/^https?\:/) {
 3275:        ($output,$response)=&externalssi($filelink);
 3276:     } else {
 3277:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3278:        $filelink .= 'inhibitmenu=yes';
 3279:        ($output,$response)=&ssi($filelink,%form);
 3280:     }
 3281:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3282:     $output=~s/^.*?\<body[^\>]*\>//si;
 3283:     $output=~s/\<\/body\s*\>.*?$//si;
 3284:     if (wantarray) {
 3285:         return ($output, $response);
 3286:     } else {
 3287:         return $output;
 3288:     }
 3289: }
 3290: 
 3291: # --------------------------------------------------------- Server Side Include
 3292: 
 3293: sub absolute_url {
 3294:     my ($host_name) = @_;
 3295:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3296:     if ($host_name eq '') {
 3297: 	$host_name = $ENV{'SERVER_NAME'};
 3298:     }
 3299:     return $protocol.$host_name;
 3300: }
 3301: 
 3302: #
 3303: #   Server side include.
 3304: # Parameters:
 3305: #  fn     Possibly encrypted resource name/id.
 3306: #  form   Hash that describes how the rendering should be done
 3307: #         and other things.
 3308: # Returns:
 3309: #   Scalar context: The content of the response.
 3310: #   Array context:  2 element list of the content and the full response object.
 3311: #     
 3312: sub ssi {
 3313: 
 3314:     my ($fn,%form)=@_;
 3315:     my $request;
 3316: 
 3317:     $form{'no_update_last_known'}=1;
 3318:     &Apache::lonenc::check_encrypt(\$fn);
 3319:     if (%form) {
 3320:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3321:       $request->content(join('&',map { 
 3322:             my $name = escape($_);
 3323:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3324:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3325:             : &escape($form{$_}) );    
 3326:         } keys(%form)));
 3327:     } else {
 3328:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3329:     }
 3330: 
 3331:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3332:     my $lonhost = $perlvar{'lonHostID'};
 3333:     my $islocal;
 3334:     if (($env{'request.course.id'}) &&
 3335:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3336:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3337:         ($form{'grade_symb'} ne '') &&
 3338:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3339:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3340:         $islocal = 1;
 3341:     }
 3342:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3343:                                                 '','','',$islocal);
 3344: 
 3345:     if (wantarray) {
 3346: 	return ($response->content, $response);
 3347:     } else {
 3348: 	return $response->content;
 3349:     }
 3350: }
 3351: 
 3352: sub externalssi {
 3353:     my ($url)=@_;
 3354:     my $request=new HTTP::Request('GET',$url);
 3355:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3356:     if (wantarray) {
 3357:         return ($response->content, $response);
 3358:     } else {
 3359:         return $response->content;
 3360:     }
 3361: }
 3362: 
 3363: 
 3364: # If the local copy of a replicated resource is outdated, trigger a  
 3365: # connection from the homeserver to flush the delayed queue. If no update 
 3366: # happens, remove local copies of outdated resource (and corresponding
 3367: # metadata file).
 3368: 
 3369: sub remove_stale_resfile {
 3370:     my ($url) = @_;
 3371:     my $removed;
 3372:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3373:         my $audom = $1;
 3374:         my $auname = $2;
 3375:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3376:             my $homeserver = &homeserver($auname,$audom);
 3377:             unless (($homeserver eq 'no_host') ||
 3378:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3379:                 my $fname = &filelocation('',$url);
 3380:                 if (-e $fname) {
 3381:                     my $hostname = &hostname($homeserver);
 3382:                     if ($hostname) {
 3383:                         my $protocol = $protocol{$homeserver};
 3384:                         $protocol = 'http' if ($protocol ne 'https');
 3385:                         my $uri = &declutter($url);
 3386:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3387:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3388:                         if ($response->is_success()) {
 3389:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3390:                             my $locmodtime = (stat($fname))[9];
 3391:                             if ($locmodtime < $remmodtime) {
 3392:                                 my $stale;
 3393:                                 my $answer = &reply('pong',$homeserver);
 3394:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3395:                                     sleep(0.2);
 3396:                                     $locmodtime = (stat($fname))[9];
 3397:                                     if ($locmodtime < $remmodtime) {
 3398:                                         my $posstransfer = $fname.'.in.transfer';
 3399:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3400:                                             $removed = 1;
 3401:                                         } else {
 3402:                                             $stale = 1;
 3403:                                         }
 3404:                                     } else {
 3405:                                         $removed = 1;
 3406:                                     }
 3407:                                 } else {
 3408:                                     $stale = 1;
 3409:                                 }
 3410:                                 if ($stale) {
 3411:                                     unlink($fname);
 3412:                                     if ($uri!~/\.meta$/) {
 3413:                                         unlink($fname.'.meta');
 3414:                                     }
 3415:                                     &reply("unsub:$fname",$homeserver);
 3416:                                     $removed = 1;
 3417:                                 }
 3418:                             }
 3419:                         }
 3420:                     }
 3421:                 }
 3422:             }
 3423:         }
 3424:     }
 3425:     return $removed;
 3426: }
 3427: 
 3428: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3429: 
 3430: sub allowuploaded {
 3431:     my ($srcurl,$url)=@_;
 3432:     $url=&clutter(&declutter($url));
 3433:     my $dir=$url;
 3434:     $dir=~s/\/[^\/]+$//;
 3435:     my %httpref=();
 3436:     my $httpurl=&hreflocation('',$url);
 3437:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3438:     &Apache::lonnet::appenv(\%httpref);
 3439: }
 3440: 
 3441: #
 3442: # Determine if the current user should be able to edit a particular resource,
 3443: # when viewing in course context.
 3444: # (a) When viewing resource used to determine if "Edit" item is included in 
 3445: #     Functions.
 3446: # (b) When displaying folder contents in course editor, used to determine if
 3447: #     "Edit" link will be displayed alongside resource.
 3448: #
 3449: #  input: six args -- filename (decluttered), course number, course domain,
 3450: #                   url, symb (if registered) and group (if this is a group
 3451: #                   item -- e.g., bulletin board, group page etc.).
 3452: #  output: array of five scalars -- 
 3453: #          $cfile -- url for file editing if editable on current server
 3454: #          $home -- homeserver of resource (i.e., for author if published,
 3455: #                                           or course if uploaded.).
 3456: #          $switchserver --  1 if server switch will be needed.
 3457: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3458: #          $forceview -- 1 if icon/link should be to go to view mode
 3459: #
 3460: 
 3461: sub can_edit_resource {
 3462:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3463:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3464: #
 3465: # For aboutme pages user can only edit his/her own.
 3466: #
 3467:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3468:         my ($sdom,$sname) = ($1,$2);
 3469:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3470:             $home = $env{'user.home'};
 3471:             $cfile = $resurl;
 3472:             if ($env{'form.forceedit'}) {
 3473:                 $forceview = 1;
 3474:             } else {
 3475:                 $forceedit = 1;
 3476:             }
 3477:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3478:         } else {
 3479:             return;
 3480:         }
 3481:     }
 3482: 
 3483:     if ($env{'request.course.id'}) {
 3484:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3485:         if ($group ne '') {
 3486: # if this is a group homepage or group bulletin board, check group privs
 3487:             my $allowed = 0;
 3488:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3489:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3490:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3491:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3492:                     $allowed = 1;
 3493:                 }
 3494:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3495:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3496:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3497:                     $allowed = 1;
 3498:                 }
 3499:             }
 3500:             if ($allowed) {
 3501:                 $home=&homeserver($cnum,$cdom);
 3502:                 if ($env{'form.forceedit'}) {
 3503:                     $forceview = 1;
 3504:                 } else {
 3505:                     $forceedit = 1;
 3506:                 }
 3507:                 $cfile = $resurl;
 3508:             } else {
 3509:                 return;
 3510:             }
 3511:         } else {
 3512:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3513:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3514:                     return;
 3515:                 }
 3516:             } elsif (!$crsedit) {
 3517: #
 3518: # No edit allowed where CC has switched to student role.
 3519: #
 3520:                 return;
 3521:             }
 3522:         }
 3523:     }
 3524: 
 3525:     if ($file ne '') {
 3526:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3527:             if (&is_course_upload($file,$cnum,$cdom)) {
 3528:                 $uploaded = 1;
 3529:                 $incourse = 1;
 3530:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3531:                     $cfile = &hreflocation('',$file);
 3532:                     if ($env{'form.forceedit'}) {
 3533:                         $forceview = 1;
 3534:                     } else {
 3535:                         $forceedit = 1;
 3536:                     }
 3537:                 }
 3538:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3539:                 $incourse = 1;
 3540:                 if ($env{'form.forceedit'}) {
 3541:                     $forceview = 1;
 3542:                 } else {
 3543:                     $forceedit = 1;
 3544:                 }
 3545:                 $cfile = $resurl;
 3546:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3547:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3548:                     $incourse = 1;
 3549:                     if ($env{'form.forceedit'}) {
 3550:                         $forceview = 1;
 3551:                     } else {
 3552:                         $forceedit = 1;
 3553:                     }
 3554:                     $cfile = $resurl;
 3555:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3556:                     $incourse = 1;
 3557:                     $cfile = $resurl.'/smpedit';
 3558:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3559:                     $incourse = 1;
 3560:                     if ($env{'form.forceedit'}) {
 3561:                         $forceview = 1;
 3562:                     } else {
 3563:                         $forceedit = 1;
 3564:                     }
 3565:                     $cfile = $resurl;
 3566:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3567:                     $incourse = 1;
 3568:                     if ($env{'form.forceedit'}) {
 3569:                         $forceview = 1;
 3570:                     } else {
 3571:                         $forceedit = 1;
 3572:                     }
 3573:                     $cfile = $resurl;
 3574:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3575:                     $incourse = 1;
 3576:                     if ($env{'form.forceedit'}) {
 3577:                         $forceview = 1;
 3578:                     } else {
 3579:                         $forceedit = 1;
 3580:                     }
 3581:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3582:                 }
 3583:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3584:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3585:                 if (&is_on_map($template)) { 
 3586:                     $incourse = 1;
 3587:                     $forceview = 1;
 3588:                     $cfile = $template;
 3589:                 }
 3590:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3591:                     $incourse = 1;
 3592:                     if ($env{'form.forceedit'}) {
 3593:                         $forceview = 1;
 3594:                     } else {
 3595:                         $forceedit = 1;
 3596:                     }
 3597:                     $cfile = $resurl;
 3598:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3599:                 $incourse = 1;
 3600:                 if ($env{'form.forceedit'}) {
 3601:                     $forceview = 1;
 3602:                 } else {
 3603:                     $forceedit = 1;
 3604:                 }
 3605:                 $cfile = $resurl;
 3606:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3607:                 $incourse = 1;
 3608:                 $forceview = 1;
 3609:                 if ($symb) {
 3610:                     my ($map,$id,$res)=&decode_symb($symb);
 3611:                     $env{'request.symb'} = $symb;
 3612:                     $cfile = &clutter($res);
 3613:                 } else {
 3614:                     $cfile = $env{'form.suppurl'};
 3615:                     my $escfile = &unescape($cfile);
 3616:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3617:                         $cfile = '/adm/wrapper'.$escfile;
 3618:                     } else {
 3619:                         $escfile =~ s{^http://}{};
 3620:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3621:                     }
 3622:                 }
 3623:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3624:                 if ($env{'form.forceedit'}) {
 3625:                     $forceview = 1;
 3626:                 } else {
 3627:                     $forceedit = 1;
 3628:                 }
 3629:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3630:             }
 3631:         }
 3632:         if ($uploaded || $incourse) {
 3633:             $home=&homeserver($cnum,$cdom);
 3634:         } elsif ($file !~ m{/$}) {
 3635:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3636:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3637:             # Check that the user has permission to edit this resource
 3638:             my $setpriv = 1;
 3639:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3640:             if (defined($cfudom)) {
 3641:                 $home=&homeserver($cfuname,$cfudom);
 3642:                 $cfile=$file;
 3643:             }
 3644:         }
 3645:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3646:             (($home ne '') && ($home ne 'no_host'))) {
 3647:             my @ids=&current_machine_ids();
 3648:             unless (grep(/^\Q$home\E$/,@ids)) {
 3649:                 $switchserver=1;
 3650:             }
 3651:         }
 3652:     }
 3653:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3654: }
 3655: 
 3656: sub is_course_upload {
 3657:     my ($file,$cnum,$cdom) = @_;
 3658:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3659:     $uploadpath =~ s{^\/}{};
 3660:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3661:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3662:         return 1;
 3663:     }
 3664:     return;
 3665: }
 3666: 
 3667: sub in_course {
 3668:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3669:     if ($hideprivileged) {
 3670:         my $skipuser;
 3671:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3672:         my @possdoms = ($cdom);  
 3673:         if ($coursehash{'checkforpriv'}) { 
 3674:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3675:         }
 3676:         if (&privileged($uname,$udom,\@possdoms)) {
 3677:             $skipuser = 1;
 3678:             if ($coursehash{'nothideprivileged'}) {
 3679:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3680:                     my $user;
 3681:                     if ($item =~ /:/) {
 3682:                         $user = $item;
 3683:                     } else {
 3684:                         $user = join(':',split(/[\@]/,$item));
 3685:                     }
 3686:                     if ($user eq $uname.':'.$udom) {
 3687:                         undef($skipuser);
 3688:                         last;
 3689:                     }
 3690:                 }
 3691:             }
 3692:             if ($skipuser) {
 3693:                 return 0;
 3694:             }
 3695:         }
 3696:     }
 3697:     $type ||= 'any';
 3698:     if (!defined($cdom) || !defined($cnum)) {
 3699:         my $cid  = $env{'request.course.id'};
 3700:         $cdom = $env{'course.'.$cid.'.domain'};
 3701:         $cnum = $env{'course.'.$cid.'.num'};
 3702:     }
 3703:     my $typesref;
 3704:     if (($type eq 'any') || ($type eq 'all')) {
 3705:         $typesref = ['active','previous','future'];
 3706:     } elsif ($type eq 'previous' || $type eq 'future') {
 3707:         $typesref = [$type];
 3708:     }
 3709:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3710:                               $typesref,undef,[$cdom]);
 3711:     my ($tmp) = keys(%roles);
 3712:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3713:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3714:     if (@course_roles > 0) {
 3715:         return 1;
 3716:     }
 3717:     return 0;
 3718: }
 3719: 
 3720: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3721: # input: action, courseID, current domain, intended
 3722: #        path to file, source of file, instruction to parse file for objects,
 3723: #        ref to hash for embedded objects,
 3724: #        ref to hash for codebase of java objects.
 3725: #        reference to scalar to accommodate mime type determined
 3726: #          from File::MMagic if $parser = parse.
 3727: #
 3728: # output: url to file (if action was uploaddoc), 
 3729: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3730: #
 3731: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3732: # course.
 3733: #
 3734: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3735: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3736: #          course's home server.
 3737: #
 3738: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3739: #          be copied from $source (current location) to 
 3740: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3741: #         and will then be copied to
 3742: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3743: #         course's home server.
 3744: #
 3745: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3746: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3747: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3748: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3749: #         in course's home server.
 3750: #
 3751: 
 3752: sub process_coursefile {
 3753:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3754:         $mimetype)=@_;
 3755:     my $fetchresult;
 3756:     my $home=&homeserver($docuname,$docudom);
 3757:     if ($action eq 'propagate') {
 3758:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3759: 			     $home);
 3760:     } else {
 3761:         my $fpath = '';
 3762:         my $fname = $file;
 3763:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3764:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3765:         my $filepath = &build_filepath($fpath);
 3766:         if ($action eq 'copy') {
 3767:             if ($source eq '') {
 3768:                 $fetchresult = 'no source file';
 3769:                 return $fetchresult;
 3770:             } else {
 3771:                 my $destination = $filepath.'/'.$fname;
 3772:                 rename($source,$destination);
 3773:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3774:                                  $home);
 3775:             }
 3776:         } elsif ($action eq 'uploaddoc') {
 3777:             open(my $fh,'>',$filepath.'/'.$fname);
 3778:             print $fh $env{'form.'.$source};
 3779:             close($fh);
 3780:             if ($parser eq 'parse') {
 3781:                 my $mm = new File::MMagic;
 3782:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3783:                 if ($type eq 'text/html') {
 3784:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3785:                     unless ($parse_result eq 'ok') {
 3786:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3787:                     }
 3788:                 }
 3789:                 if (ref($mimetype)) {
 3790:                     $$mimetype = $type;
 3791:                 } 
 3792:             }
 3793:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3794:                                  $home);
 3795:             if ($fetchresult eq 'ok') {
 3796:                 return '/uploaded/'.$fpath.'/'.$fname;
 3797:             } else {
 3798:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3799:                         ' to host '.$home.': '.$fetchresult);
 3800:                 return '/adm/notfound.html';
 3801:             }
 3802:         }
 3803:     }
 3804:     unless ( $fetchresult eq 'ok') {
 3805:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3806:              ' to host '.$home.': '.$fetchresult);
 3807:     }
 3808:     return $fetchresult;
 3809: }
 3810: 
 3811: sub build_filepath {
 3812:     my ($fpath) = @_;
 3813:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3814:     unless ($fpath eq '') {
 3815:         my @parts=split('/',$fpath);
 3816:         foreach my $part (@parts) {
 3817:             $filepath.= '/'.$part;
 3818:             if ((-e $filepath)!=1) {
 3819:                 mkdir($filepath,0777);
 3820:             }
 3821:         }
 3822:     }
 3823:     return $filepath;
 3824: }
 3825: 
 3826: sub store_edited_file {
 3827:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3828:     my $file = $primary_url;
 3829:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3830:     my $fpath = '';
 3831:     my $fname = $file;
 3832:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3833:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3834:     my $filepath = &build_filepath($fpath);
 3835:     open(my $fh,'>',$filepath.'/'.$fname);
 3836:     print $fh $content;
 3837:     close($fh);
 3838:     my $home=&homeserver($docuname,$docudom);
 3839:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3840: 			  $home);
 3841:     if ($$fetchresult eq 'ok') {
 3842:         return '/uploaded/'.$fpath.'/'.$fname;
 3843:     } else {
 3844:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3845: 		 ' to host '.$home.': '.$$fetchresult);
 3846:         return '/adm/notfound.html';
 3847:     }
 3848: }
 3849: 
 3850: sub clean_filename {
 3851:     my ($fname,$args)=@_;
 3852: # Replace Windows backslashes by forward slashes
 3853:     $fname=~s/\\/\//g;
 3854:     if (!$args->{'keep_path'}) {
 3855:         # Get rid of everything but the actual filename
 3856: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3857:     }
 3858: # Replace spaces by underscores
 3859:     $fname=~s/\s+/\_/g;
 3860: # Transliterate non-ascii text to ascii
 3861:     my $lang = &Apache::lonlocal::current_language();
 3862:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3863: # Replace all other weird characters by nothing
 3864:     $fname=~s{[^/\w\.\-]}{}g;
 3865: # Replace all .\d. sequences with _\d. so they no longer look like version
 3866: # numbers
 3867:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3868:     return $fname;
 3869: }
 3870: 
 3871: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3872: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3873: # image with the same aspect ratio as the original, but with dimensions which do 
 3874: # not exceed $resizewidth and $resizeheight.
 3875:  
 3876: sub resizeImage {
 3877:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3878:     my $ima = Image::Magick->new;
 3879:     my $resized;
 3880:     if (-e $img_path) {
 3881:         $ima->Read($img_path);
 3882:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3883:             my $width = $ima->Get('width');
 3884:             my $height = $ima->Get('height');
 3885:             if ($width > $resizewidth) {
 3886: 	        my $factor = $width/$resizewidth;
 3887:                 my $newheight = $height/$factor;
 3888:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3889:                 $resized = 1;
 3890:             }
 3891:         }
 3892:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3893:             my $width = $ima->Get('width');
 3894:             my $height = $ima->Get('height');
 3895:             if ($height > $resizeheight) {
 3896:                 my $factor = $height/$resizeheight;
 3897:                 my $newwidth = $width/$factor;
 3898:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3899:                 $resized = 1;
 3900:             }
 3901:         }
 3902:         if ($resized) {
 3903:             $ima->Write($img_path);
 3904:         }
 3905:     }
 3906:     return;
 3907: }
 3908: 
 3909: # --------------- Take an uploaded file and put it into the userfiles directory
 3910: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3911: #                    the desired filename is in $env{"form.$formname.filename"}
 3912: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3913: #                                    canceloverwrite, scantron or ''.
 3914: #                   if 'coursedoc': upload to the current course
 3915: #                   if 'existingfile': write file to tmp/overwrites directory 
 3916: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3917: #                   $context is passed as argument to &finishuserfileupload
 3918: #        $subdir - directory in userfile to store the file into
 3919: #        $parser - instruction to parse file for objects ($parser = parse) or
 3920: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3921: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3922: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3923: #        $allfiles - reference to hash for embedded objects
 3924: #        $codebase - reference to hash for codebase of java objects
 3925: #        $desuname - username for permanent storage of uploaded file
 3926: #        $dsetudom - domain for permanaent storage of uploaded file
 3927: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3928: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3929: #        $resizewidth - width (pixels) to which to resize uploaded image
 3930: #        $resizeheight - height (pixels) to which to resize uploaded image
 3931: #        $mimetype - reference to scalar to accommodate mime type determined
 3932: #                    from File::MMagic.
 3933: # 
 3934: # output: url of file in userspace, or error: <message> 
 3935: #             or /adm/notfound.html if failure to upload occurse
 3936: 
 3937: sub userfileupload {
 3938:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3939:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3940:     if (!defined($subdir)) { $subdir='unknown'; }
 3941:     my $fname=$env{'form.'.$formname.'.filename'};
 3942:     $fname=&clean_filename($fname);
 3943:     # See if there is anything left
 3944:     unless ($fname) { return 'error: no uploaded file'; }
 3945:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3946:     if ($fname =~ /^\./) {
 3947:         my ($s,$usec) = &gettimeofday();
 3948:         while (length($usec) < 6) {
 3949:             $usec = '0'.$usec;
 3950:         }
 3951:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3952:     }
 3953:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3954:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3955:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3956:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3957:         my $now = time;
 3958:         my $filepath;
 3959:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3960:              $filepath = 'tmp/helprequests/'.$now;
 3961:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3962:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3963:                          '_'.$env{'user.domain'}.'/pending';
 3964:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3965:             my ($docuname,$docudom);
 3966:             if ($destudom =~ /^$match_domain$/) {
 3967:                 $docudom = $destudom;
 3968:             } else {
 3969:                 $docudom = $env{'user.domain'};
 3970:             }
 3971:             if ($destuname =~ /^$match_username$/) {
 3972:                 $docuname = $destuname;
 3973:             } else {
 3974:                 $docuname = $env{'user.name'};
 3975:             }
 3976:             if (exists($env{'form.group'})) {
 3977:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3978:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3979:             }
 3980:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3981:             if ($context eq 'canceloverwrite') {
 3982:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3983:                 if (-e  $tempfile) {
 3984:                     my @info = stat($tempfile);
 3985:                     if ($info[9] eq $env{'form.timestamp'}) {
 3986:                         unlink($tempfile);
 3987:                     }
 3988:                 }
 3989:                 return;
 3990:             }
 3991:         }
 3992:         # Create the directory if not present
 3993:         my @parts=split(/\//,$filepath);
 3994:         my $fullpath = $perlvar{'lonDaemons'};
 3995:         for (my $i=0;$i<@parts;$i++) {
 3996:             $fullpath .= '/'.$parts[$i];
 3997:             if ((-e $fullpath)!=1) {
 3998:                 mkdir($fullpath,0777);
 3999:             }
 4000:         }
 4001:         open(my $fh,'>',$fullpath.'/'.$fname);
 4002:         print $fh $env{'form.'.$formname};
 4003:         close($fh);
 4004:         if ($context eq 'existingfile') {
 4005:             my @info = stat($fullpath.'/'.$fname);
 4006:             return ($fullpath.'/'.$fname,$info[9]);
 4007:         } else {
 4008:             return $fullpath.'/'.$fname;
 4009:         }
 4010:     }
 4011:     if ($subdir eq 'scantron') {
 4012:         $fname = 'scantron_orig_'.$fname;
 4013:     } else {
 4014:         $fname="$subdir/$fname";
 4015:     }
 4016:     if ($context eq 'coursedoc') {
 4017: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4018: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4019:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4020:             return &finishuserfileupload($docuname,$docudom,
 4021: 					 $formname,$fname,$parser,$allfiles,
 4022: 					 $codebase,$thumbwidth,$thumbheight,
 4023:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4024:         } else {
 4025:             if ($env{'form.folder'}) {
 4026:                 $fname=$env{'form.folder'}.'/'.$fname;
 4027:             }
 4028:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4029: 				       $fname,$formname,$parser,
 4030: 				       $allfiles,$codebase,$mimetype);
 4031:         }
 4032:     } elsif (defined($destuname)) {
 4033:         my $docuname=$destuname;
 4034:         my $docudom=$destudom;
 4035: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4036: 				     $parser,$allfiles,$codebase,
 4037:                                      $thumbwidth,$thumbheight,
 4038:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4039:     } else {
 4040:         my $docuname=$env{'user.name'};
 4041:         my $docudom=$env{'user.domain'};
 4042:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4043:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4044:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4045:         }
 4046: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4047: 				     $parser,$allfiles,$codebase,
 4048:                                      $thumbwidth,$thumbheight,
 4049:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4050:     }
 4051: }
 4052: 
 4053: sub finishuserfileupload {
 4054:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4055:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4056:     my $path=$docudom.'/'.$docuname.'/';
 4057:     my $filepath=$perlvar{'lonDocRoot'};
 4058:   
 4059:     my ($fnamepath,$file,$fetchthumb);
 4060:     $file=$fname;
 4061:     if ($fname=~m|/|) {
 4062:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4063: 	$path.=$fnamepath.'/';
 4064:     }
 4065:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4066:     my $count;
 4067:     for ($count=4;$count<=$#parts;$count++) {
 4068:         $filepath.="/$parts[$count]";
 4069:         if ((-e $filepath)!=1) {
 4070: 	    mkdir($filepath,0777);
 4071:         }
 4072:     }
 4073: 
 4074: # Save the file
 4075:     {
 4076: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4077: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4078: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4079: 	    return '/adm/notfound.html';
 4080: 	}
 4081:         if ($context eq 'overwrite') {
 4082:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4083:             my $target = $filepath.'/'.$file;
 4084:             if (-e $source) {
 4085:                 my @info = stat($source);
 4086:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4087:                     unless (&File::Copy::move($source,$target)) {
 4088:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4089:                         return "Moving from $source failed";
 4090:                     }
 4091:                 } else {
 4092:                     return "Temporary file: $source had unexpected date/time for last modification";
 4093:                 }
 4094:             } else {
 4095:                 return "Temporary file: $source missing";
 4096:             }
 4097:         } elsif (!print FH ($env{'form.'.$formname})) {
 4098: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4099: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4100: 	    return '/adm/notfound.html';
 4101: 	}
 4102: 	close(FH);
 4103:         if ($resizewidth && $resizeheight) {
 4104:             my $mm = new File::MMagic;
 4105:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4106:             if ($mime_type =~ m{^image/}) {
 4107: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4108:             }  
 4109: 	}
 4110:     }
 4111:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4112:         if (ref($mimetype)) {
 4113:             if ($$mimetype eq '') {
 4114:                 my $mm = new File::MMagic;
 4115:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4116:                 $$mimetype = $type;
 4117:             }
 4118:         }
 4119:     }
 4120:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4121:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4122:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4123:                                                        $allfiles,$codebase);
 4124:             unless ($parse_result eq 'ok') {
 4125:                 &logthis('Failed to parse '.$filepath.$file.
 4126: 	   	         ' for embedded media: '.$parse_result); 
 4127:             }
 4128:         }
 4129:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4130:         my $format = $env{'form.scantron_format'};
 4131:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4132:     }
 4133:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4134:         my $input = $filepath.'/'.$file;
 4135:         my $output = $filepath.'/'.'tn-'.$file;
 4136:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4137:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4138:         system({$args[0]} @args);
 4139:         if (-e $filepath.'/'.'tn-'.$file) {
 4140:             $fetchthumb  = 1; 
 4141:         }
 4142:     }
 4143:  
 4144: # Notify homeserver to grep it
 4145: #
 4146:     my $docuhome=&homeserver($docuname,$docudom);	
 4147:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4148:     if ($fetchresult eq 'ok') {
 4149:         if ($fetchthumb) {
 4150:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4151:             if ($thumbresult ne 'ok') {
 4152:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4153:                          $docuhome.': '.$thumbresult);
 4154:             }
 4155:         }
 4156: #
 4157: # Return the URL to it
 4158:         return '/uploaded/'.$path.$file;
 4159:     } else {
 4160:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4161: 		 ': '.$fetchresult);
 4162:         return '/adm/notfound.html';
 4163:     }
 4164: }
 4165: 
 4166: sub extract_embedded_items {
 4167:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4168:     my @state = ();
 4169:     my (%lastids,%related,%shockwave,%flashvars);
 4170:     my %javafiles = (
 4171:                       codebase => '',
 4172:                       code => '',
 4173:                       archive => ''
 4174:                     );
 4175:     my %mediafiles = (
 4176:                       src => '',
 4177:                       movie => '',
 4178:                      );
 4179:     my $p;
 4180:     if ($content) {
 4181:         $p = HTML::LCParser->new($content);
 4182:     } else {
 4183:         $p = HTML::LCParser->new($fullpath);
 4184:     }
 4185:     while (my $t=$p->get_token()) {
 4186: 	if ($t->[0] eq 'S') {
 4187: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4188: 	    push(@state, $tagname);
 4189:             if (lc($tagname) eq 'allow') {
 4190:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4191:             }
 4192: 	    if (lc($tagname) eq 'img') {
 4193: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4194: 	    }
 4195: 	    if (lc($tagname) eq 'a') {
 4196:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4197:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4198:                 }
 4199: 	    }
 4200:             if (lc($tagname) eq 'script') {
 4201:                 my $src;
 4202:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4203:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4204:                 } else {
 4205:                     if ($attr->{'src'} ne '') {
 4206:                         $src = $attr->{'src'};
 4207:                         &add_filetype($allfiles,$src,'src');
 4208:                     }
 4209:                 }
 4210:                 my $text = $p->get_trimmed_text();
 4211:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4212:                     my @swfargs = split(/,/,$1);
 4213:                     foreach my $item (@swfargs) {
 4214:                         $item =~ s/["']//g;
 4215:                         $item =~ s/^\s+//;
 4216:                         $item =~ s/\s+$//;
 4217:                     }
 4218:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4219:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4220:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4221:                         } else {
 4222:                             $related{$swfargs[0]} = [$swfargs[2]];
 4223:                         }
 4224:                     }
 4225:                 }
 4226:             }
 4227:             if (lc($tagname) eq 'link') {
 4228:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4229:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4230:                 }
 4231:             }
 4232: 	    if (lc($tagname) eq 'object' ||
 4233: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4234: 		foreach my $item (keys(%javafiles)) {
 4235: 		    $javafiles{$item} = '';
 4236: 		}
 4237:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4238:                     $lastids{lc($tagname)} = $attr->{'id'};
 4239:                 }
 4240: 	    }
 4241: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4242: 		my $name = lc($attr->{'name'});
 4243: 		foreach my $item (keys(%javafiles)) {
 4244: 		    if ($name eq $item) {
 4245: 			$javafiles{$item} = $attr->{'value'};
 4246: 			last;
 4247: 		    }
 4248: 		}
 4249:                 my $pathfrom;
 4250: 		foreach my $item (keys(%mediafiles)) {
 4251: 		    if ($name eq $item) {
 4252:                         $pathfrom = $attr->{'value'};
 4253:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4254: 			&add_filetype($allfiles,$pathfrom,$name);
 4255: 			last;
 4256: 		    }
 4257: 		}
 4258:                 if ($name eq 'flashvars') {
 4259:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4260:                 }
 4261:                 if ($pathfrom ne '') {
 4262:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4263:                                          $pathfrom);
 4264:                 }
 4265: 	    }
 4266: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4267: 		foreach my $item (keys(%javafiles)) {
 4268: 		    if ($attr->{$item}) {
 4269: 			$javafiles{$item} = $attr->{$item};
 4270: 			last;
 4271: 		    }
 4272: 		}
 4273: 		foreach my $item (keys(%mediafiles)) {
 4274: 		    if ($attr->{$item}) {
 4275: 			&add_filetype($allfiles,$attr->{$item},$item);
 4276: 			last;
 4277: 		    }
 4278: 		}
 4279:                 if (lc($tagname) eq 'embed') {
 4280:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4281:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4282:                                              $attr->{'src'});
 4283:                     }
 4284:                 }
 4285: 	    }
 4286:             if (lc($tagname) eq 'iframe') {
 4287:                 my $src = $attr->{'src'} ;
 4288:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4289:                     &add_filetype($allfiles,$src,'src');
 4290:                 } elsif ($src =~ m{^/}) {
 4291:                     if ($env{'request.course.id'}) {
 4292:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4293:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4294:                         my $url = &hreflocation('',$fullpath);
 4295:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4296:                             my $relpath = $1;
 4297:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4298:                                 &add_filetype($allfiles,$1,'src');
 4299:                             }
 4300:                         }
 4301:                     }
 4302:                 }
 4303:             }
 4304:             if ($t->[4] =~ m{/>$}) {
 4305:                 pop(@state);
 4306:             }
 4307: 	} elsif ($t->[0] eq 'E') {
 4308: 	    my ($tagname) = ($t->[1]);
 4309: 	    if ($javafiles{'codebase'} ne '') {
 4310: 		$javafiles{'codebase'} .= '/';
 4311: 	    }  
 4312: 	    if (lc($tagname) eq 'applet' ||
 4313: 		lc($tagname) eq 'object' ||
 4314: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4315: 		) {
 4316: 		foreach my $item (keys(%javafiles)) {
 4317: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4318: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4319: 			&add_filetype($allfiles,$file,$item);
 4320: 		    }
 4321: 		}
 4322: 	    } 
 4323: 	    pop @state;
 4324: 	}
 4325:     }
 4326:     foreach my $id (sort(keys(%flashvars))) {
 4327:         if ($shockwave{$id} ne '') {
 4328:             my @pairs = split(/\&/,$flashvars{$id});
 4329:             foreach my $pair (@pairs) {
 4330:                 my ($key,$value) = split(/\=/,$pair);
 4331:                 if ($key eq 'thumb') {
 4332:                     &add_filetype($allfiles,$value,$key);
 4333:                 } elsif ($key eq 'content') {
 4334:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4335:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4336:                     if ($ext ne '') {
 4337:                         &add_filetype($allfiles,$path.$value,$ext);
 4338:                     }
 4339:                 }
 4340:             }
 4341:         }
 4342:     }
 4343:     return 'ok';
 4344: }
 4345: 
 4346: sub add_filetype {
 4347:     my ($allfiles,$file,$type)=@_;
 4348:     if (exists($allfiles->{$file})) {
 4349: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4350: 	    push(@{$allfiles->{$file}}, &escape($type));
 4351: 	}
 4352:     } else {
 4353: 	@{$allfiles->{$file}} = (&escape($type));
 4354:     }
 4355: }
 4356: 
 4357: sub embedded_dependency {
 4358:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4359:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4360:         if (($identifier ne '') &&
 4361:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4362:             ($pathfrom ne '')) {
 4363:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4364:             foreach my $dep (@{$related->{$identifier}}) {
 4365:                 &add_filetype($allfiles,$path.$dep,'object');
 4366:             }
 4367:         }
 4368:     }
 4369:     return;
 4370: }
 4371: 
 4372: sub bubblesheet_converter {
 4373:     my ($cdom,$fullpath,$config,$format) = @_;
 4374:     if ((&domain($cdom) ne '') &&
 4375:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4376:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4377:         my (%csvcols,%csvoptions);
 4378:         if (ref($config->{'fields'}) eq 'HASH') {  
 4379:             %csvcols = %{$config->{'fields'}};
 4380:         }
 4381:         if (ref($config->{'options'}) eq 'HASH') {
 4382:             %csvoptions = %{$config->{'options'}};
 4383:         }
 4384:         my %csvbynum = reverse(%csvcols);
 4385:         my %scantronconf = &get_scantron_config($format,$cdom);
 4386:         if (keys(%scantronconf)) {
 4387:             my %bynum = (
 4388:                           $scantronconf{CODEstart} => 'CODEstart',
 4389:                           $scantronconf{IDstart}   => 'IDstart',
 4390:                           $scantronconf{PaperID}   => 'PaperID',
 4391:                           $scantronconf{FirstName} => 'FirstName',
 4392:                           $scantronconf{LastName}  => 'LastName',
 4393:                           $scantronconf{Qstart}    => 'Qstart',
 4394:                         );
 4395:             my @ordered;
 4396:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4397:                 push(@ordered,$bynum{$item});
 4398:             }
 4399:             my %mapstart = (
 4400:                               CODEstart => 'CODE',
 4401:                               IDstart   => 'ID',
 4402:                               PaperID   => 'PaperID',
 4403:                               FirstName => 'FirstName',
 4404:                               LastName  => 'LastName',
 4405:                               Qstart    => 'FirstQuestion',
 4406:                            );
 4407:             my %maplength = (
 4408:                               CODEstart => 'CODElength',
 4409:                               IDstart   => 'IDlength',
 4410:                               PaperID   => 'PaperIDlength',
 4411:                               FirstName => 'FirstNamelength',
 4412:                               LastName  => 'LastNamelength',
 4413:             );
 4414:             if (open(my $fh,'<',$fullpath)) {
 4415:                 my $output;
 4416:                 my %lettdig = &letter_to_digits();
 4417:                 my %diglett = reverse(%lettdig);
 4418:                 my $numletts = scalar(keys(%lettdig));
 4419:                 my $num = 0;
 4420:                 while (my $line=<$fh>) {
 4421:                     $num ++;
 4422:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4423:                     $line =~ s{[\r\n]+$}{};
 4424:                     my %found;
 4425:                     my @values = split(/,/,$line);
 4426:                     my ($qstart,$record);
 4427:                     for (my $i=0; $i<@values; $i++) {
 4428:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4429:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4430:                             if ($values[$i] eq '') {
 4431:                                 $values[$i] = $scantronconf{'Qoff'};
 4432:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4433:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4434:                                     $values[$i] = $lettdig{uc($values[$i])};
 4435:                                 }
 4436:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4437:                                 if ($values[$i] =~ /^[0-9]$/) {
 4438:                                     $values[$i] = $diglett{$values[$i]};
 4439:                                 }
 4440:                             } else {
 4441:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4442:                                     my $digit;
 4443:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4444:                                         $digit = $lettdig{uc($values[$i])}-1;
 4445:                                         if ($values[$i] eq 'J') {
 4446:                                             $digit += $numletts;
 4447:                                         }
 4448:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4449:                                         $digit = $values[$i]-1;
 4450:                                         if ($values[$i] eq '0') {
 4451:                                             $digit += $numletts;
 4452:                                         }
 4453:                                     }
 4454:                                     my $qval='';
 4455:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4456:                                         if ($j == $digit) {
 4457:                                             $qval .= $scantronconf{'Qon'};
 4458:                                         } else {
 4459:                                             $qval .= $scantronconf{'Qoff'};
 4460:                                         }
 4461:                                     }
 4462:                                     $values[$i] = $qval;
 4463:                                 }
 4464:                             }
 4465:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4466:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4467:                             }
 4468:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4469:                             if ($numblank > 0) {
 4470:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4471:                             }
 4472:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4473:                                 $qstart = $i;
 4474:                                 $found{$csvbynum{$i}} = $values[$i];
 4475:                             } else {
 4476:                                 $found{'FirstQuestion'} .= $values[$i];
 4477:                             }
 4478:                         } elsif (exists($csvbynum{$i})) {
 4479:                             if ($csvoptions{'rem'}) {
 4480:                                 $values[$i] =~ s/^\s+//;
 4481:                             }
 4482:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4483:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4484:                                     $values[$i] = '0'.$values[$i];
 4485:                                 }
 4486:                             }
 4487:                             $found{$csvbynum{$i}} = $values[$i];
 4488:                         }
 4489:                     }
 4490:                     foreach my $item (@ordered) {
 4491:                         my $currlength = 1+length($record);
 4492:                         my $numspaces = $scantronconf{$item} - $currlength;
 4493:                         if ($numspaces > 0) {
 4494:                             $record .= (' ' x $numspaces);
 4495:                         }
 4496:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4497:                             unless ($item eq 'Qstart') {
 4498:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4499:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4500:                                 }
 4501:                             }
 4502:                             $record .= $found{$mapstart{$item}};
 4503:                         }
 4504:                     }
 4505:                     $output .= "$record\n";
 4506:                 }
 4507:                 close($fh);
 4508:                 if ($output) {
 4509:                     if (open(my $fh,'>',$fullpath)) {
 4510:                         print $fh $output;
 4511:                         close($fh);
 4512:                     }
 4513:                 }
 4514:             }
 4515:         }
 4516:         return;
 4517:     }
 4518: }
 4519: 
 4520: sub letter_to_digits {
 4521:     my %lettdig = (
 4522:                     A => 1,
 4523:                     B => 2,
 4524:                     C => 3,
 4525:                     D => 4,
 4526:                     E => 5,
 4527:                     F => 6,
 4528:                     G => 7,
 4529:                     H => 8,
 4530:                     I => 9,
 4531:                     J => 0,
 4532:                   );
 4533:     return %lettdig;
 4534: }
 4535: 
 4536: sub get_scantron_config {
 4537:     my ($which,$cdom) = @_;
 4538:     my @lines = &get_scantronformat_file($cdom);
 4539:     my %config;
 4540:     #FIXME probably should move to XML it has already gotten a bit much now
 4541:     foreach my $line (@lines) {
 4542:         my ($name,$descrip)=split(/:/,$line);
 4543:         if ($name ne $which ) { next; }
 4544:         chomp($line);
 4545:         my @config=split(/:/,$line);
 4546:         $config{'name'}=$config[0];
 4547:         $config{'description'}=$config[1];
 4548:         $config{'CODElocation'}=$config[2];
 4549:         $config{'CODEstart'}=$config[3];
 4550:         $config{'CODElength'}=$config[4];
 4551:         $config{'IDstart'}=$config[5];
 4552:         $config{'IDlength'}=$config[6];
 4553:         $config{'Qstart'}=$config[7];
 4554:         $config{'Qlength'}=$config[8];
 4555:         $config{'Qoff'}=$config[9];
 4556:         $config{'Qon'}=$config[10];
 4557:         $config{'PaperID'}=$config[11];
 4558:         $config{'PaperIDlength'}=$config[12];
 4559:         $config{'FirstName'}=$config[13];
 4560:         $config{'FirstNamelength'}=$config[14];
 4561:         $config{'LastName'}=$config[15];
 4562:         $config{'LastNamelength'}=$config[16];
 4563:         $config{'BubblesPerRow'}=$config[17];
 4564:         last;
 4565:     }
 4566:     return %config;
 4567: }
 4568: 
 4569: sub get_scantronformat_file {
 4570:     my ($cdom) = @_;
 4571:     if ($cdom eq '') {
 4572:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4573:     }
 4574:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4575:     my $gottab = 0;
 4576:     my @lines;
 4577:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4578:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4579:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4580:             if ($formatfile ne '-1') {
 4581:                 @lines = split("\n",$formatfile,-1);
 4582:                 $gottab = 1;
 4583:             }
 4584:         }
 4585:     }
 4586:     if (!$gottab) {
 4587:         my $confname = $cdom.'-domainconfig';
 4588:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4589:         my $formatfile = &getfile($default);
 4590:         if ($formatfile ne '-1') {
 4591:             @lines = split("\n",$formatfile,-1);
 4592:             $gottab = 1;
 4593:         }
 4594:     }
 4595:     if (!$gottab) {
 4596:         my @domains = &current_machine_domains();
 4597:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4598:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4599:                 @lines = <$fh>;
 4600:                 close($fh);
 4601:             }
 4602:         } else {
 4603:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4604:                 @lines = <$fh>;
 4605:                 close($fh);
 4606:             }
 4607:         }
 4608:     }
 4609:     return @lines;
 4610: }
 4611: 
 4612: sub removeuploadedurl {
 4613:     my ($url)=@_;	
 4614:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4615:     return &removeuserfile($uname,$udom,$fname);
 4616: }
 4617: 
 4618: sub removeuserfile {
 4619:     my ($docuname,$docudom,$fname)=@_;
 4620:     my $home=&homeserver($docuname,$docudom);    
 4621:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4622:     if ($result eq 'ok') {	
 4623:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4624:             my $metafile = $fname.'.meta';
 4625:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4626: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4627:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4628:             my $sqlresult = 
 4629:                 &update_portfolio_table($docuname,$docudom,$file,
 4630:                                         'portfolio_metadata',$group,
 4631:                                         'delete');
 4632:         }
 4633:     }
 4634:     return $result;
 4635: }
 4636: 
 4637: sub mkdiruserfile {
 4638:     my ($docuname,$docudom,$dir)=@_;
 4639:     my $home=&homeserver($docuname,$docudom);
 4640:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4641: }
 4642: 
 4643: sub renameuserfile {
 4644:     my ($docuname,$docudom,$old,$new)=@_;
 4645:     my $home=&homeserver($docuname,$docudom);
 4646:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4647:                         &escape("$old").':'.&escape("$new"),$home);
 4648:     if ($result eq 'ok') {
 4649:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4650:             my $oldmeta = $old.'.meta';
 4651:             my $newmeta = $new.'.meta';
 4652:             my $metaresult = 
 4653:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4654: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4655:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4656:             my $sqlresult = 
 4657:                 &update_portfolio_table($docuname,$docudom,$file,
 4658:                                         'portfolio_metadata',$group,
 4659:                                         'delete');
 4660:         }
 4661:     }
 4662:     return $result;
 4663: }
 4664: 
 4665: # ------------------------------------------------------------------------- Log
 4666: 
 4667: sub log {
 4668:     my ($dom,$nam,$hom,$what)=@_;
 4669:     return critical("log:$dom:$nam:$what",$hom);
 4670: }
 4671: 
 4672: # ------------------------------------------------------------------ Course Log
 4673: #
 4674: # This routine flushes several buffers of non-mission-critical nature
 4675: #
 4676: 
 4677: sub flushcourselogs {
 4678:     &logthis('Flushing log buffers');
 4679: #
 4680: # course logs
 4681: # This is a log of all transactions in a course, which can be used
 4682: # for data mining purposes
 4683: #
 4684: # It also collects the courseid database, which lists last transaction
 4685: # times and course titles for all courseids
 4686: #
 4687:     my %courseidbuffer=();
 4688:     foreach my $crsid (keys(%courselogs)) {
 4689:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4690: 		          &escape($courselogs{$crsid}),
 4691: 		          $coursehombuf{$crsid}) eq 'ok') {
 4692: 	    delete $courselogs{$crsid};
 4693:         } else {
 4694:             &logthis('Failed to flush log buffer for '.$crsid);
 4695:             if (length($courselogs{$crsid})>40000) {
 4696:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4697:                         " exceeded maximum size, deleting.</font>");
 4698:                delete $courselogs{$crsid};
 4699:             }
 4700:         }
 4701:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4702:             'description' => $coursedescrbuf{$crsid},
 4703:             'inst_code'    => $courseinstcodebuf{$crsid},
 4704:             'type'        => $coursetypebuf{$crsid},
 4705:             'owner'       => $courseownerbuf{$crsid},
 4706:         };
 4707:     }
 4708: #
 4709: # Write course id database (reverse lookup) to homeserver of courses 
 4710: # Is used in pickcourse
 4711: #
 4712:     foreach my $crs_home (keys(%courseidbuffer)) {
 4713:         my $response = &courseidput(&host_domain($crs_home),
 4714:                                     $courseidbuffer{$crs_home},
 4715:                                     $crs_home,'timeonly');
 4716:     }
 4717: #
 4718: # File accesses
 4719: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4720: #
 4721:     foreach my $entry (keys(%accesshash)) {
 4722:         if ($entry =~ /___count$/) {
 4723:             my ($dom,$name);
 4724:             ($dom,$name,undef)=
 4725: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4726:             if (! defined($dom) || $dom eq '' || 
 4727:                 ! defined($name) || $name eq '') {
 4728:                 my $cid = $env{'request.course.id'};
 4729:                 $dom  = $env{'request.'.$cid.'.domain'};
 4730:                 $name = $env{'request.'.$cid.'.num'};
 4731:             }
 4732:             my $value = $accesshash{$entry};
 4733:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4734:             my %temphash=($url => $value);
 4735:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4736:             if ($result eq 'ok') {
 4737:                 delete $accesshash{$entry};
 4738:             }
 4739:         } else {
 4740:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4741:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4742:             my %temphash=($entry => $accesshash{$entry});
 4743:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4744:                 delete $accesshash{$entry};
 4745:             }
 4746:         }
 4747:     }
 4748: #
 4749: # Roles
 4750: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4751: #
 4752:     foreach my $entry (keys(%userrolehash)) {
 4753:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4754: 	    split(/\:/,$entry);
 4755:         if (&Apache::lonnet::put('nohist_userroles',
 4756:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4757:                 $rudom,$runame) eq 'ok') {
 4758: 	    delete $userrolehash{$entry};
 4759:         }
 4760:     }
 4761: #
 4762: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4763: #
 4764:     my %domrolebuffer = ();
 4765:     foreach my $entry (keys(%domainrolehash)) {
 4766:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4767:         if ($domrolebuffer{$rudom}) {
 4768:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4769:                       '='.&escape($domainrolehash{$entry});
 4770:         } else {
 4771:             $domrolebuffer{$rudom}.=&escape($entry).
 4772:                       '='.&escape($domainrolehash{$entry});
 4773:         }
 4774:         delete $domainrolehash{$entry};
 4775:     }
 4776:     foreach my $dom (keys(%domrolebuffer)) {
 4777: 	my %servers;
 4778: 	if (defined(&domain($dom,'primary'))) {
 4779: 	    my $primary=&domain($dom,'primary');
 4780: 	    my $hostname=&hostname($primary);
 4781: 	    $servers{$primary} = $hostname;
 4782: 	} else { 
 4783: 	    %servers = &get_servers($dom,'library');
 4784: 	}
 4785: 	foreach my $tryserver (keys(%servers)) {
 4786: 	    if (&reply('domroleput:'.$dom.':'.
 4787: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4788: 		last;
 4789: 	    } else {  
 4790: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4791: 	    }
 4792:         }
 4793:     }
 4794:     $dumpcount++;
 4795: }
 4796: 
 4797: sub courselog {
 4798:     my $what=shift;
 4799:     $what=time.':'.$what;
 4800:     unless ($env{'request.course.id'}) { return ''; }
 4801:     $coursedombuf{$env{'request.course.id'}}=
 4802:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4803:     $coursenumbuf{$env{'request.course.id'}}=
 4804:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4805:     $coursehombuf{$env{'request.course.id'}}=
 4806:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4807:     $coursedescrbuf{$env{'request.course.id'}}=
 4808:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4809:     $courseinstcodebuf{$env{'request.course.id'}}=
 4810:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4811:     $courseownerbuf{$env{'request.course.id'}}=
 4812:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4813:     $coursetypebuf{$env{'request.course.id'}}=
 4814:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4815:     if (defined $courselogs{$env{'request.course.id'}}) {
 4816: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4817:     } else {
 4818: 	$courselogs{$env{'request.course.id'}}.=$what;
 4819:     }
 4820:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4821: 	&flushcourselogs();
 4822:     }
 4823: }
 4824: 
 4825: sub courseacclog {
 4826:     my $fnsymb=shift;
 4827:     unless ($env{'request.course.id'}) { return ''; }
 4828:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4829:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4830:         $what.=':POST';
 4831:         # FIXME: Probably ought to escape things....
 4832: 	foreach my $key (keys(%env)) {
 4833:             if ($key=~/^form\.(.*)/) {
 4834:                 my $formitem = $1;
 4835:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4836:                     $what.=':'.$formitem.'='.$env{$key};
 4837:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4838:                     $what.=':'.$formitem.'='.$env{$key};
 4839:                 }
 4840:             }
 4841:         }
 4842:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4843:         # FIXME: We should not be depending on a form parameter that someone
 4844:         # editing lonsearchcat.pm might change in the future.
 4845:         if ($env{'form.phase'} eq 'course_search') {
 4846:             $what.= ':POST';
 4847:             # FIXME: Probably ought to escape things....
 4848:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4849:                                  'crsdiscuss') {
 4850:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4851:             }
 4852:         }
 4853:     }
 4854:     &courselog($what);
 4855: }
 4856: 
 4857: sub countacc {
 4858:     my $url=&declutter(shift);
 4859:     return if (! defined($url) || $url eq '');
 4860:     unless ($env{'request.course.id'}) { return ''; }
 4861: #
 4862: # Mark that this url was used in this course
 4863: #
 4864:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4865: #
 4866: # Increase the access count for this resource in this child process
 4867: #
 4868:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4869:     $accesshash{$key}++;
 4870: }
 4871: 
 4872: sub linklog {
 4873:     my ($from,$to)=@_;
 4874:     $from=&declutter($from);
 4875:     $to=&declutter($to);
 4876:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4877:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4878: }
 4879: 
 4880: sub statslog {
 4881:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4882:     if ($users<2) { return; }
 4883:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4884:             'course'       => $env{'request.course.id'},
 4885:             'sections'     => '"all"',
 4886:             'num_students' => $users,
 4887:             'part'         => $part,
 4888:             'symb'         => $symb,
 4889:             'mean_tries'   => $av_attempts,
 4890:             'deg_of_diff'  => $degdiff});
 4891:     foreach my $key (keys(%dynstore)) {
 4892:         $accesshash{$key}=$dynstore{$key};
 4893:     }
 4894: }
 4895:   
 4896: sub userrolelog {
 4897:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4898:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4899:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4900:        $userrolehash
 4901:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4902:                     =$tend.':'.$tstart;
 4903:     }
 4904:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4905:        $userrolehash
 4906:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4907:                     =$tend.':'.$tstart;
 4908:     }
 4909:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4910:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4911:        $domainrolehash
 4912:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4913:                     = $tend.':'.$tstart;
 4914:     }
 4915: }
 4916: 
 4917: sub courserolelog {
 4918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4919:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4920:         my $cdom = $1;
 4921:         my $cnum = $2;
 4922:         my $sec = $3;
 4923:         my $namespace = 'rolelog';
 4924:         my %storehash = (
 4925:                            role    => $trole,
 4926:                            start   => $tstart,
 4927:                            end     => $tend,
 4928:                            selfenroll => $selfenroll,
 4929:                            context    => $context,
 4930:                         );
 4931:         if ($trole eq 'gr') {
 4932:             $namespace = 'groupslog';
 4933:             $storehash{'group'} = $sec;
 4934:         } else {
 4935:             $storehash{'section'} = $sec;
 4936:         }
 4937:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4938:                    $domain,$cnum,$cdom);
 4939:         if (($trole ne 'st') || ($sec ne '')) {
 4940:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4941:         }
 4942:     }
 4943:     return;
 4944: }
 4945: 
 4946: sub domainrolelog {
 4947:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4948:     if ($area =~ m{^/($match_domain)/$}) {
 4949:         my $cdom = $1;
 4950:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4951:         my $namespace = 'rolelog';
 4952:         my %storehash = (
 4953:                            role    => $trole,
 4954:                            start   => $tstart,
 4955:                            end     => $tend,
 4956:                            context => $context,
 4957:                         );
 4958:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4959:                    $domain,$domconfiguser,$cdom);
 4960:     }
 4961:     return;
 4962: 
 4963: }
 4964: 
 4965: sub coauthorrolelog {
 4966:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4967:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4968:         my $audom = $1;
 4969:         my $auname = $2;
 4970:         my $namespace = 'rolelog';
 4971:         my %storehash = (
 4972:                            role    => $trole,
 4973:                            start   => $tstart,
 4974:                            end     => $tend,
 4975:                            context => $context,
 4976:                         );
 4977:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4978:                    $domain,$auname,$audom);
 4979:     }
 4980:     return;
 4981: }
 4982: 
 4983: sub get_course_adv_roles {
 4984:     my ($cid,$codes) = @_;
 4985:     $cid=$env{'request.course.id'} unless (defined($cid));
 4986:     my %coursehash=&coursedescription($cid);
 4987:     my $crstype = &Apache::loncommon::course_type($cid);
 4988:     my %nothide=();
 4989:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4990:         if ($user !~ /:/) {
 4991: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4992:         } else {
 4993:             $nothide{$user}=1;
 4994:         }
 4995:     }
 4996:     my @possdoms = ($coursehash{'domain'});
 4997:     if ($coursehash{'checkforpriv'}) {
 4998:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4999:     }
 5000:     my %returnhash=();
 5001:     my %dumphash=
 5002:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5003:     my $now=time;
 5004:     my %privileged;
 5005:     foreach my $entry (keys(%dumphash)) {
 5006: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5007:         if (($tstart) && ($tstart<0)) { next; }
 5008:         if (($tend) && ($tend<$now)) { next; }
 5009:         if (($tstart) && ($now<$tstart)) { next; }
 5010:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5011: 	if ($username eq '' || $domain eq '') { next; }
 5012:         if ((&privileged($username,$domain,\@possdoms)) &&
 5013:             (!$nothide{$username.':'.$domain})) { next; }
 5014: 	if ($role eq 'cr') { next; }
 5015:         if ($codes) {
 5016:             if ($section) { $role .= ':'.$section; }
 5017:             if ($returnhash{$role}) {
 5018:                 $returnhash{$role}.=','.$username.':'.$domain;
 5019:             } else {
 5020:                 $returnhash{$role}=$username.':'.$domain;
 5021:             }
 5022:         } else {
 5023:             my $key=&plaintext($role,$crstype);
 5024:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5025:             if ($returnhash{$key}) {
 5026: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5027:             } else {
 5028:                 $returnhash{$key}=$username.':'.$domain;
 5029:             }
 5030:         }
 5031:     }
 5032:     return %returnhash;
 5033: }
 5034: 
 5035: sub get_my_roles {
 5036:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5037:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5038:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5039:     my (%dumphash,%nothide);
 5040:     if ($context eq 'userroles') {
 5041:         %dumphash = &dump('roles',$udom,$uname);
 5042:     } else {
 5043:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5044:         if ($hidepriv) {
 5045:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5046:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5047:                 if ($user !~ /:/) {
 5048:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5049:                 } else {
 5050:                     $nothide{$user} = 1;
 5051:                 }
 5052:             }
 5053:         }
 5054:     }
 5055:     my %returnhash=();
 5056:     my $now=time;
 5057:     my %privileged;
 5058:     foreach my $entry (keys(%dumphash)) {
 5059:         my ($role,$tend,$tstart);
 5060:         if ($context eq 'userroles') {
 5061:             next if ($entry =~ /^rolesdef/);
 5062: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5063:         } else {
 5064:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5065:         }
 5066:         if (($tstart) && ($tstart<0)) { next; }
 5067:         my $status = 'active';
 5068:         if (($tend) && ($tend<=$now)) {
 5069:             $status = 'previous';
 5070:         } 
 5071:         if (($tstart) && ($now<$tstart)) {
 5072:             $status = 'future';
 5073:         }
 5074:         if (ref($types) eq 'ARRAY') {
 5075:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5076:                 next;
 5077:             } 
 5078:         } else {
 5079:             if ($status ne 'active') {
 5080:                 next;
 5081:             }
 5082:         }
 5083:         my ($rolecode,$username,$domain,$section,$area);
 5084:         if ($context eq 'userroles') {
 5085:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5086:             (undef,$domain,$username,$section) = split(/\//,$area);
 5087:         } else {
 5088:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5089:         }
 5090:         if (ref($roledoms) eq 'ARRAY') {
 5091:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5092:                 next;
 5093:             }
 5094:         }
 5095:         if (ref($roles) eq 'ARRAY') {
 5096:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5097:                 if ($role =~ /^cr\//) {
 5098:                     if (!grep(/^cr$/,@{$roles})) {
 5099:                         next;
 5100:                     }
 5101:                 } elsif ($role =~ /^gr\//) {
 5102:                     if (!grep(/^gr$/,@{$roles})) {
 5103:                         next;
 5104:                     }
 5105:                 } else {
 5106:                     next;
 5107:                 }
 5108:             }
 5109:         }
 5110:         if ($hidepriv) {
 5111:             my @privroles = ('dc','su');
 5112:             if ($context eq 'userroles') {
 5113:                 next if (grep(/^\Q$role\E$/,@privroles));
 5114:             } else {
 5115:                 my $possdoms = [$domain];
 5116:                 if (ref($roledoms) eq 'ARRAY') {
 5117:                    push(@{$possdoms},@{$roledoms}); 
 5118:                 }
 5119:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5120:                     if (!$nothide{$username.':'.$domain}) {
 5121:                         next;
 5122:                     }
 5123:                 }
 5124:             }
 5125:         }
 5126:         if ($withsec) {
 5127:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5128:                 $tstart.':'.$tend;
 5129:         } else {
 5130:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5131:         }
 5132:     }
 5133:     return %returnhash;
 5134: }
 5135: 
 5136: sub get_all_adhocroles {
 5137:     my ($dom) = @_;
 5138:     my @roles_by_num = ();
 5139:     my %domdefaults = &get_domain_defaults($dom);
 5140:     my (%description,%access_in_dom,%access_info);
 5141:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5142:         my $count = 0;
 5143:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5144:         my %ordered;
 5145:         foreach my $role (sort(keys(%domcurrent))) {
 5146:             my ($order,$desc,$access_in_dom);
 5147:             if (ref($domcurrent{$role}) eq 'HASH') {
 5148:                 $order = $domcurrent{$role}{'order'};
 5149:                 $desc = $domcurrent{$role}{'desc'};
 5150:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5151:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5152:             }
 5153:             if ($order eq '') {
 5154:                 $order = $count;
 5155:             }
 5156:             $ordered{$order} = $role;
 5157:             if ($desc ne '') {
 5158:                 $description{$role} = $desc;
 5159:             } else {
 5160:                 $description{$role}= $role;
 5161:             }
 5162:             $count++;
 5163:         }
 5164:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5165:             push(@roles_by_num,$ordered{$item});
 5166:         }
 5167:     }
 5168:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5169: }
 5170: 
 5171: sub get_my_adhocroles {
 5172:     my ($cid,$checkreg) = @_;
 5173:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5174:     if ($env{'request.course.id'} eq $cid) {
 5175:         $cdom = $env{'course.'.$cid.'.domain'};
 5176:         $cnum = $env{'course.'.$cid.'.num'};
 5177:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5178:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5179:         $cdom = $1;
 5180:         $cnum = $2;
 5181:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5182:                                      $cdom,$cnum);
 5183:     }
 5184:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5185:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5186:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5187:         if ($rosterhash{$user} ne '') {
 5188:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5189:             return ([],{}) if ($type eq 'auto');
 5190:         }
 5191:     }
 5192:     if (($cdom ne '') && ($cnum ne ''))  {
 5193:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5194:             my $then=$env{'user.login.time'};
 5195:             my $update=$env{'user.update.time'};
 5196:             if (!$update) {
 5197:                 $update = $then;
 5198:             }
 5199:             my @liveroles;
 5200:             foreach my $role ('dh','da') {
 5201:                 if ($env{"user.role.$role./$cdom/"}) {
 5202:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5203:                     my $limit = $update;
 5204:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5205:                         $limit = $then;
 5206:                     }
 5207:                     my $activerole = 1;
 5208:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5209:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5210:                     if ($activerole) {
 5211:                         push(@liveroles,$role);
 5212:                     }
 5213:                 }
 5214:             }
 5215:             if (@liveroles) {
 5216:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5217:                     my ($accessref,$accessinfo,%access_in_dom);
 5218:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5219:                     if (ref($roles_by_num) eq 'ARRAY') {
 5220:                         if (@{$roles_by_num}) {
 5221:                             my %settings;
 5222:                             if ($env{'request.course.id'} eq $cid) {
 5223:                                 foreach my $envkey (keys(%env)) {
 5224:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5225:                                         $settings{$1} = $env{$envkey};
 5226:                                     }
 5227:                                 }
 5228:                             } else {
 5229:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5230:                             }
 5231:                             my %setincrs;
 5232:                             if ($settings{'internal.adhocaccess'}) {
 5233:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5234:                             }
 5235:                             my @statuses;
 5236:                             if ($env{'environment.inststatus'}) {
 5237:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5238:                             }
 5239:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5240:                             if (ref($accessref) eq 'HASH') {
 5241:                                 %access_in_dom = %{$accessref};
 5242:                             }
 5243:                             foreach my $role (@{$roles_by_num}) {
 5244:                                 my ($curraccess,@okstatus,@personnel);
 5245:                                 if ($setincrs{$role}) {
 5246:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5247:                                     if ($curraccess eq 'status') {
 5248:                                         @okstatus = split(/\&/,$rest);
 5249:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5250:                                         @personnel = split(/\&/,$rest);
 5251:                                     }
 5252:                                 } else {
 5253:                                     $curraccess = $access_in_dom{$role};
 5254:                                     if (ref($accessinfo) eq 'HASH') {
 5255:                                         if ($curraccess eq 'status') {
 5256:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5257:                                                 @okstatus = @{$accessinfo->{$role}};
 5258:                                             }
 5259:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5260:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5261:                                                 @personnel = @{$accessinfo->{$role}};
 5262:                                             }
 5263:                                         }
 5264:                                     }
 5265:                                 }
 5266:                                 if ($curraccess eq 'none') {
 5267:                                     next;
 5268:                                 } elsif ($curraccess eq 'all') {
 5269:                                     push(@possroles,$role);
 5270:                                 } elsif ($curraccess eq 'dh') {
 5271:                                     if (grep(/^dh$/,@liveroles)) {
 5272:                                         push(@possroles,$role);
 5273:                                     } else {
 5274:                                         next;
 5275:                                     }
 5276:                                 } elsif ($curraccess eq 'da') {
 5277:                                     if (grep(/^da$/,@liveroles)) {
 5278:                                         push(@possroles,$role);
 5279:                                     } else {
 5280:                                         next;
 5281:                                     }
 5282:                                 } elsif ($curraccess eq 'status') {
 5283:                                     if (@okstatus) {
 5284:                                         if (!@statuses) {
 5285:                                             if (grep(/^default$/,@okstatus)) {
 5286:                                                 push(@possroles,$role);
 5287:                                             }
 5288:                                         } else {
 5289:                                             foreach my $status (@okstatus) {
 5290:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5291:                                                     push(@possroles,$role);
 5292:                                                     last;
 5293:                                                 }
 5294:                                             }
 5295:                                         }
 5296:                                     }
 5297:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5298:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5299:                                         if ($curraccess eq 'exc') {
 5300:                                             push(@possroles,$role);
 5301:                                         }
 5302:                                     } elsif ($curraccess eq 'inc') {
 5303:                                         push(@possroles,$role);
 5304:                                     }
 5305:                                 }
 5306:                             }
 5307:                         }
 5308:                     }
 5309:                 }
 5310:             }
 5311:         }
 5312:     }
 5313:     unless (ref($description) eq 'HASH') {
 5314:         if (ref($roles_by_num) eq 'ARRAY') {
 5315:             my %desc;
 5316:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5317:             $description = \%desc;
 5318:         } else {
 5319:             $description = {};
 5320:         }
 5321:     }
 5322:     return (\@possroles,$description);
 5323: }
 5324: 
 5325: # ----------------------------------------------------- Frontpage Announcements
 5326: #
 5327: #
 5328: 
 5329: sub postannounce {
 5330:     my ($server,$text)=@_;
 5331:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5332:     unless ($text=~/\w/) { $text=''; }
 5333:     return &reply('setannounce:'.&escape($text),$server);
 5334: }
 5335: 
 5336: sub getannounce {
 5337: 
 5338:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5339: 	my $announcement='';
 5340: 	while (my $line = <$fh>) { $announcement .= $line; }
 5341: 	close($fh);
 5342: 	if ($announcement=~/\w/) { 
 5343: 	    return 
 5344:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5345:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5346: 	} else {
 5347: 	    return '';
 5348: 	}
 5349:     } else {
 5350: 	return '';
 5351:     }
 5352: }
 5353: 
 5354: # ---------------------------------------------------------- Course ID routines
 5355: # Deal with domain's nohist_courseid.db files
 5356: #
 5357: 
 5358: sub courseidput {
 5359:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5360:     return unless (ref($storehash) eq 'HASH');
 5361:     my $outcome;
 5362:     if ($caller eq 'timeonly') {
 5363:         my $cids = '';
 5364:         foreach my $item (keys(%$storehash)) {
 5365:             $cids.=&escape($item).'&';
 5366:         }
 5367:         $cids=~s/\&$//;
 5368:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5369:                           $coursehome);       
 5370:     } else {
 5371:         my $items = '';
 5372:         foreach my $item (keys(%$storehash)) {
 5373:             $items.= &escape($item).'='.
 5374:                      &freeze_escape($$storehash{$item}).'&';
 5375:         }
 5376:         $items=~s/\&$//;
 5377:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5378:                           $coursehome);
 5379:     }
 5380:     if ($outcome eq 'unknown_cmd') {
 5381:         my $what;
 5382:         foreach my $cid (keys(%$storehash)) {
 5383:             $what .= &escape($cid).'=';
 5384:             foreach my $item ('description','inst_code','owner','type') {
 5385:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5386:             }
 5387:             $what =~ s/\:$/&/;
 5388:         }
 5389:         $what =~ s/\&$//;  
 5390:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5391:     } else {
 5392:         return $outcome;
 5393:     }
 5394: }
 5395: 
 5396: sub courseiddump {
 5397:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5398:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5399:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5400:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5401:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5402:     my $as_hash = 1;
 5403:     my %returnhash;
 5404:     if (!$domfilter) { $domfilter=''; }
 5405:     my %libserv = &all_library();
 5406:     foreach my $tryserver (keys(%libserv)) {
 5407:         if ( (  $hostidflag == 1 
 5408: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5409: 	     || (!defined($hostidflag)) ) {
 5410: 
 5411: 	    if (($domfilter eq '') ||
 5412: 		(&host_domain($tryserver) eq $domfilter)) {
 5413:                 my $rep;
 5414:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5415:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5416:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5417:                                 &escape($descfilter), &escape($instcodefilter), 
 5418:                                 &escape($ownerfilter), &escape($coursefilter),
 5419:                                 &escape($typefilter), &escape($regexp_ok), 
 5420:                                 $as_hash, &escape($selfenrollonly), 
 5421:                                 &escape($catfilter), $showhidden, $caller, 
 5422:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5423:                                 &escape($createdbefore), &escape($createdafter), 
 5424:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5425:                                 $reqcrsdom,&escape($reqinstcode))));
 5426:                 } else {
 5427:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5428:                              $sincefilter.':'.&escape($descfilter).':'.
 5429:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5430:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5431:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5432:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5433:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5434:                              &escape($cc_clone).':'.$cloneonly.':'.
 5435:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5436:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5437:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5438:                 }
 5439:                      
 5440:                 my @pairs=split(/\&/,$rep);
 5441:                 foreach my $item (@pairs) {
 5442:                     my ($key,$value)=split(/\=/,$item,2);
 5443:                     $key = &unescape($key);
 5444:                     next if ($key =~ /^error: 2 /);
 5445:                     my $result = &thaw_unescape($value);
 5446:                     if (ref($result) eq 'HASH') {
 5447:                         $returnhash{$key}=$result;
 5448:                     } else {
 5449:                         my @responses = split(/:/,$value);
 5450:                         my @items = ('description','inst_code','owner','type');
 5451:                         for (my $i=0; $i<@responses; $i++) {
 5452:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5453:                         }
 5454:                     }
 5455:                 }
 5456:             }
 5457:         }
 5458:     }
 5459:     return %returnhash;
 5460: }
 5461: 
 5462: sub courselastaccess {
 5463:     my ($cdom,$cnum,$hostidref) = @_;
 5464:     my %returnhash;
 5465:     if ($cdom && $cnum) {
 5466:         my $chome = &homeserver($cnum,$cdom);
 5467:         if ($chome ne 'no_host') {
 5468:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5469:             &extract_lastaccess(\%returnhash,$rep);
 5470:         }
 5471:     } else {
 5472:         if (!$cdom) { $cdom=''; }
 5473:         my %libserv = &all_library();
 5474:         foreach my $tryserver (keys(%libserv)) {
 5475:             if (ref($hostidref) eq 'ARRAY') {
 5476:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5477:             } 
 5478:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5479:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5480:                 &extract_lastaccess(\%returnhash,$rep);
 5481:             }
 5482:         }
 5483:     }
 5484:     return %returnhash;
 5485: }
 5486: 
 5487: sub extract_lastaccess {
 5488:     my ($returnhash,$rep) = @_;
 5489:     if (ref($returnhash) eq 'HASH') {
 5490:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5491:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5492:                  $rep eq '') {
 5493:             my @pairs=split(/\&/,$rep);
 5494:             foreach my $item (@pairs) {
 5495:                 my ($key,$value)=split(/\=/,$item,2);
 5496:                 $key = &unescape($key);
 5497:                 next if ($key =~ /^error: 2 /);
 5498:                 $returnhash->{$key} = &thaw_unescape($value);
 5499:             }
 5500:         }
 5501:     }
 5502:     return;
 5503: }
 5504: 
 5505: # ---------------------------------------------------------- DC e-mail
 5506: 
 5507: sub dcmailput {
 5508:     my ($domain,$msgid,$message,$server)=@_;
 5509:     my $status = &Apache::lonnet::critical(
 5510:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5511:        &escape($message),$server);
 5512:     return $status;
 5513: }
 5514: 
 5515: sub dcmaildump {
 5516:     my ($dom,$startdate,$enddate,$senders) = @_;
 5517:     my %returnhash=();
 5518: 
 5519:     if (defined(&domain($dom,'primary'))) {
 5520:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5521:                                                          &escape($enddate).':';
 5522: 	my @esc_senders=map { &escape($_)} @$senders;
 5523: 	$cmd.=&escape(join('&',@esc_senders));
 5524: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5525:             my ($key,$value) = split(/\=/,$line,2);
 5526:             if (($key) && ($value)) {
 5527:                 $returnhash{&unescape($key)} = &unescape($value);
 5528:             }
 5529:         }
 5530:     }
 5531:     return %returnhash;
 5532: }
 5533: # ---------------------------------------------------------- Domain roles
 5534: 
 5535: sub get_domain_roles {
 5536:     my ($dom,$roles,$startdate,$enddate)=@_;
 5537:     if ((!defined($startdate)) || ($startdate eq '')) {
 5538:         $startdate = '.';
 5539:     }
 5540:     if ((!defined($enddate)) || ($enddate eq '')) {
 5541:         $enddate = '.';
 5542:     }
 5543:     my $rolelist;
 5544:     if (ref($roles) eq 'ARRAY') {
 5545:         $rolelist = join('&',@{$roles});
 5546:     }
 5547:     my %personnel = ();
 5548: 
 5549:     my %servers = &get_servers($dom,'library');
 5550:     foreach my $tryserver (keys(%servers)) {
 5551: 	%{$personnel{$tryserver}}=();
 5552: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5553: 					    &escape($startdate).':'.
 5554: 					    &escape($enddate).':'.
 5555: 					    &escape($rolelist), $tryserver))) {
 5556: 	    my ($key,$value) = split(/\=/,$line,2);
 5557: 	    if (($key) && ($value)) {
 5558: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5559: 	    }
 5560: 	}
 5561:     }
 5562:     return %personnel;
 5563: }
 5564: 
 5565: sub get_active_domroles {
 5566:     my ($dom,$roles) = @_;
 5567:     return () unless (ref($roles) eq 'ARRAY');
 5568:     my $now = time;
 5569:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5570:     my %domroles;
 5571:     foreach my $server (keys(%dompersonnel)) {
 5572:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5573:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5574:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5575:         }
 5576:     }
 5577:     return %domroles;
 5578: }
 5579: 
 5580: # ----------------------------------------------------------- Interval timing 
 5581: 
 5582: {
 5583: # Caches needed for speedup of navmaps
 5584: # We don't want to cache this for very long at all (5 seconds at most)
 5585: # 
 5586: # The user for whom we cache
 5587: my $cachedkey='';
 5588: # The cached times for this user
 5589: my %cachedtimes=();
 5590: # When this was last done
 5591: my $cachedtime='';
 5592: 
 5593: sub load_all_first_access {
 5594:     my ($uname,$udom,$ignorecache)=@_;
 5595:     if (($cachedkey eq $uname.':'.$udom) &&
 5596:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5597:         (!$ignorecache)) {
 5598:         return;
 5599:     }
 5600:     $cachedtime=time;
 5601:     $cachedkey=$uname.':'.$udom;
 5602:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5603: }
 5604: 
 5605: sub get_first_access {
 5606:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5607:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5608:     if ($argsymb) { $symb=$argsymb; }
 5609:     my ($map,$id,$res)=&decode_symb($symb);
 5610:     if ($argmap) { $map = $argmap; }
 5611:     if ($type eq 'course') {
 5612: 	$res='course';
 5613:     } elsif ($type eq 'map') {
 5614: 	$res=&symbread($map);
 5615:     } else {
 5616: 	$res=$symb;
 5617:     }
 5618:     &load_all_first_access($uname,$udom,$ignorecache);
 5619:     return $cachedtimes{"$courseid\0$res"};
 5620: }
 5621: 
 5622: sub set_first_access {
 5623:     my ($type,$interval)=@_;
 5624:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5625:     my ($map,$id,$res)=&decode_symb($symb);
 5626:     if ($type eq 'course') {
 5627: 	$res='course';
 5628:     } elsif ($type eq 'map') {
 5629: 	$res=&symbread($map);
 5630:     } else {
 5631: 	$res=$symb;
 5632:     }
 5633:     $cachedkey='';
 5634:     my $firstaccess=&get_first_access($type,$symb,$map);
 5635:     if ($firstaccess) {
 5636:         &logthis("First access time already set ($firstaccess) when attempting ".
 5637:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5638:                  "in $courseid");
 5639:         return 'already_set';
 5640:     } else {
 5641:         my $start = time;
 5642: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5643:                           $udom,$uname);
 5644:         if ($putres eq 'ok') {
 5645:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5646:                  $udom,$uname); 
 5647:             &appenv(
 5648:                      {
 5649:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5650:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5651:                      }
 5652:                   );
 5653:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5654:                 $cachedtimes{"$courseid\0$res"} = $start;
 5655:             }
 5656:         } elsif ($putres ne 'refused') {
 5657:             &logthis("Result: $putres when attempting to set first access time ".
 5658:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5659:         }
 5660:         return $putres;
 5661:     }
 5662:     return 'already_set';
 5663: }
 5664: }
 5665: 
 5666: # --------------------------------------------- Set Expire Date for Spreadsheet
 5667: 
 5668: sub expirespread {
 5669:     my ($uname,$udom,$stype,$usymb)=@_;
 5670:     my $cid=$env{'request.course.id'}; 
 5671:     if ($cid) {
 5672:        my $now=time;
 5673:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5674:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5675:                             $env{'course.'.$cid.'.num'}.
 5676: 	        	    ':nohist_expirationdates:'.
 5677:                             &escape($key).'='.$now,
 5678:                             $env{'course.'.$cid.'.home'})
 5679:     }
 5680:     return 'ok';
 5681: }
 5682: 
 5683: # ----------------------------------------------------- Devalidate Spreadsheets
 5684: 
 5685: sub devalidate {
 5686:     my ($symb,$uname,$udom)=@_;
 5687:     my $cid=$env{'request.course.id'}; 
 5688:     if ($cid) {
 5689:         # delete the stored spreadsheets for
 5690:         # - the student level sheet of this user in course's homespace
 5691:         # - the assessment level sheet for this resource 
 5692:         #   for this user in user's homespace
 5693: 	# - current conditional state info
 5694: 	my $key=$uname.':'.$udom.':';
 5695:         my $status=
 5696: 	    &del('nohist_calculatedsheets',
 5697: 		 [$key.'studentcalc:'],
 5698: 		 $env{'course.'.$cid.'.domain'},
 5699: 		 $env{'course.'.$cid.'.num'})
 5700: 		.' '.
 5701: 	    &del('nohist_calculatedsheets_'.$cid,
 5702: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5703:         unless ($status eq 'ok ok') {
 5704:            &logthis('Could not devalidate spreadsheet '.
 5705:                     $uname.' at '.$udom.' for '.
 5706: 		    $symb.': '.$status);
 5707:         }
 5708: 	&delenv('user.state.'.$cid);
 5709:     }
 5710: }
 5711: 
 5712: sub get_scalar {
 5713:     my ($string,$end) = @_;
 5714:     my $value;
 5715:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5716: 	$value = $1;
 5717:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5718: 	$value = $1;
 5719:     }
 5720:     return &unescape($value);
 5721: }
 5722: 
 5723: sub array2str {
 5724:   my (@array) = @_;
 5725:   my $result=&arrayref2str(\@array);
 5726:   $result=~s/^__ARRAY_REF__//;
 5727:   $result=~s/__END_ARRAY_REF__$//;
 5728:   return $result;
 5729: }
 5730: 
 5731: sub arrayref2str {
 5732:   my ($arrayref) = @_;
 5733:   my $result='__ARRAY_REF__';
 5734:   foreach my $elem (@$arrayref) {
 5735:     if(ref($elem) eq 'ARRAY') {
 5736:       $result.=&arrayref2str($elem).'&';
 5737:     } elsif(ref($elem) eq 'HASH') {
 5738:       $result.=&hashref2str($elem).'&';
 5739:     } elsif(ref($elem)) {
 5740:       #print("Got a ref of ".(ref($elem))." skipping.");
 5741:     } else {
 5742:       $result.=&escape($elem).'&';
 5743:     }
 5744:   }
 5745:   $result=~s/\&$//;
 5746:   $result .= '__END_ARRAY_REF__';
 5747:   return $result;
 5748: }
 5749: 
 5750: sub hash2str {
 5751:   my (%hash) = @_;
 5752:   my $result=&hashref2str(\%hash);
 5753:   $result=~s/^__HASH_REF__//;
 5754:   $result=~s/__END_HASH_REF__$//;
 5755:   return $result;
 5756: }
 5757: 
 5758: sub hashref2str {
 5759:   my ($hashref)=@_;
 5760:   my $result='__HASH_REF__';
 5761:   foreach my $key (sort(keys(%$hashref))) {
 5762:     if (ref($key) eq 'ARRAY') {
 5763:       $result.=&arrayref2str($key).'=';
 5764:     } elsif (ref($key) eq 'HASH') {
 5765:       $result.=&hashref2str($key).'=';
 5766:     } elsif (ref($key)) {
 5767:       $result.='=';
 5768:       #print("Got a ref of ".(ref($key))." skipping.");
 5769:     } else {
 5770: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5771:     }
 5772: 
 5773:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5774:       $result.=&arrayref2str($hashref->{$key}).'&';
 5775:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5776:       $result.=&hashref2str($hashref->{$key}).'&';
 5777:     } elsif(ref($hashref->{$key})) {
 5778:        $result.='&';
 5779:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5780:     } else {
 5781:       $result.=&escape($hashref->{$key}).'&';
 5782:     }
 5783:   }
 5784:   $result=~s/\&$//;
 5785:   $result .= '__END_HASH_REF__';
 5786:   return $result;
 5787: }
 5788: 
 5789: sub str2hash {
 5790:     my ($string)=@_;
 5791:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5792:     return %$hash;
 5793: }
 5794: 
 5795: sub str2hashref {
 5796:   my ($string) = @_;
 5797: 
 5798:   my %hash;
 5799: 
 5800:   if($string !~ /^__HASH_REF__/) {
 5801:       if (! ($string eq '' || !defined($string))) {
 5802: 	  $hash{'error'}='Not hash reference';
 5803:       }
 5804:       return (\%hash, $string);
 5805:   }
 5806: 
 5807:   $string =~ s/^__HASH_REF__//;
 5808: 
 5809:   while($string !~ /^__END_HASH_REF__/) {
 5810:       #key
 5811:       my $key='';
 5812:       if($string =~ /^__HASH_REF__/) {
 5813:           ($key, $string)=&str2hashref($string);
 5814:           if(defined($key->{'error'})) {
 5815:               $hash{'error'}='Bad data';
 5816:               return (\%hash, $string);
 5817:           }
 5818:       } elsif($string =~ /^__ARRAY_REF__/) {
 5819:           ($key, $string)=&str2arrayref($string);
 5820:           if($key->[0] eq 'Array reference error') {
 5821:               $hash{'error'}='Bad data';
 5822:               return (\%hash, $string);
 5823:           }
 5824:       } else {
 5825:           $string =~ s/^(.*?)=//;
 5826: 	  $key=&unescape($1);
 5827:       }
 5828:       $string =~ s/^=//;
 5829: 
 5830:       #value
 5831:       my $value='';
 5832:       if($string =~ /^__HASH_REF__/) {
 5833:           ($value, $string)=&str2hashref($string);
 5834:           if(defined($value->{'error'})) {
 5835:               $hash{'error'}='Bad data';
 5836:               return (\%hash, $string);
 5837:           }
 5838:       } elsif($string =~ /^__ARRAY_REF__/) {
 5839:           ($value, $string)=&str2arrayref($string);
 5840:           if($value->[0] eq 'Array reference error') {
 5841:               $hash{'error'}='Bad data';
 5842:               return (\%hash, $string);
 5843:           }
 5844:       } else {
 5845: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5846:       }
 5847:       $string =~ s/^&//;
 5848: 
 5849:       $hash{$key}=$value;
 5850:   }
 5851: 
 5852:   $string =~ s/^__END_HASH_REF__//;
 5853: 
 5854:   return (\%hash, $string);
 5855: }
 5856: 
 5857: sub str2array {
 5858:     my ($string)=@_;
 5859:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5860:     return @$array;
 5861: }
 5862: 
 5863: sub str2arrayref {
 5864:   my ($string) = @_;
 5865:   my @array;
 5866: 
 5867:   if($string !~ /^__ARRAY_REF__/) {
 5868:       if (! ($string eq '' || !defined($string))) {
 5869: 	  $array[0]='Array reference error';
 5870:       }
 5871:       return (\@array, $string);
 5872:   }
 5873: 
 5874:   $string =~ s/^__ARRAY_REF__//;
 5875: 
 5876:   while($string !~ /^__END_ARRAY_REF__/) {
 5877:       my $value='';
 5878:       if($string =~ /^__HASH_REF__/) {
 5879:           ($value, $string)=&str2hashref($string);
 5880:           if(defined($value->{'error'})) {
 5881:               $array[0] ='Array reference error';
 5882:               return (\@array, $string);
 5883:           }
 5884:       } elsif($string =~ /^__ARRAY_REF__/) {
 5885:           ($value, $string)=&str2arrayref($string);
 5886:           if($value->[0] eq 'Array reference error') {
 5887:               $array[0] ='Array reference error';
 5888:               return (\@array, $string);
 5889:           }
 5890:       } else {
 5891: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5892:       }
 5893:       $string =~ s/^&//;
 5894: 
 5895:       push(@array, $value);
 5896:   }
 5897: 
 5898:   $string =~ s/^__END_ARRAY_REF__//;
 5899: 
 5900:   return (\@array, $string);
 5901: }
 5902: 
 5903: # -------------------------------------------------------------------Temp Store
 5904: 
 5905: sub tmpreset {
 5906:   my ($symb,$namespace,$domain,$stuname) = @_;
 5907:   if (!$symb) {
 5908:     $symb=&symbread();
 5909:     if (!$symb) { $symb= $env{'request.url'}; }
 5910:   }
 5911:   $symb=escape($symb);
 5912: 
 5913:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5914:   $namespace=~s/\//\_/g;
 5915:   $namespace=~s/\W//g;
 5916: 
 5917:   if (!$domain) { $domain=$env{'user.domain'}; }
 5918:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5919:   if ($domain eq 'public' && $stuname eq 'public') {
 5920:       $stuname=$ENV{'REMOTE_ADDR'};
 5921:   }
 5922:   my $path=LONCAPA::tempdir();
 5923:   my %hash;
 5924:   if (tie(%hash,'GDBM_File',
 5925: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5926: 	  &GDBM_WRCREAT(),0640)) {
 5927:     foreach my $key (keys(%hash)) {
 5928:       if ($key=~ /:$symb/) {
 5929: 	delete($hash{$key});
 5930:       }
 5931:     }
 5932:   }
 5933: }
 5934: 
 5935: sub tmpstore {
 5936:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5937: 
 5938:   if (!$symb) {
 5939:     $symb=&symbread();
 5940:     if (!$symb) { $symb= $env{'request.url'}; }
 5941:   }
 5942:   $symb=escape($symb);
 5943: 
 5944:   if (!$namespace) {
 5945:     # I don't think we would ever want to store this for a course.
 5946:     # it seems this will only be used if we don't have a course.
 5947:     #$namespace=$env{'request.course.id'};
 5948:     #if (!$namespace) {
 5949:       $namespace=$env{'request.state'};
 5950:     #}
 5951:   }
 5952:   $namespace=~s/\//\_/g;
 5953:   $namespace=~s/\W//g;
 5954:   if (!$domain) { $domain=$env{'user.domain'}; }
 5955:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5956:   if ($domain eq 'public' && $stuname eq 'public') {
 5957:       $stuname=$ENV{'REMOTE_ADDR'};
 5958:   }
 5959:   my $now=time;
 5960:   my %hash;
 5961:   my $path=LONCAPA::tempdir();
 5962:   if (tie(%hash,'GDBM_File',
 5963: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5964: 	  &GDBM_WRCREAT(),0640)) {
 5965:     $hash{"version:$symb"}++;
 5966:     my $version=$hash{"version:$symb"};
 5967:     my $allkeys=''; 
 5968:     foreach my $key (keys(%$storehash)) {
 5969:       $allkeys.=$key.':';
 5970:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5971:     }
 5972:     $hash{"$version:$symb:timestamp"}=$now;
 5973:     $allkeys.='timestamp';
 5974:     $hash{"$version:keys:$symb"}=$allkeys;
 5975:     if (untie(%hash)) {
 5976:       return 'ok';
 5977:     } else {
 5978:       return "error:$!";
 5979:     }
 5980:   } else {
 5981:     return "error:$!";
 5982:   }
 5983: }
 5984: 
 5985: # -----------------------------------------------------------------Temp Restore
 5986: 
 5987: sub tmprestore {
 5988:   my ($symb,$namespace,$domain,$stuname) = @_;
 5989: 
 5990:   if (!$symb) {
 5991:     $symb=&symbread();
 5992:     if (!$symb) { $symb= $env{'request.url'}; }
 5993:   }
 5994:   $symb=escape($symb);
 5995: 
 5996:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5997: 
 5998:   if (!$domain) { $domain=$env{'user.domain'}; }
 5999:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6000:   if ($domain eq 'public' && $stuname eq 'public') {
 6001:       $stuname=$ENV{'REMOTE_ADDR'};
 6002:   }
 6003:   my %returnhash;
 6004:   $namespace=~s/\//\_/g;
 6005:   $namespace=~s/\W//g;
 6006:   my %hash;
 6007:   my $path=LONCAPA::tempdir();
 6008:   if (tie(%hash,'GDBM_File',
 6009: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6010: 	  &GDBM_READER(),0640)) {
 6011:     my $version=$hash{"version:$symb"};
 6012:     $returnhash{'version'}=$version;
 6013:     my $scope;
 6014:     for ($scope=1;$scope<=$version;$scope++) {
 6015:       my $vkeys=$hash{"$scope:keys:$symb"};
 6016:       my @keys=split(/:/,$vkeys);
 6017:       my $key;
 6018:       $returnhash{"$scope:keys"}=$vkeys;
 6019:       foreach $key (@keys) {
 6020: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6021: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6022:       }
 6023:     }
 6024:     if (!(untie(%hash))) {
 6025:       return "error:$!";
 6026:     }
 6027:   } else {
 6028:     return "error:$!";
 6029:   }
 6030:   return %returnhash;
 6031: }
 6032: 
 6033: # ----------------------------------------------------------------------- Store
 6034: 
 6035: sub store {
 6036:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6037:     my $home='';
 6038: 
 6039:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6040: 
 6041:     $symb=&symbclean($symb);
 6042:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6043: 
 6044:     if (!$domain) { $domain=$env{'user.domain'}; }
 6045:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6046: 
 6047:     &devalidate($symb,$stuname,$domain);
 6048: 
 6049:     $symb=escape($symb);
 6050:     if (!$namespace) { 
 6051:        unless ($namespace=$env{'request.course.id'}) { 
 6052:           return ''; 
 6053:        } 
 6054:     }
 6055:     if (!$home) { $home=$env{'user.home'}; }
 6056: 
 6057:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6058:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6059: 
 6060:     my $namevalue='';
 6061:     foreach my $key (keys(%$storehash)) {
 6062:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6063:     }
 6064:     $namevalue=~s/\&$//;
 6065:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6066:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6067: }
 6068: 
 6069: # -------------------------------------------------------------- Critical Store
 6070: 
 6071: sub cstore {
 6072:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6073:     my $home='';
 6074: 
 6075:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6076: 
 6077:     $symb=&symbclean($symb);
 6078:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6079: 
 6080:     if (!$domain) { $domain=$env{'user.domain'}; }
 6081:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6082: 
 6083:     &devalidate($symb,$stuname,$domain);
 6084: 
 6085:     $symb=escape($symb);
 6086:     if (!$namespace) { 
 6087:        unless ($namespace=$env{'request.course.id'}) { 
 6088:           return ''; 
 6089:        } 
 6090:     }
 6091:     if (!$home) { $home=$env{'user.home'}; }
 6092: 
 6093:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6094:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6095: 
 6096:     my $namevalue='';
 6097:     foreach my $key (keys(%$storehash)) {
 6098:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6099:     }
 6100:     $namevalue=~s/\&$//;
 6101:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6102:     return critical
 6103:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6104: }
 6105: 
 6106: # --------------------------------------------------------------------- Restore
 6107: 
 6108: sub restore {
 6109:     my ($symb,$namespace,$domain,$stuname) = @_;
 6110:     my $home='';
 6111: 
 6112:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6113: 
 6114:     if (!$symb) {
 6115:         return if ($namespace eq 'courserequests');
 6116:         unless ($symb=escape(&symbread())) { return ''; }
 6117:     } else {
 6118:         unless ($namespace eq 'courserequests') {
 6119:             $symb=&escape(&symbclean($symb));
 6120:         }
 6121:     }
 6122:     if (!$namespace) { 
 6123:        unless ($namespace=$env{'request.course.id'}) { 
 6124:           return ''; 
 6125:        } 
 6126:     }
 6127:     if (!$domain) { $domain=$env{'user.domain'}; }
 6128:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6129:     if (!$home) { $home=$env{'user.home'}; }
 6130:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6131: 
 6132:     my %returnhash=();
 6133:     foreach my $line (split(/\&/,$answer)) {
 6134: 	my ($name,$value)=split(/\=/,$line);
 6135:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6136:     }
 6137:     my $version;
 6138:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6139:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6140:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6141:        }
 6142:     }
 6143:     return %returnhash;
 6144: }
 6145: 
 6146: # ---------------------------------------------------------- Course Description
 6147: #
 6148: #  
 6149: 
 6150: sub coursedescription {
 6151:     my ($courseid,$args)=@_;
 6152:     $courseid=~s/^\///;
 6153:     $courseid=~s/\_/\//g;
 6154:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6155:     my $chome=&homeserver($cnum,$cdomain);
 6156:     my $normalid=$cdomain.'_'.$cnum;
 6157:     # need to always cache even if we get errors otherwise we keep 
 6158:     # trying and trying and trying to get the course description.
 6159:     my %envhash=();
 6160:     my %returnhash=();
 6161:     
 6162:     my $expiretime=600;
 6163:     if ($env{'request.course.id'} eq $normalid) {
 6164: 	$expiretime=120;
 6165:     }
 6166: 
 6167:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6168:     if (!$args->{'freshen_cache'}
 6169: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6170: 	foreach my $key (keys(%env)) {
 6171: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6172: 	    my ($setting) = $1;
 6173: 	    $returnhash{$setting} = $env{$key};
 6174: 	}
 6175: 	return %returnhash;
 6176:     }
 6177: 
 6178:     # get the data again
 6179: 
 6180:     if (!$args->{'one_time'}) {
 6181: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6182:     }
 6183: 
 6184:     if ($chome ne 'no_host') {
 6185:        %returnhash=&dump('environment',$cdomain,$cnum);
 6186:        if (!exists($returnhash{'con_lost'})) {
 6187: 	   my $username = $env{'user.name'}; # Defult username
 6188: 	   if(defined $args->{'user'}) {
 6189: 	       $username = $args->{'user'};
 6190: 	   }
 6191:            $returnhash{'home'}= $chome;
 6192: 	   $returnhash{'domain'} = $cdomain;
 6193: 	   $returnhash{'num'} = $cnum;
 6194:            if (!defined($returnhash{'type'})) {
 6195:                $returnhash{'type'} = 'Course';
 6196:            }
 6197:            while (my ($name,$value) = each %returnhash) {
 6198:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6199:            }
 6200:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6201:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6202: 	       $username.'_'.$cdomain.'_'.$cnum;
 6203:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6204:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6205:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6206:        }
 6207:     }
 6208:     if (!$args->{'one_time'}) {
 6209: 	&appenv(\%envhash);
 6210:     }
 6211:     return %returnhash;
 6212: }
 6213: 
 6214: sub update_released_required {
 6215:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6216:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6217:         $cid = $env{'request.course.id'};
 6218:         $cdom = $env{'course.'.$cid.'.domain'};
 6219:         $cnum = $env{'course.'.$cid.'.num'};
 6220:         $chome = $env{'course.'.$cid.'.home'};
 6221:     }
 6222:     if ($needsrelease) {
 6223:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6224:         my $needsupdate;
 6225:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6226:             $needsupdate = 1;
 6227:         } else {
 6228:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6229:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6230:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6231:                 $needsupdate = 1;
 6232:             }
 6233:         }
 6234:         if ($needsupdate) {
 6235:             my %needshash = (
 6236:                              'internal.releaserequired' => $needsrelease,
 6237:                             );
 6238:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6239:             if ($putresult eq 'ok') {
 6240:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6241:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6242:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6243:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6244:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6245:                 }
 6246:             }
 6247:         }
 6248:     }
 6249:     return;
 6250: }
 6251: 
 6252: # -------------------------------------------------See if a user is privileged
 6253: 
 6254: sub privileged {
 6255:     my ($username,$domain,$possdomains,$possroles)=@_;
 6256:     my $now = time;
 6257:     my $roles;
 6258:     if (ref($possroles) eq 'ARRAY') {
 6259:         $roles = $possroles; 
 6260:     } else {
 6261:         $roles = ['dc','su'];
 6262:     }
 6263:     if (ref($possdomains) eq 'ARRAY') {
 6264:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6265:         foreach my $dom (@{$possdomains}) {
 6266:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6267:                 (ref($privileged{$dom}) eq 'HASH')) {
 6268:                 foreach my $role (@{$roles}) {
 6269:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6270:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6271:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6272:                             return 1 unless (($end && $end < $now) ||
 6273:                                              ($start && $start > $now));
 6274:                         }
 6275:                     }
 6276:                 }
 6277:             }
 6278:         }
 6279:     } else {
 6280:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6281:         my $now = time;
 6282: 
 6283:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6284:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6285:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6286:                 return 1 unless ($tend && $tend < $now) 
 6287:                         or ($tstart && $tstart > $now);
 6288:             }
 6289:         }
 6290:     }
 6291:     return 0;
 6292: }
 6293: 
 6294: sub privileged_by_domain {
 6295:     my ($domains,$roles) = @_;
 6296:     my %privileged = ();
 6297:     my $cachetime = 60*60*24;
 6298:     my $now = time;
 6299:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6300:         return %privileged;
 6301:     }
 6302:     foreach my $dom (@{$domains}) {
 6303:         next if (ref($privileged{$dom}) eq 'HASH');
 6304:         my $needroles;
 6305:         foreach my $role (@{$roles}) {
 6306:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6307:             if (defined($cached)) {
 6308:                 if (ref($result) eq 'HASH') {
 6309:                     $privileged{$dom}{$role} = $result;
 6310:                 }
 6311:             } else {
 6312:                 $needroles = 1;
 6313:             }
 6314:         }
 6315:         if ($needroles) {
 6316:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6317:             $privileged{$dom} = {};
 6318:             foreach my $server (keys(%dompersonnel)) {
 6319:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6320:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6321:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6322:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6323:                         next if ($end && $end < $now);
 6324:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6325:                             $dompersonnel{$server}{$item};
 6326:                     }
 6327:                 }
 6328:             }
 6329:             if (ref($privileged{$dom}) eq 'HASH') {
 6330:                 foreach my $role (@{$roles}) {
 6331:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6332:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6333:                     } else {
 6334:                         my %hash = ();
 6335:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6336:                     }
 6337:                 }
 6338:             }
 6339:         }
 6340:     }
 6341:     return %privileged;
 6342: }
 6343: 
 6344: # -------------------------------------------------------- Get user privileges
 6345: 
 6346: sub rolesinit {
 6347:     my ($domain, $username) = @_;
 6348:     my %userroles = ('user.login.time' => time);
 6349:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6350: 
 6351:     # firstaccess and timerinterval are related to timed maps/resources. 
 6352:     # also, blocking can be triggered by an activating timer
 6353:     # it's saved in the user's %env.
 6354:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6355:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6356:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6357:         %timerintchk, %timerintenv);
 6358: 
 6359:     foreach my $key (keys(%firstaccess)) {
 6360:         my ($cid, $rest) = split(/\0/, $key);
 6361:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6362:     }
 6363: 
 6364:     foreach my $key (keys(%timerinterval)) {
 6365:         my ($cid,$rest) = split(/\0/,$key);
 6366:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6367:     }
 6368: 
 6369:     my %allroles=();
 6370:     my %allgroups=();
 6371: 
 6372:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6373:         my $role = $rolesdump{$area};
 6374:         $area =~ s/\_\w\w$//;
 6375: 
 6376:         my ($trole, $tend, $tstart, $group_privs);
 6377: 
 6378:         if ($role =~ /^cr/) {
 6379:         # Custom role, defined by a user 
 6380:         # e.g., user.role.cr/msu/smith/mynewrole
 6381:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6382:                 $trole = $1;
 6383:                 ($tend, $tstart) = split('_', $2);
 6384:             } else {
 6385:                 $trole = $role;
 6386:             }
 6387:         } elsif ($role =~ m|^gr/|) {
 6388:         # Role of member in a group, defined within a course/community
 6389:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6390:             ($trole, $tend, $tstart) = split(/_/, $role);
 6391:             next if $tstart eq '-1';
 6392:             ($trole, $group_privs) = split(/\//, $trole);
 6393:             $group_privs = &unescape($group_privs);
 6394:         } else {
 6395:         # Just a normal role, defined in roles.tab
 6396:             ($trole, $tend, $tstart) = split(/_/,$role);
 6397:         }
 6398: 
 6399:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6400:                  $username);
 6401:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6402: 
 6403:         # role expired or not available yet?
 6404:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6405:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6406: 
 6407:         next if $area eq '' or $trole eq '';
 6408: 
 6409:         my $spec = "$trole.$area";
 6410:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6411: 
 6412:         if ($trole =~ /^cr\//) {
 6413:         # Custom role, defined by a user
 6414:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6415:         } elsif ($trole eq 'gr') {
 6416:         # Role of a member in a group, defined within a course/community
 6417:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6418:             next;
 6419:         } else {
 6420:         # Normal role, defined in roles.tab
 6421:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6422:         }
 6423: 
 6424:         my $cid = $tdomain.'_'.$trest;
 6425:         unless ($firstaccchk{$cid}) {
 6426:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6427:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6428:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6429:                         $coursetimerstarts{$cid}{$item}; 
 6430:                 }
 6431:             }
 6432:             $firstaccchk{$cid} = 1;
 6433:         }
 6434:         unless ($timerintchk{$cid}) {
 6435:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6436:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6437:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6438:                        $coursetimerintervals{$cid}{$item};
 6439:                 }
 6440:             }
 6441:             $timerintchk{$cid} = 1;
 6442:         }
 6443:     }
 6444: 
 6445:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6446:                                                           \%allroles, \%allgroups);
 6447:     $env{'user.adv'} = $userroles{'user.adv'};
 6448:     $env{'user.rar'} = $userroles{'user.rar'};
 6449: 
 6450:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6451: }
 6452: 
 6453: sub set_arearole {
 6454:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6455:     unless ($nolog) {
 6456: # log the associated role with the area
 6457:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6458:     }
 6459:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6460: }
 6461: 
 6462: sub custom_roleprivs {
 6463:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6464:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6465:     my $homsvr = &homeserver($rauthor,$rdomain);
 6466:     if (&hostname($homsvr) ne '') {
 6467:         my ($rdummy,$roledef)=
 6468:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6469:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6470:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6471:             if (defined($syspriv)) {
 6472:                 if ($trest =~ /^$match_community$/) {
 6473:                     $syspriv =~ s/bre\&S//; 
 6474:                 }
 6475:                 $$allroles{'cm./'}.=':'.$syspriv;
 6476:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6477:             }
 6478:             if ($tdomain ne '') {
 6479:                 if (defined($dompriv)) {
 6480:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6481:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6482:                 }
 6483:                 if (($trest ne '') && (defined($coursepriv))) {
 6484:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6485:                         my $rolename = $1;
 6486:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6487:                     }
 6488:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6489:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6490:                 }
 6491:             }
 6492:         }
 6493:     }
 6494: }
 6495: 
 6496: sub course_adhocrole_privs {
 6497:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6498:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6499:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6500:         my (%currprivs,%storeprivs);
 6501:         foreach my $item (split(/:/,$coursepriv)) {
 6502:             my ($priv,$restrict) = split(/\&/,$item);
 6503:             $currprivs{$priv} = $restrict;
 6504:         }
 6505:         my (%possadd,%possremove,%full);
 6506:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6507:             my ($priv,$restrict)=split(/\&/,$item);
 6508:             $full{$priv} = $restrict;
 6509:         }
 6510:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6511:              next if ($item eq '');
 6512:              my ($rule,$rest) = split(/=/,$item);
 6513:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6514:              foreach my $priv (split(/:/,$rest)) {
 6515:                  if ($priv ne '') {
 6516:                      if ($rule eq 'off') {
 6517:                          $possremove{$priv} = 1;
 6518:                      } else {
 6519:                          $possadd{$priv} = 1;
 6520:                      }
 6521:                  }
 6522:              }
 6523:          }
 6524:          foreach my $priv (sort(keys(%full))) {
 6525:              if (exists($currprivs{$priv})) {
 6526:                  unless (exists($possremove{$priv})) {
 6527:                      $storeprivs{$priv} = $currprivs{$priv};
 6528:                  }
 6529:              } elsif (exists($possadd{$priv})) {
 6530:                  $storeprivs{$priv} = $full{$priv};
 6531:              }
 6532:          }
 6533:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6534:      }
 6535:      return $coursepriv;
 6536: }
 6537: 
 6538: sub group_roleprivs {
 6539:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6540:     my $access = 1;
 6541:     my $now = time;
 6542:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6543:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6544:     if ($access) {
 6545:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6546:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6547:     }
 6548: }
 6549: 
 6550: sub standard_roleprivs {
 6551:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6552:     if (defined($pr{$trole.':s'})) {
 6553:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6554:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6555:     }
 6556:     if ($tdomain ne '') {
 6557:         if (defined($pr{$trole.':d'})) {
 6558:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6559:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6560:         }
 6561:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6562:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6563:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6564:         }
 6565:     }
 6566: }
 6567: 
 6568: sub set_userprivs {
 6569:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6570:     my $author=0;
 6571:     my $adv=0;
 6572:     my $rar=0;
 6573:     my %grouproles = ();
 6574:     if (keys(%{$allgroups}) > 0) {
 6575:         my @groupkeys; 
 6576:         foreach my $role (keys(%{$allroles})) {
 6577:             push(@groupkeys,$role);
 6578:         }
 6579:         if (ref($groups_roles) eq 'HASH') {
 6580:             foreach my $key (keys(%{$groups_roles})) {
 6581:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6582:                     push(@groupkeys,$key);
 6583:                 }
 6584:             }
 6585:         }
 6586:         if (@groupkeys > 0) {
 6587:             foreach my $role (@groupkeys) {
 6588:                 my ($trole,$area,$sec,$extendedarea);
 6589:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6590:                     $trole = $1;
 6591:                     $area = $2;
 6592:                     $sec = $3;
 6593:                     $extendedarea = $area.$sec;
 6594:                     if (exists($$allgroups{$area})) {
 6595:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6596:                             my $spec = $trole.'.'.$extendedarea;
 6597:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6598:                                                 $$allgroups{$area}{$group};
 6599:                         }
 6600:                     }
 6601:                 }
 6602:             }
 6603:         }
 6604:     }
 6605:     foreach my $group (keys(%grouproles)) {
 6606:         $$allroles{$group} = $grouproles{$group};
 6607:     }
 6608:     foreach my $role (keys(%{$allroles})) {
 6609:         my %thesepriv;
 6610:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6611:         foreach my $item (split(/:/,$$allroles{$role})) {
 6612:             if ($item ne '') {
 6613:                 my ($privilege,$restrictions)=split(/&/,$item);
 6614:                 if ($restrictions eq '') {
 6615:                     $thesepriv{$privilege}='F';
 6616:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6617:                     $thesepriv{$privilege}.=$restrictions;
 6618:                 }
 6619:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6620:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6621:             }
 6622:         }
 6623:         my $thesestr='';
 6624:         foreach my $priv (sort(keys(%thesepriv))) {
 6625: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6626: 	}
 6627:         $userroles->{'user.priv.'.$role} = $thesestr;
 6628:     }
 6629:     return ($author,$adv,$rar);
 6630: }
 6631: 
 6632: sub role_status {
 6633:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6634:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6635:         my ($one,$two) = split(m{\./},$rolekey,2);
 6636:         (undef,undef,$$role) = split(/\./,$one,3);
 6637:         unless (!defined($$role) || $$role eq '') {
 6638:             $$where = '/'.$two;
 6639:             $$trolecode=$$role.'.'.$$where;
 6640:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6641:             $$tstatus='is';
 6642:             if ($$tstart && $$tstart>$update) {
 6643:                 $$tstatus='future';
 6644:                 if ($$tstart<$now) {
 6645:                     if ($$tstart && $$tstart>$refresh) {
 6646:                         if (($$where ne '') && ($$role ne '')) {
 6647:                             my (%allroles,%allgroups,$group_privs,
 6648:                                 %groups_roles,@rolecodes);
 6649:                             my %userroles = (
 6650:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6651:                             );
 6652:                             @rolecodes = ('cm'); 
 6653:                             my $spec=$$role.'.'.$$where;
 6654:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6655:                             if ($$role =~ /^cr\//) {
 6656:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6657:                                 push(@rolecodes,'cr');
 6658:                             } elsif ($$role eq 'gr') {
 6659:                                 push(@rolecodes,$$role);
 6660:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6661:                                                     $env{'user.name'});
 6662:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6663:                                 (undef,my $group_privs) = split(/\//,$trole);
 6664:                                 $group_privs = &unescape($group_privs);
 6665:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6666:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6667:                                 &get_groups_roles($tdomain,$trest,
 6668:                                                   \%course_roles,\@rolecodes,
 6669:                                                   \%groups_roles);
 6670:                             } else {
 6671:                                 push(@rolecodes,$$role);
 6672:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6673:                             }
 6674:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6675:                                                                    \%groups_roles);
 6676:                             &appenv(\%userroles,\@rolecodes);
 6677:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6678:                         }
 6679:                     }
 6680:                     $$tstatus = 'is';
 6681:                 }
 6682:             }
 6683:             if ($$tend) {
 6684:                 if ($$tend<$update) {
 6685:                     $$tstatus='expired';
 6686:                 } elsif ($$tend<$now) {
 6687:                     $$tstatus='will_not';
 6688:                 }
 6689:             }
 6690:         }
 6691:     }
 6692: }
 6693: 
 6694: sub get_groups_roles {
 6695:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6696:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6697:                   (ref($rolecodes) eq 'ARRAY') && 
 6698:                   (ref($groups_roles) eq 'HASH')); 
 6699:     if (keys(%{$cdom_courseroles}) > 0) {
 6700:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6701:         if ($cdom ne '' && $cnum ne '') {
 6702:             foreach my $key (keys(%{$cdom_courseroles})) {
 6703:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6704:                     my $crsrole = $1;
 6705:                     my $crssec = $2;
 6706:                     if ($crsrole =~ /^cr/) {
 6707:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6708:                             push(@{$rolecodes},'cr');
 6709:                         }
 6710:                     } else {
 6711:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6712:                             push(@{$rolecodes},$crsrole);
 6713:                         }
 6714:                     }
 6715:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6716:                     if ($crssec ne '') {
 6717:                         $rolekey .= "/$crssec";
 6718:                     }
 6719:                     $rolekey .= './';
 6720:                     $groups_roles->{$rolekey} = $rolecodes;
 6721:                 }
 6722:             }
 6723:         }
 6724:     }
 6725:     return;
 6726: }
 6727: 
 6728: sub delete_env_groupprivs {
 6729:     my ($where,$courseroles,$possroles) = @_;
 6730:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6731:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6732:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6733:         %{$courseroles->{$udom}} =
 6734:             &get_my_roles('','','userroles',['active'],
 6735:                           $possroles,[$udom],1);
 6736:     }
 6737:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6738:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6739:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6740:             my $area = '/'.$cdom.'/'.$cnum;
 6741:             my $privkey = "user.priv.$crsrole.$area";
 6742:             if ($crssec ne '') {
 6743:                 $privkey .= '/'.$crssec;
 6744:             }
 6745:             $privkey .= ".$area/$group";
 6746:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6747:         }
 6748:     }
 6749:     return;
 6750: }
 6751: 
 6752: sub check_adhoc_privs {
 6753:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6754:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6755:     if ($sec) {
 6756:         $cckey .= '/'.$sec;
 6757:     } 
 6758:     my $setprivs;
 6759:     if ($env{$cckey}) {
 6760:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6761:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6762:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6763:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6764:             $setprivs = 1;
 6765:         }
 6766:     } else {
 6767:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6768:         $setprivs = 1;
 6769:     }
 6770:     return $setprivs;
 6771: }
 6772: 
 6773: sub set_adhoc_privileges {
 6774: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6775:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6776:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6777:     if ($sec ne '') {
 6778:         $area .= '/'.$sec;
 6779:     }
 6780:     my $spec = $role.'.'.$area;
 6781:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6782:                                   $env{'user.name'},1);
 6783:     my %rolehash = ();
 6784:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6785:         my $rolename = $1;
 6786:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6787:         my %domdef = &get_domain_defaults($dcdom);
 6788:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6789:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6790:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6791:             }
 6792:         }
 6793:     } else {
 6794:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6795:     }
 6796:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6797:     &appenv(\%userroles,[$role,'cm']);
 6798:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6799:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6800:             ($caller eq 'tiny')) {
 6801:         &appenv( {'request.role'        => $spec,
 6802:                   'request.role.domain' => $dcdom,
 6803:                   'request.course.sec'  => $sec,
 6804:                  }
 6805:                );
 6806:         my $tadv=0;
 6807:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6808:         &appenv({'request.role.adv'    => $tadv});
 6809:     }
 6810: }
 6811: 
 6812: # --------------------------------------------------------------- get interface
 6813: 
 6814: sub get {
 6815:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6816:    my $items='';
 6817:    foreach my $item (@$storearr) {
 6818:        $items.=&escape($item).'&';
 6819:    }
 6820:    $items=~s/\&$//;
 6821:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6822:    if (!$uname) { $uname=$env{'user.name'}; }
 6823:    my $uhome=&homeserver($uname,$udomain);
 6824: 
 6825:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6826:    my @pairs=split(/\&/,$rep);
 6827:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6828:      return @pairs;
 6829:    }
 6830:    my %returnhash=();
 6831:    my $i=0;
 6832:    foreach my $item (@$storearr) {
 6833:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6834:       $i++;
 6835:    }
 6836:    return %returnhash;
 6837: }
 6838: 
 6839: # --------------------------------------------------------------- del interface
 6840: 
 6841: sub del {
 6842:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6843:    my $items='';
 6844:    foreach my $item (@$storearr) {
 6845:        $items.=&escape($item).'&';
 6846:    }
 6847: 
 6848:    $items=~s/\&$//;
 6849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6850:    if (!$uname) { $uname=$env{'user.name'}; }
 6851:    my $uhome=&homeserver($uname,$udomain);
 6852:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6853: }
 6854: 
 6855: # -------------------------------------------------------------- dump interface
 6856: 
 6857: sub unserialize {
 6858:     my ($rep, $escapedkeys) = @_;
 6859: 
 6860:     return {} if $rep =~ /^error/;
 6861: 
 6862:     my %returnhash=();
 6863: 	foreach my $item (split(/\&/,$rep)) {
 6864: 	    my ($key, $value) = split(/=/, $item, 2);
 6865: 	    $key = unescape($key) unless $escapedkeys;
 6866: 	    next if $key =~ /^error: 2 /;
 6867: 	    $returnhash{$key} = &thaw_unescape($value);
 6868: 	}
 6869:     #return %returnhash;
 6870:     return \%returnhash;
 6871: }        
 6872: 
 6873: # see Lond::dump_with_regexp
 6874: # if $escapedkeys hash keys won't get unescaped.
 6875: sub dump {
 6876:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6878:     if (!$uname) { $uname=$env{'user.name'}; }
 6879:     my $uhome=&homeserver($uname,$udomain);
 6880: 
 6881:     if ($regexp) {
 6882:         $regexp=&escape($regexp);
 6883:     } else {
 6884:         $regexp='.';
 6885:     }
 6886:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6887:         # user is hosted on this machine
 6888:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6889:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6890:         return %{unserialize($reply, $escapedkeys)};
 6891:     }
 6892:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6893:     my @pairs=split(/\&/,$rep);
 6894:     my %returnhash=();
 6895:     if (!($rep =~ /^error/ )) {
 6896: 	foreach my $item (@pairs) {
 6897: 	    my ($key,$value)=split(/=/,$item,2);
 6898:         $key = unescape($key) unless $escapedkeys;
 6899:         #$key = &unescape($key);
 6900: 	    next if ($key =~ /^error: 2 /);
 6901: 	    $returnhash{$key}=&thaw_unescape($value);
 6902: 	}
 6903:     }
 6904:     return %returnhash;
 6905: }
 6906: 
 6907: 
 6908: # --------------------------------------------------------- dumpstore interface
 6909: 
 6910: sub dumpstore {
 6911:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6912:    # same as dump but keys must be escaped. They may contain colon separated
 6913:    # lists of values that may themself contain colons (e.g. symbs).
 6914:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6915: }
 6916: 
 6917: # -------------------------------------------------------------- keys interface
 6918: 
 6919: sub getkeys {
 6920:    my ($namespace,$udomain,$uname)=@_;
 6921:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6922:    if (!$uname) { $uname=$env{'user.name'}; }
 6923:    my $uhome=&homeserver($uname,$udomain);
 6924:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6925:    my @keyarray=();
 6926:    foreach my $key (split(/\&/,$rep)) {
 6927:       next if ($key =~ /^error: 2 /);
 6928:       push(@keyarray,&unescape($key));
 6929:    }
 6930:    return @keyarray;
 6931: }
 6932: 
 6933: # --------------------------------------------------------------- currentdump
 6934: sub currentdump {
 6935:    my ($courseid,$sdom,$sname)=@_;
 6936:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6937:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6938:    $sname    = $env{'user.name'}         if (! defined($sname));
 6939:    my $uhome = &homeserver($sname,$sdom);
 6940:    my $rep;
 6941: 
 6942:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6943:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6944:                    $courseid)));
 6945:    } else {
 6946:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6947:    }
 6948: 
 6949:    return if ($rep =~ /^(error:|no_such_host)/);
 6950:    #
 6951:    my %returnhash=();
 6952:    #
 6953:    if ($rep eq 'unknown_cmd') {
 6954:        # an old lond will not know currentdump
 6955:        # Do a dump and make it look like a currentdump
 6956:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6957:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6958:        my %hash = @tmp;
 6959:        @tmp=();
 6960:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6961:    } else {
 6962:        my @pairs=split(/\&/,$rep);
 6963:        foreach my $pair (@pairs) {
 6964:            my ($key,$value)=split(/=/,$pair,2);
 6965:            my ($symb,$param) = split(/:/,$key);
 6966:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6967:                                                         &thaw_unescape($value);
 6968:        }
 6969:    }
 6970:    return %returnhash;
 6971: }
 6972: 
 6973: sub convert_dump_to_currentdump{
 6974:     my %hash = %{shift()};
 6975:     my %returnhash;
 6976:     # Code ripped from lond, essentially.  The only difference
 6977:     # here is the unescaping done by lonnet::dump().  Conceivably
 6978:     # we might run in to problems with parameter names =~ /^v\./
 6979:     while (my ($key,$value) = each(%hash)) {
 6980:         my ($v,$symb,$param) = split(/:/,$key);
 6981: 	$symb  = &unescape($symb);
 6982: 	$param = &unescape($param);
 6983:         next if ($v eq 'version' || $symb eq 'keys');
 6984:         next if (exists($returnhash{$symb}) &&
 6985:                  exists($returnhash{$symb}->{$param}) &&
 6986:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6987:         $returnhash{$symb}->{$param}=$value;
 6988:         $returnhash{$symb}->{'v.'.$param}=$v;
 6989:     }
 6990:     #
 6991:     # Remove all of the keys in the hashes which keep track of
 6992:     # the version of the parameter.
 6993:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6994:         # use a foreach because we are going to delete from the hash.
 6995:         foreach my $key (keys(%$param_hash)) {
 6996:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6997:         }
 6998:     }
 6999:     return \%returnhash;
 7000: }
 7001: 
 7002: # ------------------------------------------------------ critical inc interface
 7003: 
 7004: sub cinc {
 7005:     return &inc(@_,'critical');
 7006: }
 7007: 
 7008: # --------------------------------------------------------------- inc interface
 7009: 
 7010: sub inc {
 7011:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7012:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7013:     if (!$uname) { $uname=$env{'user.name'}; }
 7014:     my $uhome=&homeserver($uname,$udomain);
 7015:     my $items='';
 7016:     if (! ref($store)) {
 7017:         # got a single value, so use that instead
 7018:         $items = &escape($store).'=&';
 7019:     } elsif (ref($store) eq 'SCALAR') {
 7020:         $items = &escape($$store).'=&';        
 7021:     } elsif (ref($store) eq 'ARRAY') {
 7022:         $items = join('=&',map {&escape($_);} @{$store});
 7023:     } elsif (ref($store) eq 'HASH') {
 7024:         while (my($key,$value) = each(%{$store})) {
 7025:             $items.= &escape($key).'='.&escape($value).'&';
 7026:         }
 7027:     }
 7028:     $items=~s/\&$//;
 7029:     if ($critical) {
 7030: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7031:     } else {
 7032: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7033:     }
 7034: }
 7035: 
 7036: # --------------------------------------------------------------- put interface
 7037: 
 7038: sub put {
 7039:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7040:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7041:    if (!$uname) { $uname=$env{'user.name'}; }
 7042:    my $uhome=&homeserver($uname,$udomain);
 7043:    my $items='';
 7044:    foreach my $item (keys(%$storehash)) {
 7045:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7046:    }
 7047:    $items=~s/\&$//;
 7048:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7049: }
 7050: 
 7051: # ------------------------------------------------------------ newput interface
 7052: 
 7053: sub newput {
 7054:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7055:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7056:    if (!$uname) { $uname=$env{'user.name'}; }
 7057:    my $uhome=&homeserver($uname,$udomain);
 7058:    my $items='';
 7059:    foreach my $key (keys(%$storehash)) {
 7060:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7061:    }
 7062:    $items=~s/\&$//;
 7063:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7064: }
 7065: 
 7066: # ---------------------------------------------------------  putstore interface
 7067: 
 7068: sub putstore {
 7069:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7070:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7071:    if (!$uname) { $uname=$env{'user.name'}; }
 7072:    my $uhome=&homeserver($uname,$udomain);
 7073:    my $items='';
 7074:    foreach my $key (keys(%$storehash)) {
 7075:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7076:    }
 7077:    $items=~s/\&$//;
 7078:    my $esc_symb=&escape($symb);
 7079:    my $esc_v=&escape($version);
 7080:    my $reply =
 7081:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7082: 	      $uhome);
 7083:    if (($tolog) && ($reply eq 'ok')) {
 7084:        my $namevalue='';
 7085:        foreach my $key (keys(%{$storehash})) {
 7086:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7087:        }
 7088:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7089:                      '&host='.&escape($perlvar{'lonHostID'}).
 7090:                      '&version='.$esc_v.
 7091:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7092:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7093:    }
 7094:    if ($reply eq 'unknown_cmd') {
 7095:        # gfall back to way things use to be done
 7096:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7097: 			    $uname);
 7098:    }
 7099:    return $reply;
 7100: }
 7101: 
 7102: sub old_putstore {
 7103:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7104:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7105:     if (!$uname) { $uname=$env{'user.name'}; }
 7106:     my $uhome=&homeserver($uname,$udomain);
 7107:     my %newstorehash;
 7108:     foreach my $item (keys(%$storehash)) {
 7109: 	my $key = $version.':'.&escape($symb).':'.$item;
 7110: 	$newstorehash{$key} = $storehash->{$item};
 7111:     }
 7112:     my $items='';
 7113:     my %allitems = ();
 7114:     foreach my $item (keys(%newstorehash)) {
 7115: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7116: 	    my $key = $1.':keys:'.$2;
 7117: 	    $allitems{$key} .= $3.':';
 7118: 	}
 7119: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7120:     }
 7121:     foreach my $item (keys(%allitems)) {
 7122: 	$allitems{$item} =~ s/\:$//;
 7123: 	$items.= $item.'='.$allitems{$item}.'&';
 7124:     }
 7125:     $items=~s/\&$//;
 7126:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7127: }
 7128: 
 7129: # ------------------------------------------------------ critical put interface
 7130: 
 7131: sub cput {
 7132:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7134:    if (!$uname) { $uname=$env{'user.name'}; }
 7135:    my $uhome=&homeserver($uname,$udomain);
 7136:    my $items='';
 7137:    foreach my $item (keys(%$storehash)) {
 7138:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7139:    }
 7140:    $items=~s/\&$//;
 7141:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7142: }
 7143: 
 7144: # -------------------------------------------------------------- eget interface
 7145: 
 7146: sub eget {
 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7148:    my $items='';
 7149:    foreach my $item (@$storearr) {
 7150:        $items.=&escape($item).'&';
 7151:    }
 7152:    $items=~s/\&$//;
 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7154:    if (!$uname) { $uname=$env{'user.name'}; }
 7155:    my $uhome=&homeserver($uname,$udomain);
 7156:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7157:    my @pairs=split(/\&/,$rep);
 7158:    my %returnhash=();
 7159:    my $i=0;
 7160:    foreach my $item (@$storearr) {
 7161:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7162:       $i++;
 7163:    }
 7164:    return %returnhash;
 7165: }
 7166: 
 7167: # ------------------------------------------------------------ tmpput interface
 7168: sub tmpput {
 7169:     my ($storehash,$server,$context)=@_;
 7170:     my $items='';
 7171:     foreach my $item (keys(%$storehash)) {
 7172: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7173:     }
 7174:     $items=~s/\&$//;
 7175:     if (defined($context)) {
 7176:         $items .= ':'.&escape($context);
 7177:     }
 7178:     return &reply("tmpput:$items",$server);
 7179: }
 7180: 
 7181: # ------------------------------------------------------------ tmpget interface
 7182: sub tmpget {
 7183:     my ($token,$server)=@_;
 7184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7185:     my $rep=&reply("tmpget:$token",$server);
 7186:     my %returnhash;
 7187:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7188:         return %returnhash;
 7189:     }
 7190:     foreach my $item (split(/\&/,$rep)) {
 7191: 	my ($key,$value)=split(/=/,$item);
 7192: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7193:     }
 7194:     return %returnhash;
 7195: }
 7196: 
 7197: # ------------------------------------------------------------ tmpdel interface
 7198: sub tmpdel {
 7199:     my ($token,$server)=@_;
 7200:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7201:     return &reply("tmpdel:$token",$server);
 7202: }
 7203: 
 7204: # ------------------------------------------------------------ get_timebased_id 
 7205: 
 7206: sub get_timebased_id {
 7207:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7208:         $maxtries) = @_;
 7209:     my ($newid,$error,$dellock);
 7210:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7211:         return ('','ok','invalid call to get suffix');
 7212:     }
 7213: 
 7214: # set defaults for any optional args for which values were not supplied
 7215:     if ($who eq '') {
 7216:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7217:     }
 7218:     if (!$locktries) {
 7219:         $locktries = 3;
 7220:     }
 7221:     if (!$maxtries) {
 7222:         $maxtries = 10;
 7223:     }
 7224:     
 7225:     if (($cdom eq '') || ($cnum eq '')) {
 7226:         if ($env{'request.course.id'}) {
 7227:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7228:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7229:         }
 7230:         if (($cdom eq '') || ($cnum eq '')) {
 7231:             return ('','ok','call to get suffix not in course context');
 7232:         }
 7233:     }
 7234: 
 7235: # construct locking item
 7236:     my $lockhash = {
 7237:                       $prefix."\0".'locked_'.$keyid => $who,
 7238:                    };
 7239:     my $tries = 0;
 7240: 
 7241: # attempt to get lock on nohist_$namespace file
 7242:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7243:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7244:         $tries ++;
 7245:         sleep 1;
 7246:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7247:     }
 7248: 
 7249: # attempt to get unique identifier, based on current timestamp
 7250:     if ($gotlock eq 'ok') {
 7251:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7252:         my $id = time;
 7253:         $newid = $id;
 7254:         if ($idtype eq 'addcode') {
 7255:             $newid .= &sixnum_code();
 7256:         }
 7257:         my $idtries = 0;
 7258:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7259:             if ($idtype eq 'concat') {
 7260:                 $newid = $id.$idtries;
 7261:             } elsif ($idtype eq 'addcode') {
 7262:                 $newid = $newid.&sixnum_code();
 7263:             } else {
 7264:                 $newid ++;
 7265:             }
 7266:             $idtries ++;
 7267:         }
 7268:         if (!exists($inuse{$prefix."\0".$newid})) {
 7269:             my %new_item =  (
 7270:                               $prefix."\0".$newid => $who,
 7271:                             );
 7272:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7273:                                                  $cdom,$cnum);
 7274:             if ($putresult ne 'ok') {
 7275:                 undef($newid);
 7276:                 $error = 'error saving new item: '.$putresult;
 7277:             }
 7278:         } else {
 7279:              undef($newid);
 7280:              $error = ('error: no unique suffix available for the new item ');
 7281:         }
 7282: #  remove lock
 7283:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7284:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7285:     } else {
 7286:         $error = "error: could not obtain lockfile\n";
 7287:         $dellock = 'ok';
 7288:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7289:             $dellock = 'nolock';
 7290:         }
 7291:     }
 7292:     return ($newid,$dellock,$error);
 7293: }
 7294: 
 7295: sub sixnum_code {
 7296:     my $code;
 7297:     for (0..6) {
 7298:         $code .= int( rand(9) );
 7299:     }
 7300:     return $code;
 7301: }
 7302: 
 7303: # -------------------------------------------------- portfolio access checking
 7304: 
 7305: sub portfolio_access {
 7306:     my ($requrl,$clientip) = @_;
 7307:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7308:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7309:     if ($result) {
 7310:         my %setters;
 7311:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7312:             my ($startblock,$endblock) =
 7313:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7314:             if ($startblock && $endblock) {
 7315:                 return 'B';
 7316:             }
 7317:         } else {
 7318:             my ($startblock,$endblock) =
 7319:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7320:             if ($startblock && $endblock) {
 7321:                 return 'B';
 7322:             }
 7323:         }
 7324:     }
 7325:     if ($result eq 'ok') {
 7326:        return 'F';
 7327:     } elsif ($result =~ /^[^:]+:guest_/) {
 7328:        return 'A';
 7329:     }
 7330:     return '';
 7331: }
 7332: 
 7333: sub get_portfolio_access {
 7334:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7335: 
 7336:     if (!ref($access_hash)) {
 7337: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7338: 	my %access_controls = &get_access_controls($current_perms,$group,
 7339: 						   $file_name);
 7340: 	$access_hash = $access_controls{$file_name};
 7341:     }
 7342: 
 7343:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7344:     my $now = time;
 7345:     if (ref($access_hash) eq 'HASH') {
 7346:         foreach my $key (keys(%{$access_hash})) {
 7347:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7348:             if ($start > $now) {
 7349:                 next;
 7350:             }
 7351:             if ($end && $end<$now) {
 7352:                 next;
 7353:             }
 7354:             if ($scope eq 'public') {
 7355:                 $public = $key;
 7356:                 last;
 7357:             } elsif ($scope eq 'guest') {
 7358:                 $guest = $key;
 7359:             } elsif ($scope eq 'domains') {
 7360:                 push(@domains,$key);
 7361:             } elsif ($scope eq 'users') {
 7362:                 push(@users,$key);
 7363:             } elsif ($scope eq 'course') {
 7364:                 push(@courses,$key);
 7365:             } elsif ($scope eq 'group') {
 7366:                 push(@groups,$key);
 7367:             } elsif ($scope eq 'ip') {
 7368:                 push(@ips,$key);
 7369:             }
 7370:         }
 7371:         if ($public) {
 7372:             return 'ok';
 7373:         } elsif (@ips > 0) {
 7374:             my $allowed;
 7375:             foreach my $ipkey (@ips) {
 7376:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7377:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7378:                         $allowed = 1;
 7379:                         last; 
 7380:                     }
 7381:                 }
 7382:             }
 7383:             if ($allowed) {
 7384:                 return 'ok';
 7385:             }
 7386:         }
 7387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7388:             if ($guest) {
 7389:                 return $guest;
 7390:             }
 7391:         } else {
 7392:             if (@domains > 0) {
 7393:                 foreach my $domkey (@domains) {
 7394:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7395:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7396:                             return 'ok';
 7397:                         }
 7398:                     }
 7399:                 }
 7400:             }
 7401:             if (@users > 0) {
 7402:                 foreach my $userkey (@users) {
 7403:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7404:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7405:                             if (ref($item) eq 'HASH') {
 7406:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7407:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7408:                                     return 'ok';
 7409:                                 }
 7410:                             }
 7411:                         }
 7412:                     } 
 7413:                 }
 7414:             }
 7415:             my %roleshash;
 7416:             my @courses_and_groups = @courses;
 7417:             push(@courses_and_groups,@groups); 
 7418:             if (@courses_and_groups > 0) {
 7419:                 my (%allgroups,%allroles); 
 7420:                 my ($start,$end,$role,$sec,$group);
 7421:                 foreach my $envkey (%env) {
 7422:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7423:                         my $cid = $2.'_'.$3; 
 7424:                         if ($1 eq 'gr') {
 7425:                             $group = $4;
 7426:                             $allgroups{$cid}{$group} = $env{$envkey};
 7427:                         } else {
 7428:                             if ($4 eq '') {
 7429:                                 $sec = 'none';
 7430:                             } else {
 7431:                                 $sec = $4;
 7432:                             }
 7433:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7434:                         }
 7435:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7436:                         my $cid = $2.'_'.$3;
 7437:                         if ($4 eq '') {
 7438:                             $sec = 'none';
 7439:                         } else {
 7440:                             $sec = $4;
 7441:                         }
 7442:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7443:                     }
 7444:                 }
 7445:                 if (keys(%allroles) == 0) {
 7446:                     return;
 7447:                 }
 7448:                 foreach my $key (@courses_and_groups) {
 7449:                     my %content = %{$$access_hash{$key}};
 7450:                     my $cnum = $content{'number'};
 7451:                     my $cdom = $content{'domain'};
 7452:                     my $cid = $cdom.'_'.$cnum;
 7453:                     if (!exists($allroles{$cid})) {
 7454:                         next;
 7455:                     }    
 7456:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7457:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7458:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7459:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7460:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7461:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7462:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7463:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7464:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7465:                                         if (grep/^all$/,@sections) {
 7466:                                             return 'ok';
 7467:                                         } else {
 7468:                                             if (grep/^$sec$/,@sections) {
 7469:                                                 return 'ok';
 7470:                                             }
 7471:                                         }
 7472:                                     }
 7473:                                 }
 7474:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7475:                                     if (grep/^none$/,@groups) {
 7476:                                         return 'ok';
 7477:                                     }
 7478:                                 } else {
 7479:                                     if (grep/^all$/,@groups) {
 7480:                                         return 'ok';
 7481:                                     } 
 7482:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7483:                                         if (grep/^$group$/,@groups) {
 7484:                                             return 'ok';
 7485:                                         }
 7486:                                     }
 7487:                                 } 
 7488:                             }
 7489:                         }
 7490:                     }
 7491:                 }
 7492:             }
 7493:             if ($guest) {
 7494:                 return $guest;
 7495:             }
 7496:         }
 7497:     }
 7498:     return;
 7499: }
 7500: 
 7501: sub course_group_datechecker {
 7502:     my ($dates,$now,$status) = @_;
 7503:     my ($start,$end) = split(/\./,$dates);
 7504:     if (!$start && !$end) {
 7505:         return 'ok';
 7506:     }
 7507:     if (grep/^active$/,@{$status}) {
 7508:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7509:             return 'ok';
 7510:         }
 7511:     }
 7512:     if (grep/^previous$/,@{$status}) {
 7513:         if ($end > $now ) {
 7514:             return 'ok';
 7515:         }
 7516:     }
 7517:     if (grep/^future$/,@{$status}) {
 7518:         if ($start > $now) {
 7519:             return 'ok';
 7520:         }
 7521:     }
 7522:     return; 
 7523: }
 7524: 
 7525: sub parse_portfolio_url {
 7526:     my ($url) = @_;
 7527: 
 7528:     my ($type,$udom,$unum,$group,$file_name);
 7529:     
 7530:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7531: 	$type = 1;
 7532:         $udom = $1;
 7533:         $unum = $2;
 7534:         $file_name = $3;
 7535:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7536: 	$type = 2;
 7537:         $udom = $1;
 7538:         $unum = $2;
 7539:         $group = $3;
 7540:         $file_name = $3.'/'.$4;
 7541:     }
 7542:     if (wantarray) {
 7543: 	return ($type,$udom,$unum,$file_name,$group);
 7544:     }
 7545:     return $type;
 7546: }
 7547: 
 7548: sub is_portfolio_url {
 7549:     my ($url) = @_;
 7550:     return scalar(&parse_portfolio_url($url));
 7551: }
 7552: 
 7553: sub is_portfolio_file {
 7554:     my ($file) = @_;
 7555:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7556:         return 1;
 7557:     }
 7558:     return;
 7559: }
 7560: 
 7561: sub usertools_access {
 7562:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7563:     my ($access,%tools);
 7564:     if ($context eq '') {
 7565:         $context = 'tools';
 7566:     }
 7567:     if ($context eq 'requestcourses') {
 7568:         %tools = (
 7569:                       official   => 1,
 7570:                       unofficial => 1,
 7571:                       community  => 1,
 7572:                       textbook   => 1,
 7573:                       placement  => 1,
 7574:                       lti        => 1,
 7575:                  );
 7576:     } elsif ($context eq 'requestauthor') {
 7577:         %tools = (
 7578:                       requestauthor => 1,
 7579:                  );
 7580:     } else {
 7581:         %tools = (
 7582:                       aboutme   => 1,
 7583:                       blog      => 1,
 7584:                       webdav    => 1,
 7585:                       portfolio => 1,
 7586:                  );
 7587:     }
 7588:     return if (!defined($tools{$tool}));
 7589: 
 7590:     if (($udom eq '') || ($uname eq '')) {
 7591:         $udom = $env{'user.domain'};
 7592:         $uname = $env{'user.name'};
 7593:     }
 7594: 
 7595:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7596:         if ($action ne 'reload') {
 7597:             if ($context eq 'requestcourses') {
 7598:                 return $env{'environment.canrequest.'.$tool};
 7599:             } elsif ($context eq 'requestauthor') {
 7600:                 return $env{'environment.canrequest.author'};
 7601:             } else {
 7602:                 return $env{'environment.availabletools.'.$tool};
 7603:             }
 7604:         }
 7605:     }
 7606: 
 7607:     my ($toolstatus,$inststatus,$envkey);
 7608:     if ($context eq 'requestauthor') {
 7609:         $envkey = $context; 
 7610:     } else {
 7611:         $envkey = $context.'.'.$tool;
 7612:     }
 7613: 
 7614:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7615:          ($action ne 'reload')) {
 7616:         $toolstatus = $env{'environment.'.$envkey};
 7617:         $inststatus = $env{'environment.inststatus'};
 7618:     } else {
 7619:         if (ref($userenvref) eq 'HASH') {
 7620:             $toolstatus = $userenvref->{$envkey};
 7621:             $inststatus = $userenvref->{'inststatus'};
 7622:         } else {
 7623:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7624:             $toolstatus = $userenv{$envkey};
 7625:             $inststatus = $userenv{'inststatus'};
 7626:         }
 7627:     }
 7628: 
 7629:     if ($toolstatus ne '') {
 7630:         if ($toolstatus) {
 7631:             $access = 1;
 7632:         } else {
 7633:             $access = 0;
 7634:         }
 7635:         return $access;
 7636:     }
 7637: 
 7638:     my ($is_adv,%domdef);
 7639:     if (ref($is_advref) eq 'HASH') {
 7640:         $is_adv = $is_advref->{'is_adv'};
 7641:     } else {
 7642:         $is_adv = &is_advanced_user($udom,$uname);
 7643:     }
 7644:     if (ref($domdefref) eq 'HASH') {
 7645:         %domdef = %{$domdefref};
 7646:     } else {
 7647:         %domdef = &get_domain_defaults($udom);
 7648:     }
 7649:     if (ref($domdef{$tool}) eq 'HASH') {
 7650:         if ($is_adv) {
 7651:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7652:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7653:                     $access = 1;
 7654:                 } else {
 7655:                     $access = 0;
 7656:                 }
 7657:                 return $access;
 7658:             }
 7659:         }
 7660:         if ($inststatus ne '') {
 7661:             my ($hasaccess,$hasnoaccess);
 7662:             foreach my $affiliation (split(/:/,$inststatus)) {
 7663:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7664:                     if ($domdef{$tool}{$affiliation}) {
 7665:                         $hasaccess = 1;
 7666:                     } else {
 7667:                         $hasnoaccess = 1;
 7668:                     }
 7669:                 }
 7670:             }
 7671:             if ($hasaccess || $hasnoaccess) {
 7672:                 if ($hasaccess) {
 7673:                     $access = 1;
 7674:                 } elsif ($hasnoaccess) {
 7675:                     $access = 0; 
 7676:                 }
 7677:                 return $access;
 7678:             }
 7679:         } else {
 7680:             if ($domdef{$tool}{'default'} ne '') {
 7681:                 if ($domdef{$tool}{'default'}) {
 7682:                     $access = 1;
 7683:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7684:                     $access = 0;
 7685:                 }
 7686:                 return $access;
 7687:             }
 7688:         }
 7689:     } else {
 7690:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7691:             $access = 1;
 7692:         } else {
 7693:             $access = 0;
 7694:         }
 7695:         return $access;
 7696:     }
 7697: }
 7698: 
 7699: sub is_course_owner {
 7700:     my ($cdom,$cnum,$udom,$uname) = @_;
 7701:     if (($udom eq '') || ($uname eq '')) {
 7702:         $udom = $env{'user.domain'};
 7703:         $uname = $env{'user.name'};
 7704:     }
 7705:     unless (($udom eq '') || ($uname eq '')) {
 7706:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7707:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7708:                 return 1;
 7709:             } else {
 7710:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7711:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7712:                     return 1;
 7713:                 }
 7714:             }
 7715:         }
 7716:     }
 7717:     return;
 7718: }
 7719: 
 7720: sub is_advanced_user {
 7721:     my ($udom,$uname) = @_;
 7722:     if ($udom ne '' && $uname ne '') {
 7723:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7724:             if (wantarray) {
 7725:                 return ($env{'user.adv'},$env{'user.author'});
 7726:             } else {
 7727:                 return $env{'user.adv'};
 7728:             }
 7729:         }
 7730:     }
 7731:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7732:     my %allroles;
 7733:     my ($is_adv,$is_author);
 7734:     foreach my $role (keys(%roleshash)) {
 7735:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7736:         my $area = '/'.$tdomain.'/'.$trest;
 7737:         if ($sec ne '') {
 7738:             $area .= '/'.$sec;
 7739:         }
 7740:         if (($area ne '') && ($trole ne '')) {
 7741:             my $spec=$trole.'.'.$area;
 7742:             if ($trole =~ /^cr\//) {
 7743:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7744:             } elsif ($trole ne 'gr') {
 7745:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7746:             }
 7747:             if ($trole eq 'au') {
 7748:                 $is_author = 1;
 7749:             }
 7750:         }
 7751:     }
 7752:     foreach my $role (keys(%allroles)) {
 7753:         last if ($is_adv);
 7754:         foreach my $item (split(/:/,$allroles{$role})) {
 7755:             if ($item ne '') {
 7756:                 my ($privilege,$restrictions)=split(/&/,$item);
 7757:                 if ($privilege eq 'adv') {
 7758:                     $is_adv = 1;
 7759:                     last;
 7760:                 }
 7761:             }
 7762:         }
 7763:     }
 7764:     if (wantarray) {
 7765:         return ($is_adv,$is_author);
 7766:     }
 7767:     return $is_adv;
 7768: }
 7769: 
 7770: sub check_can_request {
 7771:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7772:     my $canreq = 0;
 7773:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7774:         $uname = $env{'user.name'};
 7775:         $udom = $env{'user.domain'};
 7776:     }
 7777:     my ($types,$typename) = &Apache::loncommon::course_types();
 7778:     my @options = ('approval','validate','autolimit');
 7779:     my $optregex = join('|',@options);
 7780:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7781:         foreach my $type (@{$types}) {
 7782:             if (&usertools_access($uname,$udom,$type,undef,
 7783:                                   'requestcourses')) {
 7784:                 $canreq ++;
 7785:                 if (ref($request_domains) eq 'HASH') {
 7786:                     push(@{$request_domains->{$type}},$udom);
 7787:                 }
 7788:                 if ($dom eq $udom) {
 7789:                     $can_request->{$type} = 1;
 7790:                 }
 7791:             }
 7792:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7793:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7794:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7795:                 if (@curr > 0) {
 7796:                     foreach my $item (@curr) {
 7797:                         if (ref($request_domains) eq 'HASH') {
 7798:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7799:                             if ($otherdom ne '') {
 7800:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7801:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7802:                                         push(@{$request_domains->{$type}},$otherdom);
 7803:                                     }
 7804:                                 } else {
 7805:                                     push(@{$request_domains->{$type}},$otherdom);
 7806:                                 }
 7807:                             }
 7808:                         }
 7809:                     }
 7810:                     unless ($dom eq $env{'user.domain'}) {
 7811:                         $canreq ++;
 7812:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7813:                             $can_request->{$type} = 1;
 7814:                         }
 7815:                     }
 7816:                 }
 7817:             }
 7818:         }
 7819:     }
 7820:     return $canreq;
 7821: }
 7822: 
 7823: # ---------------------------------------------- Custom access rule evaluation
 7824: 
 7825: sub customaccess {
 7826:     my ($priv,$uri)=@_;
 7827:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7828:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7829:     $udom = &LONCAPA::clean_domain($udom);
 7830:     $ucrs = &LONCAPA::clean_username($ucrs);
 7831:     my $access=0;
 7832:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7833: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7834: 	if ($type eq 'user') {
 7835: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7836: 		my ($tdom,$tuname)=split(m{/},$scope);
 7837: 		if ($tdom) {
 7838: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7839: 		}
 7840: 		if ($tuname) {
 7841: 		    if ($tuname ne $env{'user.name'}) { next; }
 7842: 		}
 7843: 		$access=($effect eq 'allow');
 7844: 		last;
 7845: 	    }
 7846: 	} else {
 7847: 	    if ($role) {
 7848: 		if ($role ne $urole) { next; }
 7849: 	    }
 7850: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7851: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7852: 		if ($tdom) {
 7853: 		    if ($tdom ne $udom) { next; }
 7854: 		}
 7855: 		if ($tcrs) {
 7856: 		    if ($tcrs ne $ucrs) { next; }
 7857: 		}
 7858: 		if ($tsec) {
 7859: 		    if ($tsec ne $usec) { next; }
 7860: 		}
 7861: 		$access=($effect eq 'allow');
 7862: 		last;
 7863: 	    }
 7864: 	    if ($realm eq '' && $role eq '') {
 7865: 		$access=($effect eq 'allow');
 7866: 	    }
 7867: 	}
 7868:     }
 7869:     return $access;
 7870: }
 7871: 
 7872: # ------------------------------------------------- Check for a user privilege
 7873: 
 7874: sub allowed {
 7875:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7876:     my $ver_orguri=$uri;
 7877:     $uri=&deversion($uri);
 7878:     my $orguri=$uri;
 7879:     $uri=&declutter($uri);
 7880: 
 7881:     if ($priv eq 'evb') {
 7882: # Evade communication block restrictions for specified role in a course
 7883:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7884:             return $1;
 7885:         } else {
 7886:             return;
 7887:         }
 7888:     }
 7889: 
 7890:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7891: # Free bre access to adm and meta resources
 7892:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7893: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7894: 	&& ($priv eq 'bre')) {
 7895: 	return 'F';
 7896:     }
 7897: 
 7898: # Free bre access to user's own portfolio contents
 7899:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7900:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7901: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7902:         my %setters;
 7903:         my ($startblock,$endblock) = 
 7904:             &Apache::loncommon::blockcheck(\%setters,'port');
 7905:         if ($startblock && $endblock) {
 7906:             return 'B';
 7907:         } else {
 7908:             return 'F';
 7909:         }
 7910:     }
 7911: 
 7912: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7913:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7914:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7915:         if (exists($env{'request.course.id'})) {
 7916:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7917:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7918:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7919:                 my $courseprivid=$env{'request.course.id'};
 7920:                 $courseprivid=~s/\_/\//;
 7921:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7922:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7923:                     return $1; 
 7924:                 } else {
 7925:                     if ($env{'request.course.sec'}) {
 7926:                         $courseprivid.='/'.$env{'request.course.sec'};
 7927:                     }
 7928:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7929:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7930:                         return $2;
 7931:                     }
 7932:                 }
 7933:             }
 7934:         }
 7935:     }
 7936: 
 7937: # Free bre to public access
 7938: 
 7939:     if ($priv eq 'bre') {
 7940:         my $copyright;
 7941:         unless ($uri =~ /ext\.tool/) {
 7942:             $copyright=&metadata($uri,'copyright');
 7943:         }
 7944: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7945:            return 'F'; 
 7946:         }
 7947:         if ($copyright eq 'priv') {
 7948:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7949: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7950: 		return '';
 7951:             }
 7952:         }
 7953:         if ($copyright eq 'domain') {
 7954:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7955: 	    unless (($env{'user.domain'} eq $1) ||
 7956:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7957: 		return '';
 7958:             }
 7959:         }
 7960:         if ($env{'request.role'}=~ /li\.\//) {
 7961:             # Library role, so allow browsing of resources in this domain.
 7962:             return 'F';
 7963:         }
 7964:         if ($copyright eq 'custom') {
 7965: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7966:         }
 7967:     }
 7968:     # Domain coordinator is trying to create a course
 7969:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7970:         # uri is the requested domain in this case.
 7971:         # comparison to 'request.role.domain' shows if the user has selected
 7972:         # a role of dc for the domain in question.
 7973:         return 'F' if ($uri eq $env{'request.role.domain'});
 7974:     }
 7975: 
 7976:     my $thisallowed='';
 7977:     my $statecond=0;
 7978:     my $courseprivid='';
 7979: 
 7980:     my $ownaccess;
 7981:     # Community Coordinator or Assistant Co-author browsing resource space.
 7982:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7983:         if ($uri eq '') {
 7984:             $ownaccess = 1;
 7985:         } else {
 7986:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7987:                 my $udom = $env{'user.domain'};
 7988:                 my $uname = $env{'user.name'};
 7989:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7990:                     $ownaccess = 1;
 7991:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7992:                     unless ($uri =~ m{\.\./}) {
 7993:                         $ownaccess = 1;
 7994:                     }
 7995:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7996:                     my $now = time;
 7997:                     if ($uri =~ m{^([^/]+)/?$}) {
 7998:                         my $adom = $1;
 7999:                         foreach my $key (keys(%env)) {
 8000:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8001:                                 my ($start,$end) = split('.',$env{$key});
 8002:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8003:                                     $ownaccess = 1;
 8004:                                     last;
 8005:                                 }
 8006:                             }
 8007:                         }
 8008:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8009:                         my $adom = $1;
 8010:                         my $aname = $2;
 8011:                         foreach my $role ('ca','aa') { 
 8012:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8013:                                 my ($start,$end) =
 8014:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8015:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8016:                                     $ownaccess = 1;
 8017:                                     last;
 8018:                                 }
 8019:                             }
 8020:                         }
 8021:                     }
 8022:                 }
 8023:             }
 8024:         }
 8025:     }
 8026: 
 8027: # Course
 8028: 
 8029:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8030:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8031:             $thisallowed.=$1;
 8032:         }
 8033:     }
 8034: 
 8035: # Domain
 8036: 
 8037:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8038:        =~/\Q$priv\E\&([^\:]*)/) {
 8039:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8040:             $thisallowed.=$1;
 8041:         }
 8042:     }
 8043: 
 8044: # User who is not author or co-author might still be able to edit
 8045: # resource of an author in the domain (e.g., if Domain Coordinator).
 8046:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8047:         (&allowed('mdc',$env{'request.course.id'}))) {
 8048:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8049:             $thisallowed.=$1;
 8050:         }
 8051:     }
 8052: 
 8053: # Course: uri itself is a course
 8054:     my $courseuri=$uri;
 8055:     $courseuri=~s/\_(\d)/\/$1/;
 8056:     $courseuri=~s/^([^\/])/\/$1/;
 8057: 
 8058:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8059:        =~/\Q$priv\E\&([^\:]*)/) {
 8060:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8061:             $thisallowed.=$1;
 8062:         }
 8063:     }
 8064: 
 8065: # URI is an uploaded document for this course, default permissions don't matter
 8066: # not allowing 'edit' access (editupload) to uploaded course docs
 8067:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8068: 	$thisallowed='';
 8069:         my ($match)=&is_on_map($uri);
 8070:         if ($match) {
 8071:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8072:                   =~/\Q$priv\E\&([^\:]*)/) {
 8073:                 my $value = $1;
 8074:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8075:                 if ($deeplinkblock) {
 8076:                     $thisallowed='D';
 8077:                 } elsif ($noblockcheck) {
 8078:                     $thisallowed.=$value;
 8079:                 } else {
 8080:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8081:                     if (@blockers > 0) {
 8082:                         $thisallowed = 'B';
 8083:                     } else {
 8084:                         $thisallowed.=$value;
 8085:                     }
 8086:                 }
 8087:             }
 8088:         } else {
 8089:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8090:             if ($refuri) {
 8091:                 if ($refuri =~ m|^/adm/|) {
 8092:                     $thisallowed='F';
 8093:                 } else {
 8094:                     $refuri=&declutter($refuri);
 8095:                     my ($match) = &is_on_map($refuri);
 8096:                     if ($match) {
 8097:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8098:                         if ($deeplinkblock) {
 8099:                             $thisallowed='D';
 8100:                         } elsif ($noblockcheck) {
 8101:                             $thisallowed='F';
 8102:                         } else {
 8103:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8104:                             if (@blockers > 0) {
 8105:                                 $thisallowed = 'B';
 8106:                             } else {
 8107:                                 $thisallowed='F';
 8108:                             }
 8109:                         }
 8110:                     }
 8111:                 }
 8112:             }
 8113:         }
 8114:     }
 8115: 
 8116:     if ($priv eq 'bre'
 8117: 	&& $thisallowed ne 'F' 
 8118: 	&& $thisallowed ne '2'
 8119: 	&& &is_portfolio_url($uri)) {
 8120: 	$thisallowed = &portfolio_access($uri,$clientip);
 8121:     }
 8122: 
 8123: # Full access at system, domain or course-wide level? Exit.
 8124:     if ($thisallowed=~/F/) {
 8125: 	return 'F';
 8126:     }
 8127: 
 8128: # If this is generating or modifying users, exit with special codes
 8129: 
 8130:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8131: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8132: 	    my ($audom,$auname)=split('/',$uri);
 8133: # no author name given, so this just checks on the general right to make a co-author in this domain
 8134: 	    unless ($auname) { return $thisallowed; }
 8135: # an author name is given, so we are about to actually make a co-author for a certain account
 8136: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8137: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8138: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8139: 	}
 8140: 	return $thisallowed;
 8141:     }
 8142: #
 8143: # Gathered so far: system, domain and course wide privileges
 8144: #
 8145: # Course: See if uri or referer is an individual resource that is part of 
 8146: # the course
 8147: 
 8148:     if ($env{'request.course.id'}) {
 8149: 
 8150:        $courseprivid=$env{'request.course.id'};
 8151:        if ($env{'request.course.sec'}) {
 8152:           $courseprivid.='/'.$env{'request.course.sec'};
 8153:        }
 8154:        $courseprivid=~s/\_/\//;
 8155:        my $checkreferer=1;
 8156:        my ($match,$cond)=&is_on_map($uri);
 8157:        if ($match) {
 8158:            $statecond=$cond;
 8159:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8160:                =~/\Q$priv\E\&([^\:]*)/) {
 8161:                my $value = $1;
 8162:                if ($priv eq 'bre') {
 8163:                    if ($noblockcheck) {
 8164:                        $thisallowed.=$value;
 8165:                    } else {
 8166:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8167:                        if (@blockers > 0) {
 8168:                            $thisallowed = 'B';
 8169:                        } else {
 8170:                            $thisallowed.=$value;
 8171:                        }
 8172:                    }
 8173:                } else {
 8174:                    $thisallowed.=$value;
 8175:                }
 8176:                $checkreferer=0;
 8177:            }
 8178:        }
 8179:        
 8180:        if ($checkreferer) {
 8181: 	  my $refuri=$env{'httpref.'.$orguri};
 8182:             unless ($refuri) {
 8183:                 foreach my $key (keys(%env)) {
 8184: 		    if ($key=~/^httpref\..*\*/) {
 8185: 			my $pattern=$key;
 8186:                         $pattern=~s/^httpref\.\/res\///;
 8187:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8188:                         $pattern=~s/\//\\\//g;
 8189:                         if ($orguri=~/$pattern/) {
 8190: 			    $refuri=$env{$key};
 8191:                         }
 8192:                     }
 8193:                 }
 8194:             }
 8195: 
 8196:          if ($refuri) { 
 8197: 	  $refuri=&declutter($refuri);
 8198:           my ($match,$cond)=&is_on_map($refuri);
 8199:             if ($match) {
 8200:               my $refstatecond=$cond;
 8201:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8202:                   =~/\Q$priv\E\&([^\:]*)/) {
 8203:                   my $value = $1;
 8204:                   if ($priv eq 'bre') {
 8205:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8206:                       if ($deeplinkblock) {
 8207:                           $thisallowed = 'D';
 8208:                       } elsif ($noblockcheck) {
 8209:                           $thisallowed.=$value;
 8210:                       } else {
 8211:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8212:                           if (@blockers > 0) {
 8213:                               $thisallowed = 'B';
 8214:                           } else {
 8215:                               $thisallowed.=$value;
 8216:                           }
 8217:                       }
 8218:                   } else {
 8219:                       $thisallowed.=$value;
 8220:                   }
 8221:                   $uri=$refuri;
 8222:                   $statecond=$refstatecond;
 8223:               }
 8224:           }
 8225:         }
 8226:        }
 8227:    }
 8228: 
 8229: #
 8230: # Gathered now: all privileges that could apply, and condition number
 8231: # 
 8232: #
 8233: # Full or no access?
 8234: #
 8235: 
 8236:     if ($thisallowed=~/F/) {
 8237: 	return 'F';
 8238:     }
 8239: 
 8240:     unless ($thisallowed) {
 8241:         return '';
 8242:     }
 8243: 
 8244: # Restrictions exist, deal with them
 8245: #
 8246: #   C:according to course preferences
 8247: #   R:according to resource settings
 8248: #   L:unless locked
 8249: #   X:according to user session state
 8250: #
 8251: 
 8252: # Possibly locked functionality, check all courses
 8253: # Locks might take effect only after 10 minutes cache expiration for other
 8254: # courses, and 2 minutes for current course
 8255: 
 8256:     my $envkey;
 8257:     if ($thisallowed=~/L/) {
 8258:         foreach $envkey (keys(%env)) {
 8259:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8260:                my $courseid=$2;
 8261:                my $roleid=$1.'.'.$2;
 8262:                $courseid=~s/^\///;
 8263:                my $expiretime=600;
 8264:                if ($env{'request.role'} eq $roleid) {
 8265: 		  $expiretime=120;
 8266:                }
 8267: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8268:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8269:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8270: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8271:                }
 8272:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8273:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8274: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8275:                        &log($env{'user.domain'},$env{'user.name'},
 8276:                             $env{'user.home'},
 8277:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8278:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8279:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8280: 		       return '';
 8281:                    }
 8282:                }
 8283:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8284:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8285: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8286:                        &log($env{'user.domain'},$env{'user.name'},
 8287:                             $env{'user.home'},
 8288:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8289:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8290:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8291: 		       return '';
 8292:                    }
 8293:                }
 8294: 	   }
 8295:        }
 8296:     }
 8297:    
 8298: #
 8299: # Rest of the restrictions depend on selected course
 8300: #
 8301: 
 8302:     unless ($env{'request.course.id'}) {
 8303: 	if ($thisallowed eq 'A') {
 8304: 	    return 'A';
 8305:         } elsif ($thisallowed eq 'B') {
 8306:             return 'B';
 8307: 	} else {
 8308: 	    return '1';
 8309: 	}
 8310:     }
 8311: 
 8312: #
 8313: # Now user is definitely in a course
 8314: #
 8315: 
 8316: 
 8317: # Course preferences
 8318: 
 8319:    if ($thisallowed=~/C/) {
 8320:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8321:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8322:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8323: 	   =~/\Q$rolecode\E/) {
 8324: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8325: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8326: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8327: 			$env{'request.course.id'});
 8328: 	   }
 8329:            return '';
 8330:        }
 8331: 
 8332:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8333: 	   =~/\Q$unamedom\E/) {
 8334: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8335: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8336: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8337: 			$env{'request.course.id'});
 8338: 	   }
 8339:            return '';
 8340:        }
 8341:    }
 8342: 
 8343: # Resource preferences
 8344: 
 8345:    if ($thisallowed=~/R/) {
 8346:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8347:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8348: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8349: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8350: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8351: 	   }
 8352: 	   return '';
 8353:        }
 8354:    }
 8355: 
 8356: # Restricted by state or randomout?
 8357: 
 8358:    if ($thisallowed=~/X/) {
 8359:       if ($env{'acc.randomout'}) {
 8360: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8361:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8362:             return ''; 
 8363:          }
 8364:       }
 8365:       if (&condval($statecond)) {
 8366: 	 return '2';
 8367:       } else {
 8368:          return '';
 8369:       }
 8370:    }
 8371: 
 8372:     if ($thisallowed eq 'A') {
 8373: 	return 'A';
 8374:     } elsif ($thisallowed eq 'B') {
 8375:         return 'B';
 8376:     } elsif ($thisallowed eq 'D') {
 8377:         return 'D';
 8378:     }
 8379:    return 'F';
 8380: }
 8381: 
 8382: # ------------------------------------------- Check construction space access
 8383: 
 8384: sub constructaccess {
 8385:     my ($url,$setpriv)=@_;
 8386: 
 8387: # We do not allow editing of previous versions of files
 8388:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8389: 
 8390: # Get username and domain from URL
 8391:     my ($ownername,$ownerdomain,$ownerhome);
 8392: 
 8393:     ($ownerdomain,$ownername) =
 8394:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8395: 
 8396: # The URL does not really point to any authorspace, forget it
 8397:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8398: 
 8399: # Now we need to see if the user has access to the authorspace of
 8400: # $ownername at $ownerdomain
 8401: 
 8402:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8403: # Real author for this?
 8404:        $ownerhome = $env{'user.home'};
 8405:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8406:           return ($ownername,$ownerdomain,$ownerhome);
 8407:        }
 8408:     } else {
 8409: # Co-author for this?
 8410:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8411:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8412:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8413:             return ($ownername,$ownerdomain,$ownerhome);
 8414:         }
 8415:         if ($env{'request.course.id'}) {
 8416:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8417:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8418:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8419:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8420:                     return ($ownername,$ownerdomain,$ownerhome);
 8421:                 }
 8422:             }
 8423:         }
 8424:     }
 8425: 
 8426: # We don't have any access right now. If we are not possibly going to do anything about this,
 8427: # we might as well leave
 8428:    unless ($setpriv) { return ''; }
 8429: 
 8430: # Backdoor access?
 8431:     my $allowed=&allowed('eco',$ownerdomain);
 8432: # Nope
 8433:     unless ($allowed) { return ''; }
 8434: # Looks like we may have access, but could be locked by the owner of the construction space
 8435:     if ($allowed eq 'U') {
 8436:         my %blocked=&get('environment',['domcoord.author'],
 8437:                          $ownerdomain,$ownername);
 8438: # Is blocked by owner
 8439:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8440:     }
 8441:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8442: # Grant temporary access
 8443:         my $then=$env{'user.login.time'};
 8444:         my $update=$env{'user.update.time'};
 8445:         if (!$update) { $update = $then; }
 8446:         my $refresh=$env{'user.refresh.time'};
 8447:         if (!$refresh) { $refresh = $update; }
 8448:         my $now = time;
 8449:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8450:                            $now,'ca','constructaccess');
 8451:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8452:         return($ownername,$ownerdomain,$ownerhome);
 8453:     }
 8454: # No business here
 8455:     return '';
 8456: }
 8457: 
 8458: # ----------------------------------------------------------- Content Blocking
 8459: 
 8460: {
 8461: # Caches for faster Course Contents display where content blocking
 8462: # is in operation (i.e., interval param set) for timed quiz.
 8463: #
 8464: # User for whom data are being temporarily cached.
 8465: my $cacheduser='';
 8466: # Cached blockers for this user (a hash of blocking items). 
 8467: my %cachedblockers=();
 8468: # When the data were last cached.
 8469: my $cachedlast='';
 8470: 
 8471: sub load_all_blockers {
 8472:     my ($uname,$udom,$blocks)=@_;
 8473:     if (($uname ne '') && ($udom ne '')) { 
 8474:         if (($cacheduser eq $uname.':'.$udom) &&
 8475:             (abs($cachedlast-time)<5)) {
 8476:             return;
 8477:         }
 8478:     }
 8479:     $cachedlast=time;
 8480:     $cacheduser=$uname.':'.$udom;
 8481:     %cachedblockers = &get_commblock_resources($blocks);
 8482: }
 8483: 
 8484: sub get_comm_blocks {
 8485:     my ($cdom,$cnum) = @_;
 8486:     if ($cdom eq '' || $cnum eq '') {
 8487:         return unless ($env{'request.course.id'});
 8488:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8489:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8490:     }
 8491:     my %commblocks;
 8492:     my $hashid=$cdom.'_'.$cnum;
 8493:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8494:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8495:         %commblocks = %{$blocksref};
 8496:     } else {
 8497:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8498:         my $cachetime = 600;
 8499:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8500:     }
 8501:     return %commblocks;
 8502: }
 8503: 
 8504: sub get_commblock_resources {
 8505:     my ($blocks) = @_;
 8506:     my %blockers = ();
 8507:     return %blockers unless ($env{'request.course.id'});
 8508:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8509:     my %commblocks;
 8510:     if (ref($blocks) eq 'HASH') {
 8511:         %commblocks = %{$blocks};
 8512:     } else {
 8513:         %commblocks = &get_comm_blocks();
 8514:     }
 8515:     return %blockers unless (keys(%commblocks) > 0); 
 8516:     my $navmap = Apache::lonnavmaps::navmap->new();
 8517:     return %blockers unless (ref($navmap));
 8518:     my $now = time;
 8519:     foreach my $block (keys(%commblocks)) {
 8520:         if ($block =~ /^(\d+)____(\d+)$/) {
 8521:             my ($start,$end) = ($1,$2);
 8522:             if ($start <= $now && $end >= $now) {
 8523:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8524:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8525:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8526:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8527:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8528:                             }
 8529:                         }
 8530:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8531:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8532:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8533:                             }
 8534:                         }
 8535:                     }
 8536:                 }
 8537:             }
 8538:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8539:             my $item = $1;
 8540:             my @to_test;
 8541:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8542:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8543:                     my @interval;
 8544:                     my $type = 'map';
 8545:                     if ($item eq 'course') {
 8546:                         $type = 'course';
 8547:                         @interval=&EXT("resource.0.interval");
 8548:                     } else {
 8549:                         if ($item =~ /___\d+___/) {
 8550:                             $type = 'resource';
 8551:                             @interval=&EXT("resource.0.interval",$item);
 8552:                             if (ref($navmap)) {                        
 8553:                                 my $res = $navmap->getBySymb($item); 
 8554:                                 push(@to_test,$res);
 8555:                             }
 8556:                         } else {
 8557:                             my $mapsymb = &symbread($item,1);
 8558:                             if ($mapsymb) {
 8559:                                 if (ref($navmap)) {
 8560:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8561:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8562:                                     foreach my $res (@to_test) {
 8563:                                         my $symb = $res->symb();
 8564:                                         next if ($symb eq $mapsymb);
 8565:                                         if ($symb ne '') {
 8566:                                             @interval=&EXT("resource.0.interval",$symb);
 8567:                                             if ($interval[1] eq 'map') {
 8568:                                                 last;
 8569:                                             }
 8570:                                         }
 8571:                                     }
 8572:                                 }
 8573:                             }
 8574:                         }
 8575:                     }
 8576:                     if ($interval[0] =~ /^(\d+)/) {
 8577:                         my $timelimit = $1; 
 8578:                         my $first_access;
 8579:                         if ($type eq 'resource') {
 8580:                             $first_access=&get_first_access($interval[1],$item);
 8581:                         } elsif ($type eq 'map') {
 8582:                             $first_access=&get_first_access($interval[1],undef,$item);
 8583:                         } else {
 8584:                             $first_access=&get_first_access($interval[1]);
 8585:                         }
 8586:                         if ($first_access) {
 8587:                             my $timesup = $first_access+$timelimit;
 8588:                             if ($timesup > $now) {
 8589:                                 my $activeblock;
 8590:                                 foreach my $res (@to_test) {
 8591:                                     if ($res->answerable()) {
 8592:                                         $activeblock = 1;
 8593:                                         last;
 8594:                                     }
 8595:                                 }
 8596:                                 if ($activeblock) {
 8597:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8598:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8599:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8600:                                          }
 8601:                                     }
 8602:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8603:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8604:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8605:                                         }
 8606:                                     }
 8607:                                 }
 8608:                             }
 8609:                         }
 8610:                     }
 8611:                 }
 8612:             }
 8613:         }
 8614:     }
 8615:     return %blockers;
 8616: }
 8617: 
 8618: sub has_comm_blocking {
 8619:     my ($priv,$symb,$uri,$blocks) = @_;
 8620:     my @blockers;
 8621:     return unless ($env{'request.course.id'});
 8622:     return unless ($priv eq 'bre');
 8623:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8624:     return if ($env{'request.state'} eq 'construct');
 8625:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8626:     return unless (keys(%cachedblockers) > 0);
 8627:     my (%possibles,@symbs);
 8628:     if (!$symb) {
 8629:         $symb = &symbread($uri,1,1,1,\%possibles);
 8630:     }
 8631:     if ($symb) {
 8632:         @symbs = ($symb);
 8633:     } elsif (keys(%possibles)) { 
 8634:         @symbs = keys(%possibles);
 8635:     }
 8636:     my $noblock;
 8637:     foreach my $symb (@symbs) {
 8638:         last if ($noblock);
 8639:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8640:         foreach my $block (keys(%cachedblockers)) {
 8641:             if ($block =~ /^firstaccess____(.+)$/) {
 8642:                 my $item = $1;
 8643:                 if (($item eq $map) || ($item eq $symb)) {
 8644:                     $noblock = 1;
 8645:                     last;
 8646:                 }
 8647:             }
 8648:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8649:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8650:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8651:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8652:                             push(@blockers,$block);
 8653:                         }
 8654:                     }
 8655:                 }
 8656:             }
 8657:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8658:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8659:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8660:                         push(@blockers,$block);
 8661:                     }
 8662:                 }
 8663:             }
 8664:         }
 8665:     }
 8666:     return if ($noblock);
 8667:     return @blockers;
 8668: }
 8669: }
 8670: 
 8671: sub deeplink_check {
 8672:     my ($priv,$symb,$uri) = @_;
 8673:     return unless ($env{'request.course.id'});
 8674:     return unless ($priv eq 'bre');
 8675:     return if ($env{'request.state'} eq 'construct');
 8676:     return if ($env{'request.role.adv'});
 8677:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8678:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8679:     my (%possibles,@symbs);
 8680:     if (!$symb) {
 8681:         $symb = &symbread($uri,1,1,1,\%possibles);
 8682:     }
 8683:     if ($symb) {
 8684:         @symbs = ($symb);
 8685:     } elsif (keys(%possibles)) {
 8686:         @symbs = keys(%possibles);
 8687:     }
 8688: 
 8689:     my ($login,$switchrole,$allow);
 8690:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8691:         my $key = $1;
 8692:         my $tinyurl;
 8693:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8694:         if (defined($cached)) {
 8695:              $tinyurl = $result;
 8696:         } else {
 8697:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8698:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8699:              if ($currtiny{$key} ne '') {
 8700:                  $tinyurl = $currtiny{$key};
 8701:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8702:              }
 8703:         }
 8704:         if ($tinyurl ne '') {
 8705:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8706:             if ($cnumreq eq $cnum) {
 8707:                 $login = $posslogin;
 8708:             } else {
 8709:                 $switchrole = 1;
 8710:             }
 8711:         }
 8712:     }
 8713:     foreach my $symb (@symbs) {
 8714:         last if ($allow);
 8715:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8716:         if ($deeplink eq '') {
 8717:             $allow = 1;
 8718:         } else {
 8719:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8720:             if ($access eq 'any') {
 8721:                 $allow = 1;
 8722:             } elsif ($login) {
 8723:                 if ($access eq 'only') {
 8724:                     if ($scope eq 'res') {
 8725:                         if ($symb eq $login) {
 8726:                             $allow = 1;
 8727:                         }
 8728:                     } elsif ($scope eq 'map') {
 8729: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8730:                     } elsif ($scope eq 'rec') {
 8731: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8732:                     }
 8733:                 } else {
 8734:                     my ($acctype,$item) = split(/:/,$access);
 8735:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8736:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8737:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8738:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8739:                                 $allow = 1;
 8740:                             }
 8741:                         }
 8742:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8743:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8744:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8745:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8746:                                 $allow = 1;
 8747:                             }
 8748:                         }
 8749:                     }
 8750:                 }
 8751:             }
 8752:         }
 8753:     }
 8754:     return if ($allow);
 8755:     return 1;
 8756: }
 8757: 
 8758: # -------------------------------- Deversion and split uri into path an filename   
 8759: 
 8760: #
 8761: #   Removes the version from a URI and
 8762: #   splits it in to its filename and path to the filename.
 8763: #   Seems like File::Basename could have done this more clearly.
 8764: #   Parameters:
 8765: #      $uri   - input URI
 8766: #   Returns:
 8767: #     Two element list consisting of 
 8768: #     $pathname  - the URI up to and excluding the trailing /
 8769: #     $filename  - The part of the URI following the last /
 8770: #  NOTE:
 8771: #    Another realization of this is simply:
 8772: #    use File::Basename;
 8773: #    ...
 8774: #    $uri = shift;
 8775: #    $filename = basename($uri);
 8776: #    $path     = dirname($uri);
 8777: #    return ($filename, $path);
 8778: #
 8779: #     The implementation below is probably faster however.
 8780: #
 8781: sub split_uri_for_cond {
 8782:     my $uri=&deversion(&declutter(shift));
 8783:     my @uriparts=split(/\//,$uri);
 8784:     my $filename=pop(@uriparts);
 8785:     my $pathname=join('/',@uriparts);
 8786:     return ($pathname,$filename);
 8787: }
 8788: # --------------------------------------------------- Is a resource on the map?
 8789: 
 8790: sub is_on_map {
 8791:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8792:     #Trying to find the conditional for the file
 8793:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8794: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8795:     if ($match) {
 8796: 	return (1,$1);
 8797:     } else {
 8798: 	return (0,0);
 8799:     }
 8800: }
 8801: 
 8802: # --------------------------------------------------------- Get symb from alias
 8803: 
 8804: sub get_symb_from_alias {
 8805:     my $symb=shift;
 8806:     my ($map,$resid,$url)=&decode_symb($symb);
 8807: # Already is a symb
 8808:     if ($url) { return $symb; }
 8809: # Must be an alias
 8810:     my $aliassymb='';
 8811:     my %bighash;
 8812:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8813:                             &GDBM_READER(),0640)) {
 8814:         my $rid=$bighash{'mapalias_'.$symb};
 8815: 	if ($rid) {
 8816: 	    my ($mapid,$resid)=split(/\./,$rid);
 8817: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8818: 				    $resid,$bighash{'src_'.$rid});
 8819: 	}
 8820:         untie %bighash;
 8821:     }
 8822:     return $aliassymb;
 8823: }
 8824: 
 8825: # ----------------------------------------------------------------- Define Role
 8826: 
 8827: sub definerole {
 8828:   if (allowed('mcr','/')) {
 8829:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8830:     foreach my $role (split(':',$sysrole)) {
 8831: 	my ($crole,$cqual)=split(/\&/,$role);
 8832:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8833:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8834: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8835:                return "refused:s:$crole&$cqual"; 
 8836:             }
 8837:         }
 8838:     }
 8839:     foreach my $role (split(':',$domrole)) {
 8840: 	my ($crole,$cqual)=split(/\&/,$role);
 8841:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8842:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8843: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8844:                return "refused:d:$crole&$cqual"; 
 8845:             }
 8846:         }
 8847:     }
 8848:     foreach my $role (split(':',$courole)) {
 8849: 	my ($crole,$cqual)=split(/\&/,$role);
 8850:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8851:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8852: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8853:                return "refused:c:$crole&$cqual"; 
 8854:             }
 8855:         }
 8856:     }
 8857:     my $uhome;
 8858:     if (($uname ne '') && ($udom ne '')) {
 8859:         $uhome = &homeserver($uname,$udom);
 8860:         return $uhome if ($uhome eq 'no_host');
 8861:     } else {
 8862:         $uname = $env{'user.name'};
 8863:         $udom = $env{'user.domain'};
 8864:         $uhome = $env{'user.home'};
 8865:     }
 8866:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8867:                 "$udom:$uname:rolesdef_$rolename=".
 8868:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8869:     return reply($command,$uhome);
 8870:   } else {
 8871:     return 'refused';
 8872:   }
 8873: }
 8874: 
 8875: # ---------------- Make a metadata query against the network of library servers
 8876: 
 8877: sub metadata_query {
 8878:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8879:     my %rhash;
 8880:     my %libserv = &all_library();
 8881:     my @server_list = (defined($server_array) ? @$server_array
 8882:                                               : keys(%libserv) );
 8883:     for my $server (@server_list) {
 8884:         my $domains = ''; 
 8885:         if (ref($domains_hash) eq 'HASH') {
 8886:             $domains = $domains_hash->{$server}; 
 8887:         }
 8888: 	unless ($custom or $customshow) {
 8889: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8890: 	    $rhash{$server}=$reply;
 8891: 	}
 8892: 	else {
 8893: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8894: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8895: 			     $server);
 8896: 	    $rhash{$server}=$reply;
 8897: 	}
 8898:     }
 8899:     return \%rhash;
 8900: }
 8901: 
 8902: # ----------------------------------------- Send log queries and wait for reply
 8903: 
 8904: sub log_query {
 8905:     my ($uname,$udom,$query,%filters)=@_;
 8906:     my $uhome=&homeserver($uname,$udom);
 8907:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8908:     my $uhost=&hostname($uhome);
 8909:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8910:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8911:                        $uhome);
 8912:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8913:     return get_query_reply($queryid);
 8914: }
 8915: 
 8916: # -------------------------- Update MySQL table for portfolio file
 8917: 
 8918: sub update_portfolio_table {
 8919:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8920:     if ($group ne '') {
 8921:         $file_name =~s /^\Q$group\E//;
 8922:     }
 8923:     my $homeserver = &homeserver($uname,$udom);
 8924:     my $queryid=
 8925:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8926:                ':'.&escape($file_name).':'.$action,$homeserver);
 8927:     my $reply = &get_query_reply($queryid);
 8928:     return $reply;
 8929: }
 8930: 
 8931: # -------------------------- Update MySQL allusers table
 8932: 
 8933: sub update_allusers_table {
 8934:     my ($uname,$udom,$names) = @_;
 8935:     my $homeserver = &homeserver($uname,$udom);
 8936:     my $queryid=
 8937:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8938:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8939:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8940:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8941:                'generation='.&escape($names->{'generation'}).'%%'.
 8942:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8943:                'id='.&escape($names->{'id'}),$homeserver);
 8944:     return;
 8945: }
 8946: 
 8947: # ------- Request retrieval of institutional classlists for course(s)
 8948: 
 8949: sub fetch_enrollment_query {
 8950:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8951:     my ($homeserver,$sleep,$loopmax);
 8952:     my $maxtries = 1;
 8953:     if ($context eq 'automated') {
 8954:         $homeserver = $perlvar{'lonHostID'};
 8955:         $sleep = 2;
 8956:         $loopmax = 100;
 8957:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8958:     } else {
 8959:         $homeserver = &homeserver($cnum,$dom);
 8960:     }
 8961:     my $host=&hostname($homeserver);
 8962:     my $cmd = '';
 8963:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8964:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8965:     }
 8966:     $cmd =~ s/%%$//;
 8967:     $cmd = &escape($cmd);
 8968:     my $query = 'fetchenrollment';
 8969:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8970:     unless ($queryid=~/^\Q$host\E\_/) { 
 8971:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8972:         return 'error: '.$queryid;
 8973:     }
 8974:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8975:     my $tries = 1;
 8976:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8977:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8978:         $tries ++;
 8979:     }
 8980:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8981:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8982:     } else {
 8983:         my @responses = split(/:/,$reply);
 8984:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8985:             foreach my $line (@responses) {
 8986:                 my ($key,$value) = split(/=/,$line,2);
 8987:                 $$replyref{$key} = $value;
 8988:             }
 8989:         } else {
 8990:             my $pathname = LONCAPA::tempdir();
 8991:             foreach my $line (@responses) {
 8992:                 my ($key,$value) = split(/=/,$line);
 8993:                 $$replyref{$key} = $value;
 8994:                 if ($value > 0) {
 8995:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8996:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8997:                         my $destname = $pathname.'/'.$filename;
 8998:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8999:                         if ($xml_classlist =~ /^error/) {
 9000:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9001:                         } else {
 9002:                             if ( open(FILE,">",$destname) ) {
 9003:                                 print FILE &unescape($xml_classlist);
 9004:                                 close(FILE);
 9005:                             } else {
 9006:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9007:                             }
 9008:                         }
 9009:                     }
 9010:                 }
 9011:             }
 9012:         }
 9013:         return 'ok';
 9014:     }
 9015:     return 'error';
 9016: }
 9017: 
 9018: sub get_query_reply {
 9019:     my ($queryid,$sleep,$loopmax) = @_;;
 9020:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9021:         $sleep = 0.2;
 9022:     }
 9023:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9024:         $loopmax = 100;
 9025:     }
 9026:     my $replyfile=LONCAPA::tempdir().$queryid;
 9027:     my $reply='';
 9028:     for (1..$loopmax) {
 9029: 	sleep($sleep);
 9030:         if (-e $replyfile.'.end') {
 9031: 	    if (open(my $fh,"<",$replyfile)) {
 9032: 		$reply = join('',<$fh>);
 9033: 		close($fh);
 9034: 	   } else { return 'error: reply_file_error'; }
 9035:            return &unescape($reply);
 9036: 	}
 9037:     }
 9038:     return 'timeout:'.$queryid;
 9039: }
 9040: 
 9041: sub courselog_query {
 9042: #
 9043: # possible filters:
 9044: # url: url or symb
 9045: # username
 9046: # domain
 9047: # action: view, submit, grade
 9048: # start: timestamp
 9049: # end: timestamp
 9050: #
 9051:     my (%filters)=@_;
 9052:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9053:     if ($filters{'url'}) {
 9054: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9055:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9056:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9057:     }
 9058:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9059:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9060:     return &log_query($cname,$cdom,'courselog',%filters);
 9061: }
 9062: 
 9063: sub userlog_query {
 9064: #
 9065: # possible filters:
 9066: # action: log check role
 9067: # start: timestamp
 9068: # end: timestamp
 9069: #
 9070:     my ($uname,$udom,%filters)=@_;
 9071:     return &log_query($uname,$udom,'userlog',%filters);
 9072: }
 9073: 
 9074: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9075: 
 9076: sub auto_run {
 9077:     my ($cnum,$cdom) = @_;
 9078:     my $response = 0;
 9079:     my $settings;
 9080:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9081:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9082:         $settings = $domconfig{'autoenroll'};
 9083:         if ($settings->{'run'} eq '1') {
 9084:             $response = 1;
 9085:         }
 9086:     } else {
 9087:         my $homeserver;
 9088:         if (&is_course($cdom,$cnum)) {
 9089:             $homeserver = &homeserver($cnum,$cdom);
 9090:         } else {
 9091:             $homeserver = &domain($cdom,'primary');
 9092:         }
 9093:         if ($homeserver ne 'no_host') {
 9094:             $response = &reply('autorun:'.$cdom,$homeserver);
 9095:         }
 9096:     }
 9097:     return $response;
 9098: }
 9099: 
 9100: sub auto_get_sections {
 9101:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9102:     my $homeserver;
 9103:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9104:         $homeserver = &homeserver($cnum,$cdom);
 9105:     }
 9106:     if (!defined($homeserver)) { 
 9107:         if ($cdom =~ /^$match_domain$/) {
 9108:             $homeserver = &domain($cdom,'primary');
 9109:         }
 9110:     }
 9111:     my @secs;
 9112:     if (defined($homeserver)) {
 9113:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9114:         unless ($response eq 'refused') {
 9115:             @secs = split(/:/,$response);
 9116:         }
 9117:     }
 9118:     return @secs;
 9119: }
 9120: 
 9121: sub auto_new_course {
 9122:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9123:     my $homeserver = &homeserver($cnum,$cdom);
 9124:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9125:     return $response;
 9126: }
 9127: 
 9128: sub auto_validate_courseID {
 9129:     my ($cnum,$cdom,$inst_course_id) = @_;
 9130:     my $homeserver = &homeserver($cnum,$cdom);
 9131:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9132:     return $response;
 9133: }
 9134: 
 9135: sub auto_validate_instcode {
 9136:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9137:     my ($homeserver,$response);
 9138:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9139:         $homeserver = &homeserver($cnum,$cdom);
 9140:     }
 9141:     if (!defined($homeserver)) {
 9142:         if ($cdom =~ /^$match_domain$/) {
 9143:             $homeserver = &domain($cdom,'primary');
 9144:         }
 9145:     }
 9146:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9147:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9148:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9149:     return ($outcome,$description,$defaultcredits);
 9150: }
 9151: 
 9152: sub auto_create_password {
 9153:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9154:     my ($homeserver,$response);
 9155:     my $create_passwd = 0;
 9156:     my $authchk = '';
 9157:     if ($udom =~ /^$match_domain$/) {
 9158:         $homeserver = &domain($udom,'primary');
 9159:     }
 9160:     if ($homeserver eq '') {
 9161:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9162:             $homeserver = &homeserver($cnum,$cdom);
 9163:         }
 9164:     }
 9165:     if ($homeserver eq '') {
 9166:         $authchk = 'nodomain';
 9167:     } else {
 9168:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9169:         if ($response eq 'refused') {
 9170:             $authchk = 'refused';
 9171:         } else {
 9172:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9173:         }
 9174:     }
 9175:     return ($authparam,$create_passwd,$authchk);
 9176: }
 9177: 
 9178: sub auto_photo_permission {
 9179:     my ($cnum,$cdom,$students) = @_;
 9180:     my $homeserver = &homeserver($cnum,$cdom);
 9181:     my ($outcome,$perm_reqd,$conditions) = 
 9182: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9183:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9184: 	return (undef,undef);
 9185:     }
 9186:     return ($outcome,$perm_reqd,$conditions);
 9187: }
 9188: 
 9189: sub auto_checkphotos {
 9190:     my ($uname,$udom,$pid) = @_;
 9191:     my $homeserver = &homeserver($uname,$udom);
 9192:     my ($result,$resulttype);
 9193:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9194: 				   &escape($uname).':'.&escape($pid),
 9195: 				   $homeserver));
 9196:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9197: 	return (undef,undef);
 9198:     }
 9199:     if ($outcome) {
 9200:         ($result,$resulttype) = split(/:/,$outcome);
 9201:     } 
 9202:     return ($result,$resulttype);
 9203: }
 9204: 
 9205: sub auto_photochoice {
 9206:     my ($cnum,$cdom) = @_;
 9207:     my $homeserver = &homeserver($cnum,$cdom);
 9208:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9209: 						       &escape($cdom),
 9210: 						       $homeserver)));
 9211:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9212: 	return (undef,undef);
 9213:     }
 9214:     return ($update,$comment);
 9215: }
 9216: 
 9217: sub auto_photoupdate {
 9218:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9219:     my $homeserver = &homeserver($cnum,$dom);
 9220:     my $host=&hostname($homeserver);
 9221:     my $cmd = '';
 9222:     my $maxtries = 1;
 9223:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9224:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9225:     }
 9226:     $cmd =~ s/%%$//;
 9227:     $cmd = &escape($cmd);
 9228:     my $query = 'institutionalphotos';
 9229:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9230:     unless ($queryid=~/^\Q$host\E\_/) {
 9231:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9232:         return 'error: '.$queryid;
 9233:     }
 9234:     my $reply = &get_query_reply($queryid);
 9235:     my $tries = 1;
 9236:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9237:         $reply = &get_query_reply($queryid);
 9238:         $tries ++;
 9239:     }
 9240:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9241:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9242:     } else {
 9243:         my @responses = split(/:/,$reply);
 9244:         my $outcome = shift(@responses); 
 9245:         foreach my $item (@responses) {
 9246:             my ($key,$value) = split(/=/,$item);
 9247:             $$photo{$key} = $value;
 9248:         }
 9249:         return $outcome;
 9250:     }
 9251:     return 'error';
 9252: }
 9253: 
 9254: sub auto_instcode_format {
 9255:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9256: 	$cat_order) = @_;
 9257:     my $courses = '';
 9258:     my @homeservers;
 9259:     if ($caller eq 'global') {
 9260: 	my %servers = &get_servers($codedom,'library');
 9261: 	foreach my $tryserver (keys(%servers)) {
 9262: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9263: 		push(@homeservers,$tryserver);
 9264: 	    }
 9265:         }
 9266:     } elsif ($caller eq 'requests') {
 9267:         if ($codedom =~ /^$match_domain$/) {
 9268:             my $chome = &domain($codedom,'primary');
 9269:             unless ($chome eq 'no_host') {
 9270:                 push(@homeservers,$chome);
 9271:             }
 9272:         }
 9273:     } else {
 9274:         push(@homeservers,&homeserver($caller,$codedom));
 9275:     }
 9276:     foreach my $code (keys(%{$instcodes})) {
 9277:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9278:     }
 9279:     chop($courses);
 9280:     my $ok_response = 0;
 9281:     my $response;
 9282:     while (@homeservers > 0 && $ok_response == 0) {
 9283:         my $server = shift(@homeservers); 
 9284:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9285:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9286:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9287: 		split(/:/,$response);
 9288:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9289:             push(@{$codetitles},&str2array($codetitles_str));
 9290:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9291:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9292:             $ok_response = 1;
 9293:         }
 9294:     }
 9295:     if ($ok_response) {
 9296:         return 'ok';
 9297:     } else {
 9298:         return $response;
 9299:     }
 9300: }
 9301: 
 9302: sub auto_instcode_defaults {
 9303:     my ($domain,$returnhash,$code_order) = @_;
 9304:     my @homeservers;
 9305: 
 9306:     my %servers = &get_servers($domain,'library');
 9307:     foreach my $tryserver (keys(%servers)) {
 9308: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9309: 	    push(@homeservers,$tryserver);
 9310: 	}
 9311:     }
 9312: 
 9313:     my $response;
 9314:     foreach my $server (@homeservers) {
 9315:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9316:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9317: 	
 9318: 	foreach my $pair (split(/\&/,$response)) {
 9319: 	    my ($name,$value)=split(/\=/,$pair);
 9320: 	    if ($name eq 'code_order') {
 9321: 		@{$code_order} = split(/\&/,&unescape($value));
 9322: 	    } else {
 9323: 		$returnhash->{&unescape($name)}=&unescape($value);
 9324: 	    }
 9325: 	}
 9326: 	return 'ok';
 9327:     }
 9328: 
 9329:     return $response;
 9330: }
 9331: 
 9332: sub auto_possible_instcodes {
 9333:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9334:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9335:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9336:         return;
 9337:     }
 9338:     my (@homeservers,$uhome);
 9339:     if (defined(&domain($domain,'primary'))) {
 9340:         $uhome=&domain($domain,'primary');
 9341:         push(@homeservers,&domain($domain,'primary'));
 9342:     } else {
 9343:         my %servers = &get_servers($domain,'library');
 9344:         foreach my $tryserver (keys(%servers)) {
 9345:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9346:                 push(@homeservers,$tryserver);
 9347:             }
 9348:         }
 9349:     }
 9350:     my $response;
 9351:     foreach my $server (@homeservers) {
 9352:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9353:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9354:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9355:             split(':',$response);
 9356:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9357:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9358:         foreach my $item (split('&',$cat_title)) {   
 9359:             my ($name,$value)=split('=',$item);
 9360:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9361:         }
 9362:         foreach my $item (split('&',$cat_order)) {
 9363:             my ($name,$value)=split('=',$item);
 9364:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9365:         }
 9366:         return 'ok';
 9367:     }
 9368:     return $response;
 9369: }
 9370: 
 9371: sub auto_courserequest_checks {
 9372:     my ($dom) = @_;
 9373:     my ($homeserver,%validations);
 9374:     if ($dom =~ /^$match_domain$/) {
 9375:         $homeserver = &domain($dom,'primary');
 9376:     }
 9377:     unless ($homeserver eq 'no_host') {
 9378:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9379:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9380:             my @items = split(/&/,$response);
 9381:             foreach my $item (@items) {
 9382:                 my ($key,$value) = split('=',$item);
 9383:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9384:             }
 9385:         }
 9386:     }
 9387:     return %validations; 
 9388: }
 9389: 
 9390: sub auto_courserequest_validation {
 9391:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9392:     my ($homeserver,$response);
 9393:     if ($dom =~ /^$match_domain$/) {
 9394:         $homeserver = &domain($dom,'primary');
 9395:     }
 9396:     unless ($homeserver eq 'no_host') {
 9397:         my $customdata;
 9398:         if (ref($custominfo) eq 'HASH') {
 9399:             $customdata = &freeze_escape($custominfo);
 9400:         }
 9401:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9402:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9403:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9404:                                     $customdata,$homeserver));
 9405:     }
 9406:     return $response;
 9407: }
 9408: 
 9409: sub auto_validate_class_sec {
 9410:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9411:     my $homeserver = &homeserver($cnum,$cdom);
 9412:     my $ownerlist;
 9413:     if (ref($owners) eq 'ARRAY') {
 9414:         $ownerlist = join(',',@{$owners});
 9415:     } else {
 9416:         $ownerlist = $owners;
 9417:     }
 9418:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9419:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9420:     return $response;
 9421: }
 9422: 
 9423: sub auto_validate_instclasses {
 9424:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9425:     my ($homeserver,%validations);
 9426:     $homeserver = &homeserver($cnum,$cdom);
 9427:     unless ($homeserver eq 'no_host') {
 9428:         my $ownerlist;
 9429:         if (ref($owners) eq 'ARRAY') {
 9430:             $ownerlist = join(',',@{$owners});
 9431:         } else {
 9432:             $ownerlist = $owners;
 9433:         }
 9434:         if (ref($classesref) eq 'HASH') {
 9435:             my $classes = &freeze_escape($classesref);
 9436:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9437:                                 ':'.$cdom.':'.$classes,$homeserver);
 9438:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9439:                 my @items = split(/&/,$response);
 9440:                 foreach my $item (@items) {
 9441:                     my ($key,$value) = split('=',$item);
 9442:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9443:                 }
 9444:             }
 9445:         }
 9446:     }
 9447:     return %validations;
 9448: }
 9449: 
 9450: sub auto_crsreq_update {
 9451:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9452:         $code,$accessstart,$accessend,$inbound) = @_;
 9453:     my ($homeserver,%crsreqresponse);
 9454:     if ($cdom =~ /^$match_domain$/) {
 9455:         $homeserver = &domain($cdom,'primary');
 9456:     }
 9457:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9458:         my $info;
 9459:         if (ref($inbound) eq 'HASH') {
 9460:             $info = &freeze_escape($inbound);
 9461:         }
 9462:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9463:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9464:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9465:                             &escape($title).':'.&escape($code).':'.
 9466:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9467:                             $homeserver);
 9468:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9469:             my @items = split(/&/,$response);
 9470:             foreach my $item (@items) {
 9471:                 my ($key,$value) = split('=',$item);
 9472:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9473:             }
 9474:         }
 9475:     }
 9476:     return \%crsreqresponse;
 9477: }
 9478: 
 9479: sub auto_export_grades {
 9480:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9481:     my ($homeserver,%exportresponse);
 9482:     if ($cdom =~ /^$match_domain$/) {
 9483:         $homeserver = &domain($cdom,'primary');
 9484:     }
 9485:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9486:         my $info;
 9487:         if (ref($inforef) eq 'HASH') {
 9488:             $info = &freeze_escape($inforef);
 9489:         }
 9490:         if (ref($gradesref) eq 'HASH') {
 9491:             my $grades = &freeze_escape($gradesref);
 9492:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9493:                                 $info.':'.$grades,$homeserver);
 9494:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9495:                 my @items = split(/&/,$response);
 9496:                 foreach my $item (@items) {
 9497:                     my ($key,$value) = split('=',$item);
 9498:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9499:                 }
 9500:             }
 9501:         }
 9502:     }
 9503:     return \%exportresponse;
 9504: }
 9505: 
 9506: sub check_instcode_cloning {
 9507:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9508:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9509:         return;
 9510:     }
 9511:     my $canclone;
 9512:     if (@{$code_order} > 0) {
 9513:         my $instcoderegexp ='^';
 9514:         my @clonecodes = split(/\&/,$cloner);
 9515:         foreach my $item (@{$code_order}) {
 9516:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9517:                 foreach my $pair (@clonecodes) {
 9518:                     my ($key,$val) = split(/\=/,$pair,2);
 9519:                     $val = &unescape($val);
 9520:                     if ($key eq $item) {
 9521:                         $instcoderegexp .= '('.$val.')';
 9522:                         last;
 9523:                     }
 9524:                 }
 9525:             } else {
 9526:                 $instcoderegexp .= $codedefaults->{$item};
 9527:             }
 9528:         }
 9529:         $instcoderegexp .= '$';
 9530:         my (@from,@to);
 9531:         eval {
 9532:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9533:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9534:         };
 9535:         if ((@from > 0) && (@to > 0)) {
 9536:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9537:             if (!@diffs) {
 9538:                 $canclone = 1;
 9539:             }
 9540:         }
 9541:     }
 9542:     return $canclone;
 9543: }
 9544: 
 9545: sub default_instcode_cloning {
 9546:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9547:     my (%codedefaults,@code_order,$canclone);
 9548:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9549:         %codedefaults = %{$codedefaultsref};
 9550:         @code_order = @{$codeorderref};
 9551:     } elsif ($clonedom) {
 9552:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9553:     }
 9554:     if (($domdefclone) && (@code_order)) {
 9555:         my @clonecodes = split(/\+/,$domdefclone);
 9556:         my $instcoderegexp ='^';
 9557:         foreach my $item (@code_order) {
 9558:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9559:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9560:             } else {
 9561:                 $instcoderegexp .= $codedefaults{$item};
 9562:             }
 9563:         }
 9564:         $instcoderegexp .= '$';
 9565:         my (@from,@to);
 9566:         eval {
 9567:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9568:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9569:         };
 9570:         if ((@from > 0) && (@to > 0)) {
 9571:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9572:             if (!@diffs) {
 9573:                 $canclone = 1;
 9574:             }
 9575:         }
 9576:     }
 9577:     return $canclone;
 9578: }
 9579: 
 9580: # ------------------------------------------------------- Course Group routines
 9581: 
 9582: sub get_coursegroups {
 9583:     my ($cdom,$cnum,$group,$namespace) = @_;
 9584:     return(&dump($namespace,$cdom,$cnum,$group));
 9585: }
 9586: 
 9587: sub modify_coursegroup {
 9588:     my ($cdom,$cnum,$groupsettings) = @_;
 9589:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9590: }
 9591: 
 9592: sub toggle_coursegroup_status {
 9593:     my ($cdom,$cnum,$group,$action) = @_;
 9594:     my ($from_namespace,$to_namespace);
 9595:     if ($action eq 'delete') {
 9596:         $from_namespace = 'coursegroups';
 9597:         $to_namespace = 'deleted_groups';
 9598:     } else {
 9599:         $from_namespace = 'deleted_groups';
 9600:         $to_namespace = 'coursegroups';
 9601:     }
 9602:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9603:     if (my $tmp = &error(%curr_group)) {
 9604:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9605:         return ('read error',$tmp);
 9606:     } else {
 9607:         my %savedsettings = %curr_group; 
 9608:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9609:         my $deloutcome;
 9610:         if ($result eq 'ok') {
 9611:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9612:         } else {
 9613:             return ('write error',$result);
 9614:         }
 9615:         if ($deloutcome eq 'ok') {
 9616:             return 'ok';
 9617:         } else {
 9618:             return ('delete error',$deloutcome);
 9619:         }
 9620:     }
 9621: }
 9622: 
 9623: sub modify_group_roles {
 9624:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9625:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9626:     my $role = 'gr/'.&escape($userprivs);
 9627:     my ($uname,$udom) = split(/:/,$user);
 9628:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9629:     if ($result eq 'ok') {
 9630:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9631:     }
 9632:     return $result;
 9633: }
 9634: 
 9635: sub modify_coursegroup_membership {
 9636:     my ($cdom,$cnum,$membership) = @_;
 9637:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9638:     return $result;
 9639: }
 9640: 
 9641: sub get_active_groups {
 9642:     my ($udom,$uname,$cdom,$cnum) = @_;
 9643:     my $now = time;
 9644:     my %groups = ();
 9645:     foreach my $key (keys(%env)) {
 9646:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9647:             my ($start,$end) = split(/\./,$env{$key});
 9648:             if (($end!=0) && ($end<$now)) { next; }
 9649:             if (($start!=0) && ($start>$now)) { next; }
 9650:             if ($1 eq $cdom && $2 eq $cnum) {
 9651:                 $groups{$3} = $env{$key} ;
 9652:             }
 9653:         }
 9654:     }
 9655:     return %groups;
 9656: }
 9657: 
 9658: sub get_group_membership {
 9659:     my ($cdom,$cnum,$group) = @_;
 9660:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9661: }
 9662: 
 9663: sub get_users_groups {
 9664:     my ($udom,$uname,$courseid) = @_;
 9665:     my @usersgroups;
 9666:     my $cachetime=1800;
 9667: 
 9668:     my $hashid="$udom:$uname:$courseid";
 9669:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9670:     if (defined($cached)) {
 9671:         @usersgroups = split(/:/,$grouplist);
 9672:     } else {  
 9673:         $grouplist = '';
 9674:         my $courseurl = &courseid_to_courseurl($courseid);
 9675:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9676:         my $access_end = $env{'course.'.$courseid.
 9677:                               '.default_enrollment_end_date'};
 9678:         my $now = time;
 9679:         foreach my $key (keys(%roleshash)) {
 9680:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9681:                 my $group = $1;
 9682:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9683:                     my $start = $2;
 9684:                     my $end = $1;
 9685:                     if ($start == -1) { next; } # deleted from group
 9686:                     if (($start!=0) && ($start>$now)) { next; }
 9687:                     if (($end!=0) && ($end<$now)) {
 9688:                         if ($access_end && $access_end < $now) {
 9689:                             if ($access_end - $end < 86400) {
 9690:                                 push(@usersgroups,$group);
 9691:                             }
 9692:                         }
 9693:                         next;
 9694:                     }
 9695:                     push(@usersgroups,$group);
 9696:                 }
 9697:             }
 9698:         }
 9699:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9700:         $grouplist = join(':',@usersgroups);
 9701:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9702:     }
 9703:     return @usersgroups;
 9704: }
 9705: 
 9706: sub devalidate_getgroups_cache {
 9707:     my ($udom,$uname,$cdom,$cnum)=@_;
 9708:     my $courseid = $cdom.'_'.$cnum;
 9709: 
 9710:     my $hashid="$udom:$uname:$courseid";
 9711:     &devalidate_cache_new('getgroups',$hashid);
 9712: }
 9713: 
 9714: # ------------------------------------------------------------------ Plain Text
 9715: 
 9716: sub plaintext {
 9717:     my ($short,$type,$cid,$forcedefault) = @_;
 9718:     if ($short =~ m{^cr/}) {
 9719: 	return (split('/',$short))[-1];
 9720:     }
 9721:     if (!defined($cid)) {
 9722:         $cid = $env{'request.course.id'};
 9723:     }
 9724:     my %rolenames = (
 9725:                       Course    => 'std',
 9726:                       Community => 'alt1',
 9727:                       Placement => 'std',
 9728:                     );
 9729:     if ($cid ne '') {
 9730:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9731:             unless ($forcedefault) {
 9732:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9733:                 &Apache::lonlocal::mt_escape(\$roletext);
 9734:                 return &Apache::lonlocal::mt($roletext);
 9735:             }
 9736:         }
 9737:     }
 9738:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9739:         (defined($rolenames{$type})) && 
 9740:         (defined($prp{$short}{$rolenames{$type}}))) {
 9741:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9742:     } elsif ($cid ne '') {
 9743:         my $crstype = $env{'course.'.$cid.'.type'};
 9744:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9745:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9746:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9747:         }
 9748:     }
 9749:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9750: }
 9751: 
 9752: # ----------------------------------------------------------------- Assign Role
 9753: 
 9754: sub assignrole {
 9755:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9756:         $context)=@_;
 9757:     my $mrole;
 9758:     if ($role =~ /^cr\//) {
 9759:         my $cwosec=$url;
 9760:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9761: 	unless (&allowed('ccr',$cwosec)) {
 9762:            my $refused = 1;
 9763:            if ($context eq 'requestcourses') {
 9764:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9765:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9766:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9767:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9768:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9769:                            if ($crsenv{'internal.courseowner'} eq
 9770:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9771:                                $refused = '';
 9772:                            }
 9773:                        }
 9774:                    }
 9775:                }
 9776:            }
 9777:            if ($refused) {
 9778:                &logthis('Refused custom assignrole: '.
 9779:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9780:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9781:                return 'refused';
 9782:            }
 9783:         }
 9784:         $mrole='cr';
 9785:     } elsif ($role =~ /^gr\//) {
 9786:         my $cwogrp=$url;
 9787:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9788:         unless (&allowed('mdg',$cwogrp)) {
 9789:             &logthis('Refused group assignrole: '.
 9790:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9791:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9792:             return 'refused';
 9793:         }
 9794:         $mrole='gr';
 9795:     } else {
 9796:         my $cwosec=$url;
 9797:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9798:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9799:             my $refused;
 9800:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9801:                 if (!(&allowed('c'.$role,$url))) {
 9802:                     $refused = 1;
 9803:                 }
 9804:             } else {
 9805:                 $refused = 1;
 9806:             }
 9807:             if ($refused) {
 9808:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9809:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9810:                     my %crsenv;
 9811:                     if ($role eq 'cc' || $role eq 'co') {
 9812:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9813:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9814:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9815:                                 if ($crsenv{'internal.courseowner'} eq 
 9816:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9817:                                     $refused = '';
 9818:                                 }
 9819:                             }
 9820:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9821:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9822:                                 if ($crsenv{'internal.courseowner'} eq 
 9823:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9824:                                     $refused = '';
 9825:                                 }
 9826:                             }
 9827:                         }
 9828:                     }
 9829:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9830:                     if ($role eq 'st') {
 9831:                         $refused = '';
 9832:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9833:                         $refused = '';
 9834:                     }
 9835:                 } elsif ($context eq 'requestcourses') {
 9836:                     my @possroles = ('st','ta','ep','in','cc','co');
 9837:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9838:                         my $wrongcc;
 9839:                         if ($cnum =~ /^$match_community$/) {
 9840:                             $wrongcc = 1 if ($role eq 'cc');
 9841:                         } else {
 9842:                             $wrongcc = 1 if ($role eq 'co');
 9843:                         }
 9844:                         unless ($wrongcc) {
 9845:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9846:                             if ($crsenv{'internal.courseowner'} eq 
 9847:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9848:                                 $refused = '';
 9849:                             }
 9850:                         }
 9851:                     }
 9852:                 } elsif ($context eq 'requestauthor') {
 9853:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9854:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9855:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9856:                             $refused = '';
 9857:                         } else {
 9858:                             my %domdefaults = &get_domain_defaults($udom);
 9859:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9860:                                 my $checkbystatus;
 9861:                                 if ($env{'user.adv'}) { 
 9862:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9863:                                     if ($disposition eq 'automatic') {
 9864:                                         $refused = '';
 9865:                                     } elsif ($disposition eq '') {
 9866:                                         $checkbystatus = 1;
 9867:                                     } 
 9868:                                 } else {
 9869:                                     $checkbystatus = 1;
 9870:                                 }
 9871:                                 if ($checkbystatus) {
 9872:                                     if ($env{'environment.inststatus'}) {
 9873:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9874:                                         foreach my $type (@inststatuses) {
 9875:                                             if (($type ne '') &&
 9876:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9877:                                                 $refused = '';
 9878:                                             }
 9879:                                         }
 9880:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9881:                                         $refused = '';
 9882:                                     }
 9883:                                 }
 9884:                             }
 9885:                         }
 9886:                     }
 9887:                 }
 9888:                 if ($refused) {
 9889:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9890:                              ' '.$role.' '.$end.' '.$start.' by '.
 9891: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9892:                     return 'refused';
 9893:                 }
 9894:             }
 9895:         } elsif ($role eq 'au') {
 9896:             if ($url ne '/'.$udom.'/') {
 9897:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9898:                          ' to assign author role for '.$uname.':'.$udom.
 9899:                          ' in domain: '.$url.' refused (wrong domain).');
 9900:                 return 'refused';
 9901:             }
 9902:         }
 9903:         $mrole=$role;
 9904:     }
 9905:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9906:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9907:     if ($end) { $command.='_'.$end; }
 9908:     if ($start) {
 9909: 	if ($end) { 
 9910:            $command.='_'.$start; 
 9911:         } else {
 9912:            $command.='_0_'.$start;
 9913:         }
 9914:     }
 9915:     my $origstart = $start;
 9916:     my $origend = $end;
 9917:     my $delflag;
 9918: # actually delete
 9919:     if ($deleteflag) {
 9920: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9921: # modify command to delete the role
 9922:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9923:                 "$udom:$uname:$url".'_'."$mrole";
 9924: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9925: # set start and finish to negative values for userrolelog
 9926:            $start=-1;
 9927:            $end=-1;
 9928:            $delflag = 1;
 9929:         }
 9930:     }
 9931: # send command
 9932:     my $answer=&reply($command,&homeserver($uname,$udom));
 9933: # log new user role if status is ok
 9934:     if ($answer eq 'ok') {
 9935: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9936:         if (($role eq 'cc') || ($role eq 'in') ||
 9937:             ($role eq 'ep') || ($role eq 'ad') ||
 9938:             ($role eq 'ta') || ($role eq 'st') ||
 9939:             ($role=~/^cr/) || ($role eq 'gr') ||
 9940:             ($role eq 'co')) {
 9941: # for course roles, perform group memberships changes triggered by role change.
 9942:             unless ($role =~ /^gr/) {
 9943:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9944:                                                  $origstart,$selfenroll,$context);
 9945:             }
 9946:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9947:                            $selfenroll,$context);
 9948:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9949:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9950:                  ($role eq 'da')) {
 9951:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9952:                            $context);
 9953:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9954:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9955:                              $context); 
 9956:         }
 9957:         if ($role eq 'cc') {
 9958:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9959:         }
 9960:     }
 9961:     return $answer;
 9962: }
 9963: 
 9964: sub autoupdate_coowners {
 9965:     my ($url,$end,$start,$uname,$udom) = @_;
 9966:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9967:     if (($cdom ne '') && ($cnum ne '')) {
 9968:         my $now = time;
 9969:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9970:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9971:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9972:             my $instcode = $coursehash{'internal.coursecode'};
 9973:             if ($instcode ne '') {
 9974:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9975:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9976:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9977:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9978:                         if ($result eq 'valid') {
 9979:                             if ($coursehash{'internal.co-owners'}) {
 9980:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9981:                                     push(@newcoowners,$coowner);
 9982:                                 }
 9983:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9984:                                     push(@newcoowners,$uname.':'.$udom);
 9985:                                 }
 9986:                                 @newcoowners = sort(@newcoowners);
 9987:                             } else {
 9988:                                 push(@newcoowners,$uname.':'.$udom);
 9989:                             }
 9990:                         } else {
 9991:                             if ($coursehash{'internal.co-owners'}) {
 9992:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9993:                                     unless ($coowner eq $uname.':'.$udom) {
 9994:                                         push(@newcoowners,$coowner);
 9995:                                     }
 9996:                                 }
 9997:                                 unless (@newcoowners > 0) {
 9998:                                     $delcoowners = 1;
 9999:                                     $coowners = '';
10000:                                 }
10001:                             }
10002:                         }
10003:                         if (@newcoowners || $delcoowners) {
10004:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10005:                                             $delcoowners,@newcoowners);
10006:                         }
10007:                     }
10008:                 }
10009:             }
10010:         }
10011:     }
10012: }
10013: 
10014: sub store_coowners {
10015:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10016:     my $cid = $cdom.'_'.$cnum;
10017:     my ($coowners,$delresult,$putresult);
10018:     if (@newcoowners) {
10019:         $coowners = join(',',@newcoowners);
10020:         my %coownershash = (
10021:                             'internal.co-owners' => $coowners,
10022:                            );
10023:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10024:         if ($putresult eq 'ok') {
10025:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10026:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10027:             }
10028:         }
10029:     }
10030:     if ($delcoowners) {
10031:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10032:         if ($delresult eq 'ok') {
10033:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10034:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10035:             }
10036:         }
10037:     }
10038:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10039:         my %crsinfo =
10040:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10041:         if (ref($crsinfo{$cid}) eq 'HASH') {
10042:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10043:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10044:         }
10045:     }
10046: }
10047: 
10048: # -------------------------------------------------- Modify user authentication
10049: # Overrides without validation
10050: 
10051: sub modifyuserauth {
10052:     my ($udom,$uname,$umode,$upass)=@_;
10053:     my $uhome=&homeserver($uname,$udom);
10054:     unless (&allowed('mau',$udom)) { return 'refused'; }
10055:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10056:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10057:              ' in domain '.$env{'request.role.domain'});  
10058:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10059: 		     &escape($upass),$uhome);
10060:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10061:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10062:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10063:     &log($udom,,$uname,$uhome,
10064:         'Authentication changed by '.$env{'user.domain'}.', '.
10065:                                      $env{'user.name'}.', '.$umode.
10066:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10067:     unless ($reply eq 'ok') {
10068:         &logthis('Authentication mode error: '.$reply);
10069: 	return 'error: '.$reply;
10070:     }   
10071:     return 'ok';
10072: }
10073: 
10074: # --------------------------------------------------------------- Modify a user
10075: 
10076: sub modifyuser {
10077:     my ($udom,    $uname, $uid,
10078:         $umode,   $upass, $first,
10079:         $middle,  $last,  $gene,
10080:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10081:     $udom= &LONCAPA::clean_domain($udom);
10082:     $uname=&LONCAPA::clean_username($uname);
10083:     my $showcandelete = 'none';
10084:     if (ref($candelete) eq 'ARRAY') {
10085:         if (@{$candelete} > 0) {
10086:             $showcandelete = join(', ',@{$candelete});
10087:         }
10088:     }
10089:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10090:              $umode.', '.$first.', '.$middle.', '.
10091: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10092:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10093:                                      ' desiredhome not specified'). 
10094:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10095:              ' in domain '.$env{'request.role.domain'});
10096:     my $uhome=&homeserver($uname,$udom,'true');
10097:     my $newuser;
10098:     if ($uhome eq 'no_host') {
10099:         $newuser = 1;
10100:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10101:                 ($umode eq 'lti')) {
10102:             return 'error: more information needed to create new user';
10103:         }
10104:     }
10105: # ----------------------------------------------------------------- Create User
10106:     if (($uhome eq 'no_host') && 
10107: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10108:         my $unhome='';
10109:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10110:             $unhome = $desiredhome;
10111: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10112: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10113:         } else { # load balancing routine for determining $unhome
10114:             my $loadm=10000000;
10115: 	    my %servers = &get_servers($udom,'library');
10116: 	    foreach my $tryserver (keys(%servers)) {
10117: 		my $answer=reply('load',$tryserver);
10118: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10119: 		    $loadm=$answer;
10120: 		    $unhome=$tryserver;
10121: 		}
10122: 	    }
10123:         }
10124:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10125: 	    return 'error: unable to find a home server for '.$uname.
10126:                    ' in domain '.$udom;
10127:         }
10128:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10129:                          &escape($upass),$unhome);
10130: 	unless ($reply eq 'ok') {
10131:             return 'error: '.$reply;
10132:         }   
10133:         $uhome=&homeserver($uname,$udom,'true');
10134:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10135: 	    return 'error: unable verify users home machine.';
10136:         }
10137:     }   # End of creation of new user
10138: # ---------------------------------------------------------------------- Add ID
10139:     if ($uid) {
10140:        $uid=~tr/A-Z/a-z/;
10141:        my %uidhash=&idrget($udom,$uname);
10142:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10143:          && (!$forceid)) {
10144: 	  unless ($uid eq $uidhash{$uname}) {
10145: 	      return 'error: user id "'.$uid.'" does not match '.
10146:                   'current user id "'.$uidhash{$uname}.'".';
10147:           }
10148:        } else {
10149: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10150:        }
10151:     }
10152: # -------------------------------------------------------------- Add names, etc
10153:     my @tmp=&get('environment',
10154: 		   ['firstname','middlename','lastname','generation','id',
10155:                     'permanentemail','inststatus'],
10156: 		   $udom,$uname);
10157:     my (%names,%oldnames);
10158:     if ($tmp[0] =~ m/^error:.*/) { 
10159:         %names=(); 
10160:     } else {
10161:         %names = @tmp;
10162:         %oldnames = %names;
10163:     }
10164: #
10165: # If name, email and/or uid are blank (e.g., because an uploaded file
10166: # of users did not contain them), do not overwrite existing values
10167: # unless field is in $candelete array ref.  
10168: #
10169: 
10170:     my @fields = ('firstname','middlename','lastname','generation',
10171:                   'permanentemail','id');
10172:     my %newvalues;
10173:     if (ref($candelete) eq 'ARRAY') {
10174:         foreach my $field (@fields) {
10175:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10176:                 if ($field eq 'firstname') {
10177:                     $names{$field} = $first;
10178:                 } elsif ($field eq 'middlename') {
10179:                     $names{$field} = $middle;
10180:                 } elsif ($field eq 'lastname') {
10181:                     $names{$field} = $last;
10182:                 } elsif ($field eq 'generation') { 
10183:                     $names{$field} = $gene;
10184:                 } elsif ($field eq 'permanentemail') {
10185:                     $names{$field} = $email;
10186:                 } elsif ($field eq 'id') {
10187:                     $names{$field}  = $uid;
10188:                 }
10189:             }
10190:         }
10191:     }
10192:     if ($first)  { $names{'firstname'}  = $first; }
10193:     if (defined($middle)) { $names{'middlename'} = $middle; }
10194:     if ($last)   { $names{'lastname'}   = $last; }
10195:     if (defined($gene))   { $names{'generation'} = $gene; }
10196:     if ($email) {
10197:        $email=~s/[^\w\@\.\-\,]//gs;
10198:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10199:     }
10200:     if ($uid) { $names{'id'}  = $uid; }
10201:     if (defined($inststatus)) {
10202:         $names{'inststatus'} = '';
10203:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10204:         if (ref($usertypes) eq 'HASH') {
10205:             my @okstatuses; 
10206:             foreach my $item (split(/:/,$inststatus)) {
10207:                 if (defined($usertypes->{$item})) {
10208:                     push(@okstatuses,$item);  
10209:                 }
10210:             }
10211:             if (@okstatuses) {
10212:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10213:             }
10214:         }
10215:     }
10216:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10217:                  $umode.', '.$first.', '.$middle.', '.
10218:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10219:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10220:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10221:     } else {
10222:         $logmsg .= ' during self creation';
10223:     }
10224:     my $changed;
10225:     if ($newuser) {
10226:         $changed = 1;
10227:     } else {
10228:         foreach my $field (@fields) {
10229:             if ($names{$field} ne $oldnames{$field}) {
10230:                 $changed = 1;
10231:                 last;
10232:             }
10233:         }
10234:     }
10235:     unless ($changed) {
10236:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10237:         &logthis($logmsg);
10238:         return 'ok';
10239:     }
10240:     my $reply = &put('environment', \%names, $udom,$uname);
10241:     if ($reply ne 'ok') { 
10242:         return 'error: '.$reply;
10243:     }
10244:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10245:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10246:     }
10247:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10248:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10249:     $logmsg = 'Success modifying user '.$logmsg;
10250:     &logthis($logmsg);
10251:     return 'ok';
10252: }
10253: 
10254: # -------------------------------------------------------------- Modify student
10255: 
10256: sub modifystudent {
10257:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10258:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10259:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10260:     if (!$cid) {
10261: 	unless ($cid=$env{'request.course.id'}) {
10262: 	    return 'not_in_class';
10263: 	}
10264:     }
10265: # --------------------------------------------------------------- Make the user
10266:     my $reply=&modifyuser
10267: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10268:          $desiredhome,$email,$inststatus);
10269:     unless ($reply eq 'ok') { return $reply; }
10270:     # This will cause &modify_student_enrollment to get the uid from the
10271:     # student's environment
10272:     $uid = undef if (!$forceid);
10273:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10274:                                         $gene,$usec,$end,$start,$type,$locktype,
10275:                                         $cid,$selfenroll,$context,$credits,$instsec);
10276:     return $reply;
10277: }
10278: 
10279: sub modify_student_enrollment {
10280:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10281:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10282:     my ($cdom,$cnum,$chome);
10283:     if (!$cid) {
10284: 	unless ($cid=$env{'request.course.id'}) {
10285: 	    return 'not_in_class';
10286: 	}
10287: 	$cdom=$env{'course.'.$cid.'.domain'};
10288: 	$cnum=$env{'course.'.$cid.'.num'};
10289:     } else {
10290: 	($cdom,$cnum)=split(/_/,$cid);
10291:     }
10292:     $chome=$env{'course.'.$cid.'.home'};
10293:     if (!$chome) {
10294: 	$chome=&homeserver($cnum,$cdom);
10295:     }
10296:     if (!$chome) { return 'unknown_course'; }
10297:     # Make sure the user exists
10298:     my $uhome=&homeserver($uname,$udom);
10299:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10300: 	return 'error: no such user';
10301:     }
10302:     # Get student data if we were not given enough information
10303:     if (!defined($first)  || $first  eq '' || 
10304:         !defined($last)   || $last   eq '' || 
10305:         !defined($uid)    || $uid    eq '' || 
10306:         !defined($middle) || $middle eq '' || 
10307:         !defined($gene)   || $gene   eq '') {
10308:         # They did not supply us with enough data to enroll the student, so
10309:         # we need to pick up more information.
10310:         my %tmp = &get('environment',
10311:                        ['firstname','middlename','lastname', 'generation','id']
10312:                        ,$udom,$uname);
10313: 
10314:         #foreach my $key (keys(%tmp)) {
10315:         #    &logthis("key $key = ".$tmp{$key});
10316:         #}
10317:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10318:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10319:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10320:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10321:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10322:     }
10323:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10324:     my $user = "$uname:$udom";
10325:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10326:     my $reply=cput('classlist',
10327: 		   {$user => 
10328: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10329: 		   $cdom,$cnum);
10330:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10331:         &devalidate_getsection_cache($udom,$uname,$cid);
10332:     } else { 
10333: 	return 'error: '.$reply;
10334:     }
10335:     # Add student role to user
10336:     my $uurl='/'.$cid;
10337:     $uurl=~s/\_/\//g;
10338:     if ($usec) {
10339: 	$uurl.='/'.$usec;
10340:     }
10341:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10342:                              $selfenroll,$context);
10343:     if ($result ne 'ok') {
10344:         if ($old_entry{$user} ne '') {
10345:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10346:         } else {
10347:             $reply = &del('classlist',[$user],$cdom,$cnum);
10348:         }
10349:     }
10350:     return $result; 
10351: }
10352: 
10353: sub format_name {
10354:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10355:     my $name;
10356:     if ($first ne 'lastname') {
10357: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10358:     } else {
10359: 	if ($lastname=~/\S/) {
10360: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10361: 	    $name=~s/\s+,/,/;
10362: 	} else {
10363: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10364: 	}
10365:     }
10366:     $name=~s/^\s+//;
10367:     $name=~s/\s+$//;
10368:     $name=~s/\s+/ /g;
10369:     return $name;
10370: }
10371: 
10372: # ------------------------------------------------- Write to course preferences
10373: 
10374: sub writecoursepref {
10375:     my ($courseid,%prefs)=@_;
10376:     $courseid=~s/^\///;
10377:     $courseid=~s/\_/\//g;
10378:     my ($cdomain,$cnum)=split(/\//,$courseid);
10379:     my $chome=homeserver($cnum,$cdomain);
10380:     if (($chome eq '') || ($chome eq 'no_host')) { 
10381: 	return 'error: no such course';
10382:     }
10383:     my $cstring='';
10384:     foreach my $pref (keys(%prefs)) {
10385: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10386:     }
10387:     $cstring=~s/\&$//;
10388:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10389: }
10390: 
10391: # ---------------------------------------------------------- Make/modify course
10392: 
10393: sub createcourse {
10394:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10395:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10396:     $url=&declutter($url);
10397:     my $cid='';
10398:     if ($context eq 'requestcourses') {
10399:         my $can_create = 0;
10400:         my ($ownername,$ownerdom) = split(':',$course_owner);
10401:         if ($udom eq $ownerdom) {
10402:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10403:                                   $context)) {
10404:                 $can_create = 1;
10405:             }
10406:         } else {
10407:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10408:                                            $category);
10409:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10410:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10411:                 if (@curr > 0) {
10412:                     my @options = qw(approval validate autolimit);
10413:                     my $optregex = join('|',@options);
10414:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10415:                         $can_create = 1;
10416:                     }
10417:                 }
10418:             }
10419:         }
10420:         if ($can_create) {
10421:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10422:                 unless (&allowed('ccc',$udom)) {
10423:                     return 'refused'; 
10424:                 }
10425:             }
10426:         } else {
10427:             return 'refused';
10428:         }
10429:     } elsif (!&allowed('ccc',$udom)) {
10430:         return 'refused';
10431:     }
10432: # --------------------------------------------------------------- Get Unique ID
10433:     my $uname;
10434:     if ($cnum =~ /^$match_courseid$/) {
10435:         my $chome=&homeserver($cnum,$udom,'true');
10436:         if (($chome eq '') || ($chome eq 'no_host')) {
10437:             $uname = $cnum;
10438:         } else {
10439:             $uname = &generate_coursenum($udom,$crstype);
10440:         }
10441:     } else {
10442:         $uname = &generate_coursenum($udom,$crstype);
10443:     }
10444:     return $uname if ($uname =~ /^error/);
10445: # -------------------------------------------------- Check supplied server name
10446:     if (!defined($course_server)) {
10447:         if (defined(&domain($udom,'primary'))) {
10448:             $course_server = &domain($udom,'primary');
10449:         } else {
10450:             $course_server = $env{'user.home'}; 
10451:         }
10452:     }
10453:     my %host_servers =
10454:         &Apache::lonnet::get_servers($udom,'library');
10455:     unless ($host_servers{$course_server}) {
10456:         return 'error: invalid home server for course: '.$course_server;
10457:     }
10458: # ------------------------------------------------------------- Make the course
10459:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10460:                       $course_server);
10461:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10462:     my $uhome=&homeserver($uname,$udom,'true');
10463:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10464: 	return 'error: no such course';
10465:     }
10466: # ----------------------------------------------------------------- Course made
10467: # log existence
10468:     my $now = time;
10469:     my $newcourse = {
10470:                     $udom.'_'.$uname => {
10471:                                      description => $description,
10472:                                      inst_code   => $inst_code,
10473:                                      owner       => $course_owner,
10474:                                      type        => $crstype,
10475:                                      creator     => $env{'user.name'}.':'.
10476:                                                     $env{'user.domain'},
10477:                                      created     => $now,
10478:                                      context     => $context,
10479:                                                 },
10480:                     };
10481:     &courseidput($udom,$newcourse,$uhome,'notime');
10482: # set toplevel url
10483:     my $topurl=$url;
10484:     unless ($nonstandard) {
10485: # ------------------------------------------ For standard courses, make top url
10486:         my $mapurl=&clutter($url);
10487:         if ($mapurl eq '/res/') { $mapurl=''; }
10488:         $env{'form.initmap'}=(<<ENDINITMAP);
10489: <map>
10490: <resource id="1" type="start"></resource>
10491: <resource id="2" src="$mapurl"></resource>
10492: <resource id="3" type="finish"></resource>
10493: <link index="1" from="1" to="2"></link>
10494: <link index="2" from="2" to="3"></link>
10495: </map>
10496: ENDINITMAP
10497:         $topurl=&declutter(
10498:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10499:                           );
10500:     }
10501: # ----------------------------------------------------------- Write preferences
10502:     &writecoursepref($udom.'_'.$uname,
10503:                      ('description'              => $description,
10504:                       'url'                      => $topurl,
10505:                       'internal.creator'         => $env{'user.name'}.':'.
10506:                                                     $env{'user.domain'},
10507:                       'internal.created'         => $now,
10508:                       'internal.creationcontext' => $context)
10509:                     );
10510:     return '/'.$udom.'/'.$uname;
10511: }
10512: 
10513: # ------------------------------------------------------------------- Create ID
10514: sub generate_coursenum {
10515:     my ($udom,$crstype) = @_;
10516:     my $domdesc = &domain($udom);
10517:     return 'error: invalid domain' if ($domdesc eq '');
10518:     my $first;
10519:     if ($crstype eq 'Community') {
10520:         $first = '0';
10521:     } else {
10522:         $first = int(1+rand(9)); 
10523:     } 
10524:     my $uname=$first.
10525:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10526:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10527:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10528: # ----------------------------------------------- Make sure that does not exist
10529:     my $uhome=&homeserver($uname,$udom,'true');
10530:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10531:         if ($crstype eq 'Community') {
10532:             $first = '0';
10533:         } else {
10534:             $first = int(1+rand(9));
10535:         }
10536:         $uname=$first.
10537:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10538:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10539:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10540:         $uhome=&homeserver($uname,$udom,'true');
10541:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10542:             return 'error: unable to generate unique course-ID';
10543:         }
10544:     }
10545:     return $uname;
10546: }
10547: 
10548: sub is_course {
10549:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10550:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10551: 
10552:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10553:     my $uhome=&homeserver($cnum,$cdom);
10554:     my $iscourse;
10555:     if (grep { $_ eq $uhome } current_machine_ids()) {
10556:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10557:     } else {
10558:         my $hashid = $cdom.':'.$cnum;
10559:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10560:         unless (defined($cached)) {
10561:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10562:                                         $cnum,undef,undef,'.');
10563:             $iscourse = 0;
10564:             if (exists($courses{$cdom.'_'.$cnum})) {
10565:                 $iscourse = 1;
10566:             }
10567:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10568:         }
10569:     }
10570:     return unless ($iscourse);
10571:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10572: }
10573: 
10574: sub store_userdata {
10575:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10576:     my $result;
10577:     if ($datakey ne '') {
10578:         if (ref($storehash) eq 'HASH') {
10579:             if ($udom eq '' || $uname eq '') {
10580:                 $udom = $env{'user.domain'};
10581:                 $uname = $env{'user.name'};
10582:             }
10583:             my $uhome=&homeserver($uname,$udom);
10584:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10585:                 $result = 'error: no_host';
10586:             } else {
10587:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10588:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10589: 
10590:                 my $namevalue='';
10591:                 foreach my $key (keys(%{$storehash})) {
10592:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10593:                 }
10594:                 $namevalue=~s/\&$//;
10595:                 unless ($namespace eq 'courserequests') {
10596:                     $datakey = &escape($datakey);
10597:                 }
10598:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10599:                                   $namevalue,$uhome);
10600:             }
10601:         } else {
10602:             $result = 'error: data to store was not a hash reference'; 
10603:         }
10604:     } else {
10605:         $result= 'error: invalid requestkey'; 
10606:     }
10607:     return $result;
10608: }
10609: 
10610: # ---------------------------------------------------------- Assign Custom Role
10611: 
10612: sub assigncustomrole {
10613:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10614:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10615:                        $end,$start,$deleteflag,$selfenroll,$context);
10616: }
10617: 
10618: # ----------------------------------------------------------------- Revoke Role
10619: 
10620: sub revokerole {
10621:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10622:     my $now=time;
10623:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10624: }
10625: 
10626: # ---------------------------------------------------------- Revoke Custom Role
10627: 
10628: sub revokecustomrole {
10629:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10630:     my $now=time;
10631:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10632:            $deleteflag,$selfenroll,$context);
10633: }
10634: 
10635: # ------------------------------------------------------------ Disk usage
10636: sub diskusage {
10637:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10638:     $directorypath =~ s/\/$//;
10639:     my $listing=&reply('du2:'.&escape($directorypath).':'
10640:                        .&escape($getpropath).':'.&escape($uname).':'
10641:                        .&escape($udom),homeserver($uname,$udom));
10642:     if ($listing eq 'unknown_cmd') {
10643:         if ($getpropath) {
10644:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10645:         }
10646:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10647:     }
10648:     return $listing;
10649: }
10650: 
10651: sub is_locked {
10652:     my ($file_name, $domain, $user, $which) = @_;
10653:     my @check;
10654:     my $is_locked;
10655:     push (@check,$file_name);
10656:     my %locked = &get('file_permissions',\@check,
10657: 		      $env{'user.domain'},$env{'user.name'});
10658:     my ($tmp)=keys(%locked);
10659:     if ($tmp=~/^error:/) { undef(%locked); }
10660:     
10661:     if (ref($locked{$file_name}) eq 'ARRAY') {
10662:         $is_locked = 'false';
10663:         foreach my $entry (@{$locked{$file_name}}) {
10664:            if (ref($entry) eq 'ARRAY') {
10665:                $is_locked = 'true';
10666:                if (ref($which) eq 'ARRAY') {
10667:                    push(@{$which},$entry);
10668:                } else {
10669:                    last;
10670:                }
10671:            }
10672:        }
10673:     } else {
10674:         $is_locked = 'false';
10675:     }
10676:     return $is_locked;
10677: }
10678: 
10679: sub declutter_portfile {
10680:     my ($file) = @_;
10681:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10682:     return $file;
10683: }
10684: 
10685: # ------------------------------------------------------------- Mark as Read Only
10686: 
10687: sub mark_as_readonly {
10688:     my ($domain,$user,$files,$what) = @_;
10689:     my %current_permissions = &dump('file_permissions',$domain,$user);
10690:     my ($tmp)=keys(%current_permissions);
10691:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10692:     foreach my $file (@{$files}) {
10693: 	$file = &declutter_portfile($file);
10694:         push(@{$current_permissions{$file}},$what);
10695:     }
10696:     &put('file_permissions',\%current_permissions,$domain,$user);
10697:     return;
10698: }
10699: 
10700: # ------------------------------------------------------------Save Selected Files
10701: 
10702: sub save_selected_files {
10703:     my ($user, $path, @files) = @_;
10704:     my $filename = $user."savedfiles";
10705:     my @other_files = &files_not_in_path($user, $path);
10706:     open (OUT,'>',LONCAPA::tempdir().$filename);
10707:     foreach my $file (@files) {
10708:         print (OUT $env{'form.currentpath'}.$file."\n");
10709:     }
10710:     foreach my $file (@other_files) {
10711:         print (OUT $file."\n");
10712:     }
10713:     close (OUT);
10714:     return 'ok';
10715: }
10716: 
10717: sub clear_selected_files {
10718:     my ($user) = @_;
10719:     my $filename = $user."savedfiles";
10720:     open (OUT,'>',LONCAPA::tempdir().$filename);
10721:     print (OUT undef);
10722:     close (OUT);
10723:     return ("ok");    
10724: }
10725: 
10726: sub files_in_path {
10727:     my ($user, $path) = @_;
10728:     my $filename = $user."savedfiles";
10729:     my %return_files;
10730:     open (IN,'<',LONCAPA::tempdir().$filename);
10731:     while (my $line_in = <IN>) {
10732:         chomp ($line_in);
10733:         my @paths_and_file = split (m!/!, $line_in);
10734:         my $file_part = pop (@paths_and_file);
10735:         my $path_part = join ('/', @paths_and_file);
10736:         $path_part.='/';
10737:         my $path_and_file = $path_part.$file_part;
10738:         if ($path_part eq $path) {
10739:             $return_files{$file_part}= 'selected';
10740:         }
10741:     }
10742:     close (IN);
10743:     return (\%return_files);
10744: }
10745: 
10746: # called in portfolio select mode, to show files selected NOT in current directory
10747: sub files_not_in_path {
10748:     my ($user, $path) = @_;
10749:     my $filename = $user."savedfiles";
10750:     my @return_files;
10751:     my $path_part;
10752:     open(IN, '<',LONCAPA::tempdir().$filename);
10753:     while (my $line = <IN>) {
10754:         #ok, I know it's clunky, but I want it to work
10755:         my @paths_and_file = split(m|/|, $line);
10756:         my $file_part = pop(@paths_and_file);
10757:         chomp($file_part);
10758:         my $path_part = join('/', @paths_and_file);
10759:         $path_part .= '/';
10760:         my $path_and_file = $path_part.$file_part;
10761:         if ($path_part ne $path) {
10762:             push(@return_files, ($path_and_file));
10763:         }
10764:     }
10765:     close(OUT);
10766:     return (@return_files);
10767: }
10768: 
10769: #------------------------------Submitted/Handedback Portfolio Files Versioning
10770:  
10771: sub portfiles_versioning {
10772:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10773:     my $portfolio_root = '/userfiles/portfolio';
10774:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10775:     foreach my $file (@{$portfiles}) {
10776:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10777:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10778:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10779:         my $getpropath = 1;
10780:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10781:                                              $stu_name,$getpropath);
10782:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10783:         my $new_answer = 
10784:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10785:         if ($new_answer ne 'problem getting file') {
10786:             push(@{$versioned_portfiles}, $directory.$new_answer);
10787:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10788:                               [$symb,$env{'request.course.id'},'graded']);
10789:         }
10790:     }
10791: }
10792: 
10793: sub get_next_version {
10794:     my ($answer_name, $answer_ext, $dir_list) = @_;
10795:     my $version;
10796:     if (ref($dir_list) eq 'ARRAY') {
10797:         foreach my $row (@{$dir_list}) {
10798:             my ($file) = split(/\&/,$row,2);
10799:             my ($file_name,$file_version,$file_ext) =
10800:                 &file_name_version_ext($file);
10801:             if (($file_name eq $answer_name) &&
10802:                 ($file_ext eq $answer_ext)) {
10803:                      # gets here if filename and extension match,
10804:                      # regardless of version
10805:                 if ($file_version ne '') {
10806:                     # a versioned file is found  so save it for later
10807:                     if ($file_version > $version) {
10808:                         $version = $file_version;
10809:                     }
10810:                 }
10811:             }
10812:         }
10813:     }
10814:     $version ++;
10815:     return($version);
10816: }
10817: 
10818: sub version_selected_portfile {
10819:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10820:     my ($answer_name,$answer_ver,$answer_ext) =
10821:         &file_name_version_ext($file_name);
10822:     my $new_answer;
10823:     $env{'form.copy'} =
10824:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10825:     if($env{'form.copy'} eq '-1') {
10826:         $new_answer = 'problem getting file';
10827:     } else {
10828:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10829:         my $copy_result = 
10830:             &finishuserfileupload($stu_name,$domain,'copy',
10831:                                   '/portfolio'.$directory.$new_answer);
10832:     }
10833:     undef($env{'form.copy'});
10834:     return ($new_answer);
10835: }
10836: 
10837: sub file_name_version_ext {
10838:     my ($file)=@_;
10839:     my @file_parts = split(/\./, $file);
10840:     my ($name,$version,$ext);
10841:     if (@file_parts > 1) {
10842:         $ext=pop(@file_parts);
10843:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10844:             $version=pop(@file_parts);
10845:         }
10846:         $name=join('.',@file_parts);
10847:     } else {
10848:         $name=join('.',@file_parts);
10849:     }
10850:     return($name,$version,$ext);
10851: }
10852: 
10853: #----------------------------------------------Get portfolio file permissions
10854: 
10855: sub get_portfile_permissions {
10856:     my ($domain,$user) = @_;
10857:     my %current_permissions = &dump('file_permissions',$domain,$user);
10858:     my ($tmp)=keys(%current_permissions);
10859:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10860:     return \%current_permissions;
10861: }
10862: 
10863: #---------------------------------------------Get portfolio file access controls
10864: 
10865: sub get_access_controls {
10866:     my ($current_permissions,$group,$file) = @_;
10867:     my %access;
10868:     my $real_file = $file;
10869:     $file =~ s/\.meta$//;
10870:     if (defined($file)) {
10871:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10872:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10873:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10874:             }
10875:         }
10876:     } else {
10877:         foreach my $key (keys(%{$current_permissions})) {
10878:             if ($key =~ /\0accesscontrol$/) {
10879:                 if (defined($group)) {
10880:                     if ($key !~ m-^\Q$group\E/-) {
10881:                         next;
10882:                     }
10883:                 }
10884:                 my ($fullpath) = split(/\0/,$key);
10885:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10886:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10887:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10888:                     }
10889:                 }
10890:             }
10891:         }
10892:     }
10893:     return %access;
10894: }
10895: 
10896: sub modify_access_controls {
10897:     my ($file_name,$changes,$domain,$user)=@_;
10898:     my ($outcome,$deloutcome);
10899:     my %store_permissions;
10900:     my %new_values;
10901:     my %new_control;
10902:     my %translation;
10903:     my @deletions = ();
10904:     my $now = time;
10905:     if (exists($$changes{'activate'})) {
10906:         if (ref($$changes{'activate'}) eq 'HASH') {
10907:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10908:             my $numnew = scalar(@newitems);
10909:             for (my $i=0; $i<$numnew; $i++) {
10910:                 my $newkey = $newitems[$i];
10911:                 my $newid = &Apache::loncommon::get_cgi_id();
10912:                 if ($newkey =~ /^\d+:/) { 
10913:                     $newkey =~ s/^(\d+)/$newid/;
10914:                     $translation{$1} = $newid;
10915:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10916:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10917:                     $translation{$1} = $newid;
10918:                 }
10919:                 $new_values{$file_name."\0".$newkey} = 
10920:                                           $$changes{'activate'}{$newitems[$i]};
10921:                 $new_control{$newkey} = $now;
10922:             }
10923:         }
10924:     }
10925:     my %todelete;
10926:     my %changed_items;
10927:     foreach my $action ('delete','update') {
10928:         if (exists($$changes{$action})) {
10929:             if (ref($$changes{$action}) eq 'HASH') {
10930:                 foreach my $key (keys(%{$$changes{$action}})) {
10931:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10932:                     if ($action eq 'delete') { 
10933:                         $todelete{$itemnum} = 1;
10934:                     } else {
10935:                         $changed_items{$itemnum} = $key;
10936:                     }
10937:                 }
10938:             }
10939:         }
10940:     }
10941:     # get lock on access controls for file.
10942:     my $lockhash = {
10943:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10944:                                                        ':'.$env{'user.domain'},
10945:                    }; 
10946:     my $tries = 0;
10947:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10948:    
10949:     while (($gotlock ne 'ok') && $tries < 10) {
10950:         $tries ++;
10951:         sleep(0.1);
10952:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10953:     }
10954:     if ($gotlock eq 'ok') {
10955:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10956:         my ($tmp)=keys(%curr_permissions);
10957:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10958:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10959:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10960:             if (ref($curr_controls) eq 'HASH') {
10961:                 foreach my $control_item (keys(%{$curr_controls})) {
10962:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10963:                     if (defined($todelete{$itemnum})) {
10964:                         push(@deletions,$file_name."\0".$control_item);
10965:                     } else {
10966:                         if (defined($changed_items{$itemnum})) {
10967:                             $new_control{$changed_items{$itemnum}} = $now;
10968:                             push(@deletions,$file_name."\0".$control_item);
10969:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10970:                         } else {
10971:                             $new_control{$control_item} = $$curr_controls{$control_item};
10972:                         }
10973:                     }
10974:                 }
10975:             }
10976:         }
10977:         my ($group);
10978:         if (&is_course($domain,$user)) {
10979:             ($group,my $file) = split(/\//,$file_name,2);
10980:         }
10981:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10982:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10983:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10984:         #  remove lock
10985:         my @del_lock = ($file_name."\0".'locked_access_records');
10986:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10987:         my $sqlresult =
10988:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10989:                                     $group);
10990:     } else {
10991:         $outcome = "error: could not obtain lockfile\n";  
10992:     }
10993:     return ($outcome,$deloutcome,\%new_values,\%translation);
10994: }
10995: 
10996: sub make_public_indefinitely {
10997:     my (@requrl) = @_;
10998:     return &automated_portfile_access('public',\@requrl);
10999: }
11000: 
11001: sub automated_portfile_access {
11002:     my ($accesstype,$addsref,$delsref,$info) = @_;
11003:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11004:         return 'invalid';
11005:     }
11006:     my %urls;
11007:     if (ref($addsref) eq 'ARRAY') {
11008:         foreach my $requrl (@{$addsref}) {
11009:             if (&is_portfolio_url($requrl)) {
11010:                 unless (exists($urls{$requrl})) {
11011:                     $urls{$requrl} = 'add';
11012:                 }
11013:             }
11014:         }
11015:     }
11016:     if (ref($delsref) eq 'ARRAY') {
11017:         foreach my $requrl (@{$delsref}) { 
11018:             if (&is_portfolio_url($requrl)) {
11019:                 unless (exists($urls{$requrl})) {
11020:                     $urls{$requrl} = 'delete'; 
11021:                 }
11022:             }
11023:         }
11024:     }
11025:     unless (keys(%urls)) {
11026:         return 'invalid';
11027:     }
11028:     my $ip;
11029:     if ($accesstype eq 'ip') {
11030:         if (ref($info) eq 'HASH') {
11031:             if ($info->{'ip'} ne '') {
11032:                 $ip = $info->{'ip'};
11033:             }
11034:         }
11035:         if ($ip eq '') {
11036:             return 'invalid';
11037:         }
11038:     }
11039:     my $errors;
11040:     my $now = time;
11041:     my %current_perms;
11042:     foreach my $requrl (sort(keys(%urls))) {
11043:         my $action;
11044:         if ($urls{$requrl} eq 'add') {
11045:             $action = 'activate';
11046:         } else {
11047:             $action = 'none';
11048:         }
11049:         my $aclnum = 0;
11050:         my (undef,$udom,$unum,$file_name,$group) =
11051:             &parse_portfolio_url($requrl);
11052:         unless (exists($current_perms{$unum.':'.$udom})) {
11053:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11054:         }
11055:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11056:                                                    $group,$file_name);
11057:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11058:             my ($num,$scope,$end,$start) = 
11059:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11060:             if ($scope eq $accesstype) {
11061:                 if (($start <= $now) && ($end == 0)) {
11062:                     if ($accesstype eq 'ip') {
11063:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11064:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11065:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11066:                                     if ($urls{$requrl} eq 'add') {
11067:                                         $action = 'none';
11068:                                         last;
11069:                                     } else {
11070:                                         $action = 'delete';
11071:                                         $aclnum = $num;
11072:                                         last;
11073:                                     }
11074:                                 }
11075:                             }
11076:                         }
11077:                     } elsif ($accesstype eq 'public') {
11078:                         if ($urls{$requrl} eq 'add') {
11079:                             $action = 'none';
11080:                             last;
11081:                         } else {
11082:                             $action = 'delete';
11083:                             $aclnum = $num;
11084:                             last;
11085:                         }
11086:                     }
11087:                 } elsif ($accesstype eq 'public') {
11088:                     $action = 'update';
11089:                     $aclnum = $num;
11090:                     last;
11091:                 }
11092:             }
11093:         }
11094:         if ($action eq 'none') {
11095:             next;
11096:         } else {
11097:             my %changes;
11098:             my $newend = 0;
11099:             my $newstart = $now;
11100:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11101:             $changes{$action}{$newkey} = {
11102:                 type => $accesstype,
11103:                 time => {
11104:                     start => $newstart,
11105:                     end   => $newend,
11106:                 },
11107:             };
11108:             if ($accesstype eq 'ip') {
11109:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11110:             }
11111:             my ($outcome,$deloutcome,$new_values,$translation) =
11112:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11113:             unless ($outcome eq 'ok') {
11114:                 $errors .= $outcome.' ';
11115:             }
11116:         }
11117:     }
11118:     if ($errors) {
11119:         $errors =~ s/\s$//;
11120:         return $errors;
11121:     } else {
11122:         return 'ok';
11123:     }
11124: }
11125: 
11126: #------------------------------------------------------Get Marked as Read Only
11127: 
11128: sub get_marked_as_readonly {
11129:     my ($domain,$user,$what,$group) = @_;
11130:     my $current_permissions = &get_portfile_permissions($domain,$user);
11131:     my @readonly_files;
11132:     my $cmp1=$what;
11133:     if (ref($what)) { $cmp1=join('',@{$what}) };
11134:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11135:         if (defined($group)) {
11136:             if ($file_name !~ m-^\Q$group\E/-) {
11137:                 next;
11138:             }
11139:         }
11140:         if (ref($value) eq "ARRAY"){
11141:             foreach my $stored_what (@{$value}) {
11142:                 my $cmp2=$stored_what;
11143:                 if (ref($stored_what) eq 'ARRAY') {
11144:                     $cmp2=join('',@{$stored_what});
11145:                 }
11146:                 if ($cmp1 eq $cmp2) {
11147:                     push(@readonly_files, $file_name);
11148:                     last;
11149:                 } elsif (!defined($what)) {
11150:                     push(@readonly_files, $file_name);
11151:                     last;
11152:                 }
11153:             }
11154:         }
11155:     }
11156:     return @readonly_files;
11157: }
11158: #-----------------------------------------------------------Get Marked as Read Only Hash
11159: 
11160: sub get_marked_as_readonly_hash {
11161:     my ($current_permissions,$group,$what) = @_;
11162:     my %readonly_files;
11163:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11164:         if (defined($group)) {
11165:             if ($file_name !~ m-^\Q$group\E/-) {
11166:                 next;
11167:             }
11168:         }
11169:         if (ref($value) eq "ARRAY"){
11170:             foreach my $stored_what (@{$value}) {
11171:                 if (ref($stored_what) eq 'ARRAY') {
11172:                     foreach my $lock_descriptor(@{$stored_what}) {
11173:                         if ($lock_descriptor eq 'graded') {
11174:                             $readonly_files{$file_name} = 'graded';
11175:                         } elsif ($lock_descriptor eq 'handback') {
11176:                             $readonly_files{$file_name} = 'handback';
11177:                         } else {
11178:                             if (!exists($readonly_files{$file_name})) {
11179:                                 $readonly_files{$file_name} = 'locked';
11180:                             }
11181:                         }
11182:                     }
11183:                 } 
11184:             }
11185:         } 
11186:     }
11187:     return %readonly_files;
11188: }
11189: # ------------------------------------------------------------ Unmark as Read Only
11190: 
11191: sub unmark_as_readonly {
11192:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11193:     # for portfolio submissions, $what contains [$symb,$crsid] 
11194:     my ($domain,$user,$what,$file_name,$group) = @_;
11195:     $file_name = &declutter_portfile($file_name);
11196:     my $symb_crs = $what;
11197:     if (ref($what)) { $symb_crs=join('',@$what); }
11198:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11199:     my ($tmp)=keys(%current_permissions);
11200:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11201:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11202:     foreach my $file (@readonly_files) {
11203: 	my $clean_file = &declutter_portfile($file);
11204: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11205: 	my $current_locks = $current_permissions{$file};
11206:         my @new_locks;
11207:         my @del_keys;
11208:         if (ref($current_locks) eq "ARRAY"){
11209:             foreach my $locker (@{$current_locks}) {
11210:                 my $compare=$locker;
11211:                 if (ref($locker) eq 'ARRAY') {
11212:                     $compare=join('',@{$locker});
11213:                     if ($compare ne $symb_crs) {
11214:                         push(@new_locks, $locker);
11215:                     }
11216:                 }
11217:             }
11218:             if (scalar(@new_locks) > 0) {
11219:                 $current_permissions{$file} = \@new_locks;
11220:             } else {
11221:                 push(@del_keys, $file);
11222:                 &del('file_permissions',\@del_keys, $domain, $user);
11223:                 delete($current_permissions{$file});
11224:             }
11225:         }
11226:     }
11227:     &put('file_permissions',\%current_permissions,$domain,$user);
11228:     return;
11229: }
11230: 
11231: # ------------------------------------------------------------ Directory lister
11232: 
11233: sub dirlist {
11234:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11235:     $uri=~s/^\///;
11236:     $uri=~s/\/$//;
11237:     my ($udom, $uname);
11238:     if ($getuserdir) {
11239:         $udom = $userdomain;
11240:         $uname = $username;
11241:     } else {
11242:         (undef,$udom,$uname)=split(/\//,$uri);
11243:         if(defined($userdomain)) {
11244:             $udom = $userdomain;
11245:         }
11246:         if(defined($username)) {
11247:             $uname = $username;
11248:         }
11249:     }
11250:     my ($dirRoot,$listing,@listing_results);
11251: 
11252:     $dirRoot = $perlvar{'lonDocRoot'};
11253:     if (defined($getpropath)) {
11254:         $dirRoot = &propath($udom,$uname);
11255:         $dirRoot =~ s/\/$//;
11256:     } elsif (defined($getuserdir)) {
11257:         my $subdir=$uname.'__';
11258:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11259:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11260:                    ."/$udom/$subdir/$uname";
11261:     } elsif (defined($alternateRoot)) {
11262:         $dirRoot = $alternateRoot;
11263:     }
11264: 
11265:     if($udom) {
11266:         if($uname) {
11267:             my $uhome = &homeserver($uname,$udom);
11268:             if ($uhome eq 'no_host') {
11269:                 return ([],'no_host');
11270:             }
11271:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11272:                               .$getuserdir.':'.&escape($dirRoot)
11273:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11274:             if ($listing eq 'unknown_cmd') {
11275:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11276:             } else {
11277:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11278:             }
11279:             if ($listing eq 'unknown_cmd') {
11280:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11281:                 @listing_results = split(/:/,$listing);
11282:             } else {
11283:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11284:             }
11285:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11286:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11287:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11288:                 return ([],$listing);
11289:             } else {
11290:                 return (\@listing_results);
11291:             }
11292:         } elsif(!$alternateRoot) {
11293:             my (%allusers,%listerror);
11294: 	    my %servers = &get_servers($udom,'library');
11295:  	    foreach my $tryserver (keys(%servers)) {
11296:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11297:                                   &escape($udom),$tryserver);
11298:                 if ($listing eq 'unknown_cmd') {
11299: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11300: 				      $udom, $tryserver);
11301:                 } else {
11302:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11303:                 }
11304: 		if ($listing eq 'unknown_cmd') {
11305: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11306: 				      $udom, $tryserver);
11307: 		    @listing_results = split(/:/,$listing);
11308: 		} else {
11309: 		    @listing_results =
11310: 			map { &unescape($_); } split(/:/,$listing);
11311: 		}
11312:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11313:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11314:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11315:                     $listerror{$tryserver} = $listing;
11316:                 } else {
11317: 		    foreach my $line (@listing_results) {
11318: 			my ($entry) = split(/&/,$line,2);
11319: 			$allusers{$entry} = 1;
11320: 		    }
11321: 		}
11322:             }
11323:             my @alluserslist=();
11324:             foreach my $user (sort(keys(%allusers))) {
11325:                 push(@alluserslist,$user.'&user');
11326:             }
11327: 
11328:             if (!%listerror) {
11329:                 # no errors
11330:                 return (\@alluserslist);
11331:             } elsif (scalar(keys(%servers)) == 1) {
11332:                 # one library server, one error 
11333:                 my ($key) = keys(%listerror);
11334:                 return (\@alluserslist, $listerror{$key});
11335:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11336:                 # con_lost indicates that we might miss data from at least one
11337:                 # library server
11338:                 return (\@alluserslist, 'con_lost');
11339:             } else {
11340:                 # multiple library servers and no con_lost -> data should be
11341:                 # complete. 
11342:                 return (\@alluserslist);
11343:             }
11344: 
11345:         } else {
11346:             return ([],'missing username');
11347:         }
11348:     } elsif(!defined($getpropath)) {
11349:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11350:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11351:         return (\@all_domains);
11352:     } else {
11353:         return ([],'missing domain');
11354:     }
11355: }
11356: 
11357: # --------------------------------------------- GetFileTimestamp
11358: # This function utilizes dirlist and returns the date stamp for
11359: # when it was last modified.  It will also return an error of -1
11360: # if an error occurs
11361: 
11362: sub GetFileTimestamp {
11363:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11364:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11365:     $studentName   = &LONCAPA::clean_username($studentName);
11366:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11367:                                     undef,$getuserdir);
11368:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11369:         return -1;
11370:     }
11371:     if (ref($fileref) eq 'ARRAY') {
11372:         my @stats = split('&',$fileref->[0]);
11373:         # @stats contains first the filename, then the stat output
11374:         return $stats[10]; # so this is 10 instead of 9.
11375:     } else {
11376:         return -1;
11377:     }
11378: }
11379: 
11380: sub stat_file {
11381:     my ($uri) = @_;
11382:     $uri = &clutter_with_no_wrapper($uri);
11383: 
11384:     my ($udom,$uname,$file);
11385:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11386: 	($udom,$uname,$file) =
11387: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11388: 	$file = 'userfiles/'.$file;
11389:     }
11390:     if ($uri =~ m-^/res/-) {
11391: 	($udom,$uname) = 
11392: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11393: 	$file = $uri;
11394:     }
11395: 
11396:     if (!$udom || !$uname || !$file) {
11397: 	# unable to handle the uri
11398: 	return ();
11399:     }
11400:     my $getpropath;
11401:     if ($file =~ /^userfiles\//) {
11402:         $getpropath = 1;
11403:     }
11404:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11405:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11406:         return ();
11407:     } else {
11408:         if (ref($listref) eq 'ARRAY') {
11409:             my @stats = split('&',$listref->[0]);
11410: 	    shift(@stats); #filename is first
11411: 	    return @stats;
11412:         }
11413:     }
11414:     return ();
11415: }
11416: 
11417: # --------------------------------------------------------- recursedirs
11418: # Recursive function to traverse either a specific user's Authoring Space
11419: # or corresponding Published Resource Space, and populate the hash ref:
11420: # $dirhashref with URLs of all directories, and if $filehashref hash
11421: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11422: # or .rights files in resource space, and .meta, .save, .log, and .bak
11423: # files in Authoring Space.
11424: #
11425: # Inputs:
11426: #
11427: # $is_home - true if current server is home server for user's space
11428: # $context - either: priv, or res respectively for Authoring or Resource Space.
11429: # $docroot - Document root (i.e., /home/httpd/html
11430: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11431: # $relpath - Current path (relative to top level).
11432: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11433: # $filehashref - reference to hash to populate with URLs of files (Optional)
11434: #
11435: # Returns: nothing
11436: #
11437: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11438: #
11439: # Currently used by interface/londocs.pm to create linked select boxes for
11440: # directory and filename to import a Course "Author" resource into a course, and
11441: # also to create linked select boxes for Authoring Space and Directory to choose
11442: # save location for creation of a new "standard" problem from the Course Editor.
11443: #
11444: 
11445: sub recursedirs {
11446:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11447:     return unless (ref($dirhashref) eq 'HASH');
11448:     my $currpath = $docroot.$toppath;
11449:     if ($relpath) {
11450:         $currpath .= "/$relpath";
11451:     }
11452:     my $savefile;
11453:     if (ref($filehashref)) {
11454:         $savefile = 1;
11455:     }
11456:     if ($is_home) {
11457:         if (opendir(my $dirh,$currpath)) {
11458:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11459:                 next if ($item eq '');
11460:                 if (-d "$currpath/$item") {
11461:                     my $newpath;
11462:                     if ($relpath) {
11463:                         $newpath = "$relpath/$item";
11464:                     } else {
11465:                         $newpath = $item;
11466:                     }
11467:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11468:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11469:                 } elsif ($savefile) {
11470:                     if ($context eq 'priv') {
11471:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11472:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11473:                         }
11474:                     } else {
11475:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11476:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11477:                         }
11478:                     }
11479:                 }
11480:             }
11481:             closedir($dirh);
11482:         }
11483:     } else {
11484:         my ($dirlistref,$listerror) =
11485:             &dirlist($toppath.$relpath);
11486:         my @dir_lines;
11487:         my $dirptr=16384;
11488:         if (ref($dirlistref) eq 'ARRAY') {
11489:             foreach my $dir_line (sort
11490:                               {
11491:                                   my ($afile)=split('&',$a,2);
11492:                                   my ($bfile)=split('&',$b,2);
11493:                                   return (lc($afile) cmp lc($bfile));
11494:                               } (@{$dirlistref})) {
11495:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11496:                     split(/\&/,$dir_line,16);
11497:                 $item =~ s/\s+$//;
11498:                 next if (($item =~ /^\.\.?$/) || ($obs));
11499:                 if ($dirptr&$testdir) {
11500:                     my $newpath;
11501:                     if ($relpath) {
11502:                         $newpath = "$relpath/$item";
11503:                     } else {
11504:                         $relpath = '/';
11505:                         $newpath = $item;
11506:                     }
11507:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11508:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11509:                 } elsif ($savefile) {
11510:                     if ($context eq 'priv') {
11511:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11512:                             $filehashref->{$relpath}{$item} = 1;
11513:                         }
11514:                     } else {
11515:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11516:                             $filehashref->{$relpath}{$item} = 1;
11517:                         }
11518:                     }
11519:                 }
11520:             }
11521:         }
11522:     }
11523:     return;
11524: }
11525: 
11526: # -------------------------------------------------------- Value of a Condition
11527: 
11528: # gets the value of a specific preevaluated condition
11529: #    stored in the string  $env{user.state.<cid>}
11530: # or looks up a condition reference in the bighash and if if hasn't
11531: # already been evaluated recurses into docondval to get the value of
11532: # the condition, then memoizing it to 
11533: #   $env{user.state.<cid>.<condition>}
11534: sub directcondval {
11535:     my $number=shift;
11536:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11537: 	&Apache::lonuserstate::evalstate();
11538:     }
11539:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11540: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11541:     } elsif ($number =~ /^_/) {
11542: 	my $sub_condition;
11543: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11544: 		&GDBM_READER(),0640)) {
11545: 	    $sub_condition=$bighash{'conditions'.$number};
11546: 	    untie(%bighash);
11547: 	}
11548: 	my $value = &docondval($sub_condition);
11549: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11550: 	return $value;
11551:     }
11552:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11553:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11554:     } else {
11555:        return 2;
11556:     }
11557: }
11558: 
11559: # get the collection of conditions for this resource
11560: sub condval {
11561:     my $condidx=shift;
11562:     my $allpathcond='';
11563:     foreach my $cond (split(/\|/,$condidx)) {
11564: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11565: 	    $allpathcond.=
11566: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11567: 	}
11568:     }
11569:     $allpathcond=~s/\|$//;
11570:     return &docondval($allpathcond);
11571: }
11572: 
11573: #evaluates an expression of conditions
11574: sub docondval {
11575:     my ($allpathcond) = @_;
11576:     my $result=0;
11577:     if ($env{'request.course.id'}
11578: 	&& defined($allpathcond)) {
11579: 	my $operand='|';
11580: 	my @stack;
11581: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11582: 	    if ($chunk eq '(') {
11583: 		push @stack,($operand,$result);
11584: 	    } elsif ($chunk eq ')') {
11585: 		my $before=pop @stack;
11586: 		if (pop @stack eq '&') {
11587: 		    $result=$result>$before?$before:$result;
11588: 		} else {
11589: 		    $result=$result>$before?$result:$before;
11590: 		}
11591: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11592: 		$operand=$chunk;
11593: 	    } else {
11594: 		my $new=directcondval($chunk);
11595: 		if ($operand eq '&') {
11596: 		    $result=$result>$new?$new:$result;
11597: 		} else {
11598: 		    $result=$result>$new?$result:$new;
11599: 		}
11600: 	    }
11601: 	}
11602:     }
11603:     return $result;
11604: }
11605: 
11606: # ---------------------------------------------------- Devalidate courseresdata
11607: 
11608: sub devalidatecourseresdata {
11609:     my ($coursenum,$coursedomain)=@_;
11610:     my $hashid=$coursenum.':'.$coursedomain;
11611:     &devalidate_cache_new('courseres',$hashid);
11612: }
11613: 
11614: 
11615: # --------------------------------------------------- Course Resourcedata Query
11616: #
11617: #  Parameters:
11618: #      $coursenum    - Number of the course.
11619: #      $coursedomain - Domain at which the course was created.
11620: #  Returns:
11621: #     A hash of the course parameters along (I think) with timestamps
11622: #     and version info.
11623: 
11624: sub get_courseresdata {
11625:     my ($coursenum,$coursedomain)=@_;
11626:     my $coursehom=&homeserver($coursenum,$coursedomain);
11627:     my $hashid=$coursenum.':'.$coursedomain;
11628:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11629:     my %dumpreply;
11630:     unless (defined($cached)) {
11631: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11632: 	$result=\%dumpreply;
11633: 	my ($tmp) = keys(%dumpreply);
11634: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11635: 	    &do_cache_new('courseres',$hashid,$result,600);
11636: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11637: 	    return $tmp;
11638: 	} elsif ($tmp =~ /^(error)/) {
11639: 	    $result=undef;
11640: 	    &do_cache_new('courseres',$hashid,$result,600);
11641: 	}
11642:     }
11643:     return $result;
11644: }
11645: 
11646: sub devalidateuserresdata {
11647:     my ($uname,$udom)=@_;
11648:     my $hashid="$udom:$uname";
11649:     &devalidate_cache_new('userres',$hashid);
11650: }
11651: 
11652: sub get_userresdata {
11653:     my ($uname,$udom)=@_;
11654:     #most student don\'t have any data set, check if there is some data
11655:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11656: 
11657:     my $hashid="$udom:$uname";
11658:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11659:     if (!defined($cached)) {
11660: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11661: 	$result=\%resourcedata;
11662: 	&do_cache_new('userres',$hashid,$result,600);
11663:     }
11664:     my ($tmp)=keys(%$result);
11665:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11666: 	return $result;
11667:     }
11668:     #error 2 occurs when the .db doesn't exist
11669:     if ($tmp!~/error: 2 /) {
11670:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11671: 	    &logthis("<font color=\"blue\">WARNING:".
11672: 		     " Trying to get resource data for ".
11673: 		     $uname." at ".$udom.": ".
11674: 		     $tmp."</font>");
11675:         }
11676:     } elsif ($tmp=~/error: 2 /) {
11677: 	#&EXT_cache_set($udom,$uname);
11678: 	&do_cache_new('userres',$hashid,undef,600);
11679: 	undef($tmp); # not really an error so don't send it back
11680:     }
11681:     return $tmp;
11682: }
11683: #----------------------------------------------- resdata - return resource data
11684: #  Purpose:
11685: #    Return resource data for either users or for a course.
11686: #  Parameters:
11687: #     $name      - Course/user name.
11688: #     $domain    - Name of the domain the user/course is registered on.
11689: #     $type      - Type of thing $name is (must be 'course' or 'user')
11690: #     $mapp      - decluttered URL of enclosing map  
11691: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11692: #     $recurseup - Ref to array of map URLs, starting with map containing
11693: #                  $mapp up through hierarchy of nested maps to top level map.  
11694: #     $courseid  - CourseID (first part of param identifier).
11695: #     $modifier  - Middle part of param identifier.
11696: #     $what      - Last part of param identifier.
11697: #     @which     - Array of names of resources desired.
11698: #  Returns:
11699: #     The value of the first reasource in @which that is found in the
11700: #     resource hash.
11701: #  Exceptional Conditions:
11702: #     If the $type passed in is not valid (not the string 'course' or 
11703: #     'user', an undefined  reference is returned.
11704: #     If none of the resources are found, an undef is returned
11705: sub resdata {
11706:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11707:         $modifier,$what,@which)=@_;
11708:     my $result;
11709:     if ($type eq 'course') {
11710: 	$result=&get_courseresdata($name,$domain);
11711:     } elsif ($type eq 'user') {
11712: 	$result=&get_userresdata($name,$domain);
11713:     }
11714:     if (!ref($result)) { return $result; }    
11715:     foreach my $item (@which) {
11716:         if ($item->[1] eq 'course') {
11717:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11718:                 unless ($$recursed) {
11719:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11720:                     $$recursed = 1;
11721:                 }
11722:                 foreach my $item (@${recurseup}) {
11723:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11724:                     last if (defined($result->{$norecursechk}));
11725:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11726:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11727:                 }
11728:             }
11729:         }
11730:         if (defined($result->{$item->[0]})) {
11731: 	    return [$result->{$item->[0]},$item->[1]];
11732: 	}
11733:     }
11734:     return undef;
11735: }
11736: 
11737: sub get_domain_lti {
11738:     my ($cdom,$context) = @_;
11739:     my ($name,%lti);
11740:     if ($context eq 'consumer') {
11741:         $name = 'ltitools';
11742:     } elsif ($context eq 'provider') {
11743:         $name = 'lti';
11744:     } else {
11745:         return %lti;
11746:     }
11747:     my ($result,$cached)=&is_cached_new($name,$cdom);
11748:     if (defined($cached)) {
11749:         if (ref($result) eq 'HASH') {
11750:             %lti = %{$result};
11751:         }
11752:     } else {
11753:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11754:         if (ref($domconfig{$name}) eq 'HASH') {
11755:             %lti = %{$domconfig{$name}};
11756:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11757:             if (ref($encdomconfig{$name}) eq 'HASH') {
11758:                 foreach my $id (keys(%lti)) {
11759:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11760:                         foreach my $item ('key','secret') {
11761:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11762:                         }
11763:                     }
11764:                 }
11765:             }
11766:         }
11767:         my $cachetime = 24*60*60;
11768:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11769:     }
11770:     return %lti;
11771: }
11772: 
11773: sub get_numsuppfiles {
11774:     my ($cnum,$cdom,$ignorecache)=@_;
11775:     my $hashid=$cnum.':'.$cdom;
11776:     my ($suppcount,$cached);
11777:     unless ($ignorecache) {
11778:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11779:     }
11780:     unless (defined($cached)) {
11781:         my $chome=&homeserver($cnum,$cdom);
11782:         unless ($chome eq 'no_host') {
11783:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11784:             my $suppmap = 'supplemental.sequence';
11785:             ($suppcount,$supptools,$errors) =
11786:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11787:                                                          $supptools,$errors);
11788:         }
11789:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11790:     }
11791:     return $suppcount;
11792: }
11793: 
11794: #
11795: # EXT resource caching routines
11796: #
11797: 
11798: {
11799: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11800: #
11801: # The course for which we cache
11802: my $cachedmapkey='';
11803: # The cached recursive maps for this course
11804: my %cachedmaps=();
11805: # When this was last done
11806: my $cachedmaptime='';
11807: 
11808: sub clear_EXT_cache_status {
11809:     &delenv('cache.EXT.');
11810: }
11811: 
11812: sub EXT_cache_status {
11813:     my ($target_domain,$target_user) = @_;
11814:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11815:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11816:         # We know already the user has no data
11817:         return 1;
11818:     } else {
11819:         return 0;
11820:     }
11821: }
11822: 
11823: sub EXT_cache_set {
11824:     my ($target_domain,$target_user) = @_;
11825:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11826:     #&appenv({$cachename => time});
11827: }
11828: 
11829: # --------------------------------------------------------- Value of a Variable
11830: sub EXT {
11831: 
11832:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11833:     unless ($varname) { return ''; }
11834:     #get real user name/domain, courseid and symb
11835:     my $courseid;
11836:     my $publicuser;
11837:     if ($symbparm) {
11838: 	$symbparm=&get_symb_from_alias($symbparm);
11839:     }
11840:     if (!($uname && $udom)) {
11841:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11842:       if (!$symbparm) {	$symbparm=$cursymb; }
11843:     } else {
11844: 	$courseid=$env{'request.course.id'};
11845:     }
11846:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11847:     my $rest;
11848:     if (defined($therest[0])) {
11849:        $rest=join('.',@therest);
11850:     } else {
11851:        $rest='';
11852:     }
11853: 
11854:     my $qualifierrest=$qualifier;
11855:     if ($rest) { $qualifierrest.='.'.$rest; }
11856:     my $spacequalifierrest=$space;
11857:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11858:     if ($realm eq 'user') {
11859: # --------------------------------------------------------------- user.resource
11860: 	if ($space eq 'resource') {
11861: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11862: 		  || defined($Apache::lonhomework::parsing_a_task))
11863: 		 &&
11864: 		 ($symbparm eq &symbread()) ) {	
11865: 		# if we are in the middle of processing the resource the
11866: 		# get the value we are planning on committing
11867:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11868:                     return $Apache::lonhomework::results{$qualifierrest};
11869:                 } else {
11870:                     return $Apache::lonhomework::history{$qualifierrest};
11871:                 }
11872: 	    } else {
11873: 		my %restored;
11874: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11875: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11876: 		} else {
11877: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11878: 		}
11879: 		return $restored{$qualifierrest};
11880: 	    }
11881: # ----------------------------------------------------------------- user.access
11882:         } elsif ($space eq 'access') {
11883: 	    # FIXME - not supporting calls for a specific user
11884:             return &allowed($qualifier,$rest);
11885: # ------------------------------------------ user.preferences, user.environment
11886:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11887: 	    if (($uname eq $env{'user.name'}) &&
11888: 		($udom eq $env{'user.domain'})) {
11889: 		return $env{join('.',('environment',$qualifierrest))};
11890: 	    } else {
11891: 		my %returnhash;
11892: 		if (!$publicuser) {
11893: 		    %returnhash=&userenvironment($udom,$uname,
11894: 						 $qualifierrest);
11895: 		}
11896: 		return $returnhash{$qualifierrest};
11897: 	    }
11898: # ----------------------------------------------------------------- user.course
11899:         } elsif ($space eq 'course') {
11900: 	    # FIXME - not supporting calls for a specific user
11901:             return $env{join('.',('request.course',$qualifier))};
11902: # ------------------------------------------------------------------- user.role
11903:         } elsif ($space eq 'role') {
11904: 	    # FIXME - not supporting calls for a specific user
11905:             my ($role,$where)=split(/\./,$env{'request.role'});
11906:             if ($qualifier eq 'value') {
11907: 		return $role;
11908:             } elsif ($qualifier eq 'extent') {
11909:                 return $where;
11910:             }
11911: # ----------------------------------------------------------------- user.domain
11912:         } elsif ($space eq 'domain') {
11913:             return $udom;
11914: # ------------------------------------------------------------------- user.name
11915:         } elsif ($space eq 'name') {
11916:             return $uname;
11917: # ---------------------------------------------------- Any other user namespace
11918:         } else {
11919: 	    my %reply;
11920: 	    if (!$publicuser) {
11921: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11922: 	    }
11923: 	    return $reply{$qualifierrest};
11924:         }
11925:     } elsif ($realm eq 'query') {
11926: # ---------------------------------------------- pull stuff out of query string
11927:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11928: 						[$spacequalifierrest]);
11929: 	return $env{'form.'.$spacequalifierrest}; 
11930:    } elsif ($realm eq 'request') {
11931: # ------------------------------------------------------------- request.browser
11932:         if ($space eq 'browser') {
11933:             return $env{'browser.'.$qualifier};
11934: # ------------------------------------------------------------ request.filename
11935:         } else {
11936:             return $env{'request.'.$spacequalifierrest};
11937:         }
11938:     } elsif ($realm eq 'course') {
11939: # ---------------------------------------------------------- course.description
11940:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11941:     } elsif ($realm eq 'resource') {
11942: 
11943: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11944: 	    if (!$symbparm) { $symbparm=&symbread(); }
11945: 	}
11946: 
11947:         if ($qualifier eq '') {
11948: 	    if ($space eq 'title') {
11949: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11950: 	        return &gettitle($symbparm);
11951: 	    }
11952: 	
11953: 	    if ($space eq 'map') {
11954: 	        my ($map) = &decode_symb($symbparm);
11955: 	        return &symbread($map);
11956: 	    }
11957:             if ($space eq 'maptitle') {
11958:                 my ($map) = &decode_symb($symbparm);
11959:                 return &gettitle($map);
11960:             }
11961: 	    if ($space eq 'filename') {
11962: 	        if ($symbparm) {
11963: 		    return &clutter((&decode_symb($symbparm))[2]);
11964: 	        }
11965: 	        return &hreflocation('',$env{'request.filename'});
11966: 	    }
11967: 
11968:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11969:                 if ($space eq 'visibleparts') {
11970:                     my $navmap = Apache::lonnavmaps::navmap->new();
11971:                     my $item;
11972:                     if (ref($navmap)) {
11973:                         my $res = $navmap->getBySymb($symbparm);
11974:                         my $parts = $res->parts();
11975:                         if (ref($parts) eq 'ARRAY') {
11976:                             $item = join(',',@{$parts});
11977:                         }
11978:                         undef($navmap);
11979:                     }
11980:                     return $item;
11981:                 }
11982:             }
11983:         }
11984: 
11985: 	my ($section, $group, @groups, @recurseup, $recursed);
11986: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11987:         if (($courseid eq '') && ($cid)) {
11988:             $courseid = $cid;
11989:         }
11990: 	if (($symbparm && $courseid) && 
11991: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11992: 
11993: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11994: 
11995: # ----------------------------------------------------- Cascading lookup scheme
11996: 	    my $symbp=$symbparm;
11997: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11998: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11999:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12000: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12001: 	    if (($env{'user.name'} eq $uname) &&
12002: 		($env{'user.domain'} eq $udom)) {
12003: 		$section=$env{'request.course.sec'};
12004:                 @groups = split(/:/,$env{'request.course.groups'});  
12005:                 @groups=&sort_course_groups($courseid,@groups); 
12006: 	    } else {
12007: 		if (! defined($usection)) {
12008: 		    $section=&getsection($udom,$uname,$courseid);
12009: 		} else {
12010: 		    $section = $usection;
12011: 		}
12012:                 @groups = &get_users_groups($udom,$uname,$courseid);
12013: 	    }
12014: 
12015: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12016: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12017:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12018: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12019: 
12020: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12021: 	    my $courselevelr=$courseid.'.'.$symbparm;
12022:             $courseleveli=$courseid.'.'.$recurseparm;
12023: 	    $courselevelm=$courseid.'.'.$mapparm;
12024: 
12025: # ----------------------------------------------------------- first, check user
12026: 
12027: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12028:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12029: 				       ([$courselevelr,'resource'],
12030: 					[$courselevelm,'map'     ],
12031:                                         [$courseleveli,'map'     ],
12032: 					[$courselevel, 'course'  ]));
12033: 	    if (defined($userreply)) { return &get_reply($userreply); }
12034: 
12035: # ------------------------------------------------ second, check some of course
12036:             my $coursereply;
12037:             if (@groups > 0) {
12038:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12039:                                        $recurseparm,$mapparm,$spacequalifierrest,
12040:                                        $mapp,\$recursed,\@recurseup);
12041:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12042:             }
12043: 
12044: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12045: 				  $env{'course.'.$courseid.'.domain'},
12046: 				  'course',$mapp,\$recursed,\@recurseup,
12047:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12048: 				  ([$seclevelr,   'resource'],
12049: 				   [$seclevelm,   'map'     ],
12050:                                    [$secleveli,   'map'     ],
12051: 				   [$seclevel,    'course'  ],
12052: 				   [$courselevelr,'resource']));
12053: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12054: 
12055: # ------------------------------------------------------ third, check map parms
12056: 	    my %parmhash=();
12057: 	    my $thisparm='';
12058: 	    if (tie(%parmhash,'GDBM_File',
12059: 		    $env{'request.course.fn'}.'_parms.db',
12060: 		    &GDBM_READER(),0640)) {
12061: 		$thisparm=$parmhash{$symbparm};
12062: 		untie(%parmhash);
12063: 	    }
12064: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12065: 	}
12066: # ------------------------------------------ fourth, look in resource metadata
12067:  
12068:         my $what = $spacequalifierrest;
12069: 	$what=~s/\./\_/;
12070: 	my $filename;
12071: 	if (!$symbparm) { $symbparm=&symbread(); }
12072: 	if ($symbparm) {
12073: 	    $filename=(&decode_symb($symbparm))[2];
12074: 	} else {
12075: 	    $filename=$env{'request.filename'};
12076: 	}
12077:         my $toolsymb;
12078:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12079:             $toolsymb = $symbparm;
12080:         }
12081: 	my $metadata=&metadata($filename,$what,$toolsymb);
12082: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12083: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12084: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12085: 
12086: # ----------------------------------------------- fifth, look in rest of course
12087: 	if ($symbparm && defined($courseid) && 
12088: 	    $courseid eq $env{'request.course.id'}) {
12089: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12090: 				     $env{'course.'.$courseid.'.domain'},
12091: 				     'course',$mapp,\$recursed,\@recurseup,
12092:                                      $courseid,'.',$spacequalifierrest,
12093: 				     ([$courselevelm,'map'   ],
12094:                                       [$courseleveli,'map'   ],
12095: 				      [$courselevel, 'course']));
12096: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12097: 	}
12098: # ------------------------------------------------------------------ Cascade up
12099: 	unless ($space eq '0') {
12100: 	    my @parts=split(/_/,$space);
12101: 	    my $id=pop(@parts);
12102: 	    my $part=join('_',@parts);
12103: 	    if ($part eq '') { $part='0'; }
12104: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12105: 				 $symbparm,$udom,$uname,$section,1);
12106: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12107: 	}
12108: 	if ($recurse) { return undef; }
12109: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12110: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12111: # ---------------------------------------------------- Any other user namespace
12112:     } elsif ($realm eq 'environment') {
12113: # ----------------------------------------------------------------- environment
12114: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12115: 	    return $env{'environment.'.$spacequalifierrest};
12116: 	} else {
12117: 	    if ($uname eq 'anonymous' && $udom eq '') {
12118: 		return '';
12119: 	    }
12120: 	    my %returnhash=&userenvironment($udom,$uname,
12121: 					    $spacequalifierrest);
12122: 	    return $returnhash{$spacequalifierrest};
12123: 	}
12124:     } elsif ($realm eq 'system') {
12125: # ----------------------------------------------------------------- system.time
12126: 	if ($space eq 'time') {
12127: 	    return time;
12128:         }
12129:     } elsif ($realm eq 'server') {
12130: # ----------------------------------------------------------------- system.time
12131: 	if ($space eq 'name') {
12132: 	    return $ENV{'SERVER_NAME'};
12133:         }
12134:     }
12135:     return '';
12136: }
12137: 
12138: sub get_reply {
12139:     my ($reply_value) = @_;
12140:     if (ref($reply_value) eq 'ARRAY') {
12141:         if (wantarray) {
12142: 	    return @$reply_value;
12143:         }
12144:         return $reply_value->[0];
12145:     } else {
12146:         return $reply_value;
12147:     }
12148: }
12149: 
12150: sub check_group_parms {
12151:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12152:         $recursed,$recurseupref) = @_;
12153:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12154:                   [$what,'course']);
12155:     my $coursereply;
12156:     foreach my $group (@{$groups}) {
12157:         my @groupitems = ();
12158:         foreach my $level (@levels) {
12159:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12160:              push(@groupitems,[$item,$level->[1]]);
12161:         }
12162:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12163:                                    $env{'course.'.$courseid.'.domain'},
12164:                                    'course',$mapp,$recursed,$recurseupref,
12165:                                    $courseid,'.['.$group.'].',$what,
12166:                                    @groupitems);
12167:         last if (defined($coursereply));
12168:     }
12169:     return $coursereply;
12170: }
12171: 
12172: sub get_map_hierarchy {
12173:     my ($mapname,$courseid) = @_;
12174:     my @recurseup = ();
12175:     if ($mapname) {
12176:         if (($cachedmapkey eq $courseid) &&
12177:             (abs($cachedmaptime-time)<5)) {
12178:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12179:                 return @{$cachedmaps{$mapname}};
12180:             }
12181:         }
12182:         my $navmap = Apache::lonnavmaps::navmap->new();
12183:         if (ref($navmap)) {
12184:             @recurseup = $navmap->recurseup_maps($mapname);
12185:             undef($navmap);
12186:             $cachedmaps{$mapname} = \@recurseup;
12187:             $cachedmaptime=time;
12188:             $cachedmapkey=$courseid;
12189:         }
12190:     }
12191:     return @recurseup;
12192: }
12193: 
12194: }
12195: 
12196: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12197:     my ($courseid,@groups) = @_;
12198:     @groups = sort(@groups);
12199:     return @groups;
12200: }
12201: 
12202: sub packages_tab_default {
12203:     my ($uri,$varname,$toolsymb)=@_;
12204:     my (undef,$part,$name)=split(/\./,$varname);
12205: 
12206:     my (@extension,@specifics,$do_default);
12207:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12208: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12209: 	if ($pack_type eq 'default') {
12210: 	    $do_default=1;
12211: 	} elsif ($pack_type eq 'extension') {
12212: 	    push(@extension,[$package,$pack_type,$pack_part]);
12213: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12214: 	    # only look at packages defaults for packages that this id is
12215: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12216: 	}
12217:     }
12218:     # first look for a package that matches the requested part id
12219:     foreach my $package (@specifics) {
12220: 	my (undef,$pack_type,$pack_part)=@{$package};
12221: 	next if ($pack_part ne $part);
12222: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12223: 	    return $packagetab{"$pack_type&$name&default"};
12224: 	}
12225:     }
12226:     # look for any possible matching non extension_ package
12227:     foreach my $package (@specifics) {
12228: 	my (undef,$pack_type,$pack_part)=@{$package};
12229: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12230: 	    return $packagetab{"$pack_type&$name&default"};
12231: 	}
12232: 	if ($pack_type eq 'part') { $pack_part='0'; }
12233: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12234: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12235: 	}
12236:     }
12237:     # look for any posible extension_ match
12238:     foreach my $package (@extension) {
12239: 	my ($package,$pack_type)=@{$package};
12240: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12241: 	    return $packagetab{"$pack_type&$name&default"};
12242: 	}
12243: 	if (defined($packagetab{$package."&$name&default"})) {
12244: 	    return $packagetab{$package."&$name&default"};
12245: 	}
12246:     }
12247:     # look for a global default setting
12248:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12249: 	return $packagetab{"default&$name&default"};
12250:     }
12251:     return undef;
12252: }
12253: 
12254: sub add_prefix_and_part {
12255:     my ($prefix,$part)=@_;
12256:     my $keyroot;
12257:     if (defined($prefix) && $prefix !~ /^__/) {
12258: 	# prefix that has a part already
12259: 	$keyroot=$prefix;
12260:     } elsif (defined($prefix)) {
12261: 	# prefix that is missing a part
12262: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12263:     } else {
12264: 	# no prefix at all
12265: 	if (defined($part)) { $keyroot='_'.$part; }
12266:     }
12267:     return $keyroot;
12268: }
12269: 
12270: # ---------------------------------------------------------------- Get metadata
12271: 
12272: my %metaentry;
12273: my %importedpartids;
12274: my %importedrespids;
12275: sub metadata {
12276:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12277:     $uri=&declutter($uri);
12278:     # if it is a non metadata possible uri return quickly
12279:     if (($uri eq '') || 
12280: 	(($uri =~ m|^/*adm/|) && 
12281: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12282:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12283: 	return undef;
12284:     }
12285:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12286: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12287: 	return undef;
12288:     }
12289:     my $filename=$uri;
12290:     $uri=~s/\.meta$//;
12291: #
12292: # Is the metadata already cached?
12293: # Look at timestamp of caching
12294: # Everything is cached by the main uri, libraries are never directly cached
12295: #
12296:     if (!defined($liburi)) {
12297: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12298: 	if (defined($cached)) { return $result->{':'.$what}; }
12299:     }
12300: 
12301: #
12302: # If the uri is for an external tool the file from
12303: # which metadata should be retrieved depends on whether
12304: # the tool had been configured to be gradable (set in the Course
12305: # Editor or Resource Editor).
12306: #
12307: # If a valid symb has been included as the third arg in the call
12308: # to &metadata() that can be used to retrieve the value of
12309: # parameter_0_gradable set for the resource, and included in the
12310: # uploaded map containing the tool. The value is retrieved via
12311: # &EXT(), if a valid symb is available.  Otherwise the value of
12312: # gradable in the exttool_$marker.db file for the tool instance
12313: # is retrieved via &get().
12314: #
12315: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12316: # hiddenresource and encrypturl (during course initialization)
12317: # the map-level parameter for resource.0.gradable included in the 
12318: # uploaded map containing the tool will not yet have been stored
12319: # in the user_course_parms.db file for the user's session, so in 
12320: # this case fall back to retrieving gradable status from the
12321: # exttool_$marker.db file.
12322: #
12323: # In order to avoid an infinite loop, &metadata() will return
12324: # before a call to &EXT(), if the uri is for an external tool
12325: # and the $what for which metadata is being requested is
12326: # parameter_0_gradable or 0_gradable.
12327: #
12328: 
12329:     if ($uri =~ /ext\.tool$/) {
12330:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12331:             return;
12332:         } else {
12333:             my ($checked,$use_passback);
12334:             if ($toolsymb ne '') {
12335:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12336:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12337:                     $checked = 1;
12338:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12339:                         $use_passback = 1;
12340:                     }
12341:                 }
12342:             }
12343:             unless ($checked) {
12344:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12345:                 $marker=~s/\D//g;
12346:                 if ($marker) {
12347:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12348:                     $use_passback = $toolsettings{'gradable'};
12349:                 }
12350:             }
12351:             if ($use_passback) {
12352:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12353:             } else {
12354:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12355:             }
12356:         }
12357:     }
12358: 
12359:     {
12360: # Imported parts would go here
12361:         my @origfiletagids=();
12362:         my $importedparts=0;
12363: 
12364: # Imported responseids would go here
12365:         my $importedresponses=0;
12366: #
12367: # Is this a recursive call for a library?
12368: #
12369: #	if (! exists($metacache{$uri})) {
12370: #	    $metacache{$uri}={};
12371: #	}
12372: 	my $cachetime = 60*60;
12373:         if ($liburi) {
12374: 	    $liburi=&declutter($liburi);
12375:             $filename=$liburi;
12376:         } else {
12377: 	    &devalidate_cache_new('meta',$uri);
12378: 	    undef(%metaentry);
12379: 	}
12380:         my %metathesekeys=();
12381:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12382: 	my $metastring;
12383: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12384: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12385: 	    $metastring = 
12386: 		&Apache::lonnet::ssi_body($which,
12387: 					  ('grade_target' => 'meta'));
12388: 	    $cachetime = 1; # only want this cached in the child not long term
12389: 	} elsif (($uri !~ m -^(editupload)/-) && 
12390:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12391: 	    my $file=&filelocation('',&clutter($filename));
12392: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12393: 	    $metastring=&getfile($file);
12394: 	}
12395:         my $parser=HTML::LCParser->new(\$metastring);
12396:         my $token;
12397:         undef %metathesekeys;
12398:         while ($token=$parser->get_token) {
12399: 	    if ($token->[0] eq 'S') {
12400: 		if (defined($token->[2]->{'package'})) {
12401: #
12402: # This is a package - get package info
12403: #
12404: 		    my $package=$token->[2]->{'package'};
12405: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12406: 		    if (defined($token->[2]->{'id'})) { 
12407: 			$keyroot.='_'.$token->[2]->{'id'}; 
12408: 		    }
12409: 		    if ($metaentry{':packages'}) {
12410: 			$metaentry{':packages'}.=','.$package.$keyroot;
12411: 		    } else {
12412: 			$metaentry{':packages'}=$package.$keyroot;
12413: 		    }
12414: 		    foreach my $pack_entry (keys(%packagetab)) {
12415: 			my $part=$keyroot;
12416: 			$part=~s/^\_//;
12417: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12418: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12419: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12420: 			    # ignore package.tab specified default values
12421:                             # here &package_tab_default() will fetch those
12422: 			    if ($subp eq 'default') { next; }
12423: 			    my $value=$packagetab{$pack_entry};
12424: 			    my $unikey;
12425: 			    if ($pack =~ /_0$/) {
12426: 				$unikey='parameter_0_'.$name;
12427: 				$part=0;
12428: 			    } else {
12429: 				$unikey='parameter'.$keyroot.'_'.$name;
12430: 			    }
12431: 			    if ($subp eq 'display') {
12432: 				$value.=' [Part: '.$part.']';
12433: 			    }
12434: 			    $metaentry{':'.$unikey.'.part'}=$part;
12435: 			    $metathesekeys{$unikey}=1;
12436: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12437: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12438: 			    }
12439: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12440: 				$metaentry{':'.$unikey}=
12441: 				    $metaentry{':'.$unikey.'.default'};
12442: 			    }
12443: 			}
12444: 		    }
12445: 		} else {
12446: #
12447: # This is not a package - some other kind of start tag
12448: #
12449: 		    my $entry=$token->[1];
12450: 		    my $unikey='';
12451: 
12452: 		    if ($entry eq 'import') {
12453: #
12454: # Importing a library here
12455: #
12456:                         my $location=$parser->get_text('/import');
12457:                         my $dir=$filename;
12458:                         $dir=~s|[^/]*$||;
12459:                         $location=&filelocation($dir,$location);
12460: 
12461:                         my $importid=$token->[2]->{'id'};
12462:                         my $importmode=$token->[2]->{'importmode'};
12463: #
12464: # Check metadata for imported file to
12465: # see if it contained response items
12466: #
12467:                         my ($origfile,@libfilekeys);
12468:                         my %currmetaentry = %metaentry;
12469:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12470:                                                            $depthcount+1));
12471:                         if (grep(/^responseorder$/,@libfilekeys)) {
12472:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12473:                                                              undef,$depthcount+1);
12474:                             if ($libresponseorder ne '') {
12475:                                 if ($#origfiletagids<0) {
12476:                                     undef(%importedrespids);
12477:                                     undef(%importedpartids);
12478:                                 }
12479:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12480:                                 if (@respids) {
12481:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12482:                                 }
12483:                                 if ($importedrespids{$importid} ne '') {
12484:                                     $importedresponses = 1;
12485: # We need to get the original file and the imported file to get the response order correct
12486: # Load and inspect original file
12487:                                     if ($#origfiletagids<0) {
12488:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12489:                                         $origfile=&getfile($origfilelocation);
12490:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12491:                                     }
12492:                                 }
12493:                             }
12494:                         }
12495: # Do not overwrite contents of %metaentry hash for resource itself with 
12496: # hash populated for imported library file
12497:                         %metaentry = %currmetaentry;
12498:                         undef(%currmetaentry);
12499:                         if ($importmode eq 'part') {
12500: # Import as part(s)
12501:                            $importedparts=1;
12502: # We need to get the original file and the imported file to get the part order correct
12503: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12504: # Load and inspect original file if we didn't do that already
12505:                            if ($#origfiletagids<0) {
12506:                                undef(%importedrespids);
12507:                                undef(%importedpartids);
12508:                                if ($origfile eq '') {
12509:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12510:                                    $origfile=&getfile($origfilelocation);
12511:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12512:                                }
12513:                            }
12514:                            my @impfilepartids;
12515: # If <partorder> tag is included in metadata for the imported file
12516: # get the parts in the imported file from that.
12517:                            if (grep(/^partorder$/,@libfilekeys)) {
12518:                                %currmetaentry = %metaentry;
12519:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12520:                                                             $depthcount+1);
12521:                                %metaentry = %currmetaentry;
12522:                                undef(%currmetaentry);
12523:                                if ($libpartorder ne '') {
12524:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12525:                                }
12526:                            } else {
12527: # If no <partorder> tag available, load and inspect imported file
12528:                                my $impfile=&getfile($location);
12529:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12530:                            }
12531:                            if ($#impfilepartids>=0) {
12532: # This problem had parts
12533:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12534:                            } else {
12535: # Importing by turning a single problem into a problem part
12536: # It gets the import-tags ID as part-ID
12537:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12538:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12539:                            }
12540:                         } else {
12541: # Import as problem or as normal import
12542:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12543:                             unless ($importmode eq 'problem') {
12544: # Normal import
12545:                                 if (defined($token->[2]->{'id'})) {
12546:                                     $unikey.='_'.$token->[2]->{'id'};
12547:                                 }
12548:                             }
12549: # Check metadata for imported file to
12550: # see if it contained parts
12551:                             if (grep(/^partorder$/,@libfilekeys)) {
12552:                                 %currmetaentry = %metaentry;
12553:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12554:                                                              $depthcount+1);
12555:                                 %metaentry = %currmetaentry;
12556:                                 undef(%currmetaentry);
12557:                                 if ($libpartorder ne '') {
12558:                                     $importedparts = 1;
12559:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12560:                                 }
12561:                             }
12562:                         }
12563: 			if ($depthcount<20) {
12564: 			    my $metadata = 
12565: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12566: 					  $depthcount+1);
12567: 			    foreach my $meta (split(',',$metadata)) {
12568: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12569: 				$metathesekeys{$meta}=1;
12570: 			    }
12571:                         }
12572: 		    } else {
12573: #
12574: # Not importing, some other kind of non-package, non-library start tag
12575: # 
12576:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12577:                         if (defined($token->[2]->{'id'})) {
12578:                             $unikey.='_'.$token->[2]->{'id'};
12579:                         }
12580: 			if (defined($token->[2]->{'name'})) { 
12581: 			    $unikey.='_'.$token->[2]->{'name'}; 
12582: 			}
12583: 			$metathesekeys{$unikey}=1;
12584: 			foreach my $param (@{$token->[3]}) {
12585: 			    $metaentry{':'.$unikey.'.'.$param} =
12586: 				$token->[2]->{$param};
12587: 			}
12588: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12589: 			my $default=$metaentry{':'.$unikey.'.default'};
12590: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12591: 		 # only ws inside the tag, and not in default, so use default
12592: 		 # as value
12593: 			    $metaentry{':'.$unikey}=$default;
12594: 			} elsif ( $internaltext =~ /\S/ ) {
12595: 		  # something interesting inside the tag
12596: 			    $metaentry{':'.$unikey}=$internaltext;
12597: 			} else {
12598: 		  # no interesting values, don't set a default
12599: 			}
12600: # end of not-a-package not-a-library import
12601: 		    }
12602: # end of not-a-package start tag
12603: 		}
12604: # the next is the end of "start tag"
12605: 	    }
12606: 	}
12607: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12608: 	$extension = lc($extension);
12609: 	if ($extension eq 'htm') { $extension='html'; }
12610: 
12611: 	foreach my $key (keys(%packagetab)) {
12612: 	    #no specific packages #how's our extension
12613: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12614: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12615: 					 \%metathesekeys);
12616: 	}
12617: 
12618: 	if (!exists($metaentry{':packages'})
12619: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12620: 	    foreach my $key (keys(%packagetab)) {
12621: 		#no specific packages well let's get default then
12622: 		if ($key!~/^default&/) { next; }
12623: 		&metadata_create_package_def($uri,$key,'default',
12624: 					     \%metathesekeys);
12625: 	    }
12626: 	}
12627: # are there custom rights to evaluate
12628: 	if ($metaentry{':copyright'} eq 'custom') {
12629: 
12630:     #
12631:     # Importing a rights file here
12632:     #
12633: 	    unless ($depthcount) {
12634: 		my $location=$metaentry{':customdistributionfile'};
12635: 		my $dir=$filename;
12636: 		$dir=~s|[^/]*$||;
12637: 		$location=&filelocation($dir,$location);
12638: 		my $rights_metadata =
12639: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12640: 			      $depthcount+1);
12641: 		foreach my $rights (split(',',$rights_metadata)) {
12642: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12643: 		    $metathesekeys{$rights}=1;
12644: 		}
12645: 	    }
12646: 	}
12647: 	# uniqifiy package listing
12648: 	my %seen;
12649: 	my @uniq_packages =
12650: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12651: 	$metaentry{':packages'} = join(',',@uniq_packages);
12652: 
12653:         if (($importedresponses) || ($importedparts)) {
12654:             if ($importedparts) {
12655: # We had imported parts and need to rebuild partorder
12656:                 $metaentry{':partorder'}='';
12657:                 $metathesekeys{'partorder'}=1;
12658:             }
12659:             if ($importedresponses) {
12660: # We had imported responses and need to rebuil responseorder
12661:                 $metaentry{':responseorder'}='';
12662:                 $metathesekeys{'responseorder'}=1;
12663:             }
12664:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12665:                 my $origid = $origfiletagids[$index+1];
12666:                 if ($origfiletagids[$index] eq 'part') {
12667: # Original part, part of the problem
12668:                     if ($importedparts) {
12669:                         $metaentry{':partorder'}.=','.$origid;
12670:                     }
12671:                 } elsif ($origfiletagids[$index] eq 'import') {
12672:                     if ($importedparts) {
12673: # We have imported parts at this position
12674:                         if ($importedpartids{$origid} ne '') {
12675:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12676:                         }
12677:                     }
12678:                     if ($importedresponses) {
12679: # We have imported responses at this position
12680:                         if ($importedrespids{$origid} ne '') {
12681:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12682:                         }
12683:                     }
12684:                 } else {
12685: # Original response item, part of the problem
12686:                     if ($importedresponses) {
12687:                         $metaentry{':responseorder'}.=','.$origid;
12688:                     }
12689:                 }
12690:             }
12691:             if ($importedparts) {
12692:                 $metaentry{':partorder'}=~s/^\,//;
12693:             }
12694:             if ($importedresponses) {
12695:                 $metaentry{':responseorder'}=~s/^\,//;
12696:             }
12697:         }
12698: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12699: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12700: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12701:         unless ($liburi) {
12702: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12703:         }
12704: # this is the end of "was not already recently cached
12705:     }
12706:     return $metaentry{':'.$what};
12707: }
12708: 
12709: sub metadata_create_package_def {
12710:     my ($uri,$key,$package,$metathesekeys)=@_;
12711:     my ($pack,$name,$subp)=split(/\&/,$key);
12712:     if ($subp eq 'default') { next; }
12713:     
12714:     if (defined($metaentry{':packages'})) {
12715: 	$metaentry{':packages'}.=','.$package;
12716:     } else {
12717: 	$metaentry{':packages'}=$package;
12718:     }
12719:     my $value=$packagetab{$key};
12720:     my $unikey;
12721:     $unikey='parameter_0_'.$name;
12722:     $metaentry{':'.$unikey.'.part'}=0;
12723:     $$metathesekeys{$unikey}=1;
12724:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12725: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12726:     }
12727:     if (defined($metaentry{':'.$unikey.'.default'})) {
12728: 	$metaentry{':'.$unikey}=
12729: 	    $metaentry{':'.$unikey.'.default'};
12730:     }
12731: }
12732: 
12733: sub metadata_generate_part0 {
12734:     my ($metadata,$metacache,$uri) = @_;
12735:     my %allnames;
12736:     foreach my $metakey (keys(%$metadata)) {
12737: 	if ($metakey=~/^parameter\_(.*)/) {
12738: 	  my $part=$$metacache{':'.$metakey.'.part'};
12739: 	  my $name=$$metacache{':'.$metakey.'.name'};
12740: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12741: 	    $allnames{$name}=$part;
12742: 	  }
12743: 	}
12744:     }
12745:     foreach my $name (keys(%allnames)) {
12746:       $$metadata{"parameter_0_$name"}=1;
12747:       my $key=":parameter_0_$name";
12748:       $$metacache{"$key.part"}='0';
12749:       $$metacache{"$key.name"}=$name;
12750:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12751: 					   $allnames{$name}.'_'.$name.
12752: 					   '.type'};
12753:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12754: 			     '.display'};
12755:       my $expr='[Part: '.$allnames{$name}.']';
12756:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12757:       $$metacache{"$key.display"}=$olddis;
12758:     }
12759: }
12760: 
12761: # ------------------------------------------------------ Devalidate title cache
12762: 
12763: sub devalidate_title_cache {
12764:     my ($url)=@_;
12765:     if (!$env{'request.course.id'}) { return; }
12766:     my $symb=&symbread($url);
12767:     if (!$symb) { return; }
12768:     my $key=$env{'request.course.id'}."\0".$symb;
12769:     &devalidate_cache_new('title',$key);
12770: }
12771: 
12772: # ------------------------------------------------- Get the title of a course
12773: 
12774: sub current_course_title {
12775:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12776: }
12777: # ------------------------------------------------- Get the title of a resource
12778: 
12779: sub gettitle {
12780:     my $urlsymb=shift;
12781:     my $symb=&symbread($urlsymb);
12782:     if ($symb) {
12783: 	my $key=$env{'request.course.id'}."\0".$symb;
12784: 	my ($result,$cached)=&is_cached_new('title',$key);
12785: 	if (defined($cached)) { 
12786: 	    return $result;
12787: 	}
12788: 	my ($map,$resid,$url)=&decode_symb($symb);
12789: 	my $title='';
12790: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12791: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12792: 	} else {
12793: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12794: 		    &GDBM_READER(),0640)) {
12795: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12796: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12797: 		untie(%bighash);
12798: 	    }
12799: 	}
12800: 	$title=~s/\&colon\;/\:/gs;
12801: 	if ($title) {
12802: # Remember both $symb and $title for dynamic metadata
12803:             $accesshash{$symb.'___crstitle'}=$title;
12804:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12805: # Cache this title and then return it
12806: 	    return &do_cache_new('title',$key,$title,600);
12807: 	}
12808: 	$urlsymb=$url;
12809:     }
12810:     my $title=&metadata($urlsymb,'title');
12811:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12812:     return $title;
12813: }
12814: 
12815: sub get_slot {
12816:     my ($which,$cnum,$cdom)=@_;
12817:     if (!$cnum || !$cdom) {
12818: 	(undef,my $courseid)=&whichuser();
12819: 	$cdom=$env{'course.'.$courseid.'.domain'};
12820: 	$cnum=$env{'course.'.$courseid.'.num'};
12821:     }
12822:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12823:     my %slotinfo;
12824:     if (exists($remembered{$key})) {
12825: 	$slotinfo{$which} = $remembered{$key};
12826:     } else {
12827: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12828: 	&Apache::lonhomework::showhash(%slotinfo);
12829: 	my ($tmp)=keys(%slotinfo);
12830: 	if ($tmp=~/^error:/) { return (); }
12831: 	$remembered{$key} = $slotinfo{$which};
12832:     }
12833:     if (ref($slotinfo{$which}) eq 'HASH') {
12834: 	return %{$slotinfo{$which}};
12835:     }
12836:     return $slotinfo{$which};
12837: }
12838: 
12839: sub get_reservable_slots {
12840:     my ($cnum,$cdom,$uname,$udom) = @_;
12841:     my $now = time;
12842:     my $reservable_info;
12843:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12844:     if (exists($remembered{$key})) {
12845:         $reservable_info = $remembered{$key};
12846:     } else {
12847:         my %resv;
12848:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12849:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12850:         $reservable_info = \%resv;
12851:         $remembered{$key} = $reservable_info;
12852:     }
12853:     return $reservable_info;
12854: }
12855: 
12856: sub get_course_slots {
12857:     my ($cnum,$cdom) = @_;
12858:     my $hashid=$cnum.':'.$cdom;
12859:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12860:     if (defined($cached)) {
12861:         if (ref($result) eq 'HASH') {
12862:             return %{$result};
12863:         }
12864:     } else {
12865:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12866:         my ($tmp) = keys(%slots);
12867:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12868:             &do_cache_new('allslots',$hashid,\%slots,600);
12869:             return %slots;
12870:         }
12871:     }
12872:     return;
12873: }
12874: 
12875: sub devalidate_slots_cache {
12876:     my ($cnum,$cdom)=@_;
12877:     my $hashid=$cnum.':'.$cdom;
12878:     &devalidate_cache_new('allslots',$hashid);
12879: }
12880: 
12881: sub get_coursechange {
12882:     my ($cdom,$cnum) = @_;
12883:     if ($cdom eq '' || $cnum eq '') {
12884:         return unless ($env{'request.course.id'});
12885:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12886:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12887:     }
12888:     my $hashid=$cdom.'_'.$cnum;
12889:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12890:     if ((defined($cached)) && ($change ne '')) {
12891:         return $change;
12892:     } else {
12893:         my %crshash;
12894:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12895:         if ($crshash{'internal.contentchange'} eq '') {
12896:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12897:             if ($change eq '') {
12898:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12899:                 $change = $crshash{'internal.created'};
12900:             }
12901:         } else {
12902:             $change = $crshash{'internal.contentchange'};
12903:         }
12904:         my $cachetime = 600;
12905:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12906:     }
12907:     return $change;
12908: }
12909: 
12910: sub devalidate_coursechange_cache {
12911:     my ($cnum,$cdom)=@_;
12912:     my $hashid=$cnum.':'.$cdom;
12913:     &devalidate_cache_new('crschange',$hashid);
12914: }
12915: 
12916: # ------------------------------------------------- Update symbolic store links
12917: 
12918: sub symblist {
12919:     my ($mapname,%newhash)=@_;
12920:     $mapname=&deversion(&declutter($mapname));
12921:     my %hash;
12922:     if (($env{'request.course.fn'}) && (%newhash)) {
12923:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12924:                       &GDBM_WRCREAT(),0640)) {
12925: 	    foreach my $url (keys(%newhash)) {
12926: 		next if ($url eq 'last_known'
12927: 			 && $env{'form.no_update_last_known'});
12928: 		$hash{declutter($url)}=&encode_symb($mapname,
12929: 						    $newhash{$url}->[1],
12930: 						    $newhash{$url}->[0]);
12931:             }
12932:             if (untie(%hash)) {
12933: 		return 'ok';
12934:             }
12935:         }
12936:     }
12937:     return 'error';
12938: }
12939: 
12940: # --------------------------------------------------------------- Verify a symb
12941: 
12942: sub symbverify {
12943:     my ($symb,$thisurl,$encstate)=@_;
12944:     my $thisfn=$thisurl;
12945:     $thisfn=&declutter($thisfn);
12946: # direct jump to resource in page or to a sequence - will construct own symbs
12947:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12948: # check URL part
12949:     my ($map,$resid,$url)=&decode_symb($symb);
12950: 
12951:     unless ($url eq $thisfn) { return 0; }
12952: 
12953:     $symb=&symbclean($symb);
12954:     $thisurl=&deversion($thisurl);
12955:     $thisfn=&deversion($thisfn);
12956: 
12957:     my %bighash;
12958:     my $okay=0;
12959: 
12960:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12961:                             &GDBM_READER(),0640)) {
12962:         my $noclutter;
12963:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12964:             $thisurl =~ s/\?.+$//;
12965:             if ($map =~ m{^uploaded/.+\.page$}) {
12966:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12967:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12968:                 $noclutter = 1;
12969:             }
12970:         }
12971:         my $ids;
12972:         if ($noclutter) {
12973:             $ids=$bighash{'ids_'.$thisurl};
12974:         } else {
12975:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12976:         }
12977:         unless ($ids) {
12978:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12979:             $ids=$bighash{$idkey};
12980:         }
12981:         if ($ids) {
12982: # ------------------------------------------------------------------- Has ID(s)
12983:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12984:                 $symb =~ s/\?.+$//;
12985:             }
12986: 	    foreach my $id (split(/\,/,$ids)) {
12987: 	       my ($mapid,$resid)=split(/\./,$id);
12988:                if (
12989:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12990:    eq $symb) {
12991:                    if (ref($encstate)) {
12992:                        $$encstate = $bighash{'encrypted_'.$id};
12993:                    }
12994: 		   if (($env{'request.role.adv'}) ||
12995: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12996:                        ($thisurl eq '/adm/navmaps')) {
12997: 		       $okay=1;
12998:                        last;
12999: 		   }
13000: 	       }
13001: 	   }
13002:         }
13003: 	untie(%bighash);
13004:     }
13005:     return $okay;
13006: }
13007: 
13008: # --------------------------------------------------------------- Clean-up symb
13009: 
13010: sub symbclean {
13011:     my $symb=shift;
13012:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13013: # remove version from map
13014:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13015: 
13016: # remove version from URL
13017:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13018: 
13019: # remove wrapper
13020: 
13021:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13022:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13023:     return $symb;
13024: }
13025: 
13026: # ---------------------------------------------- Split symb to find map and url
13027: 
13028: sub encode_symb {
13029:     my ($map,$resid,$url)=@_;
13030:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13031: }
13032: 
13033: sub decode_symb {
13034:     my $symb=shift;
13035:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13036:     my ($map,$resid,$url)=split(/___/,$symb);
13037:     return (&fixversion($map),$resid,&fixversion($url));
13038: }
13039: 
13040: sub fixversion {
13041:     my $fn=shift;
13042:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13043:     my %bighash;
13044:     my $uri=&clutter($fn);
13045:     my $key=$env{'request.course.id'}.'_'.$uri;
13046: # is this cached?
13047:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13048:     if (defined($cached)) { return $result; }
13049: # unfortunately not cached, or expired
13050:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13051: 	    &GDBM_READER(),0640)) {
13052:  	if ($bighash{'version_'.$uri}) {
13053:  	    my $version=$bighash{'version_'.$uri};
13054:  	    unless (($version eq 'mostrecent') || 
13055: 		    ($version==&getversion($uri))) {
13056:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13057:  	    }
13058:  	}
13059:  	untie %bighash;
13060:     }
13061:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13062: }
13063: 
13064: sub deversion {
13065:     my $url=shift;
13066:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13067:     return $url;
13068: }
13069: 
13070: # ------------------------------------------------------ Return symb list entry
13071: 
13072: sub symbread {
13073:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13074:     my $cache_str='request.symbread.cached.'.$thisfn;
13075:     if (defined($env{$cache_str})) {
13076:         if ($ignorecachednull) {
13077:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13078:         } else {
13079:             return $env{$cache_str};
13080:         }
13081:     }
13082: # no filename provided? try from environment
13083:     unless ($thisfn) {
13084:         if ($env{'request.symb'}) {
13085: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13086: 	}
13087: 	$thisfn=$env{'request.filename'};
13088:     }
13089:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13090: # is that filename actually a symb? Verify, clean, and return
13091:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13092: 	if (&symbverify($thisfn,$1)) {
13093: 	    return $env{$cache_str}=&symbclean($thisfn);
13094: 	}
13095:     }
13096:     $thisfn=declutter($thisfn);
13097:     my %hash;
13098:     my %bighash;
13099:     my $syval='';
13100:     if (($env{'request.course.fn'}) && ($thisfn)) {
13101:         my $targetfn = $thisfn;
13102:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13103:             $targetfn = 'adm/wrapper/'.$thisfn;
13104:         }
13105: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13106: 	    $targetfn=$1;
13107: 	}
13108:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13109:                       &GDBM_READER(),0640)) {
13110: 	    $syval=$hash{$targetfn};
13111:             untie(%hash);
13112:         }
13113: # ---------------------------------------------------------- There was an entry
13114:         if ($syval) {
13115: 	    #unless ($syval=~/\_\d+$/) {
13116: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13117: 		    #&appenv({'request.ambiguous' => $thisfn});
13118: 		    #return $env{$cache_str}='';
13119: 		#}    
13120: 		#$syval.=$1;
13121: 	    #}
13122:         } else {
13123: # ------------------------------------------------------- Was not in symb table
13124:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13125:                             &GDBM_READER(),0640)) {
13126: # ---------------------------------------------- Get ID(s) for current resource
13127:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13128:               unless ($ids) { 
13129:                  $ids=$bighash{'ids_/'.$thisfn};
13130:               }
13131:               unless ($ids) {
13132: # alias?
13133: 		  $ids=$bighash{'mapalias_'.$thisfn};
13134:               }
13135:               if ($ids) {
13136: # ------------------------------------------------------------------- Has ID(s)
13137:                  my @possibilities=split(/\,/,$ids);
13138:                  if ($#possibilities==0) {
13139: # ----------------------------------------------- There is only one possibility
13140: 		     my ($mapid,$resid)=split(/\./,$ids);
13141: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13142: 						    $resid,$thisfn);
13143:                      if (ref($possibles) eq 'HASH') {
13144:                          $possibles->{$syval} = 1;    
13145:                      }
13146:                      if ($checkforblock) {
13147:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13148:                          if (@blockers) {
13149:                              $syval = '';
13150:                              return;
13151:                          }
13152:                      }
13153:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13154: # ------------------------------------------ There is more than one possibility
13155:                      my $realpossible=0;
13156:                      foreach my $id (@possibilities) {
13157: 			 my $file=$bighash{'src_'.$id};
13158:                          my $canaccess;
13159:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13160:                              $canaccess = 1;
13161:                          } else { 
13162:                              $canaccess = &allowed('bre',$file);
13163:                          }
13164:                          if ($canaccess) {
13165:          		     my ($mapid,$resid)=split(/\./,$id);
13166:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13167:                                  my $poss_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',$poss_syval,$file);
13174:                                      unless (@blockers > 0) {
13175:                                          $syval = $poss_syval;
13176:                                          $realpossible++;
13177:                                      }
13178:                                  } else {
13179:                                      $syval = $poss_syval;
13180:                                      $realpossible++;
13181:                                  }
13182:                              }
13183: 			 }
13184:                      }
13185: 		     if ($realpossible!=1) { $syval=''; }
13186:                  } else {
13187:                      $syval='';
13188:                  }
13189: 	      }
13190:               untie(%bighash);
13191:            }
13192:         }
13193:         if ($syval) {
13194: 	    return $env{$cache_str}=$syval;
13195:         }
13196:     }
13197:     &appenv({'request.ambiguous' => $thisfn});
13198:     return $env{$cache_str}='';
13199: }
13200: 
13201: # ---------------------------------------------------------- Return random seed
13202: 
13203: sub numval {
13204:     my $txt=shift;
13205:     $txt=~tr/A-J/0-9/;
13206:     $txt=~tr/a-j/0-9/;
13207:     $txt=~tr/K-T/0-9/;
13208:     $txt=~tr/k-t/0-9/;
13209:     $txt=~tr/U-Z/0-5/;
13210:     $txt=~tr/u-z/0-5/;
13211:     $txt=~s/\D//g;
13212:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13213:     return int($txt);
13214: }
13215: 
13216: sub numval2 {
13217:     my $txt=shift;
13218:     $txt=~tr/A-J/0-9/;
13219:     $txt=~tr/a-j/0-9/;
13220:     $txt=~tr/K-T/0-9/;
13221:     $txt=~tr/k-t/0-9/;
13222:     $txt=~tr/U-Z/0-5/;
13223:     $txt=~tr/u-z/0-5/;
13224:     $txt=~s/\D//g;
13225:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13226:     my $total;
13227:     foreach my $val (@txts) { $total+=$val; }
13228:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13229:     return int($total);
13230: }
13231: 
13232: sub numval3 {
13233:     use integer;
13234:     my $txt=shift;
13235:     $txt=~tr/A-J/0-9/;
13236:     $txt=~tr/a-j/0-9/;
13237:     $txt=~tr/K-T/0-9/;
13238:     $txt=~tr/k-t/0-9/;
13239:     $txt=~tr/U-Z/0-5/;
13240:     $txt=~tr/u-z/0-5/;
13241:     $txt=~s/\D//g;
13242:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13243:     my $total;
13244:     foreach my $val (@txts) { $total+=$val; }
13245:     if ($_64bit) { $total=(($total<<32)>>32); }
13246:     return $total;
13247: }
13248: 
13249: sub digest {
13250:     my ($data)=@_;
13251:     my $digest=&Digest::MD5::md5($data);
13252:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13253:     my ($e,$f);
13254:     {
13255:         use integer;
13256:         $e=($a+$b);
13257:         $f=($c+$d);
13258:         if ($_64bit) {
13259:             $e=(($e<<32)>>32);
13260:             $f=(($f<<32)>>32);
13261:         }
13262:     }
13263:     if (wantarray) {
13264: 	return ($e,$f);
13265:     } else {
13266: 	my $g;
13267: 	{
13268: 	    use integer;
13269: 	    $g=($e+$f);
13270: 	    if ($_64bit) {
13271: 		$g=(($g<<32)>>32);
13272: 	    }
13273: 	}
13274: 	return $g;
13275:     }
13276: }
13277: 
13278: sub latest_rnd_algorithm_id {
13279:     return '64bit5';
13280: }
13281: 
13282: sub get_rand_alg {
13283:     my ($courseid)=@_;
13284:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13285:     if ($courseid) {
13286: 	return $env{"course.$courseid.rndseed"};
13287:     }
13288:     return &latest_rnd_algorithm_id();
13289: }
13290: 
13291: sub validCODE {
13292:     my ($CODE)=@_;
13293:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13294:     return 0;
13295: }
13296: 
13297: sub getCODE {
13298:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13299:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13300: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13301: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13302: 	return $Apache::lonhomework::history{'resource.CODE'};
13303:     }
13304:     return undef;
13305: }
13306: #
13307: #  Determines the random seed for a specific context:
13308: #
13309: # parameters:
13310: #   symb      - in course context the symb for the seed.
13311: #   course_id - The course id of the form domain_coursenum.
13312: #   domain    - Domain for the user.
13313: #   course    - Course for the user.
13314: #   cenv      - environment of the course.
13315: #
13316: # NOTE:
13317: #   All parameters are picked out of the environment if missing
13318: #   or not defined.
13319: #   If a symb cannot be determined the current time is used instead.
13320: #
13321: #  For a given well defined symb, courside, domain, username,
13322: #  and course environment, the seed is reproducible.
13323: #
13324: sub rndseed {
13325:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13326:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13327:     if (!defined($symb)) {
13328: 	unless ($symb=$wsymb) { return time; }
13329:     }
13330:     if (!defined $courseid) { 
13331: 	$courseid=$wcourseid; 
13332:     }
13333:     if (!defined $domain) { $domain=$wdomain; }
13334:     if (!defined $username) { $username=$wusername }
13335: 
13336:     my $which;
13337:     if (defined($cenv->{'rndseed'})) {
13338: 	$which = $cenv->{'rndseed'};
13339:     } else {
13340: 	$which =&get_rand_alg($courseid);
13341:     }
13342:     if (defined(&getCODE())) {
13343: 
13344: 	if ($which eq '64bit5') {
13345: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13346: 	} elsif ($which eq '64bit4') {
13347: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13348: 	} else {
13349: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13350: 	}
13351:     } elsif ($which eq '64bit5') {
13352: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13353:     } elsif ($which eq '64bit4') {
13354: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13355:     } elsif ($which eq '64bit3') {
13356: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13357:     } elsif ($which eq '64bit2') {
13358: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13359:     } elsif ($which eq '64bit') {
13360: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13361:     }
13362:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13363: }
13364: 
13365: sub rndseed_32bit {
13366:     my ($symb,$courseid,$domain,$username)=@_;
13367:     {
13368: 	use integer;
13369: 	my $symbchck=unpack("%32C*",$symb) << 27;
13370: 	my $symbseed=numval($symb) << 22;
13371: 	my $namechck=unpack("%32C*",$username) << 17;
13372: 	my $nameseed=numval($username) << 12;
13373: 	my $domainseed=unpack("%32C*",$domain) << 7;
13374: 	my $courseseed=unpack("%32C*",$courseid);
13375: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13376: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13377: 	#&logthis("rndseed :$num:$symb");
13378: 	if ($_64bit) { $num=(($num<<32)>>32); }
13379: 	return $num;
13380:     }
13381: }
13382: 
13383: sub rndseed_64bit {
13384:     my ($symb,$courseid,$domain,$username)=@_;
13385:     {
13386: 	use integer;
13387: 	my $symbchck=unpack("%32S*",$symb) << 21;
13388: 	my $symbseed=numval($symb) << 10;
13389: 	my $namechck=unpack("%32S*",$username);
13390: 	
13391: 	my $nameseed=numval($username) << 21;
13392: 	my $domainseed=unpack("%32S*",$domain) << 10;
13393: 	my $courseseed=unpack("%32S*",$courseid);
13394: 	
13395: 	my $num1=$symbchck+$symbseed+$namechck;
13396: 	my $num2=$nameseed+$domainseed+$courseseed;
13397: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13398: 	#&logthis("rndseed :$num:$symb");
13399: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13400: 	return "$num1,$num2";
13401:     }
13402: }
13403: 
13404: sub rndseed_64bit2 {
13405:     my ($symb,$courseid,$domain,$username)=@_;
13406:     {
13407: 	use integer;
13408: 	# strings need to be an even # of cahracters long, it it is odd the
13409:         # last characters gets thrown away
13410: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13411: 	my $symbseed=numval($symb) << 10;
13412: 	my $namechck=unpack("%32S*",$username.' ');
13413: 	
13414: 	my $nameseed=numval($username) << 21;
13415: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13416: 	my $courseseed=unpack("%32S*",$courseid.' ');
13417: 	
13418: 	my $num1=$symbchck+$symbseed+$namechck;
13419: 	my $num2=$nameseed+$domainseed+$courseseed;
13420: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13421: 	#&logthis("rndseed :$num:$symb");
13422: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13423: 	return "$num1,$num2";
13424:     }
13425: }
13426: 
13427: sub rndseed_64bit3 {
13428:     my ($symb,$courseid,$domain,$username)=@_;
13429:     {
13430: 	use integer;
13431: 	# strings need to be an even # of cahracters long, it it is odd the
13432:         # last characters gets thrown away
13433: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13434: 	my $symbseed=numval2($symb) << 10;
13435: 	my $namechck=unpack("%32S*",$username.' ');
13436: 	
13437: 	my $nameseed=numval2($username) << 21;
13438: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13439: 	my $courseseed=unpack("%32S*",$courseid.' ');
13440: 	
13441: 	my $num1=$symbchck+$symbseed+$namechck;
13442: 	my $num2=$nameseed+$domainseed+$courseseed;
13443: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13444: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13445: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13446: 	
13447: 	return "$num1:$num2";
13448:     }
13449: }
13450: 
13451: sub rndseed_64bit4 {
13452:     my ($symb,$courseid,$domain,$username)=@_;
13453:     {
13454: 	use integer;
13455: 	# strings need to be an even # of cahracters long, it it is odd the
13456:         # last characters gets thrown away
13457: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13458: 	my $symbseed=numval3($symb) << 10;
13459: 	my $namechck=unpack("%32S*",$username.' ');
13460: 	
13461: 	my $nameseed=numval3($username) << 21;
13462: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13463: 	my $courseseed=unpack("%32S*",$courseid.' ');
13464: 	
13465: 	my $num1=$symbchck+$symbseed+$namechck;
13466: 	my $num2=$nameseed+$domainseed+$courseseed;
13467: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13468: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13469: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13470: 	
13471: 	return "$num1:$num2";
13472:     }
13473: }
13474: 
13475: sub rndseed_64bit5 {
13476:     my ($symb,$courseid,$domain,$username)=@_;
13477:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13478:     return "$num1:$num2";
13479: }
13480: 
13481: sub rndseed_CODE_64bit {
13482:     my ($symb,$courseid,$domain,$username)=@_;
13483:     {
13484: 	use integer;
13485: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13486: 	my $symbseed=numval2($symb);
13487: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13488: 	my $CODEseed=numval(&getCODE());
13489: 	my $courseseed=unpack("%32S*",$courseid.' ');
13490: 	my $num1=$symbseed+$CODEchck;
13491: 	my $num2=$CODEseed+$courseseed+$symbchck;
13492: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13493: 	#&logthis("rndseed :$num1:$num2:$symb");
13494: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13495: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13496: 	return "$num1:$num2";
13497:     }
13498: }
13499: 
13500: sub rndseed_CODE_64bit4 {
13501:     my ($symb,$courseid,$domain,$username)=@_;
13502:     {
13503: 	use integer;
13504: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13505: 	my $symbseed=numval3($symb);
13506: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13507: 	my $CODEseed=numval3(&getCODE());
13508: 	my $courseseed=unpack("%32S*",$courseid.' ');
13509: 	my $num1=$symbseed+$CODEchck;
13510: 	my $num2=$CODEseed+$courseseed+$symbchck;
13511: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13512: 	#&logthis("rndseed :$num1:$num2:$symb");
13513: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13514: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13515: 	return "$num1:$num2";
13516:     }
13517: }
13518: 
13519: sub rndseed_CODE_64bit5 {
13520:     my ($symb,$courseid,$domain,$username)=@_;
13521:     my $code = &getCODE();
13522:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13523:     return "$num1:$num2";
13524: }
13525: 
13526: sub setup_random_from_rndseed {
13527:     my ($rndseed)=@_;
13528:     if ($rndseed =~/([,:])/) {
13529:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13530:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13531:             &Math::Random::random_set_seed_from_phrase($rndseed);
13532:         } else {
13533:             &Math::Random::random_set_seed($num1,$num2);
13534:         }
13535:     } else {
13536: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13537:     }
13538: }
13539: 
13540: sub latest_receipt_algorithm_id {
13541:     return 'receipt3';
13542: }
13543: 
13544: sub recunique {
13545:     my $fucourseid=shift;
13546:     my $unique;
13547:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13548: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13549: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13550:     } else {
13551: 	$unique=$perlvar{'lonReceipt'};
13552:     }
13553:     return unpack("%32C*",$unique);
13554: }
13555: 
13556: sub recprefix {
13557:     my $fucourseid=shift;
13558:     my $prefix;
13559:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13560: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13561: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13562:     } else {
13563: 	$prefix=$perlvar{'lonHostID'};
13564:     }
13565:     return unpack("%32C*",$prefix);
13566: }
13567: 
13568: sub ireceipt {
13569:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13570: 
13571:     my $return =&recprefix($fucourseid).'-';
13572: 
13573:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13574: 	$env{'request.state'} eq 'construct') {
13575: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13576: 	return $return;
13577:     }
13578: 
13579:     my $cuname=unpack("%32C*",$funame);
13580:     my $cudom=unpack("%32C*",$fudom);
13581:     my $cucourseid=unpack("%32C*",$fucourseid);
13582:     my $cusymb=unpack("%32C*",$fusymb);
13583:     my $cunique=&recunique($fucourseid);
13584:     my $cpart=unpack("%32S*",$part);
13585:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13586: 
13587: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13588: 			       
13589: 	$return.= ($cunique%$cuname+
13590: 		   $cunique%$cudom+
13591: 		   $cusymb%$cuname+
13592: 		   $cusymb%$cudom+
13593: 		   $cucourseid%$cuname+
13594: 		   $cucourseid%$cudom+
13595: 		   $cpart%$cuname+
13596: 		   $cpart%$cudom);
13597:     } else {
13598: 	$return.= ($cunique%$cuname+
13599: 		   $cunique%$cudom+
13600: 		   $cusymb%$cuname+
13601: 		   $cusymb%$cudom+
13602: 		   $cucourseid%$cuname+
13603: 		   $cucourseid%$cudom);
13604:     }
13605:     return $return;
13606: }
13607: 
13608: sub receipt {
13609:     my ($part)=@_;
13610:     my ($symb,$courseid,$domain,$name) = &whichuser();
13611:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13612: }
13613: 
13614: sub whichuser {
13615:     my ($passedsymb)=@_;
13616:     my ($symb,$courseid,$domain,$name,$publicuser);
13617:     if (defined($env{'form.grade_symb'})) {
13618: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13619: 	my $allowed=&allowed('vgr',$tmp_courseid);
13620: 	if (!$allowed &&
13621: 	    exists($env{'request.course.sec'}) &&
13622: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13623: 	    $allowed=&allowed('vgr',$tmp_courseid.
13624: 			      '/'.$env{'request.course.sec'});
13625: 	}
13626: 	if ($allowed) {
13627: 	    ($symb)=&get_env_multiple('form.grade_symb');
13628: 	    $courseid=$tmp_courseid;
13629: 	    ($domain)=&get_env_multiple('form.grade_domain');
13630: 	    ($name)=&get_env_multiple('form.grade_username');
13631: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13632: 	}
13633:     }
13634:     if (!$passedsymb) {
13635: 	$symb=&symbread();
13636:     } else {
13637: 	$symb=$passedsymb;
13638:     }
13639:     $courseid=$env{'request.course.id'};
13640:     $domain=$env{'user.domain'};
13641:     $name=$env{'user.name'};
13642:     if ($name eq 'public' && $domain eq 'public') {
13643: 	if (!defined($env{'form.username'})) {
13644: 	    $env{'form.username'}.=time.rand(10000000);
13645: 	}
13646: 	$name.=$env{'form.username'};
13647:     }
13648:     return ($symb,$courseid,$domain,$name,$publicuser);
13649: 
13650: }
13651: 
13652: # ------------------------------------------------------------ Serves up a file
13653: # returns either the contents of the file or 
13654: # -1 if the file doesn't exist
13655: #
13656: # if the target is a file that was uploaded via DOCS, 
13657: # a check will be made to see if a current copy exists on the local server,
13658: # if it does this will be served, otherwise a copy will be retrieved from
13659: # the home server for the course and stored in /home/httpd/html/userfiles on
13660: # the local server.   
13661: 
13662: sub getfile {
13663:     my ($file) = @_;
13664:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13665:     &repcopy($file);
13666:     return &readfile($file);
13667: }
13668: 
13669: sub repcopy_userfile {
13670:     my ($file)=@_;
13671:     my $londocroot = $perlvar{'lonDocRoot'};
13672:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13673:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13674:     my ($cdom,$cnum,$filename) = 
13675: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13676:     my $uri="/uploaded/$cdom/$cnum/$filename";
13677:     if (-e "$file") {
13678: # we already have a local copy, check it out
13679: 	my @fileinfo = stat($file);
13680: 	my $rtncode;
13681: 	my $info;
13682: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13683: 	if ($lwpresp ne 'ok') {
13684: # there is no such file anymore, even though we had a local copy
13685: 	    if ($rtncode eq '404') {
13686: 		unlink($file);
13687: 	    }
13688: 	    return -1;
13689: 	}
13690: 	if ($info < $fileinfo[9]) {
13691: # nice, the file we have is up-to-date, just say okay
13692: 	    return 'ok';
13693: 	} else {
13694: # the file is outdated, get rid of it
13695: 	    unlink($file);
13696: 	}
13697:     }
13698: # one way or the other, at this point, we don't have the file
13699: # construct the correct path for the file
13700:     my @parts = ($cdom,$cnum); 
13701:     if ($filename =~ m|^(.+)/[^/]+$|) {
13702: 	push @parts, split(/\//,$1);
13703:     }
13704:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13705:     foreach my $part (@parts) {
13706: 	$path .= '/'.$part;
13707: 	if (!-e $path) {
13708: 	    mkdir($path,0770);
13709: 	}
13710:     }
13711: # now the path exists for sure
13712: # get a user agent
13713:     my $transferfile=$file.'.in.transfer';
13714: # FIXME: this should flock
13715:     if (-e $transferfile) { return 'ok'; }
13716:     my $request;
13717:     $uri=~s/^\///;
13718:     my $homeserver = &homeserver($cnum,$cdom);
13719:     my $hostname = &hostname($homeserver);
13720:     my $protocol = $protocol{$homeserver};
13721:     $protocol = 'http' if ($protocol ne 'https');
13722:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13723:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13724: # did it work?
13725:     if ($response->is_error()) {
13726: 	unlink($transferfile);
13727: 	&logthis("Userfile repcopy failed for $uri");
13728: 	return -1;
13729:     }
13730: # worked, rename the transfer file
13731:     rename($transferfile,$file);
13732:     return 'ok';
13733: }
13734: 
13735: sub tokenwrapper {
13736:     my $uri=shift;
13737:     $uri=~s|^https?\://([^/]+)||;
13738:     $uri=~s|^/||;
13739:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13740:     my $token=$1;
13741:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13742:     if ($udom && $uname && $file) {
13743: 	$file=~s|(\?\.*)*$||;
13744:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13745:         my $homeserver = &homeserver($uname,$udom);
13746:         my $hostname = &hostname($homeserver);
13747:         my $protocol = $protocol{$homeserver};
13748:         $protocol = 'http' if ($protocol ne 'https');
13749:         return $protocol.'://'.$hostname.'/'.$uri.
13750:                (($uri=~/\?/)?'&':'?').'token='.$token.
13751:                                '&tokenissued='.$perlvar{'lonHostID'};
13752:     } else {
13753:         return '/adm/notfound.html';
13754:     }
13755: }
13756: 
13757: # call with reqtype HEAD: get last modification time
13758: # call with reqtype GET: get the file contents
13759: # Do not call this with reqtype GET for large files! It loads everything into memory
13760: #
13761: sub getuploaded {
13762:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13763:     $uri=~s/^\///;
13764:     my $homeserver = &homeserver($cnum,$cdom);
13765:     my $hostname = &hostname($homeserver);
13766:     my $protocol = $protocol{$homeserver};
13767:     $protocol = 'http' if ($protocol ne 'https');
13768:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13769:     my $request=new HTTP::Request($reqtype,$uri);
13770:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13771:     $$rtncode = $response->code;
13772:     if (! $response->is_success()) {
13773: 	return 'failed';
13774:     }      
13775:     if ($reqtype eq 'HEAD') {
13776: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13777:     } elsif ($reqtype eq 'GET') {
13778: 	$$info = $response->content;
13779:     }
13780:     return 'ok';
13781: }
13782: 
13783: sub readfile {
13784:     my $file = shift;
13785:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13786:     my $fh;
13787:     open($fh,"<",$file);
13788:     my $a='';
13789:     while (my $line = <$fh>) { $a .= $line; }
13790:     return $a;
13791: }
13792: 
13793: sub filelocation {
13794:     my ($dir,$file) = @_;
13795:     my $location;
13796:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13797: 
13798:     if ($file =~ m-^/adm/-) {
13799: 	$file=~s-^/adm/wrapper/-/-;
13800: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13801:     }
13802: 
13803:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13804:         $location = $file;
13805:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13806:         my ($udom,$uname,$filename)=
13807:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13808:         my $home=&homeserver($uname,$udom);
13809:         my $is_me=0;
13810:         my @ids=&current_machine_ids();
13811:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13812:         if ($is_me) {
13813:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13814:         } else {
13815:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13816:   	      $udom.'/'.$uname.'/'.$filename;
13817:         }
13818:     } elsif ($file =~ m-^/adm/-) {
13819: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13820:     } else {
13821:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13822:         $file=~s:^/(res|priv)/:/:;
13823:         my $space=$1;
13824:         if ( !( $file =~ m:^/:) ) {
13825:             $location = $dir. '/'.$file;
13826:         } else {
13827:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13828:         }
13829:     }
13830:     $location=~s://+:/:g; # remove duplicate /
13831:     while ($location=~m{/\.\./}) {
13832: 	if ($location =~ m{/[^/]+/\.\./}) {
13833: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13834: 	} else {
13835: 	    $location=~ s{/\.\./}{/}g;
13836: 	}
13837:     } #remove dir/..
13838:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13839:     return $location;
13840: }
13841: 
13842: sub hreflocation {
13843:     my ($dir,$file)=@_;
13844:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13845: 	$file=filelocation($dir,$file);
13846:     } elsif ($file=~m-^/adm/-) {
13847: 	$file=~s-^/adm/wrapper/-/-;
13848: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13849:     }
13850:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13851: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13852:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13853: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13854: 	        {/uploaded/$1/$2/}x;
13855:     }
13856:     if ($file=~ m{^/userfiles/}) {
13857: 	$file =~ s{^/userfiles/}{/uploaded/};
13858:     }
13859:     return $file;
13860: }
13861: 
13862: 
13863: 
13864: 
13865: 
13866: sub current_machine_domains {
13867:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13868: }
13869: 
13870: sub machine_domains {
13871:     my ($hostname) = @_;
13872:     my @domains;
13873:     my %hostname = &all_hostnames();
13874:     while( my($id, $name) = each(%hostname)) {
13875: #	&logthis("-$id-$name-$hostname-");
13876: 	if ($hostname eq $name) {
13877: 	    push(@domains,&host_domain($id));
13878: 	}
13879:     }
13880:     return @domains;
13881: }
13882: 
13883: sub current_machine_ids {
13884:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13885: }
13886: 
13887: sub machine_ids {
13888:     my ($hostname) = @_;
13889:     $hostname ||= &hostname($perlvar{'lonHostID'});
13890:     my @ids;
13891:     my %name_to_host = &all_names();
13892:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13893: 	return @{ $name_to_host{$hostname} };
13894:     }
13895:     return;
13896: }
13897: 
13898: sub additional_machine_domains {
13899:     my @domains;
13900:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13901:     while( my $line = <$fh>) {
13902:         $line =~ s/\s//g;
13903:         push(@domains,$line);
13904:     }
13905:     return @domains;
13906: }
13907: 
13908: sub default_login_domain {
13909:     my $domain = $perlvar{'lonDefDomain'};
13910:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13911:     foreach my $posdom (&current_machine_domains(),
13912:                         &additional_machine_domains()) {
13913:         if (lc($posdom) eq lc($testdomain)) {
13914:             $domain=$posdom;
13915:             last;
13916:         }
13917:     }
13918:     return $domain;
13919: }
13920: 
13921: sub uses_sts {
13922:     my ($ignore_cache) = @_;
13923:     my $lonhost = $perlvar{'lonHostID'};
13924:     my $hostname = &hostname($lonhost);
13925:     my $sts_on;
13926:     if ($protocol{$lonhost} eq 'https') {
13927:         my $cachetime = 12*3600;
13928:         if (!$ignore_cache) {
13929:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13930:             if (defined($cached)) {
13931:                 return $sts_on;
13932:             }
13933:         }
13934:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13935:         my $request=new HTTP::Request('HEAD',$url);
13936:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
13937:         if ($response->is_success) {
13938:             my $has_sts = $response->header('Strict-Transport-Security');
13939:             if ($has_sts eq '') {
13940:                 $sts_on = 0;
13941:             } else {
13942:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13943:                     my $maxage = $1;
13944:                     if ($maxage) {
13945:                         $sts_on = 1;
13946:                     } else {
13947:                         $sts_on = 0;
13948:                     }
13949:                 } else {
13950:                     $sts_on = 0;
13951:                 }
13952:             }
13953:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13954:         }
13955:     }
13956:     return;
13957: }
13958: 
13959: # ------------------------------------------------------------- Declutters URLs
13960: 
13961: sub declutter {
13962:     my $thisfn=shift;
13963:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13964:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13965:         $thisfn=~s{^/home/httpd/html}{};
13966:     }
13967:     $thisfn=~s/^\///;
13968:     $thisfn=~s|^adm/wrapper/||;
13969:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13970:     $thisfn=~s/^res\///;
13971:     $thisfn=~s/^priv\///;
13972:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13973:         $thisfn=~s/\?.+$//;
13974:     }
13975:     return $thisfn;
13976: }
13977: 
13978: # ------------------------------------------------------------- Clutter up URLs
13979: 
13980: sub clutter {
13981:     my $thisfn='/'.&declutter(shift);
13982:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13983: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13984:        $thisfn='/res'.$thisfn; 
13985:     }
13986:     if ($thisfn !~m|^/adm|) {
13987: 	if ($thisfn =~ m|^/ext/|) {
13988: 	    $thisfn='/adm/wrapper'.$thisfn;
13989: 	} else {
13990: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13991: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13992: 	    if ($embstyle eq 'ssi'
13993: 		|| ($embstyle eq 'hdn')
13994: 		|| ($embstyle eq 'rat')
13995: 		|| ($embstyle eq 'prv')
13996: 		|| ($embstyle eq 'ign')) {
13997: 		#do nothing with these
13998: 	    } elsif (($embstyle eq 'img') 
13999: 		|| ($embstyle eq 'emb')
14000: 		|| ($embstyle eq 'wrp')) {
14001: 		$thisfn='/adm/wrapper'.$thisfn;
14002: 	    } elsif ($embstyle eq 'unk'
14003: 		     && $thisfn!~/\.(sequence|page)$/) {
14004: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14005: 	    } else {
14006: #		&logthis("Got a blank emb style");
14007: 	    }
14008: 	}
14009:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14010:         $thisfn='/adm/wrapper'.$thisfn;
14011:     }
14012:     return $thisfn;
14013: }
14014: 
14015: sub clutter_with_no_wrapper {
14016:     my $uri = &clutter(shift);
14017:     if ($uri =~ m-^/adm/-) {
14018: 	$uri =~ s-^/adm/wrapper/-/-;
14019: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14020:     }
14021:     return $uri;
14022: }
14023: 
14024: sub freeze_escape {
14025:     my ($value)=@_;
14026:     if (ref($value)) {
14027: 	$value=&nfreeze($value);
14028: 	return '__FROZEN__'.&escape($value);
14029:     }
14030:     return &escape($value);
14031: }
14032: 
14033: 
14034: sub thaw_unescape {
14035:     my ($value)=@_;
14036:     if ($value =~ /^__FROZEN__/) {
14037: 	substr($value,0,10,undef);
14038: 	$value=&unescape($value);
14039: 	return &thaw($value);
14040:     }
14041:     return &unescape($value);
14042: }
14043: 
14044: sub correct_line_ends {
14045:     my ($result)=@_;
14046:     $$result =~s/\r\n/\n/mg;
14047:     $$result =~s/\r/\n/mg;
14048: }
14049: # ================================================================ Main Program
14050: 
14051: sub goodbye {
14052:    &logthis("Starting Shut down");
14053: #not converted to using infrastruture and probably shouldn't be
14054:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14055: #converted
14056: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14057:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14058: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14059: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14060: #1.1 only
14061: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14062: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14063: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14064: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14065:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14066:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14067:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14068:    &flushcourselogs();
14069:    &logthis("Shutting down");
14070: }
14071: 
14072: sub get_dns {
14073:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14074:     if (!$ignore_cache) {
14075: 	my ($content,$cached)=
14076: 	    &Apache::lonnet::is_cached_new('dns',$url);
14077: 	if ($cached) {
14078: 	    &$func($content,$hashref);
14079: 	    return;
14080: 	}
14081:     }
14082: 
14083:     my %alldns;
14084:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14085:         foreach my $dns (<$config>) {
14086: 	    next if ($dns !~ /^\^(\S*)/x);
14087:             my $line = $1;
14088:             my ($host,$protocol) = split(/:/,$line);
14089:             if ($protocol ne 'https') {
14090:                 $protocol = 'http';
14091:             }
14092: 	    $alldns{$host} = $protocol;
14093:         }
14094:         close($config);
14095:     }
14096:     while (%alldns) {
14097: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14098: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14099:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14100:         delete($alldns{$dns});
14101: 	next if ($response->is_error());
14102:         if ($url eq '/adm/dns/loncapaCRL') {
14103:             return &$func($response);
14104:         } else {
14105: 	    my @content = split("\n",$response->content);
14106: 	    unless ($nocache) {
14107: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14108: 	    }
14109: 	    &$func(\@content,$hashref);
14110:             return;
14111:         }
14112:     }
14113:     my $which = (split('/',$url,4))[3];
14114:     if ($which eq 'loncapaCRL') {
14115:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14116:         if (-e $diskfile) {
14117:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14118:         } else {
14119:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14120:         }
14121:     } else {
14122:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14123:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14124:             my @content = <$config>;
14125:             close($config);
14126:             &$func(\@content,$hashref);
14127:         }
14128:     }
14129:     return;
14130: }
14131: 
14132: # ------------------------------------------------------Get DNS checksums file
14133: sub parse_dns_checksums_tab {
14134:     my ($lines,$hashref) = @_;
14135:     my $lonhost = $perlvar{'lonHostID'};
14136:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14137:     my $loncaparev = &get_server_loncaparev($machine_dom);
14138:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14139:     my $webconfdir = '/etc/httpd/conf';
14140:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14141:         $webconfdir = '/etc/apache2';
14142:     } elsif ($distro =~ /^sles(\d+)$/) {
14143:         if ($1 >= 10) {
14144:             $webconfdir = '/etc/apache2';
14145:         }
14146:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14147:         if ($1 >= 10.0) {
14148:             $webconfdir = '/etc/apache2';
14149:         }
14150:     }
14151:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14152:     my (%chksum,%revnum);
14153:     if (ref($lines) eq 'ARRAY') {
14154:         chomp(@{$lines});
14155:         my $version = shift(@{$lines});
14156:         if ($version eq $release) {  
14157:             foreach my $line (@{$lines}) {
14158:                 my ($file,$version,$shasum) = split(/,/,$line);
14159:                 if ($file =~ m{^/etc/httpd/conf}) {
14160:                     if ($webconfdir eq '/etc/apache2') {
14161:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14162:                     }
14163:                 }
14164:                 $chksum{$file} = $shasum;
14165:                 $revnum{$file} = $version;
14166:             }
14167:             if (ref($hashref) eq 'HASH') {
14168:                 %{$hashref} = (
14169:                                 sums     => \%chksum,
14170:                                 versions => \%revnum,
14171:                               );
14172:             }
14173:         }
14174:     }
14175:     return;
14176: }
14177: 
14178: sub fetch_dns_checksums {
14179:     my %checksums;
14180:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14181:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14182:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14183:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14184:              \%checksums);
14185:     return \%checksums;
14186: }
14187: 
14188: sub fetch_crl_pemfile {
14189:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14190: }
14191: 
14192: sub save_crl_pem {
14193:     my ($response) = @_;
14194:     my ($msg,$hadchanges);
14195:     if (ref($response)) {
14196:         my $now = time;
14197:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14198:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14199:         if (open(my $fh,'>',"$tmpcrl")) {
14200:             print $fh $response->content;
14201:             close($fh);
14202:             if (-e $lonca) {
14203:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14204:                     my $check = <PIPE>;
14205:                     close(PIPE);
14206:                     chomp($check);
14207:                     if ($check eq 'verify OK') {
14208:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14209:                         my $backup;
14210:                         if (-e $dest) {
14211:                             if (&File::Copy::move($dest,"$dest.bak")) {
14212:                                 $backup = 'ok';
14213:                             }
14214:                         }
14215:                         if (&File::Copy::move($tmpcrl,$dest)) {
14216:                             $msg = 'ok';
14217:                             if ($backup) {
14218:                                 my (%oldnums,%newnums);
14219:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14220:                                     while (<PIPE>) {
14221:                                         $oldnums{(split(/:/))[1]} = 1;
14222:                                     }
14223:                                     close(PIPE);
14224:                                 }
14225:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14226:                                     while(<PIPE>) {
14227:                                         $newnums{(split(/:/))[1]} = 1;
14228:                                     }
14229:                                     close(PIPE);
14230:                                 }
14231:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14232:                                     unless (exists($oldnums{$key})) {
14233:                                         $hadchanges = 1;
14234:                                         last;
14235:                                     }
14236:                                 }
14237:                                 unless ($hadchanges) {
14238:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14239:                                         unless (exists($newnums{$key})) {
14240:                                             $hadchanges = 1;
14241:                                             last;
14242:                                         }
14243:                                     }
14244:                                 }
14245:                             }
14246:                         }
14247:                     } else {
14248:                         unlink($tmpcrl);
14249:                     }
14250:                 } else {
14251:                     unlink($tmpcrl);
14252:                 }
14253:             } else {
14254:                 unlink($tmpcrl);
14255:             }
14256:         }
14257:     }
14258:     return ($msg,$hadchanges);
14259: }
14260: 
14261: # ------------------------------------------------------------ Read domain file
14262: {
14263:     my $loaded;
14264:     my %domain;
14265: 
14266:     sub parse_domain_tab {
14267: 	my ($lines) = @_;
14268: 	foreach my $line (@$lines) {
14269: 	    next if ($line =~ /^(\#|\s*$ )/x);
14270: 
14271: 	    chomp($line);
14272: 	    my ($name,@elements) = split(/:/,$line,9);
14273: 	    my %this_domain;
14274: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14275: 			       'lang_def', 'city', 'longi', 'lati',
14276: 			       'primary') {
14277: 		$this_domain{$field} = shift(@elements);
14278: 	    }
14279: 	    $domain{$name} = \%this_domain;
14280: 	}
14281:     }
14282: 
14283:     sub reset_domain_info {
14284: 	undef($loaded);
14285: 	undef(%domain);
14286:     }
14287: 
14288:     sub load_domain_tab {
14289: 	my ($ignore_cache,$nocache) = @_;
14290: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14291: 	my $fh;
14292: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14293: 	    my @lines = <$fh>;
14294: 	    &parse_domain_tab(\@lines);
14295: 	}
14296: 	close($fh);
14297: 	$loaded = 1;
14298:     }
14299: 
14300:     sub domain {
14301: 	&load_domain_tab() if (!$loaded);
14302: 
14303: 	my ($name,$what) = @_;
14304: 	return if ( !exists($domain{$name}) );
14305: 
14306: 	if (!$what) {
14307: 	    return $domain{$name}{'description'};
14308: 	}
14309: 	return $domain{$name}{$what};
14310:     }
14311: 
14312:     sub domain_info {
14313:         &load_domain_tab() if (!$loaded);
14314:         return %domain;
14315:     }
14316: 
14317: }
14318: 
14319: 
14320: # ------------------------------------------------------------- Read hosts file
14321: {
14322:     my %hostname;
14323:     my %hostdom;
14324:     my %libserv;
14325:     my $loaded;
14326:     my %name_to_host;
14327:     my %internetdom;
14328:     my %LC_dns_serv;
14329: 
14330:     sub parse_hosts_tab {
14331: 	my ($file) = @_;
14332: 	foreach my $configline (@$file) {
14333: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14334:             chomp($configline);
14335: 	    if ($configline =~ /^\^/) {
14336:                 if ($configline =~ /^\^([\w.\-]+)/) {
14337:                     $LC_dns_serv{$1} = 1;
14338:                 }
14339:                 next;
14340:             }
14341: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14342: 	    $name=~s/\s//g;
14343: 	    if ($id && $domain && $role && $name) {
14344:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14345:                     my $curr = $hostname{$id};
14346:                     my $skip;
14347:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14348:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14349:                             $skip = 1;
14350:                         } else {
14351:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14352:                         }
14353:                     }
14354:                     unless ($skip) {
14355:                         push(@{$name_to_host{$name}},$id);
14356:                     }
14357:                 } else {
14358:                     push(@{$name_to_host{$name}},$id);
14359:                 }
14360: 		$hostname{$id}=$name;
14361: 		$hostdom{$id}=$domain;
14362: 		if ($role eq 'library') { $libserv{$id}=$name; }
14363:                 if (defined($protocol)) {
14364:                     if ($protocol eq 'https') {
14365:                         $protocol{$id} = $protocol;
14366:                     } else {
14367:                         $protocol{$id} = 'http'; 
14368:                     }
14369:                 } else {
14370:                     $protocol{$id} = 'http';
14371:                 }
14372:                 if (defined($intdom)) {
14373:                     $internetdom{$id} = $intdom;
14374:                 }
14375: 	    }
14376: 	}
14377:     }
14378:     
14379:     sub reset_hosts_info {
14380: 	&purge_remembered();
14381: 	&reset_domain_info();
14382: 	&reset_hosts_ip_info();
14383:         undef(%internetdom);
14384: 	undef(%name_to_host);
14385: 	undef(%hostname);
14386: 	undef(%hostdom);
14387: 	undef(%libserv);
14388: 	undef($loaded);
14389:     }
14390: 
14391:     sub load_hosts_tab {
14392: 	my ($ignore_cache,$nocache) = @_;
14393: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14394: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14395: 	my @config = <$config>;
14396: 	&parse_hosts_tab(\@config);
14397: 	close($config);
14398: 	$loaded=1;
14399:     }
14400: 
14401:     sub hostname {
14402: 	&load_hosts_tab() if (!$loaded);
14403: 
14404: 	my ($lonid) = @_;
14405: 	return $hostname{$lonid};
14406:     }
14407: 
14408:     sub all_hostnames {
14409: 	&load_hosts_tab() if (!$loaded);
14410: 
14411: 	return %hostname;
14412:     }
14413: 
14414:     sub all_names {
14415:         my ($ignore_cache,$nocache) = @_;
14416: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14417: 
14418: 	return %name_to_host;
14419:     }
14420: 
14421:     sub all_host_domain {
14422:         &load_hosts_tab() if (!$loaded);
14423:         return %hostdom;
14424:     }
14425: 
14426:     sub all_host_intdom {
14427:         &load_hosts_tab() if (!$loaded);
14428:         return %internetdom;
14429:     }
14430: 
14431:     sub is_library {
14432: 	&load_hosts_tab() if (!$loaded);
14433: 
14434: 	return exists($libserv{$_[0]});
14435:     }
14436: 
14437:     sub all_library {
14438: 	&load_hosts_tab() if (!$loaded);
14439: 
14440: 	return %libserv;
14441:     }
14442: 
14443:     sub unique_library {
14444: 	#2x reverse removes all hostnames that appear more than once
14445:         my %unique = reverse &all_library();
14446:         return reverse %unique;
14447:     }
14448: 
14449:     sub get_servers {
14450: 	&load_hosts_tab() if (!$loaded);
14451: 
14452: 	my ($domain,$type) = @_;
14453: 	my %possible_hosts = ($type eq 'library') ? %libserv
14454: 	                                          : %hostname;
14455: 	my %result;
14456: 	if (ref($domain) eq 'ARRAY') {
14457: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14458: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14459: 		    $result{$host} = $hostname;
14460: 		}
14461: 	    }
14462: 	} else {
14463: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14464: 		if ($hostdom{$host} eq $domain) {
14465: 		    $result{$host} = $hostname;
14466: 		}
14467: 	    }
14468: 	}
14469: 	return %result;
14470:     }
14471: 
14472:     sub get_unique_servers {
14473:         my %unique = reverse &get_servers(@_);
14474: 	return reverse %unique;
14475:     }
14476: 
14477:     sub host_domain {
14478: 	&load_hosts_tab() if (!$loaded);
14479: 
14480: 	my ($lonid) = @_;
14481: 	return $hostdom{$lonid};
14482:     }
14483: 
14484:     sub all_domains {
14485: 	&load_hosts_tab() if (!$loaded);
14486: 
14487: 	my %seen;
14488: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14489: 	return @uniq;
14490:     }
14491: 
14492:     sub internet_dom {
14493:         &load_hosts_tab() if (!$loaded);
14494: 
14495:         my ($lonid) = @_;
14496:         return $internetdom{$lonid};
14497:     }
14498: 
14499:     sub is_LC_dns {
14500:         &load_hosts_tab() if (!$loaded);
14501: 
14502:         my ($hostname) = @_;
14503:         return exists($LC_dns_serv{$hostname});
14504:     }
14505: 
14506: }
14507: 
14508: { 
14509:     my %iphost;
14510:     my %name_to_ip;
14511:     my %lonid_to_ip;
14512: 
14513:     sub get_hosts_from_ip {
14514: 	my ($ip) = @_;
14515: 	my %iphosts = &get_iphost();
14516: 	if (ref($iphosts{$ip})) {
14517: 	    return @{$iphosts{$ip}};
14518: 	}
14519: 	return;
14520:     }
14521:     
14522:     sub reset_hosts_ip_info {
14523: 	undef(%iphost);
14524: 	undef(%name_to_ip);
14525: 	undef(%lonid_to_ip);
14526:     }
14527: 
14528:     sub get_host_ip {
14529: 	my ($lonid) = @_;
14530: 	if (exists($lonid_to_ip{$lonid})) {
14531: 	    return $lonid_to_ip{$lonid};
14532: 	}
14533: 	my $name=&hostname($lonid);
14534:    	my $ip = gethostbyname($name);
14535: 	return if (!$ip || length($ip) ne 4);
14536: 	$ip=inet_ntoa($ip);
14537: 	$name_to_ip{$name}   = $ip;
14538: 	$lonid_to_ip{$lonid} = $ip;
14539: 	return $ip;
14540:     }
14541:     
14542:     sub get_iphost {
14543: 	my ($ignore_cache,$nocache) = @_;
14544: 
14545: 	if (!$ignore_cache) {
14546: 	    if (%iphost) {
14547: 		return %iphost;
14548: 	    }
14549: 	    my ($ip_info,$cached)=
14550: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14551: 	    if ($cached) {
14552: 		%iphost      = %{$ip_info->[0]};
14553: 		%name_to_ip  = %{$ip_info->[1]};
14554: 		%lonid_to_ip = %{$ip_info->[2]};
14555: 		return %iphost;
14556: 	    }
14557: 	}
14558: 
14559: 	# get yesterday's info for fallback
14560: 	my %old_name_to_ip;
14561: 	my ($ip_info,$cached)=
14562: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14563: 	if ($cached) {
14564: 	    %old_name_to_ip = %{$ip_info->[1]};
14565: 	}
14566: 
14567: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14568: 	foreach my $name (keys(%name_to_host)) {
14569: 	    my $ip;
14570: 	    if (!exists($name_to_ip{$name})) {
14571: 		$ip = gethostbyname($name);
14572: 		if (!$ip || length($ip) ne 4) {
14573: 		    if (defined($old_name_to_ip{$name})) {
14574: 			$ip = $old_name_to_ip{$name};
14575: 			&logthis("Can't find $name defaulting to old $ip");
14576: 		    } else {
14577: 			&logthis("Name $name no IP found");
14578: 			next;
14579: 		    }
14580: 		} else {
14581: 		    $ip=inet_ntoa($ip);
14582: 		}
14583: 		$name_to_ip{$name} = $ip;
14584: 	    } else {
14585: 		$ip = $name_to_ip{$name};
14586: 	    }
14587: 	    foreach my $id (@{ $name_to_host{$name} }) {
14588: 		$lonid_to_ip{$id} = $ip;
14589: 	    }
14590: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14591: 	}
14592:         unless ($nocache) {
14593: 	    &do_cache_new('iphost','iphost',
14594: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14595: 		          48*60*60);
14596:         }
14597: 
14598: 	return %iphost;
14599:     }
14600: 
14601:     #
14602:     #  Given a DNS returns the loncapa host name for that DNS 
14603:     # 
14604:     sub host_from_dns {
14605:         my ($dns) = @_;
14606:         my @hosts;
14607:         my $ip;
14608: 
14609:         if (exists($name_to_ip{$dns})) {
14610:             $ip = $name_to_ip{$dns};
14611:         }
14612:         if (!$ip) {
14613:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14614:             if (length($ip) == 4) { 
14615: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14616:             }
14617:         }
14618:         if ($ip) {
14619: 	    @hosts = get_hosts_from_ip($ip);
14620: 	    return $hosts[0];
14621:         }
14622:         return undef;
14623:     }
14624: 
14625:     sub get_internet_names {
14626:         my ($lonid) = @_;
14627:         return if ($lonid eq '');
14628:         my ($idnref,$cached)=
14629:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14630:         if ($cached) {
14631:             return $idnref;
14632:         }
14633:         my $ip = &get_host_ip($lonid);
14634:         my @hosts = &get_hosts_from_ip($ip);
14635:         my %iphost = &get_iphost();
14636:         my (@idns,%seen);
14637:         foreach my $id (@hosts) {
14638:             my $dom = &host_domain($id);
14639:             my $prim_id = &domain($dom,'primary');
14640:             my $prim_ip = &get_host_ip($prim_id);
14641:             next if ($seen{$prim_ip});
14642:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14643:                 foreach my $id (@{$iphost{$prim_ip}}) {
14644:                     my $intdom = &internet_dom($id);
14645:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14646:                         push(@idns,$intdom);
14647:                     }
14648:                 }
14649:             }
14650:             $seen{$prim_ip} = 1;
14651:         }
14652:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14653:     }
14654: 
14655: }
14656: 
14657: sub all_loncaparevs {
14658:     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);
14659: }
14660: 
14661: # ---------------------------------------------------------- Read loncaparev table
14662: {
14663:     sub load_loncaparevs { 
14664:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14665:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14666:                 while (my $configline=<$config>) {
14667:                     chomp($configline);
14668:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14669:                     $loncaparevs{$hostid}=$loncaparev;
14670:                 }
14671:                 close($config);
14672:             }
14673:         }
14674:     }
14675: }
14676: 
14677: # ---------------------------------------------------------- Read serverhostID table
14678: {
14679:     sub load_serverhomeIDs {
14680:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14681:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14682:                 while (my $configline=<$config>) {
14683:                     chomp($configline);
14684:                     my ($name,$id)=split(/:/,$configline);
14685:                     $serverhomeIDs{$name}=$id;
14686:                 }
14687:                 close($config);
14688:             }
14689:         }
14690:     }
14691: }
14692: 
14693: 
14694: BEGIN {
14695: 
14696: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14697:     unless ($readit) {
14698: {
14699:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14700:     %perlvar = (%perlvar,%{$configvars});
14701: }
14702: 
14703: 
14704: # ------------------------------------------------------ Read spare server file
14705: {
14706:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14707: 
14708:     while (my $configline=<$config>) {
14709:        chomp($configline);
14710:        if ($configline) {
14711: 	   my ($host,$type) = split(':',$configline,2);
14712: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14713: 	   push(@{ $spareid{$type} }, $host);
14714:        }
14715:     }
14716:     close($config);
14717: }
14718: # ------------------------------------------------------------ Read permissions
14719: {
14720:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14721: 
14722:     while (my $configline=<$config>) {
14723: 	chomp($configline);
14724: 	if ($configline) {
14725: 	    my ($role,$perm)=split(/ /,$configline);
14726: 	    if ($perm ne '') { $pr{$role}=$perm; }
14727: 	}
14728:     }
14729:     close($config);
14730: }
14731: 
14732: # -------------------------------------------- Read plain texts for permissions
14733: {
14734:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14735: 
14736:     while (my $configline=<$config>) {
14737: 	chomp($configline);
14738: 	if ($configline) {
14739: 	    my ($short,@plain)=split(/:/,$configline);
14740:             %{$prp{$short}} = ();
14741: 	    if (@plain > 0) {
14742:                 $prp{$short}{'std'} = $plain[0];
14743:                 for (my $i=1; $i<@plain; $i++) {
14744:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14745:                 }
14746:             }
14747: 	}
14748:     }
14749:     close($config);
14750: }
14751: 
14752: # ---------------------------------------------------------- Read package table
14753: {
14754:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14755: 
14756:     while (my $configline=<$config>) {
14757: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14758: 	chomp($configline);
14759: 	my ($short,$plain)=split(/:/,$configline);
14760: 	my ($pack,$name)=split(/\&/,$short);
14761: 	if ($plain ne '') {
14762: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14763: 	    $packagetab{$short}=$plain; 
14764: 	}
14765:     }
14766:     close($config);
14767: }
14768: 
14769: # ---------------------------------------------------------- Read loncaparev table
14770: 
14771: &load_loncaparevs();
14772: 
14773: # ---------------------------------------------------------- Read serverhostID table
14774: 
14775: &load_serverhomeIDs();
14776: 
14777: # ---------------------------------------------------------- Read releaseslist XML
14778: {
14779:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14780:     if (-e $file) {
14781:         my $parser = HTML::LCParser->new($file);
14782:         while (my $token = $parser->get_token()) {
14783:             if ($token->[0] eq 'S') {
14784:                 my $item = $token->[1];
14785:                 my $name = $token->[2]{'name'};
14786:                 my $value = $token->[2]{'value'};
14787:                 my $valuematch = $token->[2]{'valuematch'};
14788:                 my $namematch = $token->[2]{'namematch'};
14789:                 if ($item eq 'parameter') {
14790:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14791:                         my $release = $parser->get_text();
14792:                         $release =~ s/(^\s*|\s*$ )//gx;
14793:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14794:                     }
14795:                 } elsif ($item ne '' && $name ne '') {
14796:                     my $release = $parser->get_text();
14797:                     $release =~ s/(^\s*|\s*$ )//gx;
14798:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14799:                 }
14800:             }
14801:         }
14802:     }
14803: }
14804: 
14805: # ---------------------------------------------------------- Read managers table
14806: {
14807:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14808:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14809:             while (my $configline=<$config>) {
14810:                 chomp($configline);
14811:                 next if ($configline =~ /^\#/);
14812:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14813:                     $managerstab{$configline} = 1;
14814:                 }
14815:             }
14816:             close($config);
14817:         }
14818:     }
14819: }
14820: 
14821: # ------------- set up temporary directory
14822: {
14823:     $tmpdir = LONCAPA::tempdir();
14824: 
14825: }
14826: 
14827: # ------------- set default texengine (domain default overrides this)
14828: {
14829:     $deftex = LONCAPA::texengine();
14830: }
14831: 
14832: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14833: 				'compress_threshold'=> 20_000,
14834:  			        });
14835: 
14836: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14837: $dumpcount=0;
14838: $locknum=0;
14839: 
14840: &logtouch();
14841: &logthis('<font color="yellow">INFO: Read configuration</font>');
14842: $readit=1;
14843:     {
14844: 	use integer;
14845: 	my $test=(2**32)+1;
14846: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14847: 	&logthis(" Detected 64bit platform ($_64bit)");
14848:     }
14849: }
14850: }
14851: 
14852: 1;
14853: __END__
14854: 
14855: =pod
14856: 
14857: =head1 NAME
14858: 
14859: Apache::lonnet - Subroutines to ask questions about things in the network.
14860: 
14861: =head1 SYNOPSIS
14862: 
14863: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14864: 
14865:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14866: 
14867: Common parameters:
14868: 
14869: =over 4
14870: 
14871: =item *
14872: 
14873: $uname : an internal username (if $cname expecting a course Id specifically)
14874: 
14875: =item *
14876: 
14877: $udom : a domain (if $cdom expecting a course's domain specifically)
14878: 
14879: =item *
14880: 
14881: $symb : a resource instance identifier
14882: 
14883: =item *
14884: 
14885: $namespace : the name of a .db file that contains the data needed or
14886: being set.
14887: 
14888: =back
14889: 
14890: =head1 OVERVIEW
14891: 
14892: lonnet provides subroutines which interact with the
14893: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14894: about classes, users, and resources.
14895: 
14896: For many of these objects you can also use this to store data about
14897: them or modify them in various ways.
14898: 
14899: =head2 Symbs
14900: 
14901: To identify a specific instance of a resource, LON-CAPA uses symbols
14902: or "symbs"X<symb>. These identifiers are built from the URL of the
14903: map, the resource number of the resource in the map, and the URL of
14904: the resource itself. The latter is somewhat redundant, but might help
14905: if maps change.
14906: 
14907: An example is
14908: 
14909:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14910: 
14911: The respective map entry is
14912: 
14913:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14914:   title="Problem 2">
14915:  </resource>
14916: 
14917: Symbs are used by the random number generator, as well as to store and
14918: restore data specific to a certain instance of for example a problem.
14919: 
14920: =head2 Storing And Retrieving Data
14921: 
14922: X<store()>X<cstore()>X<restore()>Three of the most important functions
14923: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14924: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14925: is is the non-critical message twin of cstore. These functions are for
14926: handlers to store a perl hash to a user's permanent data space in an
14927: easy manner, and to retrieve it again on another call. It is expected
14928: that a handler would use this once at the beginning to retrieve data,
14929: and then again once at the end to send only the new data back.
14930: 
14931: The data is stored in the user's data directory on the user's
14932: homeserver under the ID of the course.
14933: 
14934: The hash that is returned by restore will have all of the previous
14935: value for all of the elements of the hash.
14936: 
14937: Example:
14938: 
14939:  #creating a hash
14940:  my %hash;
14941:  $hash{'foo'}='bar';
14942: 
14943:  #storing it
14944:  &Apache::lonnet::cstore(\%hash);
14945: 
14946:  #changing a value
14947:  $hash{'foo'}='notbar';
14948: 
14949:  #adding a new value
14950:  $hash{'bar'}='foo';
14951:  &Apache::lonnet::cstore(\%hash);
14952: 
14953:  #retrieving the hash
14954:  my %history=&Apache::lonnet::restore();
14955: 
14956:  #print the hash
14957:  foreach my $key (sort(keys(%history))) {
14958:    print("\%history{$key} = $history{$key}");
14959:  }
14960: 
14961: Will print out:
14962: 
14963:  %history{1:foo} = bar
14964:  %history{1:keys} = foo:timestamp
14965:  %history{1:timestamp} = 990455579
14966:  %history{2:bar} = foo
14967:  %history{2:foo} = notbar
14968:  %history{2:keys} = foo:bar:timestamp
14969:  %history{2:timestamp} = 990455580
14970:  %history{bar} = foo
14971:  %history{foo} = notbar
14972:  %history{timestamp} = 990455580
14973:  %history{version} = 2
14974: 
14975: Note that the special hash entries C<keys>, C<version> and
14976: C<timestamp> were added to the hash. C<version> will be equal to the
14977: total number of versions of the data that have been stored. The
14978: C<timestamp> attribute will be the UNIX time the hash was
14979: stored. C<keys> is available in every historical section to list which
14980: keys were added or changed at a specific historical revision of a
14981: hash.
14982: 
14983: B<Warning>: do not store the hash that restore returns directly. This
14984: will cause a mess since it will restore the historical keys as if the
14985: were new keys. I.E. 1:foo will become 1:1:foo etc.
14986: 
14987: Calling convention:
14988: 
14989:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14990:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14991: 
14992: For more detailed information, see lonnet specific documentation.
14993: 
14994: =head1 RETURN MESSAGES
14995: 
14996: =over 4
14997: 
14998: =item * B<con_lost>: unable to contact remote host
14999: 
15000: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15001: when the connection is brought back up
15002: 
15003: =item * B<con_failed>: unable to contact remote host and unable to save message
15004: for later delivery
15005: 
15006: =item * B<error:>: an error a occurred, a description of the error follows the :
15007: 
15008: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15009: that was requested
15010: 
15011: =back
15012: 
15013: =head1 PUBLIC SUBROUTINES
15014: 
15015: =head2 Session Environment Functions
15016: 
15017: =over 4
15018: 
15019: =item * 
15020: X<appenv()>
15021: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15022: the user envirnoment file, and will be restored for each access this
15023: user makes during this session, also modifies the %env for the current
15024: process. Optional rolesarrayref - if defined contains a reference to an array
15025: of roles which are exempt from the restriction on modifying user.role entries 
15026: in the user's environment.db and in %env.    
15027: 
15028: =item *
15029: X<delenv()>
15030: B<delenv($delthis,$regexp)>: removes all items from the session
15031: environment file that begin with $delthis. If the 
15032: optional second arg - $regexp - is true, $delthis is treated as a 
15033: regular expression, otherwise \Q$delthis\E is used. 
15034: The values are also deleted from the current processes %env.
15035: 
15036: =item * get_env_multiple($name) 
15037: 
15038: gets $name from the %env hash, it seemlessly handles the cases where multiple
15039: values may be defined and end up as an array ref.
15040: 
15041: returns an array of values
15042: 
15043: =back
15044: 
15045: =head2 User Information
15046: 
15047: =over 4
15048: 
15049: =item *
15050: X<queryauthenticate()>
15051: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15052: authentication scheme
15053: 
15054: =item *
15055: X<authenticate()>
15056: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15057: authenticate user from domain's lib servers (first use the current
15058: one). C<$upass> should be the users password.
15059: $checkdefauth is optional (value is 1 if a check should be made to
15060:    authenticate user using default authentication method, and allow
15061:    account creation if username does not have account in the domain).
15062: $clientcancheckhost is optional (value is 1 if checking whether the
15063:    server can host will occur on the client side in lonauth.pm).   
15064: 
15065: =item *
15066: X<homeserver()>
15067: B<homeserver($uname,$udom)>: find the server which has
15068: the user's directory and files (there must be only one), this caches
15069: the answer, and also caches if there is a borken connection.
15070: 
15071: =item *
15072: X<idget()>
15073: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15074: a list of student/employee IDs or clicker IDs
15075: (student/employee IDs are a unique resource in a domain, there must be 
15076: only 1 ID per username, and only 1 username per ID in a specific domain).
15077: clickerIDs are not necessarily unique, as students might share clickers.
15078: (returns hash: id=>name,id=>name)
15079: 
15080: =item *
15081: X<idrget()>
15082: B<idrget($udom,@unames)>: find the IDs behind a list of
15083: usernames (returns hash: name=>id,name=>id)
15084: 
15085: =item *
15086: X<idput()>
15087: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15088: names and associated student/employee IDs or clicker IDs.
15089: 
15090: =item *
15091: X<iddel()>
15092: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15093: student/employee ID or clicker ID username look-ups from domain.
15094: The homeserver ($uhome) and namespace ($namespace) are optional.
15095: If no $uhome is provided, it will be determined usig &homeserver()
15096: for each user.  If no $namespace is provided, the default is ids.
15097: 
15098: =item *
15099: X<updateclickers()>
15100: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15101: clicker ID-to-username look-ups in clickers.db on library server.
15102: Permitted actions are add or del (i.e., add or delete). The 
15103: clickers.db contains clickerID as keys (escaped), and each corresponding
15104: value is an escaped comma-separated list of usernames (for whom the
15105: library server is the homeserver), who registered that particular ID.
15106: If $critical is true, the update will be sent via &critical, otherwise
15107: &reply() will be used.
15108: 
15109: =item *
15110: X<rolesinit()>
15111: B<rolesinit($udom,$username)>: get user privileges.
15112: returns user role, first access and timer interval hashes
15113: 
15114: =item *
15115: X<privileged()>
15116: B<privileged($username,$domain)>: returns a true if user has a
15117: privileged and active role (i.e. su or dc), false otherwise.
15118: 
15119: =item *
15120: X<getsection()>
15121: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15122: course $cname, return section name/number or '' for "not in course"
15123: and '-1' for "no section"
15124: 
15125: =item *
15126: X<userenvironment()>
15127: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15128: passed in @what from the requested user's environment, returns a hash
15129: 
15130: =item * 
15131: X<userlog_query()>
15132: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15133: activity.log file. %filters defines filters applied when parsing the
15134: log file. These can be start or end timestamps, or the type of action
15135: - log to look for Login or Logout events, check for Checkin or
15136: Checkout, role for role selection. The response is in the form
15137: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15138: escaped strings of the action recorded in the activity.log file.
15139: 
15140: =back
15141: 
15142: =head2 User Roles
15143: 
15144: =over 4
15145: 
15146: =item *
15147: 
15148: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15149: returns codes for allowed actions.
15150: 
15151: The first argument is required, all others are optional.
15152: 
15153: $priv is the privilege being checked.
15154: $uri contains additional information about what is being checked for access (e.g.,
15155: URL, course ID etc.). 
15156: $symb is the unique resource instance identifier in a course; if needed,
15157: but not provided, it will be retrieved via a call to &symbread(). 
15158: $role is the role for which a priv is being checked (only used if priv is evb). 
15159: $clientip is the user's IP address (only used when checking for access to portfolio 
15160: files).
15161: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15162: prevents recursive calls to &allowed.
15163: 
15164:  F: full access
15165:  U,I,K: authentication modes (cxx only)
15166:  '': forbidden
15167:  1: user needs to choose course
15168:  2: browse allowed
15169:  A: passphrase authentication needed
15170:  B: access temporarily blocked because of a blocking event in a course.
15171:  D: access blocked because access is required via session initiated via deep-link 
15172: 
15173: =item *
15174: 
15175: constructaccess($url,$setpriv) : check for access to construction space URL
15176: 
15177: See if the owner domain and name in the URL match those in the
15178: expected environment.  If so, return three element list
15179: ($ownername,$ownerdomain,$ownerhome).
15180: 
15181: Otherwise return the null string.
15182: 
15183: If second argument 'setpriv' is true, it assigns the privileges,
15184: and returns the same three element list, unless the owner has
15185: blocked "ad hoc" Domain Coordinator access to the Author Space,
15186: in which case the null string is returned.
15187: 
15188: =item *
15189: 
15190: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15191: define a custom role rolename set privileges in format of lonTabs/roles.tab
15192: for system, domain, and course level. $uname and $udom are optional (current
15193: user's username and domain will be used when either of $uname or $udom are absent.
15194: 
15195: =item *
15196: 
15197: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15198: (rolesplain.tab); plain text explanation of a user role term.
15199: $type is Course (default) or Community.
15200: If $forcedefault evaluates to true, text returned will be default 
15201: text for $type. Otherwise, if this is a course, the text returned 
15202: will be a custom name for the role (if defined in the course's 
15203: environment).  If no custom name is defined the default is returned.
15204:    
15205: =item *
15206: 
15207: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15208: All arguments are optional. Returns a hash of a roles, either for
15209: co-author/assistant author roles for a user's Construction Space
15210: (default), or if $context is 'userroles', roles for the user himself,
15211: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15212: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15213: For each key, value is set to colon-separated start and end times for
15214: the role.  If no username and domain are specified, will default to
15215: current user/domain. Types, roles, and roledoms are references to arrays
15216: of role statuses (active, future or previous), roles 
15217: (e.g., cc,in, st etc.) and domains of the roles which can be used
15218: to restrict the list of roles reported. If no array ref is 
15219: provided for types, will default to return only active roles.
15220: 
15221: =item *
15222: 
15223: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15224: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15225: 
15226: Additional optional arguments are: $type (if role checking is to be restricted 
15227: to certain user status types -- previous (expired roles), active (currently
15228: available roles) or future (roles available in the future), and
15229: $hideprivileged -- if true will not report course roles for users who
15230: have active Domain Coordinator role in course's domain or in additional
15231: domains (specified in 'Domains to check for privileged users' in course
15232: environment -- set via:  Course Settings -> Classlists and staff listing).
15233: 
15234: =item *
15235: 
15236: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15237: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15238: $possdomains and $possroles are optional array refs -- to domains to check and
15239: roles to check.  If $possdomains is not specified, a dump will be done of the
15240: users' roles.db to check for a dc or su role in any domain. This can be
15241: time consuming if &privileged is called repeatedly (e.g., when displaying a
15242: classlist), so in such cases, supplying a $possdomains array is preferred, as
15243: this then allows &privileged_by_domain() to be used, which caches the identity
15244: of privileged users, eliminating the need for repeated calls to &dump().
15245: 
15246: =item *
15247: 
15248: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15249: where the outer hash keys are domains specified in the $possdomains array ref,
15250: next inner hash keys are privileged roles specified in the $roles array ref,
15251: and the innermost hash contains key = value pairs for username:domain = end:start
15252: for active or future "privileged" users with that role in that domain. To avoid
15253: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15254: innerhash are cached using priv_$role and $dom as the identifiers.
15255: 
15256: =back
15257: 
15258: =head2 User Modification
15259: 
15260: =over 4
15261: 
15262: =item *
15263: 
15264: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15265: user for the level given by URL.  Optional start and end dates (leave empty
15266: string or zero for "no date")
15267: 
15268: =item *
15269: 
15270: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15271: change a users, password, possible return values are: ok,
15272: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15273: refused
15274: 
15275: =item *
15276: 
15277: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15278: 
15279: =item *
15280: 
15281: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15282:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15283: 
15284: will update user information (firstname,middlename,lastname,generation,
15285: permanentemail), and if forceid is true, student/employee ID also.
15286: A user's institutional affiliation(s) can also be updated.
15287: User information fields will not be overwritten with empty entries 
15288: unless the field is included in the $candelete array reference.
15289: This array is included when a single user is modified via "Manage Users",
15290: or when Autoupdate.pl is run by cron in a domain.
15291: 
15292: =item *
15293: 
15294: modifystudent
15295: 
15296: modify a student's enrollment and identification information.
15297: The course id is resolved based on the current user's environment.  
15298: This means the invoking user must be a course coordinator or otherwise
15299: associated with a course.
15300: 
15301: This call is essentially a wrapper for lonnet::modifyuser and
15302: lonnet::modify_student_enrollment
15303: 
15304: Inputs: 
15305: 
15306: =over 4
15307: 
15308: =item B<$udom> Student's loncapa domain
15309: 
15310: =item B<$uname> Student's loncapa login name
15311: 
15312: =item B<$uid> Student/Employee ID
15313: 
15314: =item B<$umode> Student's authentication mode
15315: 
15316: =item B<$upass> Student's password
15317: 
15318: =item B<$first> Student's first name
15319: 
15320: =item B<$middle> Student's middle name
15321: 
15322: =item B<$last> Student's last name
15323: 
15324: =item B<$gene> Student's generation
15325: 
15326: =item B<$usec> Student's section in course
15327: 
15328: =item B<$end> Unix time of the roles expiration
15329: 
15330: =item B<$start> Unix time of the roles start date
15331: 
15332: =item B<$forceid> If defined, allow $uid to be changed
15333: 
15334: =item B<$desiredhome> server to use as home server for student
15335: 
15336: =item B<$email> Student's permanent e-mail address
15337: 
15338: =item B<$type> Type of enrollment (auto or manual)
15339: 
15340: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15341: 
15342: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15343: 
15344: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15345: 
15346: =item B<$context> role change context (shown in User Management Logs display in a course)
15347: 
15348: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15349: 
15350: =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.
15351: 
15352: =back
15353: 
15354: =item *
15355: 
15356: modify_student_enrollment
15357: 
15358: Change a student's enrollment status in a class.  The environment variable
15359: 'role.request.course' must be defined for this function to proceed.
15360: 
15361: Inputs:
15362: 
15363: =over 4
15364: 
15365: =item $udom, student's domain
15366: 
15367: =item $uname, student's name
15368: 
15369: =item $uid, student's user id
15370: 
15371: =item $first, student's first name
15372: 
15373: =item $middle
15374: 
15375: =item $last
15376: 
15377: =item $gene
15378: 
15379: =item $usec
15380: 
15381: =item $end
15382: 
15383: =item $start
15384: 
15385: =item $type
15386: 
15387: =item $locktype
15388: 
15389: =item $cid
15390: 
15391: =item $selfenroll
15392: 
15393: =item $context
15394: 
15395: =item $credits, number of credits student will earn from this class
15396: 
15397: =item $instsec, institutional course section code for student
15398: 
15399: =back
15400: 
15401: 
15402: =item *
15403: 
15404: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15405: custom role; give a custom role to a user for the level given by URL.  Specify
15406: name and domain of role author, and role name
15407: 
15408: =item *
15409: 
15410: revokerole($udom,$uname,$url,$role) : revoke a role for url
15411: 
15412: =item *
15413: 
15414: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15415: 
15416: =back
15417: 
15418: =head2 Course Infomation
15419: 
15420: =over 4
15421: 
15422: =item *
15423: 
15424: coursedescription($courseid,$options) : returns a hash of information about the
15425: specified course id, including all environment settings for the
15426: course, the description of the course will be in the hash under the
15427: key 'description'
15428: 
15429: $options is an optional parameter that if supplied is a hash reference that controls
15430: what how this function works.  It has the following key/values:
15431: 
15432: =over 4
15433: 
15434: =item freshen_cache
15435: 
15436: If defined, and the environment cache for the course is valid, it is 
15437: returned in the returned hash.
15438: 
15439: =item one_time
15440: 
15441: If defined, the last cache time is set to _now_
15442: 
15443: =item user
15444: 
15445: If defined, the supplied username is used instead of the current user.
15446: 
15447: 
15448: =back
15449: 
15450: =item *
15451: 
15452: resdata($name,$domain,$type,@which) : request for current parameter
15453: setting for a specific $type, where $type is either 'course' or 'user',
15454: @what should be a list of parameters to ask about. This routine caches
15455: answers for 10 minutes.
15456: 
15457: =item *
15458: 
15459: get_courseresdata($courseid, $domain) : dump the entire course resource
15460: data base, returning a hash that is keyed by the resource name and has
15461: values that are the resource value.  I believe that the timestamps and
15462: versions are also returned.
15463: 
15464: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15465: supplemental content area. This routine caches the number of files for 
15466: 10 minutes.
15467: 
15468: =back
15469: 
15470: =head2 Course Modification
15471: 
15472: =over 4
15473: 
15474: =item *
15475: 
15476: writecoursepref($courseid,%prefs) : write preferences (environment
15477: database) for a course
15478: 
15479: =item *
15480: 
15481: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15482: 
15483: =item *
15484: 
15485: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15486: 
15487: =item *
15488: 
15489: is_course($courseid), is_course($cdom, $cnum)
15490: 
15491: Accepts either a combined $courseid (in the form of domain_courseid) or the
15492: two component version $cdom, $cnum. It checks if the specified course exists.
15493: 
15494: Returns:
15495:     undef if the course doesn't exist, otherwise
15496:     in scalar context the combined courseid.
15497:     in list context the two components of the course identifier, domain and 
15498:     courseid.    
15499: 
15500: =back
15501: 
15502: =head2 Bubblesheet Configuration
15503: 
15504: =over 4
15505: 
15506: =item *
15507: 
15508: get_scantron_config($which)
15509: 
15510: $which - the name of the configuration to parse from the file.
15511: 
15512: Parses and returns the bubblesheet configuration line selected as a
15513: hash of configuration file fields.
15514: 
15515: 
15516: Returns:
15517:     If the named configuration is not in the file, an empty
15518:     hash is returned.
15519: 
15520:     a hash with the fields
15521:       name         - internal name for the this configuration setup
15522:       description  - text to display to operator that describes this config
15523:       CODElocation - if 0 or the string 'none'
15524:                           - no CODE exists for this config
15525:                      if -1 || the string 'letter'
15526:                           - a CODE exists for this config and is
15527:                             a string of letters
15528:                      Unsupported value (but planned for future support)
15529:                           if a positive integer
15530:                                - The CODE exists as the first n items from
15531:                                  the question section of the form
15532:                           if the string 'number'
15533:                                - The CODE exists for this config and is
15534:                                  a string of numbers
15535:       CODEstart   - (only matter if a CODE exists) column in the line where
15536:                      the CODE starts
15537:       CODElength  - length of the CODE
15538:       IDstart     - column where the student/employee ID starts
15539:       IDlength    - length of the student/employee ID info
15540:       Qstart      - column where the information from the bubbled
15541:                     'questions' start
15542:       Qlength     - number of columns comprising a single bubble line from
15543:                     the sheet. (usually either 1 or 10)
15544:       Qon         - either a single character representing the character used
15545:                     to signal a bubble was chosen in the positional setup, or
15546:                     the string 'letter' if the letter of the chosen bubble is
15547:                     in the final, or 'number' if a number representing the
15548:                     chosen bubble is in the file (1->A 0->J)
15549:       Qoff        - the character used to represent that a bubble was
15550:                     left blank
15551:       PaperID     - if the scanning process generates a unique number for each
15552:                     sheet scanned the column that this ID number starts in
15553:       PaperIDlength - number of columns that comprise the unique ID number
15554:                       for the sheet of paper
15555:       FirstName   - column that the first name starts in
15556:       FirstNameLength - number of columns that the first name spans
15557:       LastName    - column that the last name starts in
15558:       LastNameLength - number of columns that the last name spans
15559:       BubblesPerRow - number of bubbles available in each row used to
15560:                       bubble an answer. (If not specified, 10 assumed).
15561: 
15562: 
15563: =item *
15564: 
15565: get_scantronformat_file($cdom)
15566: 
15567: $cdom - the course's domain (optional); if not supplied, uses
15568: domain for current $env{'request.course.id'}.
15569: 
15570: Returns an array containing lines from the scantron format file for
15571: the domain of the course.
15572: 
15573: If a url for a custom.tab file is listed in domain's configuration.db,
15574: lines are from this file.
15575: 
15576: Otherwise, if a default.tab has been published in RES space by the
15577: domainconfig user, lines are from this file.
15578: 
15579: Otherwise, fall back to getting lines from the legacy file on the
15580: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15581: 
15582: =back
15583: 
15584: =head2 Resource Subroutines
15585: 
15586: =over 4
15587: 
15588: =item *
15589: 
15590: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15591: 
15592: =item *
15593: 
15594: repcopy($filename) : subscribes to the requested file, and attempts to
15595: replicate from the owning library server, Might return
15596: 'unavailable', 'not_found', 'forbidden', 'ok', or
15597: 'bad_request', also attempts to grab the metadata for the
15598: resource. Expects the local filesystem pathname
15599: (/home/httpd/html/res/....)
15600: 
15601: =back
15602: 
15603: =head2 Resource Information
15604: 
15605: =over 4
15606: 
15607: =item *
15608: 
15609: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15610: and returns the value of a variety of different possible values,
15611: $varname should be a request string, and the other parameters can be
15612: used to specify who and what one is asking about. Ordinarily, $cid 
15613: does not need to be specified, as it is retrived from 
15614: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15615: within lonuserstate::loadmap() when initializing a course, before
15616: $env{'request.course.id'} has been set, so it needs to be provided
15617: in that one case.
15618: 
15619: Possible values for $varname are environment.lastname (or other item
15620: from the envirnment hash), user.name (or someother aspect about the
15621: user), resource.0.maxtries (or some other part and parameter of a
15622: resource)
15623: 
15624: =item *
15625: 
15626: directcondval($number) : get current value of a condition; reads from a state
15627: string
15628: 
15629: =item *
15630: 
15631: condval($condidx) : value of condition index based on state
15632: 
15633: =item *
15634: 
15635: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15636: resource's metadata, $what should be either a specific key, or either
15637: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15638: packages that this resource currently uses, the last 3 arguments are 
15639: only used internally for recursive metadata.
15640: 
15641: the toolsymb is only used where the uri is for an external tool (for which
15642: the uri as well as the symb are guaranteed to be unique).
15643: 
15644: this function automatically caches all requests except any made recursively
15645: to retrieve a list of metadata keys for an imported library file ($liburi is 
15646: defined).
15647: 
15648: =item *
15649: 
15650: metadata_query($query,$custom,$customshow) : make a metadata query against the
15651: network of library servers; returns file handle of where SQL and regex results
15652: will be stored for query
15653: 
15654: =item *
15655: 
15656: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15657: return symbolic list entry (all arguments optional). 
15658: 
15659: Args: filename is the filename (including path) for the file for which a symb 
15660: is required; donotrecurse, if true will prevent calls to allowed() being made 
15661: to check access status if more than one resource was found in the bighash 
15662: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15663: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15664: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15665: cause possible symbs to be checked to determine if they are subject to content
15666: blocking, if so they will not be included as possible symbs; possibles is a
15667: ref to a hash, which, as a side effect, will be populated with all possible 
15668: symbs (content blocking not tested).
15669:  
15670: returns the data handle
15671: 
15672: =item *
15673: 
15674: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15675: and is a possible symb for the URL in $thisfn, and if is an encrypted
15676: resource that the user accessed using /enc/ returns a 1 on success, 0
15677: on failure, user must be in a course, as it assumes the existence of
15678: the course initial hash, and uses $env('request.course.id'}.  The third
15679: arg is an optional reference to a scalar.  If this arg is passed in the 
15680: call to symbverify, it will be set to 1 if the symb has been set to be 
15681: encrypted; otherwise it will be null.  
15682: 
15683: =item *
15684: 
15685: symbclean($symb) : removes versions numbers from a symb, returns the
15686: cleaned symb
15687: 
15688: =item *
15689: 
15690: is_on_map($uri) : checks if the $uri is somewhere on the current
15691: course map, user must be in a course for it to work.
15692: 
15693: =item *
15694: 
15695: numval($salt) : return random seed value (addend for rndseed)
15696: 
15697: =item *
15698: 
15699: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15700: a random seed, all arguments are optional, if they aren't sent it uses the
15701: environment to derive them. Note: if symb isn't sent and it can't get one
15702: from &symbread it will use the current time as its return value
15703: 
15704: =item *
15705: 
15706: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15707: unfakeable, receipt
15708: 
15709: =item *
15710: 
15711: receipt() : API to ireceipt working off of env values; given out to users
15712: 
15713: =item *
15714: 
15715: countacc($url) : count the number of accesses to a given URL
15716: 
15717: =item *
15718: 
15719: 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
15720: 
15721: =item *
15722: 
15723: 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)
15724: 
15725: =item *
15726: 
15727: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15728: 
15729: =item *
15730: 
15731: devalidate($symb) : devalidate temporary spreadsheet calculations,
15732: forcing spreadsheet to reevaluate the resource scores next time.
15733: 
15734: =item * 
15735: 
15736: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15737: when viewing in course context.
15738: 
15739:  input: six args -- filename (decluttered), course number, course domain,
15740:                     url, symb (if registered) and group (if this is a 
15741:                     group item -- e.g., bulletin board, group page etc.).
15742: 
15743:  output: array of five scalars --
15744:          $cfile -- url for file editing if editable on current server
15745:          $home -- homeserver of resource (i.e., for author if published,
15746:                                           or course if uploaded.).
15747:          $switchserver --  1 if server switch will be needed.
15748:          $forceedit -- 1 if icon/link should be to go to edit mode 
15749:          $forceview -- 1 if icon/link should be to go to view mode
15750: 
15751: =item *
15752: 
15753: is_course_upload($file,$cnum,$cdom)
15754: 
15755: Used in course context to determine if current file was uploaded to 
15756: the course (i.e., would be found in /userfiles/docs on the course's 
15757: homeserver.
15758: 
15759:   input: 3 args -- filename (decluttered), course number and course domain.
15760:   output: boolean -- 1 if file was uploaded.
15761: 
15762: =back
15763: 
15764: =head2 Storing/Retreiving Data
15765: 
15766: =over 4
15767: 
15768: =item *
15769: 
15770: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15771: permanently for this url; hashref needs to be given and should be a \%hashname;
15772: the remaining args aren't required and if they aren't passed or are '' they will
15773: be derived from the env (with the exception of $laststore, which is an 
15774: optional arg used when a user's submission is stored in grading).
15775: $laststore is $version=$timestamp, where $version is the most recent version
15776: number retrieved for the corresponding $symb in the $namespace db file, and
15777: $timestamp is the timestamp for that transaction (UNIX time).
15778: $laststore is currently only passed when cstore() is called by 
15779: structuretags::finalize_storage().
15780: 
15781: =item *
15782: 
15783: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15784: but uses critical subroutine
15785: 
15786: =item *
15787: 
15788: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15789: all args are optional
15790: 
15791: =item *
15792: 
15793: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15794: dumps the complete (or key matching regexp) namespace into a hash
15795: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15796: normally &store()ed into
15797: 
15798: $range should be either an integer '100' (give me the first 100
15799:                                            matching records)
15800:               or be  two integers sperated by a - with no spaces
15801:                  '30-50' (give me the 30th through the 50th matching
15802:                           records)
15803: 
15804: 
15805: =item *
15806: 
15807: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15808: replaces a &store() version of data with a replacement set of data
15809: for a particular resource in a namespace passed in the $storehash hash 
15810: reference. If $tolog is true, the transaction is logged in the courselog
15811: with an action=PUTSTORE.
15812: 
15813: =item *
15814: 
15815: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15816: works very similar to store/cstore, but all data is stored in a
15817: temporary location and can be reset using tmpreset, $storehash should
15818: be a hash reference, returns nothing on success
15819: 
15820: =item *
15821: 
15822: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15823: similar to restore, but all data is stored in a temporary location and
15824: can be reset using tmpreset. Returns a hash of values on success,
15825: error string otherwise.
15826: 
15827: =item *
15828: 
15829: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15830: deltes all keys for $symb form the temporary storage hash.
15831: 
15832: =item *
15833: 
15834: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15835: reference filled in from namesp ($udom and $uname are optional)
15836: 
15837: =item *
15838: 
15839: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15840: namesp ($udom and $uname are optional)
15841: 
15842: =item *
15843: 
15844: dump($namespace,$udom,$uname,$regexp,$range) : 
15845: dumps the complete (or key matching regexp) namespace into a hash
15846: ($udom, $uname, $regexp, $range are optional)
15847: 
15848: $range should be either an integer '100' (give me the first 100
15849:                                            matching records)
15850:               or be  two integers sperated by a - with no spaces
15851:                  '30-50' (give me the 30th through the 50th matching
15852:                           records)
15853: =item *
15854: 
15855: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15856: $store can be a scalar, an array reference, or if the amount to be 
15857: incremented is > 1, a hash reference.
15858: 
15859: ($udom and $uname are optional)
15860: 
15861: =item *
15862: 
15863: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15864: ($udom and $uname are optional)
15865: 
15866: =item *
15867: 
15868: cput($namespace,$storehash,$udom,$uname) : critical put
15869: ($udom and $uname are optional)
15870: 
15871: =item *
15872: 
15873: newput($namespace,$storehash,$udom,$uname) :
15874: 
15875: Attempts to store the items in the $storehash, but only if they don't
15876: currently exist, if this succeeds you can be certain that you have 
15877: successfully created a new key value pair in the $namespace db.
15878: 
15879: 
15880: Args:
15881:  $namespace: name of database to store values to
15882:  $storehash: hashref to store to the db
15883:  $udom: (optional) domain of user containing the db
15884:  $uname: (optional) name of user caontaining the db
15885: 
15886: Returns:
15887:  'ok' -> succeeded in storing all keys of $storehash
15888:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15889:                         least <key> already existed in the db (other
15890:                         requested keys may also already exist)
15891:  'error: <msg>' -> unable to tie the DB or other error occurred
15892:  'con_lost' -> unable to contact request server
15893:  'refused' -> action was not allowed by remote machine
15894: 
15895: 
15896: =item *
15897: 
15898: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15899: reference filled in from namesp (encrypts the return communication)
15900: ($udom and $uname are optional)
15901: 
15902: =item *
15903: 
15904: log($udom,$name,$home,$message) : write to permanent log for user; use
15905: critical subroutine
15906: 
15907: =item *
15908: 
15909: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15910: array reference filled in from namespace found in domain level on either
15911: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15912: 
15913: =item *
15914: 
15915: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15916: domain level either on specified domain server ($uhome) or primary domain 
15917: server ($udom and $uhome are optional)
15918: 
15919: =item * 
15920: 
15921: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15922: for: authentication, language, quotas, timezone, date locale, and portal URL in
15923: the target domain.
15924: 
15925: May also include additional key => value pairs for the following groups:
15926: 
15927: =over
15928: 
15929: =item
15930: disk quotas (MB allocated by default to portfolios and authoring spaces).
15931: 
15932: =over
15933: 
15934: =item defaultquota, authorquota
15935: 
15936: =back
15937: 
15938: =item
15939: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15940: portfolio for users).
15941: 
15942: =over
15943: 
15944: =item
15945: aboutme, blog, webdav, portfolio
15946: 
15947: =back
15948: 
15949: =item
15950: requestcourses: ability to request courses, and how requests are processed.
15951: 
15952: =over
15953: 
15954: =item
15955: official, unofficial, community, textbook, placement
15956: 
15957: =back
15958: 
15959: =item
15960: inststatus: types of institutional affiliation, and order in which they are displayed.
15961: 
15962: =over
15963: 
15964: =item
15965: inststatustypes, inststatusorder, inststatusguest
15966: 
15967: =back
15968: 
15969: =item
15970: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15971: for course's uploaded content.
15972: 
15973: =over
15974: 
15975: =item
15976: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15977: communityquota, textbookquota, placementquota
15978: 
15979: =back
15980: 
15981: =item
15982: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15983: on your servers.
15984: 
15985: =over
15986: 
15987: =item 
15988: remotesessions, hostedsessions
15989: 
15990: =back
15991: 
15992: =back
15993: 
15994: In cases where a domain coordinator has never used the "Set Domain Configuration"
15995: utility to create a configuration.db file on a domain's primary library server 
15996: only the following domain defaults: auth_def, auth_arg_def, lang_def
15997: -- corresponding values are authentication type (internal, krb4, krb5,
15998: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15999: will be available. Values are retrieved from cache (if current), unless the
16000: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16001: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16002: 
16003: Typical usage:
16004: 
16005: %domdefaults = &get_domain_defaults($target_domain);
16006: 
16007: =back
16008: 
16009: =head2 Network Status Functions
16010: 
16011: =over 4
16012: 
16013: =item *
16014: 
16015: dirlist() : return directory list based on URI (first arg).
16016: 
16017: Inputs: 1 required, 5 optional.
16018: 
16019: =over
16020: 
16021: =item 
16022: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16023: 
16024: =item
16025: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16026: 
16027: =item
16028: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16029: 
16030: =item
16031: $getpropath - boolean: 1 if prepend path using &propath(). 
16032: 
16033: =item
16034: $getuserdir - boolean: 1 if prepend path for "userfiles".
16035: 
16036: =item 
16037: $alternateRoot - path to prepend in place of path from $uri.
16038: 
16039: =back
16040: 
16041: Returns: Array of up to two items.
16042: 
16043: =over
16044: 
16045: a reference to an array of files/subdirectories
16046: 
16047: =over
16048: 
16049: Each element in the array of files/subdirectories is a & separated list of
16050: item name and the result of running stat on the item.  If dirlist was requested
16051: for a file instead of a directory, the item name will be ''. For a directory 
16052: listing, if the item is a metadata file, the element will end &N&M 
16053: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16054: default copyright set (1).  
16055: 
16056: =back
16057: 
16058: a scalar containing error condition (if encountered).
16059: 
16060: =over
16061: 
16062: =item 
16063: no_host (no homeserver identified for $username:$domain).
16064: 
16065: =item 
16066: no_such_host (server contacted for listing not identified as valid host).
16067: 
16068: =item 
16069: con_lost (connection to remote server failed).
16070: 
16071: =item 
16072: refused (invalid $username:$domain received on lond side).
16073: 
16074: =item 
16075: no_such_dir (directory at specified path on lond side does not exist). 
16076: 
16077: =item 
16078: empty (directory at specified path on lond side is empty).
16079: 
16080: =over
16081: 
16082: This is currently not encountered because the &ls3, &ls2, 
16083: &ls (_handler) routines on the lond side do not filter out
16084: . and .. from a directory listing. 
16085: 
16086: =back
16087: 
16088: =back
16089: 
16090: =back
16091: 
16092: =item *
16093: 
16094: spareserver() : find server with least workload from spare.tab
16095: 
16096: 
16097: =item *
16098: 
16099: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16100: if there is no corresponding loncapa host.
16101: 
16102: =back
16103: 
16104: 
16105: =head2 Apache Request
16106: 
16107: =over 4
16108: 
16109: =item *
16110: 
16111: ssi($url,%hash) : server side include, does a complete request cycle on url to
16112: localhost, posts hash
16113: 
16114: =back
16115: 
16116: =head2 Data to String to Data
16117: 
16118: =over 4
16119: 
16120: =item *
16121: 
16122: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16123: and '&' separators, supports elements that are arrayrefs and hashrefs
16124: 
16125: =item *
16126: 
16127: hashref2str($hashref) : convert a hashref into a string complete with
16128: escaping and '=' and '&' separators, supports elements that are
16129: arrayrefs and hashrefs
16130: 
16131: =item *
16132: 
16133: arrayref2str($arrayref) : convert an arrayref into a string complete
16134: with escaping and '&' separators, supports elements that are arrayrefs
16135: and hashrefs
16136: 
16137: =item *
16138: 
16139: str2hash($string) : convert string to hash using unescaping and
16140: splitting on '=' and '&', supports elements that are arrayrefs and
16141: hashrefs
16142: 
16143: =item *
16144: 
16145: str2array($string) : convert string to hash using unescaping and
16146: splitting on '&', supports elements that are arrayrefs and hashrefs
16147: 
16148: =back
16149: 
16150: =head2 Logging Routines
16151: 
16152: 
16153: These routines allow one to make log messages in the lonnet.log and
16154: lonnet.perm logfiles.
16155: 
16156: =over 4
16157: 
16158: =item *
16159: 
16160: logtouch() : make sure the logfile, lonnet.log, exists
16161: 
16162: =item *
16163: 
16164: logthis() : append message to the normal lonnet.log file, it gets
16165: preiodically rolled over and deleted.
16166: 
16167: =item *
16168: 
16169: logperm() : append a permanent message to lonnet.perm.log, this log
16170: file never gets deleted by any automated portion of the system, only
16171: messages of critical importance should go in here.
16172: 
16173: 
16174: =back
16175: 
16176: =head2 General File Helper Routines
16177: 
16178: =over 4
16179: 
16180: =item *
16181: 
16182: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16183: (a) files in /uploaded
16184:   (i) If a local copy of the file exists - 
16185:       compares modification date of local copy with last-modified date for 
16186:       definitive version stored on home server for course. If local copy is 
16187:       stale, requests a new version from the home server and stores it. 
16188:       If the original has been removed from the home server, then local copy 
16189:       is unlinked.
16190:   (ii) If local copy does not exist -
16191:       requests the file from the home server and stores it. 
16192:   
16193:   If $caller is 'uploadrep':  
16194:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16195:     for request for files originally uploaded via DOCS. 
16196:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16197:   
16198:   Otherwise:
16199:      This indicates a call from the content generation phase of the request.
16200:      -  returns the entire contents of the file or -1.
16201:      
16202: (b) files in /res
16203:    - returns the entire contents of a file or -1; 
16204:    it properly subscribes to and replicates the file if neccessary.
16205: 
16206: 
16207: =item *
16208: 
16209: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16210:                   reference
16211: 
16212: returns either a stat() list of data about the file or an empty list
16213: if the file doesn't exist or couldn't find out about it (connection
16214: problems or user unknown)
16215: 
16216: =item *
16217: 
16218: filelocation($dir,$file) : returns file system location of a file
16219: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16220: directory that relative $file lookups are to looked in ($dir of /a/dir
16221: and a file of ../bob will become /a/bob)
16222: 
16223: =item *
16224: 
16225: hreflocation($dir,$file) : returns file system location or a URL; same as
16226: filelocation except for hrefs
16227: 
16228: =item *
16229: 
16230: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16231: also removes beginning /home/httpd/html unless /priv/ follows it.
16232: 
16233: =back
16234: 
16235: =head2 Usererfile file routines (/uploaded*)
16236: 
16237: =over 4
16238: 
16239: =item *
16240: 
16241: userfileupload(): main rotine for putting a file in a user or course's
16242:                   filespace, arguments are,
16243: 
16244:  formname - required - this is the name of the element in $env where the
16245:            filename, and the contents of the file to create/modifed exist
16246:            the filename is in $env{'form.'.$formname.'.filename'} and the
16247:            contents of the file is located in $env{'form.'.$formname}
16248:  context - if coursedoc, store the file in the course of the active role
16249:              of the current user; 
16250:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16251:            if 'canceloverwrite': delete file in tmp/overwrites directory
16252:  subdir - required - subdirectory to put the file in under ../userfiles/
16253:          if undefined, it will be placed in "unknown"
16254: 
16255:  (This routine calls clean_filename() to remove any dangerous
16256:  characters from the filename, and then calls finuserfileupload() to
16257:  complete the transaction)
16258: 
16259:  returns either the url of the uploaded file (/uploaded/....) if successful
16260:  and /adm/notfound.html if unsuccessful
16261: 
16262: =item *
16263: 
16264: clean_filename(): routine for cleaing a filename up for storage in
16265:                  userfile space, argument is:
16266: 
16267:  filename - proposed filename
16268: 
16269: returns: the new clean filename
16270: 
16271: =item *
16272: 
16273: finishuserfileupload(): routine that creates and sends the file to
16274: userspace, probably shouldn't be called directly
16275: 
16276:   docuname: username or courseid of destination for the file
16277:   docudom: domain of user/course of destination for the file
16278:   formname: same as for userfileupload()
16279:   fname: filename (including subdirectories) for the file
16280:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16281:           if hashref, and context is scantron, will convert csv format to standard format
16282:   allfiles: reference to hash used to store objects found by parser
16283:   codebase: reference to hash used for codebases of java objects found by parser
16284:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16285:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16286:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16287:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16288:   context: if 'overwrite', will move the uploaded file from its temporary location to
16289:             userfiles to facilitate overwriting a previously uploaded file with same name.
16290:   mimetype: reference to scalar to accommodate mime type determined
16291:             from File::MMagic if $parser = parse.
16292: 
16293:  returns either the url of the uploaded file (/uploaded/....) if successful
16294:  and /adm/notfound.html if unsuccessful (or an error message if context 
16295:  was 'overwrite').
16296:  
16297: 
16298: =item *
16299: 
16300: renameuserfile(): renames an existing userfile to a new name
16301: 
16302:   Args:
16303:    docuname: username or courseid of destination for the file
16304:    docudom: domain of user/course of destination for the file
16305:    old: current file name (including any subdirs under userfiles)
16306:    new: desired file name (including any subdirs under userfiles)
16307: 
16308: =item *
16309: 
16310: mkdiruserfile(): creates a directory is a userfiles dir
16311: 
16312:   Args:
16313:    docuname: username or courseid of destination for the file
16314:    docudom: domain of user/course of destination for the file
16315:    dir: dir to create (including any subdirs under userfiles)
16316: 
16317: =item *
16318: 
16319: removeuserfile(): removes a file that exists in userfiles
16320: 
16321:   Args:
16322:    docuname: username or courseid of destination for the file
16323:    docudom: domain of user/course of destination for the file
16324:    fname: filname to delete (including any subdirs under userfiles)
16325: 
16326: =item *
16327: 
16328: removeuploadedurl(): convience function for removeuserfile()
16329: 
16330:   Args:
16331:    url:  a full /uploaded/... url to delete
16332: 
16333: =item * 
16334: 
16335: get_portfile_permissions():
16336:   Args:
16337:     domain: domain of user or course contain the portfolio files
16338:     user: name of user or num of course contain the portfolio files
16339:   Returns:
16340:     hashref of a dump of the proper file_permissions.db
16341:    
16342: 
16343: =item * 
16344: 
16345: get_access_controls():
16346: 
16347: Args:
16348:   current_permissions: the hash ref returned from get_portfile_permissions()
16349:   group: (optional) the group you want the files associated with
16350:   file: (optional) the file you want access info on
16351: 
16352: Returns:
16353:     a hash (keys are file names) of hashes containing
16354:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16355:         values are XML containing access control settings (see below) 
16356: 
16357: Internal notes:
16358: 
16359:  access controls are stored in file_permissions.db as key=value pairs.
16360:     key -> path to file/file_name\0uniqueID:scope_end_start
16361:         where scope -> public,guest,course,group,domains or users.
16362:               end -> UNIX time for end of access (0 -> no end date)
16363:               start -> UNIX time for start of access
16364: 
16365:     value -> XML description of access control
16366:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16367:             <start></start>
16368:             <end></end>
16369: 
16370:             <password></password>  for scope type = guest
16371: 
16372:             <domain></domain>     for scope type = course or group
16373:             <number></number>
16374:             <roles id="">
16375:              <role></role>
16376:              <access></access>
16377:              <section></section>
16378:              <group></group>
16379:             </roles>
16380: 
16381:             <dom></dom>         for scope type = domains
16382: 
16383:             <users>             for scope type = users
16384:              <user>
16385:               <uname></uname>
16386:               <udom></udom>
16387:              </user>
16388:             </users>
16389:            </scope> 
16390:               
16391:  Access data is also aggregated for each file in an additional key=value pair:
16392:  key -> path to file/file_name\0accesscontrol 
16393:  value -> reference to hash
16394:           hash contains key = value pairs
16395:           where key = uniqueID:scope_end_start
16396:                 value = UNIX time record was last updated
16397: 
16398:           Used to improve speed of look-ups of access controls for each file.  
16399:  
16400:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16401: 
16402: =item *
16403: 
16404: modify_access_controls():
16405: 
16406: Modifies access controls for a portfolio file
16407: Args
16408: 1. file name
16409: 2. reference to hash of required changes,
16410: 3. domain
16411: 4. username
16412:   where domain,username are the domain of the portfolio owner 
16413:   (either a user or a course) 
16414: 
16415: Returns:
16416: 1. result of additions or updates ('ok' or 'error', with error message). 
16417: 2. result of deletions ('ok' or 'error', with error message).
16418: 3. reference to hash of any new or updated access controls.
16419: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16420:    key = integer (inbound ID)
16421:    value = uniqueID
16422: 
16423: =item *
16424: 
16425: get_timebased_id():
16426: 
16427: Attempts to get a unique timestamp-based suffix for use with items added to a 
16428: course via the Course Editor (e.g., folders, composite pages, 
16429: group bulletin boards).
16430: 
16431: Args: (first three required; six others optional)
16432: 
16433: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16434:    docssequence, or name of group
16435: 
16436: 2. keyid (alphanumeric): name of temporary locking key in hash,
16437:    e.g., num, boardids
16438: 
16439: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16440:    file will be named nohist_namespace.db
16441: 
16442: 4. cdom: domain of course; default is current course domain from %env
16443: 
16444: 5. cnum: course number; default is current course number from %env
16445: 
16446: 6. idtype: set to concat if an additional digit is to be appended to the 
16447:    unix timestamp to form the suffix, if the plain timestamp is already
16448:    in use.  Default is to not do this, but simply increment the unix 
16449:    timestamp by 1 until a unique key is obtained.
16450: 
16451: 7. who: holder of locking key; defaults to user:domain for user.
16452: 
16453: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16454:    retrying); default is 3.
16455: 
16456: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16457: 
16458: Returns:
16459: 
16460: 1. suffix obtained (numeric)
16461: 
16462: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16463: 
16464: 3. error: contains (localized) error message if an error occurred.
16465: 
16466: 
16467: =back
16468: 
16469: =head2 HTTP Helper Routines
16470: 
16471: =over 4
16472: 
16473: =item *
16474: 
16475: escape() : unpack non-word characters into CGI-compatible hex codes
16476: 
16477: =item *
16478: 
16479: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16480: 
16481: =back
16482: 
16483: =head1 PRIVATE SUBROUTINES
16484: 
16485: =head2 Underlying communication routines (Shouldn't call)
16486: 
16487: =over 4
16488: 
16489: =item *
16490: 
16491: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16492: 
16493: =item *
16494: 
16495: reply() : uses subreply to send a message to remote machine, logs all failures
16496: 
16497: =item *
16498: 
16499: critical() : passes a critical message to another server; if cannot
16500: get through then place message in connection buffer directory and
16501: returns con_delayed, if incapable of saving message, returns
16502: con_failed
16503: 
16504: =item *
16505: 
16506: reconlonc() : tries to reconnect lonc client processes.
16507: 
16508: =back
16509: 
16510: =head2 Resource Access Logging
16511: 
16512: =over 4
16513: 
16514: =item *
16515: 
16516: flushcourselogs() : flush (save) buffer logs and access logs
16517: 
16518: =item *
16519: 
16520: courselog($what) : save message for course in hash
16521: 
16522: =item *
16523: 
16524: courseacclog($what) : save message for course using &courselog().  Perform
16525: special processing for specific resource types (problems, exams, quizzes, etc).
16526: 
16527: =item *
16528: 
16529: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16530: as a PerlChildExitHandler
16531: 
16532: =back
16533: 
16534: =head2 Other
16535: 
16536: =over 4
16537: 
16538: =item *
16539: 
16540: symblist($mapname,%newhash) : update symbolic storage links
16541: 
16542: =back
16543: 
16544: =cut
16545: 

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