File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1409: download - view: text, annotated - select for diffs
Mon Apr 29 22:19:45 2019 UTC (5 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support domain configuration which allows a Course Owner to change a
  student's password, if:
 (a) same domain is used by owner, course, and student
 (b) student has no active or future roles besides student role in courses
     owned by the course owner making the change
 (c) course container is not Community or Placement Test
 (d) owner is course cordinator in the course
 (e) setting to disable this action has not been set for the specific course

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1409 2019/04/29 22:19:45 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: 
  117: # ------------------------------------ Logging (parameters, docs, slots, roles)
  118: {
  119:     my $logid;
  120:     sub write_log {
  121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  122:         if ($context eq 'course') {
  123:             if (($cnum eq '') || ($cdom eq '')) {
  124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  126:             }
  127:         }
  128: 	$logid ++;
  129:         my $now = time();
  130: 	my $id=$now.'00000'.$$.'00000'.$logid;
  131:         my $logentry = { 
  132:                           $id => {
  133:                                    'exe_uname' => $env{'user.name'},
  134:                                    'exe_udom'  => $env{'user.domain'},
  135:                                    'exe_time'  => $now,
  136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  137:                                    'delflag'   => $delflag,
  138:                                    'logentry'  => $storehash,
  139:                                    'uname'     => $uname,
  140:                                    'udom'      => $udom,
  141:                                   }
  142:                        };
  143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_servercerts_info {
  234:     my ($lonhost,$hostname,$context) = @_;
  235:     return if ($lonhost eq '');
  236:     if ($hostname eq '') {
  237:         $hostname = &hostname($lonhost);
  238:     }
  239:     return if ($hostname eq '');
  240:     my ($rep,$uselocal);
  241:     if ($context eq 'install') {
  242:         $uselocal = 1;
  243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  244:         $uselocal = 1;
  245:     }
  246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  248:         if ($distro eq '') {
  249:             $uselocal = 0;
  250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  251:             if ($1 < 6) {
  252:                 $uselocal = 0;
  253:             }
  254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  255:             if ($1 < 12) {
  256:                 $uselocal = 0;
  257:             }
  258:         }
  259:     }
  260:     if ($uselocal) {
  261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  262:     } else {
  263:         $rep=&reply('servercerts',$lonhost);
  264:     }
  265:     my ($result,%returnhash);
  266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  267:         ($rep eq 'unknown_cmd')) {
  268:         $result = $rep;
  269:     } else {
  270:         $result = 'ok';
  271:         my @pairs=split(/\&/,$rep);
  272:         foreach my $item (@pairs) {
  273:             my ($key,$value)=split(/=/,$item,2);
  274:             my $what = &unescape($key);
  275:             $returnhash{$what}=&thaw_unescape($value);
  276:         }
  277:     }
  278:     return ($result,\%returnhash);
  279: }
  280: 
  281: sub get_server_loncaparev {
  282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  283:     if (defined($lonhost)) {
  284:         if (!defined(&hostname($lonhost))) {
  285:             undef($lonhost);
  286:         }
  287:     }
  288:     if (!defined($lonhost)) {
  289:         if (defined(&domain($dom,'primary'))) {
  290:             $lonhost=&domain($dom,'primary');
  291:             if ($lonhost eq 'no_host') {
  292:                 undef($lonhost);
  293:             }
  294:         }
  295:     }
  296:     if (defined($lonhost)) {
  297:         my $cachetime = 12*3600;
  298:         if (!$ignore_cache) {
  299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  300:             if (defined($cached)) {
  301:                 return $loncaparev;
  302:             }
  303:         }
  304:         my ($answer,$loncaparev);
  305:         my @ids=&current_machine_ids();
  306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  307:             $answer = $perlvar{'lonVersion'};
  308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  309:                 $loncaparev = $1;
  310:             }
  311:         } else {
  312:             $answer = &reply('serverloncaparev',$lonhost);
  313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  314:                 if ($caller eq 'loncron') {
  315:                     my $hostname = &hostname($lonhost);
  316:                     my $protocol = $protocol{$lonhost};
  317:                     $protocol = 'http' if ($protocol ne 'https');
  318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  319:                     my $request=new HTTP::Request('GET',$url);
  320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  321:                     unless ($response->is_error()) {
  322:                         my $content = $response->content;
  323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  324:                             $loncaparev = $1;
  325:                         }
  326:                     }
  327:                 } else {
  328:                     $loncaparev = $loncaparevs{$lonhost};
  329:                 }
  330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  331:                 $loncaparev = $1;
  332:             }
  333:         }
  334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  335:     }
  336: }
  337: 
  338: sub get_server_homeID {
  339:     my ($hostname,$ignore_cache,$caller) = @_;
  340:     unless ($ignore_cache) {
  341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  342:         if (defined($cached)) {
  343:             return $serverhomeID;
  344:         }
  345:     }
  346:     my $cachetime = 12*3600;
  347:     my $serverhomeID;
  348:     if ($caller eq 'loncron') { 
  349:         my @machine_ids = &machine_ids($hostname);
  350:         foreach my $id (@machine_ids) {
  351:             my $response = &reply('serverhomeID',$id);
  352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  353:                 $serverhomeID = $response;
  354:                 last;
  355:             }
  356:         }
  357:         if ($serverhomeID eq '') {
  358:             $serverhomeID = $machine_ids[-1];
  359:         }
  360:     } else {
  361:         $serverhomeID = $serverhomeIDs{$hostname};
  362:     }
  363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  364: }
  365: 
  366: sub get_remote_globals {
  367:     my ($lonhost,$whathash,$ignore_cache) = @_;
  368:     my ($result,%returnhash,%whatneeded);
  369:     if (ref($whathash) eq 'HASH') {
  370:         foreach my $what (sort(keys(%{$whathash}))) {
  371:             my $hashid = $lonhost.'-'.$what;
  372:             my ($response,$cached);
  373:             unless ($ignore_cache) {
  374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  375:             }
  376:             if (defined($cached)) {
  377:                 $returnhash{$what} = $response;
  378:             } else {
  379:                 $whatneeded{$what} = 1;
  380:             }
  381:         }
  382:         if (keys(%whatneeded) == 0) {
  383:             $result = 'ok';
  384:         } else {
  385:             my $requested = &freeze_escape(\%whatneeded);
  386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  388:                 ($rep eq 'unknown_cmd')) {
  389:                 $result = $rep;
  390:             } else {
  391:                 $result = 'ok';
  392:                 my @pairs=split(/\&/,$rep);
  393:                 foreach my $item (@pairs) {
  394:                     my ($key,$value)=split(/=/,$item,2);
  395:                     my $what = &unescape($key);
  396:                     my $hashid = $lonhost.'-'.$what;
  397:                     $returnhash{$what}=&thaw_unescape($value);
  398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  399:                 }
  400:             }
  401:         }
  402:     }
  403:     return ($result,\%returnhash);
  404: }
  405: 
  406: sub remote_devalidate_cache {
  407:     my ($lonhost,$cachekeys) = @_;
  408:     my $items;
  409:     return unless (ref($cachekeys) eq 'ARRAY');
  410:     my $cachestr = join('&',@{$cachekeys});
  411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  412:     return $response;
  413: }
  414: 
  415: # -------------------------------------------------- Non-critical communication
  416: sub subreply {
  417:     my ($cmd,$server)=@_;
  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  419:     #
  420:     #  With loncnew process trimming, there's a timing hole between lonc server
  421:     #  process exit and the master server picking up the listen on the AF_UNIX
  422:     #  socket.  In that time interval, a lock file will exist:
  423: 
  424:     my $lockfile=$peerfile.".lock";
  425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  426: 	sleep(0.1);
  427:     }
  428:     # At this point, either a loncnew parent is listening or an old lonc
  429:     # or loncnew child is listening so we can connect or everything's dead.
  430:     #
  431:     #   We'll give the connection a few tries before abandoning it.  If
  432:     #   connection is not possible, we'll con_lost back to the client.
  433:     #   
  434:     my $client;
  435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  437: 				      Type    => SOCK_STREAM,
  438: 				      Timeout => 10);
  439: 	if ($client) {
  440: 	    last;		# Connected!
  441: 	} else {
  442: 	    &create_connection(&hostname($server),$server);
  443: 	}
  444:         sleep(0.1);	# Try again later if failed connection.
  445:     }
  446:     my $answer;
  447:     if ($client) {
  448: 	print $client "sethost:$server:$cmd\n";
  449: 	$answer=<$client>;
  450: 	if (!$answer) { $answer="con_lost"; }
  451: 	chomp($answer);
  452:     } else {
  453: 	$answer = 'con_lost';	# Failed connection.
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: sub reply {
  459:     my ($cmd,$server)=@_;
  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  461:     my $answer=subreply($cmd,$server);
  462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  463:         my $logged = $cmd;
  464:         if ($cmd =~ /^encrypt:([^:]+):/) {
  465:             my $subcmd = $1;
  466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  469:                 (undef,undef,my @rest) = split(/:/,$cmd);
  470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  471:                     splice(@rest,2,1,'Hidden');
  472:                 } elsif ($subcmd eq 'passwd') {
  473:                     splice(@rest,2,2,('Hidden','Hidden'));
  474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  475:                          ($subcmd eq 'autoexportgrades')) {
  476:                     splice(@rest,3,1,'Hidden');
  477:                 }
  478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  479:             }
  480:         }
  481:         &logthis("<font color=\"blue\">WARNING:".
  482:                  " $logged to $server returned $answer</font>");
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: # ----------------------------------------------------------- Send USR1 to lonc
  488: 
  489: sub reconlonc {
  490:     my ($lonid) = @_;
  491:     if ($lonid) {
  492:         my $hostname = &hostname($lonid);
  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  494: 	if ($hostname && -e $peerfile) {
  495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  497: 					     Type    => SOCK_STREAM,
  498: 					     Timeout => 10);
  499: 	    if ($client) {
  500: 		print $client ("reset_retries\n");
  501: 		my $answer=<$client>;
  502: 		#reset just this one.
  503: 	    }
  504: 	}
  505: 	return;
  506:     }
  507: 
  508:     &logthis("Trying to reconnect lonc");
  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  510:     if (open(my $fh,"<",$loncfile)) {
  511: 	my $loncpid=<$fh>;
  512:         chomp($loncpid);
  513:         if (kill 0 => $loncpid) {
  514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  515:             kill USR1 => $loncpid;
  516:             sleep 1;
  517:         } else {
  518: 	    &logthis(
  519:                "<font color=\"blue\">WARNING:".
  520:                " lonc at pid $loncpid not responding, giving up</font>");
  521:         }
  522:     } else {
  523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  524:     }
  525: }
  526: 
  527: # ------------------------------------------------------ Critical communication
  528: 
  529: sub critical {
  530:     my ($cmd,$server)=@_;
  531:     unless (&hostname($server)) {
  532:         &logthis("<font color=\"blue\">WARNING:".
  533:                " Critical message to unknown server ($server)</font>");
  534:         return 'no_such_host';
  535:     }
  536:     my $answer=reply($cmd,$server);
  537:     if ($answer eq 'con_lost') {
  538: 	&reconlonc($server);
  539: 	my $answer=reply($cmd,$server);
  540:         if ($answer eq 'con_lost') {
  541:             my $now=time;
  542:             my $middlename=$cmd;
  543:             $middlename=substr($middlename,0,16);
  544:             $middlename=~s/\W//g;
  545:             my $dfilename=
  546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  547:             $dumpcount++;
  548:             {
  549: 		my $dfh;
  550: 		if (open($dfh,">",$dfilename)) {
  551: 		    print $dfh "$cmd\n"; 
  552: 		    close($dfh);
  553: 		}
  554:             }
  555:             sleep 1;
  556:             my $wcmd='';
  557:             {
  558: 		my $dfh;
  559: 		if (open($dfh,"<",$dfilename)) {
  560: 		    $wcmd=<$dfh>; 
  561: 		    close($dfh);
  562: 		}
  563:             }
  564:             chomp($wcmd);
  565:             if ($wcmd eq $cmd) {
  566: 		&logthis("<font color=\"blue\">WARNING: ".
  567:                          "Connection buffer $dfilename: $cmd</font>");
  568:                 &logperm("D:$server:$cmd");
  569: 	        return 'con_delayed';
  570:             } else {
  571:                 &logthis("<font color=\"red\">CRITICAL:"
  572:                         ." Critical connection failed: $server $cmd</font>");
  573:                 &logperm("F:$server:$cmd");
  574:                 return 'con_failed';
  575:             }
  576:         }
  577:     }
  578:     return $answer;
  579: }
  580: 
  581: # ------------------------------------------- check if return value is an error
  582: 
  583: sub error {
  584:     my ($result) = @_;
  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  586: 	if ($2 == 2) { return undef; }
  587: 	return $1;
  588:     }
  589:     return undef;
  590: }
  591: 
  592: sub convert_and_load_session_env {
  593:     my ($lonidsdir,$handle)=@_;
  594:     my @profile;
  595:     {
  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  597: 	if (!$opened) {
  598: 	    return 0;
  599: 	}
  600: 	flock($idf,LOCK_SH);
  601: 	@profile=<$idf>;
  602: 	close($idf);
  603:     }
  604:     my %temp_env;
  605:     foreach my $line (@profile) {
  606: 	if ($line !~ m/=/) {
  607: 	    return 0;
  608: 	}
  609: 	chomp($line);
  610: 	my ($envname,$envvalue)=split(/=/,$line,2);
  611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  612:     }
  613:     unlink("$lonidsdir/$handle.id");
  614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  615: 	    0640)) {
  616: 	%disk_env = %temp_env;
  617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  618: 	untie(%disk_env);
  619:     }
  620:     return 1;
  621: }
  622: 
  623: # ------------------------------------------- Transfer profile into environment
  624: my $env_loaded;
  625: sub transfer_profile_to_env {
  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
  627:     if (!$force_transfer && $env_loaded) { return; } 
  628: 
  629:     if (!defined($lonidsdir)) {
  630: 	$lonidsdir = $perlvar{'lonIDsDir'};
  631:     }
  632:     if (!defined($handle)) {
  633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  634:     }
  635: 
  636:     my $convert;
  637:     {
  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  639: 	if (!$opened) {
  640: 	    return;
  641: 	}
  642: 	flock($idf,LOCK_SH);
  643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  644: 		&GDBM_READER(),0640)) {
  645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  646: 	    untie(%disk_env);
  647: 	} else {
  648: 	    $convert = 1;
  649: 	}
  650:     }
  651:     if ($convert) {
  652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  653: 	    &logthis("Failed to load session, or convert session.");
  654: 	}
  655:     }
  656: 
  657:     my %remove;
  658:     while ( my $envname = each(%env) ) {
  659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  660:             if ($time < time-300) {
  661:                 $remove{$key}++;
  662:             }
  663:         }
  664:     }
  665: 
  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  667:     $env_loaded=1;
  668:     foreach my $expired_key (keys(%remove)) {
  669:         &delenv($expired_key);
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------- Check for valid session 
  674: sub check_for_valid_session {
  675:     my ($r,$name,$userhashref,$domref) = @_;
  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  678:     if ($name eq 'lonDAV') {
  679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  680:     } else {
  681:         $lonidsdir=$r->dir_config('lonIDsDir');
  682:         if ($name eq '') {
  683:             $name = 'lonID';
  684:         }
  685:     }
  686:     if ($name eq 'lonID') {
  687:         $secure = 'lonSID';
  688:         $linkname = 'lonLinkID';
  689:         $pubname = 'lonPubID';
  690:         if (exists($cookies{$secure})) {
  691:             $lonid=$cookies{$secure};
  692:         } elsif (exists($cookies{$name})) {
  693:             $lonid=$cookies{$name};
  694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  695:             $lonid=$cookies{$linkname};
  696:         } elsif (exists($cookies{$pubname})) {
  697:             $lonid=$cookies{$pubname};
  698:         }
  699:     } else {
  700:         $lonid=$cookies{$name};
  701:     }
  702:     return undef if (!$lonid);
  703: 
  704:     my $handle=&LONCAPA::clean_handle($lonid->value);
  705:     if (-l "$lonidsdir/$handle.id") {
  706:         my $link = readlink("$lonidsdir/$handle.id");
  707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  708:             $handle = $1;
  709:         }
  710:     }
  711:     if (!-e "$lonidsdir/$handle.id") {
  712:         if ((ref($domref)) && ($name eq 'lonID') && 
  713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  716:                 $$domref = $possudom;
  717:             }
  718:         }
  719:         return undef;
  720:     }
  721: 
  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  723:     return undef if (!$opened);
  724: 
  725:     flock($idf,LOCK_SH);
  726:     my %disk_env;
  727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  728: 	    &GDBM_READER(),0640)) {
  729: 	return undef;	
  730:     }
  731: 
  732:     if (!defined($disk_env{'user.name'})
  733: 	|| !defined($disk_env{'user.domain'})) {
  734:         untie(%disk_env);
  735: 	return undef;
  736:     }
  737: 
  738:     if (ref($userhashref) eq 'HASH') {
  739:         $userhashref->{'name'} = $disk_env{'user.name'};
  740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  742:         if ($userhashref->{'lti'}) {
  743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  745:         }
  746:     }
  747:     untie(%disk_env);
  748: 
  749:     return $handle;
  750: }
  751: 
  752: sub timed_flock {
  753:     my ($file,$lock_type) = @_;
  754:     my $failed=0;
  755:     eval {
  756: 	local $SIG{__DIE__}='DEFAULT';
  757: 	local $SIG{ALRM}=sub {
  758: 	    $failed=1;
  759: 	    die("failed lock");
  760: 	};
  761: 	alarm(13);
  762: 	flock($file,$lock_type);
  763: 	alarm(0);
  764:     };
  765:     if ($failed) {
  766: 	return undef;
  767:     } else {
  768: 	return 1;
  769:     }
  770: }
  771: 
  772: sub get_sessionfile_vars {
  773:     my ($handle,$lonidsdir,$storearr) = @_;
  774:     my %returnhash;
  775:     unless (ref($storearr) eq 'ARRAY') {
  776:         return %returnhash;
  777:     }
  778:     if (-l "$lonidsdir/$handle.id") {
  779:         my $link = readlink("$lonidsdir/$handle.id");
  780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  781:             $handle = $1;
  782:         }
  783:     }
  784:     if ((-e "$lonidsdir/$handle.id") &&
  785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  789:                 flock($idf,LOCK_SH);
  790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  791:                         &GDBM_READER(),0640)) {
  792:                     foreach my $item (@{$storearr}) {
  793:                         $returnhash{$item} = $disk_env{$item};
  794:                     }
  795:                     untie(%disk_env);
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return %returnhash;
  801: }
  802: 
  803: # ---------------------------------------------------------- Append Environment
  804: 
  805: sub appenv {
  806:     my ($newenv,$roles) = @_;
  807:     if (ref($newenv) eq 'HASH') {
  808:         foreach my $key (keys(%{$newenv})) {
  809:             my $refused = 0;
  810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  811:                 $refused = 1;
  812:                 if (ref($roles) eq 'ARRAY') {
  813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  815:                         $refused = 0;
  816:                     }
  817:                 }
  818:             }
  819:             if ($refused) {
  820:                 &logthis("<font color=\"blue\">WARNING: ".
  821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  822:                          .'</font>');
  823: 	        delete($newenv->{$key});
  824:             } else {
  825:                 $env{$key}=$newenv->{$key};
  826:             }
  827:         }
  828:         my $lonids = $perlvar{'lonIDsDir'};
  829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  831:             if ($opened
  832: 	        && &timed_flock($env_file,LOCK_EX)
  833: 	        &&
  834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  836: 	        while (my ($key,$value) = each(%{$newenv})) {
  837: 	            $disk_env{$key} = $value;
  838: 	        }
  839: 	        untie(%disk_env);
  840:             }
  841:         }
  842:     }
  843:     return 'ok';
  844: }
  845: # ----------------------------------------------------- Delete from Environment
  846: 
  847: sub delenv {
  848:     my ($delthis,$regexp,$roles) = @_;
  849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  850:         my $refused = 1;
  851:         if (ref($roles) eq 'ARRAY') {
  852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  853:             if (grep(/^\Q$role\E$/,@{$roles})) {
  854:                 $refused = 0;
  855:             }
  856:         }
  857:         if ($refused) {
  858:             &logthis("<font color=\"blue\">WARNING: ".
  859:                      "Attempt to delete from environment ".$delthis);
  860:             return 'error';
  861:         }
  862:     }
  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  864:     if ($opened
  865: 	&& &timed_flock($env_file,LOCK_EX)
  866: 	&&
  867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  869: 	foreach my $key (keys(%disk_env)) {
  870: 	    if ($regexp) {
  871:                 if ($key=~/^$delthis/) {
  872:                     delete($env{$key});
  873:                     delete($disk_env{$key});
  874:                 } 
  875:             } else {
  876:                 if ($key=~/^\Q$delthis\E/) {
  877: 		    delete($env{$key});
  878: 		    delete($disk_env{$key});
  879: 	        }
  880:             }
  881: 	}
  882: 	untie(%disk_env);
  883:     }
  884:     return 'ok';
  885: }
  886: 
  887: sub get_env_multiple {
  888:     my ($name) = @_;
  889:     my @values;
  890:     if (defined($env{$name})) {
  891:         # exists is it an array
  892:         if (ref($env{$name})) {
  893:             @values=@{ $env{$name} };
  894:         } else {
  895:             $values[0]=$env{$name};
  896:         }
  897:     }
  898:     return(@values);
  899: }
  900: 
  901: # ------------------------------------------------------------------- Locking
  902: 
  903: sub set_lock {
  904:     my ($text)=@_;
  905:     $locknum++;
  906:     my $id=$$.'-'.$locknum;
  907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  908:              'session.lock.'.$id => $text});
  909:     return $id;
  910: }
  911: 
  912: sub get_locks {
  913:     my $num=0;
  914:     my %texts=();
  915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  916:        if ($lock=~/\w/) {
  917:           $num++;
  918:           $texts{$lock}=$env{'session.lock.'.$lock};
  919:        }
  920:    }
  921:    return ($num,%texts);
  922: }
  923: 
  924: sub remove_lock {
  925:     my ($id)=@_;
  926:     my $newlocks='';
  927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  928:        if (($lock=~/\w/) && ($lock ne $id)) {
  929:           $newlocks.=','.$lock;
  930:        }
  931:     }
  932:     &appenv({'session.locks' => $newlocks});
  933:     &delenv('session.lock.'.$id);
  934: }
  935: 
  936: sub remove_all_locks {
  937:     my $activelocks=$env{'session.locks'};
  938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  939:        if ($lock=~/\w/) {
  940:           &remove_lock($lock);
  941:        }
  942:     }
  943: }
  944: 
  945: 
  946: # ------------------------------------------ Find out current server userload
  947: sub userload {
  948:     my $numusers=0;
  949:     {
  950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  951: 	my $filename;
  952: 	my $curtime=time;
  953: 	while ($filename=readdir(LONIDS)) {
  954: 	    next if ($filename eq '.' || $filename eq '..');
  955: 	    next if ($filename =~ /publicuser_\d+\.id/);
  956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  959: 	}
  960: 	closedir(LONIDS);
  961:     }
  962:     my $userloadpercent=0;
  963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  964:     if ($maxuserload) {
  965: 	$userloadpercent=100*$numusers/$maxuserload;
  966:     }
  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  968:     return $userloadpercent;
  969: }
  970: 
  971: # ------------------------------ Find server with least workload from spare.tab
  972: 
  973: sub spareserver {
  974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  975:     my $spare_server;
  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  978:                                                      :  $userloadpercent;
  979:     my ($uint_dom,$remotesessions);
  980:     if (($udom ne '') && (&domain($udom) ne '')) {
  981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  984:         $remotesessions = $udomdefaults{'remotesessions'};
  985:     }
  986:     my $spareshash = &this_host_spares($udom);
  987:     if (ref($spareshash) eq 'HASH') {
  988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  991:                                              $try_server));
  992: 	        ($spare_server, $lowest_load) =
  993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  994:             }
  995:         }
  996: 
  997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  998: 
  999:         if (!$found_server) {
 1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1002:                     next unless (&spare_can_host($udom,$uint_dom,
 1003:                                                  $remotesessions,$try_server));
 1004: 	            ($spare_server, $lowest_load) =
 1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1006:                 }
 1007: 	    }
 1008:         }
 1009:     }
 1010: 
 1011:     if (!$want_server_name) {
 1012:         if (defined($spare_server)) {
 1013:             my $hostname = &hostname($spare_server);
 1014:             if (defined($hostname)) {
 1015:                 my $protocol = 'http';
 1016:                 if ($protocol{$spare_server} eq 'https') {
 1017:                     $protocol = $protocol{$spare_server};
 1018:                 }
 1019: 	        $spare_server = $protocol.'://'.$hostname;
 1020:             }
 1021:         }
 1022:     }
 1023:     return $spare_server;
 1024: }
 1025: 
 1026: sub compare_server_load {
 1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1028: 
 1029:     if ($required) {
 1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1033:         if (($major eq '' && $minor eq '') ||
 1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1035:             return ($spare_server,$lowest_load);
 1036:         }
 1037:     }
 1038: 
 1039:     my $loadans     = &reply('load',    $try_server);
 1040:     my $userloadans = &reply('userload',$try_server);
 1041: 
 1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1044:     }
 1045: 
 1046:     my $load;
 1047:     if ($loadans =~ /\d/) {
 1048: 	if ($userloadans =~ /\d/) {
 1049: 	    #both are numbers, pick the bigger one
 1050: 	    $load = ($loadans > $userloadans) ? $loadans 
 1051: 		                              : $userloadans;
 1052: 	} else {
 1053: 	    $load = $loadans;
 1054: 	}
 1055:     } else {
 1056: 	$load = $userloadans;
 1057:     }
 1058: 
 1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1060: 	$spare_server = $try_server;
 1061: 	$lowest_load  = $load;
 1062:     }
 1063:     return ($spare_server,$lowest_load);
 1064: }
 1065: 
 1066: # --------------------------- ask offload servers if user already has a session
 1067: sub find_existing_session {
 1068:     my ($udom,$uname) = @_;
 1069:     my $spareshash = &this_host_spares($udom);
 1070:     if (ref($spareshash) eq 'HASH') {
 1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1074:             }
 1075:         }
 1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1079:             }
 1080:         }
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: # check if user's browser sent load balancer cookie and server still has session
 1086: # and is not overloaded.
 1087: sub check_for_balancer_cookie {
 1088:     my ($r,$update_mtime) = @_;
 1089:     my ($otherserver,$cookie);
 1090:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1091:     if (exists($cookies{'balanceID'})) {
 1092:         my $balid = $cookies{'balanceID'};
 1093:         $cookie=&LONCAPA::clean_handle($balid->value);
 1094:         my $balancedir=$r->dir_config('lonBalanceDir');
 1095:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1096:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1097:                 my ($possudom,$possuname) = ($1,$2);
 1098:                 my $has_session = 0;
 1099:                 if ((&domain($possudom) ne '') &&
 1100:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1101:                     my $try_server;
 1102:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1103:                     if ($opened) {
 1104:                         flock($idf,LOCK_SH);
 1105:                         while (my $line = <$idf>) {
 1106:                             chomp($line);
 1107:                             if (&hostname($line) ne '') {
 1108:                                 $try_server = $line;
 1109:                                 last;
 1110:                             }
 1111:                         }
 1112:                         close($idf);
 1113:                         if (($try_server) &&
 1114:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1115:                             my $lowest_load = 30000;
 1116:                             ($otherserver,$lowest_load) =
 1117:                                 &compare_server_load($try_server,undef,$lowest_load);
 1118:                             if ($otherserver ne '' && $lowest_load < 100) {
 1119:                                 $has_session = 1;
 1120:                             } else {
 1121:                                 undef($otherserver);
 1122:                             }
 1123:                         }
 1124:                     }
 1125:                 }
 1126:                 if ($has_session) {
 1127:                     if ($update_mtime) {
 1128:                         my $atime = my $mtime = time;
 1129:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1130:                     }
 1131:                 } else {
 1132:                     unlink("$balancedir/$cookie.id");
 1133:                 }
 1134:             }
 1135:         }
 1136:     }
 1137:     return ($otherserver,$cookie);
 1138: }
 1139: 
 1140: sub delbalcookie {
 1141:     my ($cookie,$balancer) =@_;
 1142:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1143:         my ($udom,$uname) = ($1,$2);
 1144:         my $uprimary_id = &domain($udom,'primary');
 1145:         my $uintdom = &internet_dom($uprimary_id);
 1146:         my $intdom = &internet_dom($balancer);
 1147:         my $serverhomedom = &host_domain($balancer);
 1148:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1149:             return &reply("delbalcookie:$cookie",$balancer);
 1150:         }
 1151:     }
 1152: }
 1153: 
 1154: # -------------------------------- ask if server already has a session for user
 1155: sub has_user_session {
 1156:     my ($lonid,$udom,$uname) = @_;
 1157:     my $result = &reply(join(':','userhassession',
 1158: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1159:     return 1 if ($result eq 'ok');
 1160: 
 1161:     return 0;
 1162: }
 1163: 
 1164: # --------- determine least loaded server in a user's domain which allows login
 1165: 
 1166: sub choose_server {
 1167:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1168:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1169:     my %servers = &get_servers($udom);
 1170:     my $lowest_load = 30000;
 1171:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1172:     if ($skiploadbal) {
 1173:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1174:         unless (defined($cached)) {
 1175:             my $cachetime = 60*60*24;
 1176:             my %domconfig =
 1177:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1178:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1179:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1180:                                            $cachetime);
 1181:             }
 1182:         }
 1183:     }
 1184:     foreach my $lonhost (keys(%servers)) {
 1185:         if ($skiploadbal) {
 1186:             if (ref($balancers) eq 'HASH') {
 1187:                 next if (exists($balancers->{$lonhost}));
 1188:             }
 1189:         }
 1190:         my $loginvia;
 1191:         if ($checkloginvia) {
 1192:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1193:             if ($loginvia) {
 1194:                 my ($server,$path) = split(/:/,$loginvia);
 1195:                 ($login_host, $lowest_load) =
 1196:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1197:                 if ($login_host eq $server) {
 1198:                     $portal_path = $path;
 1199:                     $isredirect = 1;
 1200:                 }
 1201:             } else {
 1202:                 ($login_host, $lowest_load) =
 1203:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1204:                 if ($login_host eq $lonhost) {
 1205:                     $portal_path = '';
 1206:                     $isredirect = ''; 
 1207:                 }
 1208:             }
 1209:         } else {
 1210:             ($login_host, $lowest_load) =
 1211:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1212:         }
 1213:     }
 1214:     if ($login_host ne '') {
 1215:         $hostname = &hostname($login_host);
 1216:     }
 1217:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1218: }
 1219: 
 1220: # --------------------------------------------- Try to change a user's password
 1221: 
 1222: sub changepass {
 1223:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1224:     $currentpass = &escape($currentpass);
 1225:     $newpass     = &escape($newpass);
 1226:     my $lonhost = $perlvar{'lonHostID'};
 1227:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1228: 		       $server);
 1229:     if (! $answer) {
 1230: 	&logthis("No reply on password change request to $server ".
 1231: 		 "by $uname in domain $udom.");
 1232:     } elsif ($answer =~ "^ok") {
 1233:         &logthis("$uname in $udom successfully changed their password ".
 1234: 		 "on $server.");
 1235:     } elsif ($answer =~ "^pwchange_failure") {
 1236: 	&logthis("$uname in $udom was unable to change their password ".
 1237: 		 "on $server.  The action was blocked by either lcpasswd ".
 1238: 		 "or pwchange");
 1239:     } elsif ($answer =~ "^non_authorized") {
 1240:         &logthis("$uname in $udom did not get their password correct when ".
 1241: 		 "attempting to change it on $server.");
 1242:     } elsif ($answer =~ "^auth_mode_error") {
 1243:         &logthis("$uname in $udom attempted to change their password despite ".
 1244: 		 "not being locally or internally authenticated on $server.");
 1245:     } elsif ($answer =~ "^unknown_user") {
 1246:         &logthis("$uname in $udom attempted to change their password ".
 1247: 		 "on $server but were unable to because $server is not ".
 1248: 		 "their home server.");
 1249:     } elsif ($answer =~ "^refused") {
 1250: 	&logthis("$server refused to change $uname in $udom password because ".
 1251: 		 "it was sent an unencrypted request to change the password.");
 1252:     } elsif ($answer =~ "invalid_client") {
 1253:         &logthis("$server refused to change $uname in $udom password because ".
 1254:                  "it was a reset by e-mail originating from an invalid server.");
 1255:     } elsif ($answer =~ "^prioruse") {
 1256:        &logthis("$server refused to change $uname in $udom password because ".
 1257:                 "the password had been used before");
 1258:     }
 1259:     return $answer;
 1260: }
 1261: 
 1262: # ----------------------- Try to determine user's current authentication scheme
 1263: 
 1264: sub queryauthenticate {
 1265:     my ($uname,$udom)=@_;
 1266:     my $uhome=&homeserver($uname,$udom);
 1267:     if (!$uhome) {
 1268: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1269: 	return 'no_host';
 1270:     }
 1271:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1272:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1273: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1274:     }
 1275:     return $answer;
 1276: }
 1277: 
 1278: # --------- Try to authenticate user from domain's lib servers (first this one)
 1279: 
 1280: sub authenticate {
 1281:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1282:     $upass=&escape($upass);
 1283:     $uname= &LONCAPA::clean_username($uname);
 1284:     my $uhome=&homeserver($uname,$udom,1);
 1285:     my $newhome;
 1286:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1287: # Maybe the machine was offline and only re-appeared again recently?
 1288:         &reconlonc();
 1289: # One more
 1290: 	$uhome=&homeserver($uname,$udom,1);
 1291:         if (($uhome eq 'no_host') && $checkdefauth) {
 1292:             if (defined(&domain($udom,'primary'))) {
 1293:                 $newhome=&domain($udom,'primary');
 1294:             }
 1295:             if ($newhome ne '') {
 1296:                 $uhome = $newhome;
 1297:             }
 1298:         }
 1299: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1300: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1301: 	    return 'no_host';
 1302:         }
 1303:     }
 1304:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1305:     if ($answer eq 'authorized') {
 1306:         if ($newhome) {
 1307:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1308:             return 'no_account_on_host'; 
 1309:         } else {
 1310:             &logthis("User $uname at $udom authorized by $uhome");
 1311:             return $uhome;
 1312:         }
 1313:     }
 1314:     if ($answer eq 'non_authorized') {
 1315: 	&logthis("User $uname at $udom rejected by $uhome");
 1316: 	return 'no_host'; 
 1317:     }
 1318:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1319:     return 'no_host';
 1320: }
 1321: 
 1322: sub can_host_session {
 1323:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1324:     my $canhost = 1;
 1325:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1326:     if (ref($remotesessions) eq 'HASH') {
 1327:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1328:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1329:                 $canhost = 0;
 1330:             } else {
 1331:                 $canhost = 1;
 1332:             }
 1333:         }
 1334:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1335:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1336:                 $canhost = 1;
 1337:             } else {
 1338:                 $canhost = 0;
 1339:             }
 1340:         }
 1341:         if ($canhost) {
 1342:             if ($remotesessions->{'version'} ne '') {
 1343:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1344:                 if ($reqmajor ne '' && $reqminor ne '') {
 1345:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1346:                         my $major = $1;
 1347:                         my $minor = $2;
 1348:                         if (($major < $reqmajor ) ||
 1349:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1350:                             $canhost = 0;
 1351:                         }
 1352:                     } else {
 1353:                         $canhost = 0;
 1354:                     }
 1355:                 }
 1356:             }
 1357:         }
 1358:     }
 1359:     if ($canhost) {
 1360:         if (ref($hostedsessions) eq 'HASH') {
 1361:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1362:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1363:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1364:                 if (($uint_dom ne '') && 
 1365:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1366:                     $canhost = 0;
 1367:                 } else {
 1368:                     $canhost = 1;
 1369:                 }
 1370:             }
 1371:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1372:                 if (($uint_dom ne '') && 
 1373:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1374:                     $canhost = 1;
 1375:                 } else {
 1376:                     $canhost = 0;
 1377:                 }
 1378:             }
 1379:         }
 1380:     }
 1381:     return $canhost;
 1382: }
 1383: 
 1384: sub spare_can_host {
 1385:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1386:     my $canhost=1;
 1387:     my $try_server_hostname = &hostname($try_server);
 1388:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1389:     my $serverhomedom = &host_domain($serverhomeID);
 1390:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1391:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1392:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1393:             $canhost = 0;
 1394:         }
 1395:     }
 1396:     if (($canhost) && ($uint_dom)) {
 1397:         my @intdoms;
 1398:         my $internet_names = &get_internet_names($try_server);
 1399:         if (ref($internet_names) eq 'ARRAY') {
 1400:             @intdoms = @{$internet_names};
 1401:         }
 1402:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1403:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1404:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1405:                                          $remotesessions,
 1406:                                          $defdomdefaults{'hostedsessions'});
 1407:         }
 1408:     }
 1409:     return $canhost;
 1410: }
 1411: 
 1412: sub this_host_spares {
 1413:     my ($dom) = @_;
 1414:     my ($dom_in_use,$lonhost_in_use,$result);
 1415:     my @hosts = &current_machine_ids();
 1416:     foreach my $lonhost (@hosts) {
 1417:         if (&host_domain($lonhost) eq $dom) {
 1418:             $dom_in_use = $dom;
 1419:             $lonhost_in_use = $lonhost;
 1420:             last;
 1421:         }
 1422:     }
 1423:     if ($dom_in_use ne '') {
 1424:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1425:     }
 1426:     if (ref($result) ne 'HASH') {
 1427:         $lonhost_in_use = $perlvar{'lonHostID'};
 1428:         $dom_in_use = &host_domain($lonhost_in_use);
 1429:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1430:         if (ref($result) ne 'HASH') {
 1431:             $result = \%spareid;
 1432:         }
 1433:     }
 1434:     return $result;
 1435: }
 1436: 
 1437: sub spares_for_offload  {
 1438:     my ($dom_in_use,$lonhost_in_use) = @_;
 1439:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1440:     if (defined($cached)) {
 1441:         return $result;
 1442:     } else {
 1443:         my $cachetime = 60*60*24;
 1444:         my %domconfig =
 1445:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1446:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1447:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1448:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1449:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1450:                 }
 1451:             }
 1452:         }
 1453:     }
 1454:     return;
 1455: }
 1456: 
 1457: sub get_lonbalancer_config {
 1458:     my ($servers) = @_;
 1459:     my ($currbalancer,$currtargets);
 1460:     if (ref($servers) eq 'HASH') {
 1461:         foreach my $server (keys(%{$servers})) {
 1462:             my %what = (
 1463:                          spareid => 1,
 1464:                          perlvar => 1,
 1465:                        );
 1466:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1467:             if ($result eq 'ok') {
 1468:                 if (ref($returnhash) eq 'HASH') {
 1469:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1470:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1471:                             $currbalancer = $server;
 1472:                             $currtargets = {};
 1473:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1474:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1475:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1476:                                 }
 1477:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1478:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1479:                                 }
 1480:                             }
 1481:                             last;
 1482:                         }
 1483:                     }
 1484:                 }
 1485:             }
 1486:         }
 1487:     }
 1488:     return ($currbalancer,$currtargets);
 1489: }
 1490: 
 1491: sub check_loadbalancing {
 1492:     my ($uname,$udom,$caller) = @_;
 1493:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1494:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1495:     my $lonhost = $perlvar{'lonHostID'};
 1496:     my @hosts = &current_machine_ids();
 1497:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1498:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1499:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1500:     my $serverhomedom = &host_domain($lonhost);
 1501:     my $domneedscache;
 1502:     my $cachetime = 60*60*24;
 1503: 
 1504:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1505:         $dom_in_use = $udom;
 1506:         $homeintdom = 1;
 1507:     } else {
 1508:         $dom_in_use = $serverhomedom;
 1509:     }
 1510:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1511:     unless (defined($cached)) {
 1512:         my %domconfig =
 1513:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1514:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1515:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1516:         } else {
 1517:             $domneedscache = $dom_in_use;
 1518:         }
 1519:     }
 1520:     if (ref($result) eq 'HASH') {
 1521:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1522:             &check_balancer_result($result,@hosts);
 1523:         if ($is_balancer) {
 1524:             if (ref($currrules) eq 'HASH') {
 1525:                 if ($homeintdom) {
 1526:                     if ($uname ne '') {
 1527:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1528:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1529:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1530:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1531:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1532:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1533:                             }
 1534:                         }
 1535:                         if ($rule_in_effect eq '') {
 1536:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1537:                             if ($userenv{'inststatus'} ne '') {
 1538:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1539:                                 my ($othertitle,$usertypes,$types) =
 1540:                                     &Apache::loncommon::sorted_inst_types($udom);
 1541:                                 if (ref($types) eq 'ARRAY') {
 1542:                                     foreach my $type (@{$types}) {
 1543:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1544:                                             if (exists($currrules->{$type})) {
 1545:                                                 $rule_in_effect = $currrules->{$type};
 1546:                                             }
 1547:                                         }
 1548:                                     }
 1549:                                 }
 1550:                             } else {
 1551:                                 if (exists($currrules->{'default'})) {
 1552:                                     $rule_in_effect = $currrules->{'default'};
 1553:                                 }
 1554:                             }
 1555:                         }
 1556:                     } else {
 1557:                         if (exists($currrules->{'default'})) {
 1558:                             $rule_in_effect = $currrules->{'default'};
 1559:                         }
 1560:                     }
 1561:                 } else {
 1562:                     if ($currrules->{'_LC_external'} ne '') {
 1563:                         $rule_in_effect = $currrules->{'_LC_external'};
 1564:                     }
 1565:                 }
 1566:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1567:                                                        $uname,$udom);
 1568:             }
 1569:         }
 1570:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1571:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1572:         unless (defined($cached)) {
 1573:             my %domconfig =
 1574:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1575:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1577:             } else {
 1578:                 $domneedscache = $serverhomedom;
 1579:             }
 1580:         }
 1581:         if (ref($result) eq 'HASH') {
 1582:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1583:                 &check_balancer_result($result,@hosts);
 1584:             if ($is_balancer) {
 1585:                 if (ref($currrules) eq 'HASH') {
 1586:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1587:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1588:                     }
 1589:                 }
 1590:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1591:                                                        $uname,$udom);
 1592:             }
 1593:         } else {
 1594:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1595:                 $is_balancer = 1;
 1596:                 $offloadto = &this_host_spares($dom_in_use);
 1597:             }
 1598:             unless (defined($cached)) {
 1599:                 $domneedscache = $serverhomedom;
 1600:             }
 1601:         }
 1602:     } else {
 1603:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1604:             $is_balancer = 1;
 1605:             $offloadto = &this_host_spares($dom_in_use);
 1606:         }
 1607:         unless (defined($cached)) {
 1608:             $domneedscache = $serverhomedom;
 1609:         }
 1610:     }
 1611:     if ($domneedscache) {
 1612:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1613:     }
 1614:     if ($is_balancer) {
 1615:         my $lowest_load = 30000;
 1616:         if (ref($offloadto) eq 'HASH') {
 1617:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1618:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1619:                     ($otherserver,$lowest_load) =
 1620:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1621:                 }
 1622:             }
 1623:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1624: 
 1625:             if (!$found_server) {
 1626:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1627:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1628:                         ($otherserver,$lowest_load) =
 1629:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1630:                     }
 1631:                 }
 1632:             }
 1633:         } elsif (ref($offloadto) eq 'ARRAY') {
 1634:             if (@{$offloadto} == 1) {
 1635:                 $otherserver = $offloadto->[0];
 1636:             } elsif (@{$offloadto} > 1) {
 1637:                 foreach my $try_server (@{$offloadto}) {
 1638:                     ($otherserver,$lowest_load) =
 1639:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1640:                 }
 1641:             }
 1642:         }
 1643:         unless ($caller eq 'login') {
 1644:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1645:                 $is_balancer = 0;
 1646:                 if ($uname ne '' && $udom ne '') {
 1647:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1648:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1649:                                  'user.loadbalcheck.time' => time});
 1650:                     }
 1651:                 }
 1652:             }
 1653:         }
 1654:         unless ($homeintdom) {
 1655:             undef($setcookie);
 1656:         }
 1657:     }
 1658:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1659: }
 1660: 
 1661: sub check_balancer_result {
 1662:     my ($result,@hosts) = @_;
 1663:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1664:     if (ref($result) eq 'HASH') {
 1665:         if ($result->{'lonhost'} ne '') {
 1666:             my $currbalancer = $result->{'lonhost'};
 1667:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1668:                 $is_balancer = 1;
 1669:                 $currtargets = $result->{'targets'};
 1670:                 $currrules = $result->{'rules'};
 1671:             }
 1672:             $dom_balancers = $currbalancer;
 1673:         } else {
 1674:             if (keys(%{$result})) {
 1675:                 foreach my $key (keys(%{$result})) {
 1676:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1677:                         (ref($result->{$key}) eq 'HASH')) {
 1678:                         $is_balancer = 1;
 1679:                         $currrules = $result->{$key}{'rules'};
 1680:                         $currtargets = $result->{$key}{'targets'};
 1681:                         $setcookie = $result->{$key}{'cookie'};
 1682:                         last;
 1683:                     }
 1684:                 }
 1685:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1686:             }
 1687:         }
 1688:     }
 1689:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1690: }
 1691: 
 1692: sub get_loadbalancer_targets {
 1693:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1694:     my $offloadto;
 1695:     if ($rule_in_effect eq 'none') {
 1696:         return [$perlvar{'lonHostID'}];
 1697:     } elsif ($rule_in_effect eq '') {
 1698:         $offloadto = $currtargets;
 1699:     } else {
 1700:         if ($rule_in_effect eq 'homeserver') {
 1701:             my $homeserver = &homeserver($uname,$udom);
 1702:             if ($homeserver ne 'no_host') {
 1703:                 $offloadto = [$homeserver];
 1704:             }
 1705:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1706:             my %domconfig =
 1707:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1708:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1709:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1710:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1711:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1712:                     }
 1713:                 }
 1714:             } else {
 1715:                 my %servers = &internet_dom_servers($udom);
 1716:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1717:                 if (&hostname($remotebalancer) ne '') {
 1718:                     $offloadto = [$remotebalancer];
 1719:                 }
 1720:             }
 1721:         } elsif (&hostname($rule_in_effect) ne '') {
 1722:             $offloadto = [$rule_in_effect];
 1723:         }
 1724:     }
 1725:     return $offloadto;
 1726: }
 1727: 
 1728: sub internet_dom_servers {
 1729:     my ($dom) = @_;
 1730:     my (%uniqservers,%servers);
 1731:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1732:     my @machinedoms = &machine_domains($primaryserver);
 1733:     foreach my $mdom (@machinedoms) {
 1734:         my %currservers = %servers;
 1735:         my %server = &get_servers($mdom);
 1736:         %servers = (%currservers,%server);
 1737:     }
 1738:     my %by_hostname;
 1739:     foreach my $id (keys(%servers)) {
 1740:         push(@{$by_hostname{$servers{$id}}},$id);
 1741:     }
 1742:     foreach my $hostname (sort(keys(%by_hostname))) {
 1743:         if (@{$by_hostname{$hostname}} > 1) {
 1744:             my $match = 0;
 1745:             foreach my $id (@{$by_hostname{$hostname}}) {
 1746:                 if (&host_domain($id) eq $dom) {
 1747:                     $uniqservers{$id} = $hostname;
 1748:                     $match = 1;
 1749:                 }
 1750:             }
 1751:             unless ($match) {
 1752:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1753:             }
 1754:         } else {
 1755:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1756:         }
 1757:     }
 1758:     return %uniqservers;
 1759: }
 1760: 
 1761: sub trusted_domains {
 1762:     my ($cmdtype,$calldom) = @_;
 1763:     my ($trusted,$untrusted);
 1764:     if (&domain($calldom) eq '') {
 1765:         return ($trusted,$untrusted);
 1766:     }
 1767:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1768:         return ($trusted,$untrusted);
 1769:     }
 1770:     my $callprimary = &domain($calldom,'primary');
 1771:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1772:     if ($intcalldom eq '') {
 1773:         return ($trusted,$untrusted);
 1774:     }
 1775: 
 1776:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1777:     unless (defined($cached)) {
 1778:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1779:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1780:         $trustconfig = $domconfig{'trust'};
 1781:     }
 1782:     if (ref($trustconfig)) {
 1783:         my (%possexc,%possinc,@allexc,@allinc); 
 1784:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1785:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1786:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1787:             }
 1788:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1789:                 $possinc{$intcalldom} = 1;
 1790:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1791:             }
 1792:         }
 1793:         if (keys(%possexc)) {
 1794:             if (keys(%possinc)) {
 1795:                 foreach my $key (sort(keys(%possexc))) {
 1796:                     next if ($key eq $intcalldom);
 1797:                     unless ($possinc{$key}) {
 1798:                         push(@allexc,$key);
 1799:                     }
 1800:                 }
 1801:             } else {
 1802:                 @allexc = sort(keys(%possexc));
 1803:             }
 1804:         }
 1805:         if (keys(%possinc)) {
 1806:             $possinc{$intcalldom} = 1;
 1807:             @allinc = sort(keys(%possinc));
 1808:         }
 1809:         if ((@allexc > 0) || (@allinc > 0)) {
 1810:             my %doms_by_intdom;
 1811:             my %allintdoms = &all_host_intdom();
 1812:             my %alldoms = &all_host_domain();
 1813:             foreach my $key (%allintdoms) {
 1814:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1815:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1816:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1817:                     }
 1818:                 } else {
 1819:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1820:                 }
 1821:             }
 1822:             foreach my $exc (@allexc) {
 1823:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1824:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1825:                 }
 1826:             }
 1827:             foreach my $inc (@allinc) {
 1828:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1829:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1830:                 }
 1831:             }
 1832:         }
 1833:     }
 1834:     return ($trusted,$untrusted);
 1835: }
 1836: 
 1837: sub will_trust {
 1838:     my ($cmdtype,$domain,$possdom) = @_;
 1839:     return 1 if ($domain eq $possdom);
 1840:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1841:     my $willtrust; 
 1842:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1843:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1844:             $willtrust = 1;
 1845:         }
 1846:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1847:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1848:             $willtrust = 1;
 1849:         }
 1850:     } else {
 1851:         $willtrust = 1;
 1852:     }
 1853:     return $willtrust;
 1854: }
 1855: 
 1856: # ---------------------- Find the homebase for a user from domain's lib servers
 1857: 
 1858: my %homecache;
 1859: sub homeserver {
 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
 1861:     my $index="$uname:$udom";
 1862: 
 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1864: 
 1865:     my %servers = &get_servers($udom,'library');
 1866:     foreach my $tryserver (keys(%servers)) {
 1867:         next if ($ignoreBadCache ne 'true' && 
 1868: 		 exists($badServerCache{$tryserver}));
 1869: 
 1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1871: 	if ($answer eq 'found') {
 1872: 	    delete($badServerCache{$tryserver}); 
 1873: 	    return $homecache{$index}=$tryserver;
 1874: 	} elsif ($answer eq 'no_host') {
 1875: 	    $badServerCache{$tryserver}=1;
 1876: 	}
 1877:     }    
 1878:     return 'no_host';
 1879: }
 1880: 
 1881: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1882: 
 1883: sub idget {
 1884:     my ($udom,$idsref,$namespace)=@_;
 1885:     my %returnhash=();
 1886:     my @ids=(); 
 1887:     if (ref($idsref) eq 'ARRAY') {
 1888:         @ids = @{$idsref};
 1889:     } else {
 1890:         return %returnhash; 
 1891:     }
 1892:     if ($namespace eq '') {
 1893:         $namespace = 'ids';
 1894:     }
 1895:     
 1896:     my %servers = &get_servers($udom,'library');
 1897:     foreach my $tryserver (keys(%servers)) {
 1898: 	my $idlist=join('&', map { &escape($_); } @ids);
 1899: 	if ($namespace eq 'ids') {
 1900: 	    $idlist=~tr/A-Z/a-z/;
 1901: 	}
 1902: 	my $reply;
 1903: 	if ($namespace eq 'ids') {
 1904: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1905: 	} else {
 1906: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1907: 	}
 1908: 	my @answer=();
 1909: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1910: 	    @answer=split(/\&/,$reply);
 1911: 	}                    ;
 1912: 	my $i;
 1913: 	for ($i=0;$i<=$#ids;$i++) {
 1914: 	    if ($answer[$i]) {
 1915: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1916: 	    }
 1917: 	}
 1918:     }
 1919:     return %returnhash;
 1920: }
 1921: 
 1922: # ------------------------------------- Find the IDs behind a list of usernames
 1923: 
 1924: sub idrget {
 1925:     my ($udom,@unames)=@_;
 1926:     my %returnhash=();
 1927:     foreach my $uname (@unames) {
 1928:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1929:     }
 1930:     return %returnhash;
 1931: }
 1932: 
 1933: # Store away a list of names and associated student/employee IDs or clicker IDs
 1934: 
 1935: sub idput {
 1936:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1937:     my %servers=();
 1938:     my %ids=();
 1939:     my %byid = ();
 1940:     if (ref($idsref) eq 'HASH') {
 1941:         %ids=%{$idsref};
 1942:     }
 1943:     if ($namespace eq '') {
 1944:         $namespace = 'ids'; 
 1945:     }
 1946:     foreach my $uname (keys(%ids)) {
 1947: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1948:         if ($uhom eq '') {
 1949:             $uhom=&homeserver($uname,$udom);
 1950:         }
 1951:         if ($uhom ne 'no_host') {
 1952:             my $esc_unam=&escape($uname);
 1953:             if ($namespace eq 'ids') {
 1954:                 my $id=&escape($ids{$uname});
 1955:                 $id=~tr/A-Z/a-z/;
 1956:                 my $esc_unam=&escape($uname);
 1957:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1958:             } else {
 1959:                 my @currids = split(/,/,$ids{$uname});
 1960:                 foreach my $id (@currids) {
 1961:                     $byid{$uhom}{$id} .= $uname.',';
 1962:                 }
 1963:             }
 1964:         }
 1965:     }
 1966:     if ($namespace eq 'clickers') {
 1967:         foreach my $server (keys(%byid)) {
 1968:             if (ref($byid{$server}) eq 'HASH') {
 1969:                 foreach my $id (keys(%{$byid{$server}})) {
 1970:                     $byid{$server} =~ s/,$//;
 1971:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1972:                 }
 1973:             }
 1974:         }
 1975:     }
 1976:     foreach my $server (keys(%servers)) {
 1977:         $servers{$server} =~ s/\&$//;
 1978:         if ($namespace eq 'ids') {     
 1979:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1980:         } else {
 1981:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1982:         }
 1983:     }
 1984: }
 1985: 
 1986: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1987: 
 1988: sub iddel {
 1989:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1990:     my %result=();
 1991:     my %ids=();
 1992:     my %byid = ();
 1993:     if (ref($idshashref) eq 'HASH') {
 1994:         %ids=%{$idshashref};
 1995:     } else {
 1996:         return %result;
 1997:     }
 1998:     if ($namespace eq '') {
 1999:         $namespace = 'ids';
 2000:     }
 2001:     my %servers=();
 2002:     while (my ($id,$unamestr) = each(%ids)) {
 2003:         if ($namespace eq 'ids') {
 2004:             my $uhom = $uhome;
 2005:             if ($uhom eq '') { 
 2006:                 $uhom=&homeserver($unamestr,$udom);
 2007:             }
 2008:             if ($uhom ne 'no_host') {
 2009:                 $servers{$uhom}.='&'.&escape($id);
 2010:             }
 2011:          } else {
 2012:             my @curritems = split(/,/,$ids{$id});
 2013:             foreach my $uname (@curritems) {
 2014:                 my $uhom = $uhome;
 2015:                 if ($uhom eq '') {
 2016:                     $uhom=&homeserver($uname,$udom);
 2017:                 }
 2018:                 if ($uhom ne 'no_host') { 
 2019:                     $byid{$uhom}{$id} .= $uname.',';
 2020:                 }
 2021:             }
 2022:         }
 2023:     }
 2024:     if ($namespace eq 'clickers') {
 2025:         foreach my $server (keys(%byid)) {
 2026:             if (ref($byid{$server}) eq 'HASH') {
 2027:                 foreach my $id (keys(%{$byid{$server}})) {
 2028:                     $byid{$server}{$id} =~ s/,$//;
 2029:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     foreach my $server (keys(%servers)) {
 2035:         $servers{$server} =~ s/\&$//;
 2036:         if ($namespace eq 'ids') {
 2037:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2038:         } elsif ($namespace eq 'clickers') {
 2039:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2040:         }
 2041:     }
 2042:     return %result;
 2043: }
 2044: 
 2045: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2046: 
 2047: sub updateclickers {
 2048:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2049:     my %clickers;
 2050:     if (ref($idshashref) eq 'HASH') {
 2051:         %clickers=%{$idshashref};
 2052:     } else {
 2053:         return;
 2054:     }
 2055:     my $items='';
 2056:     foreach my $item (keys(%clickers)) {
 2057:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2058:     }
 2059:     $items=~s/\&$//;
 2060:     my $request = "updateclickers:$udom:$action:$items";
 2061:     if ($critical) {
 2062:         return &critical($request,$uhome);
 2063:     } else {
 2064:         return &reply($request,$uhome);
 2065:     }
 2066: }
 2067: 
 2068: # ------------------------------dump from db file owned by domainconfig user
 2069: sub dump_dom {
 2070:     my ($namespace, $udom, $regexp) = @_;
 2071: 
 2072:     $udom ||= $env{'user.domain'};
 2073: 
 2074:     return () unless $udom;
 2075: 
 2076:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2077: }
 2078: 
 2079: # ------------------------------------------ get items from domain db files   
 2080: 
 2081: sub get_dom {
 2082:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2083:     return if ($udom eq 'public');
 2084:     my $items='';
 2085:     foreach my $item (@$storearr) {
 2086:         $items.=&escape($item).'&';
 2087:     }
 2088:     $items=~s/\&$//;
 2089:     if (!$udom) {
 2090:         $udom=$env{'user.domain'};
 2091:         return if ($udom eq 'public');
 2092:         if (defined(&domain($udom,'primary'))) {
 2093:             $uhome=&domain($udom,'primary');
 2094:         } else {
 2095:             undef($uhome);
 2096:         }
 2097:     } else {
 2098:         if (!$uhome) {
 2099:             if (defined(&domain($udom,'primary'))) {
 2100:                 $uhome=&domain($udom,'primary');
 2101:             }
 2102:         }
 2103:     }
 2104:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2105:         my $rep;
 2106:         if ($namespace =~ /^enc/) {
 2107:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2108:         } else {
 2109:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2110:         }
 2111:         my %returnhash;
 2112:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2113:             return %returnhash;
 2114:         }
 2115:         my @pairs=split(/\&/,$rep);
 2116:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2117:             return @pairs;
 2118:         }
 2119:         my $i=0;
 2120:         foreach my $item (@$storearr) {
 2121:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2122:             $i++;
 2123:         }
 2124:         return %returnhash;
 2125:     } else {
 2126:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2127:     }
 2128: }
 2129: 
 2130: # -------------------------------------------- put items in domain db files 
 2131: 
 2132: sub put_dom {
 2133:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2134:     if (!$udom) {
 2135:         $udom=$env{'user.domain'};
 2136:         if (defined(&domain($udom,'primary'))) {
 2137:             $uhome=&domain($udom,'primary');
 2138:         } else {
 2139:             undef($uhome);
 2140:         }
 2141:     } else {
 2142:         if (!$uhome) {
 2143:             if (defined(&domain($udom,'primary'))) {
 2144:                 $uhome=&domain($udom,'primary');
 2145:             }
 2146:         }
 2147:     } 
 2148:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2149:         my $items='';
 2150:         foreach my $item (keys(%$storehash)) {
 2151:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2152:         }
 2153:         $items=~s/\&$//;
 2154:         if ($namespace =~ /^enc/) {
 2155:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2156:         } else {
 2157:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2158:         }
 2159:     } else {
 2160:         &logthis("put_dom failed - no homeserver and/or domain");
 2161:     }
 2162: }
 2163: 
 2164: # --------------------- newput for items in db file owned by domainconfig user
 2165: sub newput_dom {
 2166:     my ($namespace,$storehash,$udom) = @_;
 2167:     my $result;
 2168:     if (!$udom) {
 2169:         $udom=$env{'user.domain'};
 2170:     }
 2171:     if ($udom) {
 2172:         my $uname = &get_domainconfiguser($udom);
 2173:         $result = &newput($namespace,$storehash,$udom,$uname);
 2174:     }
 2175:     return $result;
 2176: }
 2177: 
 2178: # --------------------- delete for items in db file owned by domainconfig user
 2179: sub del_dom {
 2180:     my ($namespace,$storearr,$udom)=@_;
 2181:     if (ref($storearr) eq 'ARRAY') {
 2182:         if (!$udom) {
 2183:             $udom=$env{'user.domain'};
 2184:         }
 2185:         if ($udom) {
 2186:             my $uname = &get_domainconfiguser($udom); 
 2187:             return &del($namespace,$storearr,$udom,$uname);
 2188:         }
 2189:     }
 2190: }
 2191: 
 2192: # ----------------------------------construct domainconfig user for a domain 
 2193: sub get_domainconfiguser {
 2194:     my ($udom) = @_;
 2195:     return $udom.'-domainconfig';
 2196: }
 2197: 
 2198: sub retrieve_inst_usertypes {
 2199:     my ($udom) = @_;
 2200:     my (%returnhash,@order);
 2201:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2202:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2203:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2204:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2205:     } else {
 2206:         if (defined(&domain($udom,'primary'))) {
 2207:             my $uhome=&domain($udom,'primary');
 2208:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2209:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2210:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2211:                 return (\%returnhash,\@order);
 2212:             }
 2213:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2214:             my @pairs=split(/\&/,$hashitems);
 2215:             foreach my $item (@pairs) {
 2216:                 my ($key,$value)=split(/=/,$item,2);
 2217:                 $key = &unescape($key);
 2218:                 next if ($key =~ /^error: 2 /);
 2219:                 $returnhash{$key}=&thaw_unescape($value);
 2220:             }
 2221:             my @esc_order = split(/\&/,$orderitems);
 2222:             foreach my $item (@esc_order) {
 2223:                 push(@order,&unescape($item));
 2224:             }
 2225:         } else {
 2226:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2227:         }
 2228:         return (\%returnhash,\@order);
 2229:     }
 2230: }
 2231: 
 2232: sub is_domainimage {
 2233:     my ($url) = @_;
 2234:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2235:         if (&domain($1) ne '') {
 2236:             return '1';
 2237:         }
 2238:     }
 2239:     return;
 2240: }
 2241: 
 2242: sub inst_directory_query {
 2243:     my ($srch) = @_;
 2244:     my $udom = $srch->{'srchdomain'};
 2245:     my %results;
 2246:     my $homeserver = &domain($udom,'primary');
 2247:     my $outcome;
 2248:     if ($homeserver ne '') {
 2249:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2250:             if ($srch->{'srchby'} eq 'email') {
 2251:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2252:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2253:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2254:                     (($major == 2) && ($minor < 12))) {
 2255:                     return;
 2256:                 }
 2257:             }
 2258:         }
 2259: 	my $queryid=&reply("querysend:instdirsearch:".
 2260: 			   &escape($srch->{'srchby'}).':'.
 2261: 			   &escape($srch->{'srchterm'}).':'.
 2262: 			   &escape($srch->{'srchtype'}),$homeserver);
 2263: 	my $host=&hostname($homeserver);
 2264: 	if ($queryid !~/^\Q$host\E\_/) {
 2265: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2266: 	    return;
 2267: 	}
 2268: 	my $response = &get_query_reply($queryid);
 2269: 	my $maxtries = 5;
 2270: 	my $tries = 1;
 2271: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2272: 	    $response = &get_query_reply($queryid);
 2273: 	    $tries ++;
 2274: 	}
 2275: 
 2276:         if (!&error($response) && $response ne 'refused') {
 2277:             if ($response eq 'unavailable') {
 2278:                 $outcome = $response;
 2279:             } else {
 2280:                 $outcome = 'ok';
 2281:                 my @matches = split(/\n/,$response);
 2282:                 foreach my $match (@matches) {
 2283:                     my ($key,$value) = split(/=/,$match);
 2284:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2285:                 }
 2286:             }
 2287:         }
 2288:     }
 2289:     return ($outcome,%results);
 2290: }
 2291: 
 2292: sub usersearch {
 2293:     my ($srch) = @_;
 2294:     my $dom = $srch->{'srchdomain'};
 2295:     my %results;
 2296:     my %libserv = &all_library();
 2297:     my $query = 'usersearch';
 2298:     foreach my $tryserver (keys(%libserv)) {
 2299:         if (&host_domain($tryserver) eq $dom) {
 2300:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2301:                 if ($srch->{'srchby'} eq 'email') {
 2302:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2303:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2304:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2305:                              (($major == 2) && ($minor < 12)));
 2306:                 }
 2307:             }
 2308:             my $host=&hostname($tryserver);
 2309:             my $queryid=
 2310:                 &reply("querysend:".&escape($query).':'.
 2311:                        &escape($srch->{'srchby'}).':'.
 2312:                        &escape($srch->{'srchtype'}).':'.
 2313:                        &escape($srch->{'srchterm'}),$tryserver);
 2314:             if ($queryid !~/^\Q$host\E\_/) {
 2315:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2316:                 next;
 2317:             }
 2318:             my $reply = &get_query_reply($queryid);
 2319:             my $maxtries = 1;
 2320:             my $tries = 1;
 2321:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2322:                 $reply = &get_query_reply($queryid);
 2323:                 $tries ++;
 2324:             }
 2325:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2326:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2327:             } else {
 2328:                 my @matches;
 2329:                 if ($reply =~ /\n/) {
 2330:                     @matches = split(/\n/,$reply);
 2331:                 } else {
 2332:                     @matches = split(/\&/,$reply);
 2333:                 }
 2334:                 foreach my $match (@matches) {
 2335:                     my ($uname,$udom,%userhash);
 2336:                     foreach my $entry (split(/:/,$match)) {
 2337:                         my ($key,$value) =
 2338:                             map {&unescape($_);} split(/=/,$entry);
 2339:                         $userhash{$key} = $value;
 2340:                         if ($key eq 'username') {
 2341:                             $uname = $value;
 2342:                         } elsif ($key eq 'domain') {
 2343:                             $udom = $value;
 2344:                         }
 2345:                     }
 2346:                     $results{$uname.':'.$udom} = \%userhash;
 2347:                 }
 2348:             }
 2349:         }
 2350:     }
 2351:     return %results;
 2352: }
 2353: 
 2354: sub get_instuser {
 2355:     my ($udom,$uname,$id) = @_;
 2356:     my $homeserver = &domain($udom,'primary');
 2357:     my ($outcome,%results);
 2358:     if ($homeserver ne '') {
 2359:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2360:                            &escape($id).':'.&escape($udom),$homeserver);
 2361:         my $host=&hostname($homeserver);
 2362:         if ($queryid !~/^\Q$host\E\_/) {
 2363:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2364:             return;
 2365:         }
 2366:         my $response = &get_query_reply($queryid);
 2367:         my $maxtries = 5;
 2368:         my $tries = 1;
 2369:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2370:             $response = &get_query_reply($queryid);
 2371:             $tries ++;
 2372:         }
 2373:         if (!&error($response) && $response ne 'refused') {
 2374:             if ($response eq 'unavailable') {
 2375:                 $outcome = $response;
 2376:             } else {
 2377:                 $outcome = 'ok';
 2378:                 my @matches = split(/\n/,$response);
 2379:                 foreach my $match (@matches) {
 2380:                     my ($key,$value) = split(/=/,$match);
 2381:                     $results{&unescape($key)} = &thaw_unescape($value);
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     my %userinfo;
 2387:     if (ref($results{$uname}) eq 'HASH') {
 2388:         %userinfo = %{$results{$uname}};
 2389:     } 
 2390:     return ($outcome,%userinfo);
 2391: }
 2392: 
 2393: sub get_multiple_instusers {
 2394:     my ($udom,$users,$caller) = @_;
 2395:     my ($outcome,$results);
 2396:     if (ref($users) eq 'HASH') {
 2397:         my $count = keys(%{$users}); 
 2398:         my $requested = &freeze_escape($users);
 2399:         my $homeserver = &domain($udom,'primary');
 2400:         if ($homeserver ne '') {
 2401:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2402:             my $host=&hostname($homeserver);
 2403:             if ($queryid !~/^\Q$host\E\_/) {
 2404:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2405:                          ' for host: '.$homeserver.'in domain '.$udom);
 2406:                 return ($outcome,$results);
 2407:             }
 2408:             my $response = &get_query_reply($queryid);
 2409:             my $maxtries = 5;
 2410:             if ($count > 100) {
 2411:                 $maxtries = 1+int($count/20);
 2412:             }
 2413:             my $tries = 1;
 2414:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2415:                 $response = &get_query_reply($queryid);
 2416:                 $tries ++;
 2417:             }
 2418:             if ($response eq '') {
 2419:                 $results = {};
 2420:                 foreach my $key (keys(%{$users})) {
 2421:                     my ($uname,$id);
 2422:                     if ($caller eq 'id') {
 2423:                         $id = $key;
 2424:                     } else {
 2425:                         $uname = $key;
 2426:                     }
 2427:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2428:                     $outcome = $resp;
 2429:                     if ($resp eq 'ok') {
 2430:                         %{$results} = (%{$results}, %info);
 2431:                     } else {
 2432:                         last;
 2433:                     }
 2434:                 }
 2435:             } elsif(!&error($response) && ($response ne 'refused')) {
 2436:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2437:                     $outcome = $response;
 2438:                 } else {
 2439:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2440:                     if ($outcome eq 'ok') {
 2441:                         $results = &thaw_unescape($userdata); 
 2442:                     }
 2443:                 }
 2444:             }
 2445:         }
 2446:     }
 2447:     return ($outcome,$results);
 2448: }
 2449: 
 2450: sub inst_rulecheck {
 2451:     my ($udom,$uname,$id,$item,$rules) = @_;
 2452:     my %returnhash;
 2453:     if ($udom ne '') {
 2454:         if (ref($rules) eq 'ARRAY') {
 2455:             @{$rules} = map {&escape($_);} (@{$rules});
 2456:             my $rulestr = join(':',@{$rules});
 2457:             my $homeserver=&domain($udom,'primary');
 2458:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2459:                 my $response;
 2460:                 if ($item eq 'username') {                
 2461:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2462:                                               ':'.&escape($uname).':'.$rulestr,
 2463:                                               $homeserver));
 2464:                 } elsif ($item eq 'id') {
 2465:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2466:                                               ':'.&escape($id).':'.$rulestr,
 2467:                                               $homeserver));
 2468:                 } elsif ($item eq 'selfcreate') {
 2469:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2470:                                                &escape($udom).':'.&escape($uname).
 2471:                                               ':'.$rulestr,$homeserver));
 2472:                 }
 2473:                 if ($response ne 'refused') {
 2474:                     my @pairs=split(/\&/,$response);
 2475:                     foreach my $item (@pairs) {
 2476:                         my ($key,$value)=split(/=/,$item,2);
 2477:                         $key = &unescape($key);
 2478:                         next if ($key =~ /^error: 2 /);
 2479:                         $returnhash{$key}=&thaw_unescape($value);
 2480:                     }
 2481:                 }
 2482:             }
 2483:         }
 2484:     }
 2485:     return %returnhash;
 2486: }
 2487: 
 2488: sub inst_userrules {
 2489:     my ($udom,$check) = @_;
 2490:     my (%ruleshash,@ruleorder);
 2491:     if ($udom ne '') {
 2492:         my $homeserver=&domain($udom,'primary');
 2493:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2494:             my $response;
 2495:             if ($check eq 'id') {
 2496:                 $response=&reply('instidrules:'.&escape($udom),
 2497:                                  $homeserver);
 2498:             } elsif ($check eq 'email') {
 2499:                 $response=&reply('instemailrules:'.&escape($udom),
 2500:                                  $homeserver);
 2501:             } else {
 2502:                 $response=&reply('instuserrules:'.&escape($udom),
 2503:                                  $homeserver);
 2504:             }
 2505:             if (($response ne 'refused') && ($response ne 'error') && 
 2506:                 ($response ne 'unknown_cmd') && 
 2507:                 ($response ne 'no_such_host')) {
 2508:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2509:                 my @pairs=split(/\&/,$hashitems);
 2510:                 foreach my $item (@pairs) {
 2511:                     my ($key,$value)=split(/=/,$item,2);
 2512:                     $key = &unescape($key);
 2513:                     next if ($key =~ /^error: 2 /);
 2514:                     $ruleshash{$key}=&thaw_unescape($value);
 2515:                 }
 2516:                 my @esc_order = split(/\&/,$orderitems);
 2517:                 foreach my $item (@esc_order) {
 2518:                     push(@ruleorder,&unescape($item));
 2519:                 }
 2520:             }
 2521:         }
 2522:     }
 2523:     return (\%ruleshash,\@ruleorder);
 2524: }
 2525: 
 2526: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2527: 
 2528: sub get_domain_defaults {
 2529:     my ($domain,$ignore_cache) = @_;
 2530:     return if (($domain eq '') || ($domain eq 'public'));
 2531:     my $cachetime = 60*60*24;
 2532:     unless ($ignore_cache) {
 2533:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2534:         if (defined($cached)) {
 2535:             if (ref($result) eq 'HASH') {
 2536:                 return %{$result};
 2537:             }
 2538:         }
 2539:     }
 2540:     my %domdefaults;
 2541:     my %domconfig =
 2542:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2543:                                   'requestcourses','inststatus',
 2544:                                   'coursedefaults','usersessions',
 2545:                                   'requestauthor','selfenrollment',
 2546:                                   'coursecategories','ssl','autoenroll',
 2547:                                   'trust','helpsettings'],$domain);
 2548:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2549:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2550:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2551:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2552:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2553:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2554:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2555:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2556:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2557:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2558:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2559:     } else {
 2560:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2561:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2562:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2563:     }
 2564:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2565:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2566:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2567:         } else {
 2568:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2569:         }
 2570:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2571:         foreach my $item (@usertools) {
 2572:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2573:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2574:             }
 2575:         }
 2576:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2577:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2578:         }
 2579:     }
 2580:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2581:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2582:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2583:         }
 2584:     }
 2585:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2586:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2587:     }
 2588:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2589:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2590:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2591:         }
 2592:     }
 2593:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2594:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2595:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2596:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2597:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2598:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2599:         }
 2600:         foreach my $type (@coursetypes) {
 2601:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2602:                 unless ($type eq 'community') {
 2603:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2604:                 }
 2605:             }
 2606:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2607:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2608:             }
 2609:             if ($domdefaults{'postsubmit'} eq 'on') {
 2610:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2611:                     $domdefaults{$type.'postsubtimeout'} = 
 2612:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2613:                 }
 2614:             }
 2615:         }
 2616:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2617:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2618:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2619:                 if (@clonecodes) {
 2620:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2621:                 }
 2622:             }
 2623:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2624:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2625:         }
 2626:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2627:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2628:         } 
 2629:     }
 2630:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2631:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2632:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2633:         }
 2634:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2635:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2636:         }
 2637:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2638:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2639:         }
 2640:     }
 2641:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2642:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2643:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2644:                             'approval','limit');
 2645:             foreach my $type (@coursetypes) {
 2646:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2647:                     my @mgrdc = ();
 2648:                     foreach my $item (@settings) {
 2649:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2650:                             push(@mgrdc,$item);
 2651:                         }
 2652:                     }
 2653:                     if (@mgrdc) {
 2654:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2655:                     }
 2656:                 }
 2657:             }
 2658:         }
 2659:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2660:             foreach my $type (@coursetypes) {
 2661:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2662:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2663:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2664:                     }
 2665:                 }
 2666:             }
 2667:         }
 2668:     }
 2669:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2670:         $domdefaults{'catauth'} = 'std';
 2671:         $domdefaults{'catunauth'} = 'std';
 2672:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2673:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2674:         }
 2675:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2676:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2677:         }
 2678:     }
 2679:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2680:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2681:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2682:         }
 2683:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2684:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2685:         }
 2686:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2687:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2688:         }
 2689:     }
 2690:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2691:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2692:         foreach my $prefix (@prefixes) {
 2693:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2694:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2695:             }
 2696:         }
 2697:     }
 2698:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2699:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2700:     }
 2701:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2702:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2703:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2704:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2705:         }
 2706:     }
 2707:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2708:     return %domdefaults;
 2709: }
 2710: 
 2711: sub course_portal_url {
 2712:     my ($cnum,$cdom) = @_;
 2713:     my $chome = &homeserver($cnum,$cdom);
 2714:     my $hostname = &hostname($chome);
 2715:     my $protocol = $protocol{$chome};
 2716:     $protocol = 'http' if ($protocol ne 'https');
 2717:     my %domdefaults = &get_domain_defaults($cdom);
 2718:     my $firsturl;
 2719:     if ($domdefaults{'portal_def'}) {
 2720:         $firsturl = $domdefaults{'portal_def'};
 2721:     } else {
 2722:         $firsturl = $protocol.'://'.$hostname;
 2723:     }
 2724:     return $firsturl;
 2725: }
 2726: 
 2727: # --------------------------------------------- Get domain config for passwords
 2728: 
 2729: sub get_passwdconf {
 2730:     my ($dom) = @_;
 2731:     my (%passwdconf,$gotconf,$lookup);
 2732:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2733:     if (defined($cached)) {
 2734:         if (ref($result) eq 'HASH') {
 2735:             %passwdconf = %{$result};
 2736:             $gotconf = 1;
 2737:         }
 2738:     }
 2739:     unless ($gotconf) {
 2740:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2741:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2742:             %passwdconf = %{$domconfig{'passwords'}};
 2743:         }
 2744:         my $cachetime = 24*60*60;
 2745:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2746:     }
 2747:     return %passwdconf;
 2748: }
 2749: 
 2750: # --------------------------------------------------- Assign a key to a student
 2751: 
 2752: sub assign_access_key {
 2753: #
 2754: # a valid key looks like uname:udom#comments
 2755: # comments are being appended
 2756: #
 2757:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2758:     $kdom=
 2759:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2760:     $knum=
 2761:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2762:     $cdom=
 2763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2764:     $cnum=
 2765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2766:     $udom=$env{'user.name'} unless (defined($udom));
 2767:     $uname=$env{'user.domain'} unless (defined($uname));
 2768:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2769:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2770:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2771:                                                   # assigned to this person
 2772:                                                   # - this should not happen,
 2773:                                                   # unless something went wrong
 2774:                                                   # the first time around
 2775: # ready to assign
 2776:         $logentry=$1.'; '.$logentry;
 2777:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2778:                                                  $kdom,$knum) eq 'ok') {
 2779: # key now belongs to user
 2780: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2781:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2782:                 &appenv({'environment.'.$envkey => $ckey});
 2783:                 return 'ok';
 2784:             } else {
 2785:                 return 
 2786:   'error: Count not permanently assign key, will need to be re-entered later.';
 2787: 	    }
 2788:         } else {
 2789:             return 'error: Could not assign key, try again later.';
 2790:         }
 2791:     } elsif (!$existing{$ckey}) {
 2792: # the key does not exist
 2793: 	return 'error: The key does not exist';
 2794:     } else {
 2795: # the key is somebody else's
 2796: 	return 'error: The key is already in use';
 2797:     }
 2798: }
 2799: 
 2800: # ------------------------------------------ put an additional comment on a key
 2801: 
 2802: sub comment_access_key {
 2803: #
 2804: # a valid key looks like uname:udom#comments
 2805: # comments are being appended
 2806: #
 2807:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2808:     $cdom=
 2809:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2810:     $cnum=
 2811:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2812:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2813:     if ($existing{$ckey}) {
 2814:         $existing{$ckey}.='; '.$logentry;
 2815: # ready to assign
 2816:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2817:                                                  $cdom,$cnum) eq 'ok') {
 2818: 	    return 'ok';
 2819:         } else {
 2820: 	    return 'error: Count not store comment.';
 2821:         }
 2822:     } else {
 2823: # the key does not exist
 2824: 	return 'error: The key does not exist';
 2825:     }
 2826: }
 2827: 
 2828: # ------------------------------------------------------ Generate a set of keys
 2829: 
 2830: sub generate_access_keys {
 2831:     my ($number,$cdom,$cnum,$logentry)=@_;
 2832:     $cdom=
 2833:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2834:     $cnum=
 2835:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2836:     unless (&allowed('mky',$cdom)) { return 0; }
 2837:     unless (($cdom) && ($cnum)) { return 0; }
 2838:     if ($number>10000) { return 0; }
 2839:     sleep(2); # make sure don't get same seed twice
 2840:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2841:     my $total=0;
 2842:     for (my $i=1;$i<=$number;$i++) {
 2843:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2844:                   sprintf("%lx",int(100000*rand)).'-'.
 2845:                   sprintf("%lx",int(100000*rand));
 2846:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2847:        $newkey=~s/0/h/g; # and also 0 and O
 2848:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2849:        if ($existing{$newkey}) {
 2850:            $i--;
 2851:        } else {
 2852: 	  if (&put('accesskeys',
 2853:               { $newkey => '# generated '.localtime().
 2854:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2855:                            '; '.$logentry },
 2856: 		   $cdom,$cnum) eq 'ok') {
 2857:               $total++;
 2858: 	  }
 2859:        }
 2860:     }
 2861:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2862:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2863:     return $total;
 2864: }
 2865: 
 2866: # ------------------------------------------------------- Validate an accesskey
 2867: 
 2868: sub validate_access_key {
 2869:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2870:     $cdom=
 2871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2872:     $cnum=
 2873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2874:     $udom=$env{'user.domain'} unless (defined($udom));
 2875:     $uname=$env{'user.name'} unless (defined($uname));
 2876:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2877:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2878: }
 2879: 
 2880: # ------------------------------------- Find the section of student in a course
 2881: sub devalidate_getsection_cache {
 2882:     my ($udom,$unam,$courseid)=@_;
 2883:     my $hashid="$udom:$unam:$courseid";
 2884:     &devalidate_cache_new('getsection',$hashid);
 2885: }
 2886: 
 2887: sub courseid_to_courseurl {
 2888:     my ($courseid) = @_;
 2889:     #already url style courseid
 2890:     return $courseid if ($courseid =~ m{^/});
 2891: 
 2892:     if (exists($env{'course.'.$courseid.'.num'})) {
 2893: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2894: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2895: 	return "/$cdom/$cnum";
 2896:     }
 2897: 
 2898:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2899:     if (exists($courseinfo{'num'})) {
 2900: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2901:     }
 2902: 
 2903:     return undef;
 2904: }
 2905: 
 2906: sub getsection {
 2907:     my ($udom,$unam,$courseid)=@_;
 2908:     my $cachetime=1800;
 2909: 
 2910:     my $hashid="$udom:$unam:$courseid";
 2911:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2912:     if (defined($cached)) { return $result; }
 2913: 
 2914:     my %Pending; 
 2915:     my %Expired;
 2916:     #
 2917:     # Each role can either have not started yet (pending), be active, 
 2918:     #    or have expired.
 2919:     #
 2920:     # If there is an active role, we are done.
 2921:     #
 2922:     # If there is more than one role which has not started yet, 
 2923:     #     choose the one which will start sooner
 2924:     # If there is one role which has not started yet, return it.
 2925:     #
 2926:     # If there is more than one expired role, choose the one which ended last.
 2927:     # If there is a role which has expired, return it.
 2928:     #
 2929:     $courseid = &courseid_to_courseurl($courseid);
 2930:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2931:     foreach my $key (keys(%roleshash)) {
 2932:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2933:         my $section=$1;
 2934:         if ($key eq $courseid.'_st') { $section=''; }
 2935:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2936:         my $now=time;
 2937:         if (defined($end) && $end && ($now > $end)) {
 2938:             $Expired{$end}=$section;
 2939:             next;
 2940:         }
 2941:         if (defined($start) && $start && ($now < $start)) {
 2942:             $Pending{$start}=$section;
 2943:             next;
 2944:         }
 2945:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2946:     }
 2947:     #
 2948:     # Presumedly there will be few matching roles from the above
 2949:     # loop and the sorting time will be negligible.
 2950:     if (scalar(keys(%Pending))) {
 2951:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2952:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2953:     } 
 2954:     if (scalar(keys(%Expired))) {
 2955:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2956:         my $time = pop(@sorted);
 2957:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2958:     }
 2959:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2960: }
 2961: 
 2962: sub save_cache {
 2963:     &purge_remembered();
 2964:     #&Apache::loncommon::validate_page();
 2965:     undef(%env);
 2966:     undef($env_loaded);
 2967: }
 2968: 
 2969: my $to_remember=-1;
 2970: my %remembered;
 2971: my %accessed;
 2972: my $kicks=0;
 2973: my $hits=0;
 2974: sub make_key {
 2975:     my ($name,$id) = @_;
 2976:     if (length($id) > 65 
 2977: 	&& length(&escape($id)) > 200) {
 2978: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2979:     }
 2980:     return &escape($name.':'.$id);
 2981: }
 2982: 
 2983: sub devalidate_cache_new {
 2984:     my ($name,$id,$debug) = @_;
 2985:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2986:     my $remembered_id=$name.':'.$id;
 2987:     $id=&make_key($name,$id);
 2988:     $memcache->delete($id);
 2989:     delete($remembered{$remembered_id});
 2990:     delete($accessed{$remembered_id});
 2991: }
 2992: 
 2993: sub is_cached_new {
 2994:     my ($name,$id,$debug) = @_;
 2995:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2996:     if (exists($remembered{$remembered_id})) {
 2997: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2998: 	$accessed{$remembered_id}=[&gettimeofday()];
 2999: 	$hits++;
 3000: 	return ($remembered{$remembered_id},1);
 3001:     }
 3002:     $id=&make_key($name,$id);
 3003:     my $value = $memcache->get($id);
 3004:     if (!(defined($value))) {
 3005: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3006: 	return (undef,undef);
 3007:     }
 3008:     if ($value eq '__undef__') {
 3009: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3010: 	$value=undef;
 3011:     }
 3012:     &make_room($remembered_id,$value,$debug);
 3013:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3014:     return ($value,1);
 3015: }
 3016: 
 3017: sub do_cache_new {
 3018:     my ($name,$id,$value,$time,$debug) = @_;
 3019:     my $remembered_id=$name.':'.$id;
 3020:     $id=&make_key($name,$id);
 3021:     my $setvalue=$value;
 3022:     if (!defined($setvalue)) {
 3023: 	$setvalue='__undef__';
 3024:     }
 3025:     if (!defined($time) ) {
 3026: 	$time=600;
 3027:     }
 3028:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3029:     my $result = $memcache->set($id,$setvalue,$time);
 3030:     if (! $result) {
 3031: 	&logthis("caching of id -> $id  failed");
 3032: 	$memcache->disconnect_all();
 3033:     }
 3034:     # need to make a copy of $value
 3035:     &make_room($remembered_id,$value,$debug);
 3036:     return $value;
 3037: }
 3038: 
 3039: sub make_room {
 3040:     my ($remembered_id,$value,$debug)=@_;
 3041: 
 3042:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3043:                                     : $value;
 3044:     if ($to_remember<0) { return; }
 3045:     $accessed{$remembered_id}=[&gettimeofday()];
 3046:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3047:     my $to_kick;
 3048:     my $max_time=0;
 3049:     foreach my $other (keys(%accessed)) {
 3050: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3051: 	    $to_kick=$other;
 3052: 	    $max_time=&tv_interval($accessed{$other});
 3053: 	}
 3054:     }
 3055:     delete($remembered{$to_kick});
 3056:     delete($accessed{$to_kick});
 3057:     $kicks++;
 3058:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3059:     return;
 3060: }
 3061: 
 3062: sub purge_remembered {
 3063:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3064:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3065:     undef(%remembered);
 3066:     undef(%accessed);
 3067: }
 3068: # ------------------------------------- Read an entry from a user's environment
 3069: 
 3070: sub userenvironment {
 3071:     my ($udom,$unam,@what)=@_;
 3072:     my $items;
 3073:     foreach my $item (@what) {
 3074:         $items.=&escape($item).'&';
 3075:     }
 3076:     $items=~s/\&$//;
 3077:     my %returnhash=();
 3078:     my $uhome = &homeserver($unam,$udom);
 3079:     unless ($uhome eq 'no_host') {
 3080:         my @answer=split(/\&/, 
 3081:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3082:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3083:             return %returnhash;
 3084:         }
 3085:         my $i;
 3086:         for ($i=0;$i<=$#what;$i++) {
 3087: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3088:         }
 3089:     }
 3090:     return %returnhash;
 3091: }
 3092: 
 3093: # ---------------------------------------------------------- Get a studentphoto
 3094: sub studentphoto {
 3095:     my ($udom,$unam,$ext) = @_;
 3096:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3097:     if (defined($env{'request.course.id'})) {
 3098:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3099:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3100:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3101:             } else {
 3102:                 my ($result,$perm_reqd)=
 3103: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3104:                 if ($result eq 'ok') {
 3105:                     if (!($perm_reqd eq 'yes')) {
 3106:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3107:                     }
 3108:                 }
 3109:             }
 3110:         }
 3111:     } else {
 3112:         my ($result,$perm_reqd) = 
 3113: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3114:         if ($result eq 'ok') {
 3115:             if (!($perm_reqd eq 'yes')) {
 3116:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3117:             }
 3118:         }
 3119:     }
 3120:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3121: }
 3122: 
 3123: sub retrievestudentphoto {
 3124:     my ($udom,$unam,$ext,$type) = @_;
 3125:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3126:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3127:     if ($ret eq 'ok') {
 3128:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3129:         if ($type eq 'thumbnail') {
 3130:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3131:         }
 3132:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3133:         return $tokenurl;
 3134:     } else {
 3135:         if ($type eq 'thumbnail') {
 3136:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3137:         } else { 
 3138:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3139:         }
 3140:     }
 3141: }
 3142: 
 3143: # -------------------------------------------------------------------- New chat
 3144: 
 3145: sub chatsend {
 3146:     my ($newentry,$anon,$group)=@_;
 3147:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3148:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3149:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3150:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3151: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3152: 		   &escape($newentry)).':'.$group,$chome);
 3153: }
 3154: 
 3155: # ------------------------------------------ Find current version of a resource
 3156: 
 3157: sub getversion {
 3158:     my $fname=&clutter(shift);
 3159:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3160:     return &currentversion(&filelocation('',$fname));
 3161: }
 3162: 
 3163: sub currentversion {
 3164:     my $fname=shift;
 3165:     my $author=$fname;
 3166:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3167:     my ($udom,$uname)=split(/\//,$author);
 3168:     my $home=&homeserver($uname,$udom);
 3169:     if ($home eq 'no_host') { 
 3170:         return -1; 
 3171:     }
 3172:     my $answer=&reply("currentversion:$fname",$home);
 3173:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3174: 	return -1;
 3175:     }
 3176:     return $answer;
 3177: }
 3178: 
 3179: #
 3180: # Return special version number of resource if set by override, empty otherwise
 3181: #
 3182: sub usedversion {
 3183:     my $fname=shift;
 3184:     unless ($fname) { $fname=$env{'request.uri'}; }
 3185:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3186:     if ($urlversion) { return $urlversion; }
 3187:     return '';
 3188: }
 3189: 
 3190: # ----------------------------- Subscribe to a resource, return URL if possible
 3191: 
 3192: sub subscribe {
 3193:     my $fname=shift;
 3194:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3195:     $fname=~s/[\n\r]//g;
 3196:     my $author=$fname;
 3197:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3198:     my ($udom,$uname)=split(/\//,$author);
 3199:     my $home=homeserver($uname,$udom);
 3200:     if ($home eq 'no_host') {
 3201:         return 'not_found';
 3202:     }
 3203:     my $answer=reply("sub:$fname",$home);
 3204:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3205: 	$answer.=' by '.$home;
 3206:     }
 3207:     return $answer;
 3208: }
 3209:     
 3210: # -------------------------------------------------------------- Replicate file
 3211: 
 3212: sub repcopy {
 3213:     my $filename=shift;
 3214:     $filename=~s/\/+/\//g;
 3215:     my $londocroot = $perlvar{'lonDocRoot'};
 3216:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3217:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3218:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3219: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3220: 	return &repcopy_userfile($filename);
 3221:     }
 3222:     $filename=~s/[\n\r]//g;
 3223:     my $transname="$filename.in.transfer";
 3224: # FIXME: this should flock
 3225:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3226:     my $remoteurl=subscribe($filename);
 3227:     if ($remoteurl =~ /^con_lost by/) {
 3228: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3229:            return 'unavailable';
 3230:     } elsif ($remoteurl eq 'not_found') {
 3231: 	   #&logthis("Subscribe returned not_found: $filename");
 3232: 	   return 'not_found';
 3233:     } elsif ($remoteurl =~ /^rejected by/) {
 3234: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3235:            return 'forbidden';
 3236:     } elsif ($remoteurl eq 'directory') {
 3237:            return 'ok';
 3238:     } else {
 3239:         my $author=$filename;
 3240:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3241:         my ($udom,$uname)=split(/\//,$author);
 3242:         my $home=homeserver($uname,$udom);
 3243:         unless ($home eq $perlvar{'lonHostID'}) {
 3244:            my @parts=split(/\//,$filename);
 3245:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3246:            if ($path ne "$londocroot/res") {
 3247:                &logthis("Malconfiguration for replication: $filename");
 3248: 	       return 'bad_request';
 3249:            }
 3250:            my $count;
 3251:            for ($count=5;$count<$#parts;$count++) {
 3252:                $path.="/$parts[$count]";
 3253:                if ((-e $path)!=1) {
 3254: 		   mkdir($path,0777);
 3255:                }
 3256:            }
 3257:            my $request=new HTTP::Request('GET',"$remoteurl");
 3258:            my $response;
 3259:            if ($remoteurl =~ m{/raw/}) {
 3260:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3261:            } else {
 3262:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3263:            }
 3264:            if ($response->is_error()) {
 3265: 	       unlink($transname);
 3266:                my $message=$response->status_line;
 3267:                &logthis("<font color=\"blue\">WARNING:"
 3268:                        ." LWP get: $message: $filename</font>");
 3269:                return 'unavailable';
 3270:            } else {
 3271: 	       if ($remoteurl!~/\.meta$/) {
 3272:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3273:                   my $mresponse;
 3274:                   if ($remoteurl =~ m{/raw/}) {
 3275:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3276:                   } else {
 3277:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3278:                   }
 3279:                   if ($mresponse->is_error()) {
 3280: 		      unlink($filename.'.meta');
 3281:                       &logthis(
 3282:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3283:                   }
 3284: 	       }
 3285:                rename($transname,$filename);
 3286:                return 'ok';
 3287:            }
 3288:        }
 3289:     }
 3290: }
 3291: 
 3292: # ------------------------------------------------ Get server side include body
 3293: sub ssi_body {
 3294:     my ($filelink,%form)=@_;
 3295:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3296:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3297:     }
 3298:     my $output='';
 3299:     my $response;
 3300:     if ($filelink=~/^https?\:/) {
 3301:        ($output,$response)=&externalssi($filelink);
 3302:     } else {
 3303:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3304:        $filelink .= 'inhibitmenu=yes';
 3305:        ($output,$response)=&ssi($filelink,%form);
 3306:     }
 3307:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3308:     $output=~s/^.*?\<body[^\>]*\>//si;
 3309:     $output=~s/\<\/body\s*\>.*?$//si;
 3310:     if (wantarray) {
 3311:         return ($output, $response);
 3312:     } else {
 3313:         return $output;
 3314:     }
 3315: }
 3316: 
 3317: # --------------------------------------------------------- Server Side Include
 3318: 
 3319: sub absolute_url {
 3320:     my ($host_name) = @_;
 3321:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3322:     if ($host_name eq '') {
 3323: 	$host_name = $ENV{'SERVER_NAME'};
 3324:     }
 3325:     return $protocol.$host_name;
 3326: }
 3327: 
 3328: #
 3329: #   Server side include.
 3330: # Parameters:
 3331: #  fn     Possibly encrypted resource name/id.
 3332: #  form   Hash that describes how the rendering should be done
 3333: #         and other things.
 3334: # Returns:
 3335: #   Scalar context: The content of the response.
 3336: #   Array context:  2 element list of the content and the full response object.
 3337: #     
 3338: sub ssi {
 3339: 
 3340:     my ($fn,%form)=@_;
 3341:     my $request;
 3342: 
 3343:     $form{'no_update_last_known'}=1;
 3344:     &Apache::lonenc::check_encrypt(\$fn);
 3345:     if (%form) {
 3346:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3347:       $request->content(join('&',map { 
 3348:             my $name = escape($_);
 3349:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3350:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3351:             : &escape($form{$_}) );    
 3352:         } keys(%form)));
 3353:     } else {
 3354:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3355:     }
 3356: 
 3357:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3358:     my $lonhost = $perlvar{'lonHostID'};
 3359:     my $islocal;
 3360:     if (($env{'request.course.id'}) &&
 3361:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3362:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3363:         ($form{'grade_symb'} ne '') &&
 3364:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3365:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3366:         $islocal = 1;
 3367:     }
 3368:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3369:                                                 '','','',$islocal);
 3370: 
 3371:     if (wantarray) {
 3372: 	return ($response->content, $response);
 3373:     } else {
 3374: 	return $response->content;
 3375:     }
 3376: }
 3377: 
 3378: sub externalssi {
 3379:     my ($url)=@_;
 3380:     my $request=new HTTP::Request('GET',$url);
 3381:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3382:     if (wantarray) {
 3383:         return ($response->content, $response);
 3384:     } else {
 3385:         return $response->content;
 3386:     }
 3387: }
 3388: 
 3389: 
 3390: # If the local copy of a replicated resource is outdated, trigger a  
 3391: # connection from the homeserver to flush the delayed queue. If no update 
 3392: # happens, remove local copies of outdated resource (and corresponding
 3393: # metadata file).
 3394: 
 3395: sub remove_stale_resfile {
 3396:     my ($url) = @_;
 3397:     my $removed;
 3398:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3399:         my $audom = $1;
 3400:         my $auname = $2;
 3401:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3402:             my $homeserver = &homeserver($auname,$audom);
 3403:             unless (($homeserver eq 'no_host') ||
 3404:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3405:                 my $fname = &filelocation('',$url);
 3406:                 if (-e $fname) {
 3407:                     my $hostname = &hostname($homeserver);
 3408:                     if ($hostname) {
 3409:                         my $protocol = $protocol{$homeserver};
 3410:                         $protocol = 'http' if ($protocol ne 'https');
 3411:                         my $uri = &declutter($url);
 3412:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3413:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3414:                         if ($response->is_success()) {
 3415:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3416:                             my $locmodtime = (stat($fname))[9];
 3417:                             if ($locmodtime < $remmodtime) {
 3418:                                 my $stale;
 3419:                                 my $answer = &reply('pong',$homeserver);
 3420:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3421:                                     sleep(0.2);
 3422:                                     $locmodtime = (stat($fname))[9];
 3423:                                     if ($locmodtime < $remmodtime) {
 3424:                                         my $posstransfer = $fname.'.in.transfer';
 3425:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3426:                                             $removed = 1;
 3427:                                         } else {
 3428:                                             $stale = 1;
 3429:                                         }
 3430:                                     } else {
 3431:                                         $removed = 1;
 3432:                                     }
 3433:                                 } else {
 3434:                                     $stale = 1;
 3435:                                 }
 3436:                                 if ($stale) {
 3437:                                     unlink($fname);
 3438:                                     if ($uri!~/\.meta$/) {
 3439:                                         unlink($fname.'.meta');
 3440:                                     }
 3441:                                     &reply("unsub:$fname",$homeserver);
 3442:                                     $removed = 1;
 3443:                                 }
 3444:                             }
 3445:                         }
 3446:                     }
 3447:                 }
 3448:             }
 3449:         }
 3450:     }
 3451:     return $removed;
 3452: }
 3453: 
 3454: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3455: 
 3456: sub allowuploaded {
 3457:     my ($srcurl,$url)=@_;
 3458:     $url=&clutter(&declutter($url));
 3459:     my $dir=$url;
 3460:     $dir=~s/\/[^\/]+$//;
 3461:     my %httpref=();
 3462:     my $httpurl=&hreflocation('',$url);
 3463:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3464:     &Apache::lonnet::appenv(\%httpref);
 3465: }
 3466: 
 3467: #
 3468: # Determine if the current user should be able to edit a particular resource,
 3469: # when viewing in course context.
 3470: # (a) When viewing resource used to determine if "Edit" item is included in 
 3471: #     Functions.
 3472: # (b) When displaying folder contents in course editor, used to determine if
 3473: #     "Edit" link will be displayed alongside resource.
 3474: #
 3475: #  input: six args -- filename (decluttered), course number, course domain,
 3476: #                   url, symb (if registered) and group (if this is a group
 3477: #                   item -- e.g., bulletin board, group page etc.).
 3478: #  output: array of five scalars -- 
 3479: #          $cfile -- url for file editing if editable on current server
 3480: #          $home -- homeserver of resource (i.e., for author if published,
 3481: #                                           or course if uploaded.).
 3482: #          $switchserver --  1 if server switch will be needed.
 3483: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3484: #          $forceview -- 1 if icon/link should be to go to view mode
 3485: #
 3486: 
 3487: sub can_edit_resource {
 3488:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3489:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3490: #
 3491: # For aboutme pages user can only edit his/her own.
 3492: #
 3493:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3494:         my ($sdom,$sname) = ($1,$2);
 3495:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3496:             $home = $env{'user.home'};
 3497:             $cfile = $resurl;
 3498:             if ($env{'form.forceedit'}) {
 3499:                 $forceview = 1;
 3500:             } else {
 3501:                 $forceedit = 1;
 3502:             }
 3503:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3504:         } else {
 3505:             return;
 3506:         }
 3507:     }
 3508: 
 3509:     if ($env{'request.course.id'}) {
 3510:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3511:         if ($group ne '') {
 3512: # if this is a group homepage or group bulletin board, check group privs
 3513:             my $allowed = 0;
 3514:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3515:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3516:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3517:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3518:                     $allowed = 1;
 3519:                 }
 3520:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3521:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3522:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3523:                     $allowed = 1;
 3524:                 }
 3525:             }
 3526:             if ($allowed) {
 3527:                 $home=&homeserver($cnum,$cdom);
 3528:                 if ($env{'form.forceedit'}) {
 3529:                     $forceview = 1;
 3530:                 } else {
 3531:                     $forceedit = 1;
 3532:                 }
 3533:                 $cfile = $resurl;
 3534:             } else {
 3535:                 return;
 3536:             }
 3537:         } else {
 3538:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3539:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3540:                     return;
 3541:                 }
 3542:             } elsif (!$crsedit) {
 3543: #
 3544: # No edit allowed where CC has switched to student role.
 3545: #
 3546:                 return;
 3547:             }
 3548:         }
 3549:     }
 3550: 
 3551:     if ($file ne '') {
 3552:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3553:             if (&is_course_upload($file,$cnum,$cdom)) {
 3554:                 $uploaded = 1;
 3555:                 $incourse = 1;
 3556:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3557:                     $cfile = &hreflocation('',$file);
 3558:                     if ($env{'form.forceedit'}) {
 3559:                         $forceview = 1;
 3560:                     } else {
 3561:                         $forceedit = 1;
 3562:                     }
 3563:                 }
 3564:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3565:                 $incourse = 1;
 3566:                 if ($env{'form.forceedit'}) {
 3567:                     $forceview = 1;
 3568:                 } else {
 3569:                     $forceedit = 1;
 3570:                 }
 3571:                 $cfile = $resurl;
 3572:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3573:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3574:                     $incourse = 1;
 3575:                     if ($env{'form.forceedit'}) {
 3576:                         $forceview = 1;
 3577:                     } else {
 3578:                         $forceedit = 1;
 3579:                     }
 3580:                     $cfile = $resurl;
 3581:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3582:                     $incourse = 1;
 3583:                     $cfile = $resurl.'/smpedit';
 3584:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3585:                     $incourse = 1;
 3586:                     if ($env{'form.forceedit'}) {
 3587:                         $forceview = 1;
 3588:                     } else {
 3589:                         $forceedit = 1;
 3590:                     }
 3591:                     $cfile = $resurl;
 3592:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3593:                     $incourse = 1;
 3594:                     if ($env{'form.forceedit'}) {
 3595:                         $forceview = 1;
 3596:                     } else {
 3597:                         $forceedit = 1;
 3598:                     }
 3599:                     $cfile = $resurl;
 3600:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3601:                     $incourse = 1;
 3602:                     if ($env{'form.forceedit'}) {
 3603:                         $forceview = 1;
 3604:                     } else {
 3605:                         $forceedit = 1;
 3606:                     }
 3607:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3608:                 }
 3609:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3610:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3611:                 if (&is_on_map($template)) { 
 3612:                     $incourse = 1;
 3613:                     $forceview = 1;
 3614:                     $cfile = $template;
 3615:                 }
 3616:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3617:                     $incourse = 1;
 3618:                     if ($env{'form.forceedit'}) {
 3619:                         $forceview = 1;
 3620:                     } else {
 3621:                         $forceedit = 1;
 3622:                     }
 3623:                     $cfile = $resurl;
 3624:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3625:                 $incourse = 1;
 3626:                 if ($env{'form.forceedit'}) {
 3627:                     $forceview = 1;
 3628:                 } else {
 3629:                     $forceedit = 1;
 3630:                 }
 3631:                 $cfile = $resurl;
 3632:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3633:                 $incourse = 1;
 3634:                 $forceview = 1;
 3635:                 if ($symb) {
 3636:                     my ($map,$id,$res)=&decode_symb($symb);
 3637:                     $env{'request.symb'} = $symb;
 3638:                     $cfile = &clutter($res);
 3639:                 } else {
 3640:                     $cfile = $env{'form.suppurl'};
 3641:                     my $escfile = &unescape($cfile);
 3642:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3643:                         $cfile = '/adm/wrapper'.$escfile;
 3644:                     } else {
 3645:                         $escfile =~ s{^http://}{};
 3646:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3647:                     }
 3648:                 }
 3649:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3650:                 if ($env{'form.forceedit'}) {
 3651:                     $forceview = 1;
 3652:                 } else {
 3653:                     $forceedit = 1;
 3654:                 }
 3655:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3656:             }
 3657:         }
 3658:         if ($uploaded || $incourse) {
 3659:             $home=&homeserver($cnum,$cdom);
 3660:         } elsif ($file !~ m{/$}) {
 3661:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3662:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3663:             # Check that the user has permission to edit this resource
 3664:             my $setpriv = 1;
 3665:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3666:             if (defined($cfudom)) {
 3667:                 $home=&homeserver($cfuname,$cfudom);
 3668:                 $cfile=$file;
 3669:             }
 3670:         }
 3671:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3672:             (($home ne '') && ($home ne 'no_host'))) {
 3673:             my @ids=&current_machine_ids();
 3674:             unless (grep(/^\Q$home\E$/,@ids)) {
 3675:                 $switchserver=1;
 3676:             }
 3677:         }
 3678:     }
 3679:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3680: }
 3681: 
 3682: sub is_course_upload {
 3683:     my ($file,$cnum,$cdom) = @_;
 3684:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3685:     $uploadpath =~ s{^\/}{};
 3686:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3687:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3688:         return 1;
 3689:     }
 3690:     return;
 3691: }
 3692: 
 3693: sub in_course {
 3694:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3695:     if ($hideprivileged) {
 3696:         my $skipuser;
 3697:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3698:         my @possdoms = ($cdom);  
 3699:         if ($coursehash{'checkforpriv'}) { 
 3700:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3701:         }
 3702:         if (&privileged($uname,$udom,\@possdoms)) {
 3703:             $skipuser = 1;
 3704:             if ($coursehash{'nothideprivileged'}) {
 3705:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3706:                     my $user;
 3707:                     if ($item =~ /:/) {
 3708:                         $user = $item;
 3709:                     } else {
 3710:                         $user = join(':',split(/[\@]/,$item));
 3711:                     }
 3712:                     if ($user eq $uname.':'.$udom) {
 3713:                         undef($skipuser);
 3714:                         last;
 3715:                     }
 3716:                 }
 3717:             }
 3718:             if ($skipuser) {
 3719:                 return 0;
 3720:             }
 3721:         }
 3722:     }
 3723:     $type ||= 'any';
 3724:     if (!defined($cdom) || !defined($cnum)) {
 3725:         my $cid  = $env{'request.course.id'};
 3726:         $cdom = $env{'course.'.$cid.'.domain'};
 3727:         $cnum = $env{'course.'.$cid.'.num'};
 3728:     }
 3729:     my $typesref;
 3730:     if (($type eq 'any') || ($type eq 'all')) {
 3731:         $typesref = ['active','previous','future'];
 3732:     } elsif ($type eq 'previous' || $type eq 'future') {
 3733:         $typesref = [$type];
 3734:     }
 3735:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3736:                               $typesref,undef,[$cdom]);
 3737:     my ($tmp) = keys(%roles);
 3738:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3739:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3740:     if (@course_roles > 0) {
 3741:         return 1;
 3742:     }
 3743:     return 0;
 3744: }
 3745: 
 3746: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3747: # input: action, courseID, current domain, intended
 3748: #        path to file, source of file, instruction to parse file for objects,
 3749: #        ref to hash for embedded objects,
 3750: #        ref to hash for codebase of java objects.
 3751: #        reference to scalar to accommodate mime type determined
 3752: #          from File::MMagic if $parser = parse.
 3753: #
 3754: # output: url to file (if action was uploaddoc), 
 3755: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3756: #
 3757: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3758: # course.
 3759: #
 3760: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3761: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3762: #          course's home server.
 3763: #
 3764: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3765: #          be copied from $source (current location) to 
 3766: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3767: #         and will then be copied to
 3768: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3769: #         course's home server.
 3770: #
 3771: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3772: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3773: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3774: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3775: #         in course's home server.
 3776: #
 3777: 
 3778: sub process_coursefile {
 3779:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3780:         $mimetype)=@_;
 3781:     my $fetchresult;
 3782:     my $home=&homeserver($docuname,$docudom);
 3783:     if ($action eq 'propagate') {
 3784:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3785: 			     $home);
 3786:     } else {
 3787:         my $fpath = '';
 3788:         my $fname = $file;
 3789:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3790:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3791:         my $filepath = &build_filepath($fpath);
 3792:         if ($action eq 'copy') {
 3793:             if ($source eq '') {
 3794:                 $fetchresult = 'no source file';
 3795:                 return $fetchresult;
 3796:             } else {
 3797:                 my $destination = $filepath.'/'.$fname;
 3798:                 rename($source,$destination);
 3799:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3800:                                  $home);
 3801:             }
 3802:         } elsif ($action eq 'uploaddoc') {
 3803:             open(my $fh,'>',$filepath.'/'.$fname);
 3804:             print $fh $env{'form.'.$source};
 3805:             close($fh);
 3806:             if ($parser eq 'parse') {
 3807:                 my $mm = new File::MMagic;
 3808:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3809:                 if ($type eq 'text/html') {
 3810:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3811:                     unless ($parse_result eq 'ok') {
 3812:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3813:                     }
 3814:                 }
 3815:                 if (ref($mimetype)) {
 3816:                     $$mimetype = $type;
 3817:                 } 
 3818:             }
 3819:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3820:                                  $home);
 3821:             if ($fetchresult eq 'ok') {
 3822:                 return '/uploaded/'.$fpath.'/'.$fname;
 3823:             } else {
 3824:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3825:                         ' to host '.$home.': '.$fetchresult);
 3826:                 return '/adm/notfound.html';
 3827:             }
 3828:         }
 3829:     }
 3830:     unless ( $fetchresult eq 'ok') {
 3831:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3832:              ' to host '.$home.': '.$fetchresult);
 3833:     }
 3834:     return $fetchresult;
 3835: }
 3836: 
 3837: sub build_filepath {
 3838:     my ($fpath) = @_;
 3839:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3840:     unless ($fpath eq '') {
 3841:         my @parts=split('/',$fpath);
 3842:         foreach my $part (@parts) {
 3843:             $filepath.= '/'.$part;
 3844:             if ((-e $filepath)!=1) {
 3845:                 mkdir($filepath,0777);
 3846:             }
 3847:         }
 3848:     }
 3849:     return $filepath;
 3850: }
 3851: 
 3852: sub store_edited_file {
 3853:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3854:     my $file = $primary_url;
 3855:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3856:     my $fpath = '';
 3857:     my $fname = $file;
 3858:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3859:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3860:     my $filepath = &build_filepath($fpath);
 3861:     open(my $fh,'>',$filepath.'/'.$fname);
 3862:     print $fh $content;
 3863:     close($fh);
 3864:     my $home=&homeserver($docuname,$docudom);
 3865:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3866: 			  $home);
 3867:     if ($$fetchresult eq 'ok') {
 3868:         return '/uploaded/'.$fpath.'/'.$fname;
 3869:     } else {
 3870:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3871: 		 ' to host '.$home.': '.$$fetchresult);
 3872:         return '/adm/notfound.html';
 3873:     }
 3874: }
 3875: 
 3876: sub clean_filename {
 3877:     my ($fname,$args)=@_;
 3878: # Replace Windows backslashes by forward slashes
 3879:     $fname=~s/\\/\//g;
 3880:     if (!$args->{'keep_path'}) {
 3881:         # Get rid of everything but the actual filename
 3882: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3883:     }
 3884: # Replace spaces by underscores
 3885:     $fname=~s/\s+/\_/g;
 3886: # Transliterate non-ascii text to ascii
 3887:     my $lang = &Apache::lonlocal::current_language();
 3888:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3889: # Replace all other weird characters by nothing
 3890:     $fname=~s{[^/\w\.\-]}{}g;
 3891: # Replace all .\d. sequences with _\d. so they no longer look like version
 3892: # numbers
 3893:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3894:     return $fname;
 3895: }
 3896: 
 3897: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3898: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3899: # image with the same aspect ratio as the original, but with dimensions which do 
 3900: # not exceed $resizewidth and $resizeheight.
 3901:  
 3902: sub resizeImage {
 3903:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3904:     my $ima = Image::Magick->new;
 3905:     my $resized;
 3906:     if (-e $img_path) {
 3907:         $ima->Read($img_path);
 3908:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3909:             my $width = $ima->Get('width');
 3910:             my $height = $ima->Get('height');
 3911:             if ($width > $resizewidth) {
 3912: 	        my $factor = $width/$resizewidth;
 3913:                 my $newheight = $height/$factor;
 3914:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3915:                 $resized = 1;
 3916:             }
 3917:         }
 3918:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3919:             my $width = $ima->Get('width');
 3920:             my $height = $ima->Get('height');
 3921:             if ($height > $resizeheight) {
 3922:                 my $factor = $height/$resizeheight;
 3923:                 my $newwidth = $width/$factor;
 3924:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3925:                 $resized = 1;
 3926:             }
 3927:         }
 3928:         if ($resized) {
 3929:             $ima->Write($img_path);
 3930:         }
 3931:     }
 3932:     return;
 3933: }
 3934: 
 3935: # --------------- Take an uploaded file and put it into the userfiles directory
 3936: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3937: #                    the desired filename is in $env{"form.$formname.filename"}
 3938: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3939: #                                    canceloverwrite, scantron or ''.
 3940: #                   if 'coursedoc': upload to the current course
 3941: #                   if 'existingfile': write file to tmp/overwrites directory 
 3942: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3943: #                   $context is passed as argument to &finishuserfileupload
 3944: #        $subdir - directory in userfile to store the file into
 3945: #        $parser - instruction to parse file for objects ($parser = parse) or
 3946: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3947: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3948: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3949: #        $allfiles - reference to hash for embedded objects
 3950: #        $codebase - reference to hash for codebase of java objects
 3951: #        $desuname - username for permanent storage of uploaded file
 3952: #        $dsetudom - domain for permanaent storage of uploaded file
 3953: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3954: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3955: #        $resizewidth - width (pixels) to which to resize uploaded image
 3956: #        $resizeheight - height (pixels) to which to resize uploaded image
 3957: #        $mimetype - reference to scalar to accommodate mime type determined
 3958: #                    from File::MMagic.
 3959: # 
 3960: # output: url of file in userspace, or error: <message> 
 3961: #             or /adm/notfound.html if failure to upload occurse
 3962: 
 3963: sub userfileupload {
 3964:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3965:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3966:     if (!defined($subdir)) { $subdir='unknown'; }
 3967:     my $fname=$env{'form.'.$formname.'.filename'};
 3968:     $fname=&clean_filename($fname);
 3969:     # See if there is anything left
 3970:     unless ($fname) { return 'error: no uploaded file'; }
 3971:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3972:     if ($fname =~ /^\./) {
 3973:         my ($s,$usec) = &gettimeofday();
 3974:         while (length($usec) < 6) {
 3975:             $usec = '0'.$usec;
 3976:         }
 3977:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3978:     }
 3979:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3980:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3981:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3982:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3983:         my $now = time;
 3984:         my $filepath;
 3985:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3986:              $filepath = 'tmp/helprequests/'.$now;
 3987:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3988:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3989:                          '_'.$env{'user.domain'}.'/pending';
 3990:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3991:             my ($docuname,$docudom);
 3992:             if ($destudom =~ /^$match_domain$/) {
 3993:                 $docudom = $destudom;
 3994:             } else {
 3995:                 $docudom = $env{'user.domain'};
 3996:             }
 3997:             if ($destuname =~ /^$match_username$/) {
 3998:                 $docuname = $destuname;
 3999:             } else {
 4000:                 $docuname = $env{'user.name'};
 4001:             }
 4002:             if (exists($env{'form.group'})) {
 4003:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4004:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4005:             }
 4006:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4007:             if ($context eq 'canceloverwrite') {
 4008:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4009:                 if (-e  $tempfile) {
 4010:                     my @info = stat($tempfile);
 4011:                     if ($info[9] eq $env{'form.timestamp'}) {
 4012:                         unlink($tempfile);
 4013:                     }
 4014:                 }
 4015:                 return;
 4016:             }
 4017:         }
 4018:         # Create the directory if not present
 4019:         my @parts=split(/\//,$filepath);
 4020:         my $fullpath = $perlvar{'lonDaemons'};
 4021:         for (my $i=0;$i<@parts;$i++) {
 4022:             $fullpath .= '/'.$parts[$i];
 4023:             if ((-e $fullpath)!=1) {
 4024:                 mkdir($fullpath,0777);
 4025:             }
 4026:         }
 4027:         open(my $fh,'>',$fullpath.'/'.$fname);
 4028:         print $fh $env{'form.'.$formname};
 4029:         close($fh);
 4030:         if ($context eq 'existingfile') {
 4031:             my @info = stat($fullpath.'/'.$fname);
 4032:             return ($fullpath.'/'.$fname,$info[9]);
 4033:         } else {
 4034:             return $fullpath.'/'.$fname;
 4035:         }
 4036:     }
 4037:     if ($subdir eq 'scantron') {
 4038:         $fname = 'scantron_orig_'.$fname;
 4039:     } else {
 4040:         $fname="$subdir/$fname";
 4041:     }
 4042:     if ($context eq 'coursedoc') {
 4043: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4044: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4045:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4046:             return &finishuserfileupload($docuname,$docudom,
 4047: 					 $formname,$fname,$parser,$allfiles,
 4048: 					 $codebase,$thumbwidth,$thumbheight,
 4049:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4050:         } else {
 4051:             if ($env{'form.folder'}) {
 4052:                 $fname=$env{'form.folder'}.'/'.$fname;
 4053:             }
 4054:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4055: 				       $fname,$formname,$parser,
 4056: 				       $allfiles,$codebase,$mimetype);
 4057:         }
 4058:     } elsif (defined($destuname)) {
 4059:         my $docuname=$destuname;
 4060:         my $docudom=$destudom;
 4061: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4062: 				     $parser,$allfiles,$codebase,
 4063:                                      $thumbwidth,$thumbheight,
 4064:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4065:     } else {
 4066:         my $docuname=$env{'user.name'};
 4067:         my $docudom=$env{'user.domain'};
 4068:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4069:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4070:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4071:         }
 4072: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4073: 				     $parser,$allfiles,$codebase,
 4074:                                      $thumbwidth,$thumbheight,
 4075:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4076:     }
 4077: }
 4078: 
 4079: sub finishuserfileupload {
 4080:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4081:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4082:     my $path=$docudom.'/'.$docuname.'/';
 4083:     my $filepath=$perlvar{'lonDocRoot'};
 4084:   
 4085:     my ($fnamepath,$file,$fetchthumb);
 4086:     $file=$fname;
 4087:     if ($fname=~m|/|) {
 4088:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4089: 	$path.=$fnamepath.'/';
 4090:     }
 4091:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4092:     my $count;
 4093:     for ($count=4;$count<=$#parts;$count++) {
 4094:         $filepath.="/$parts[$count]";
 4095:         if ((-e $filepath)!=1) {
 4096: 	    mkdir($filepath,0777);
 4097:         }
 4098:     }
 4099: 
 4100: # Save the file
 4101:     {
 4102: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4103: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4104: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4105: 	    return '/adm/notfound.html';
 4106: 	}
 4107:         if ($context eq 'overwrite') {
 4108:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4109:             my $target = $filepath.'/'.$file;
 4110:             if (-e $source) {
 4111:                 my @info = stat($source);
 4112:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4113:                     unless (&File::Copy::move($source,$target)) {
 4114:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4115:                         return "Moving from $source failed";
 4116:                     }
 4117:                 } else {
 4118:                     return "Temporary file: $source had unexpected date/time for last modification";
 4119:                 }
 4120:             } else {
 4121:                 return "Temporary file: $source missing";
 4122:             }
 4123:         } elsif (!print FH ($env{'form.'.$formname})) {
 4124: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4125: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4126: 	    return '/adm/notfound.html';
 4127: 	}
 4128: 	close(FH);
 4129:         if ($resizewidth && $resizeheight) {
 4130:             my $mm = new File::MMagic;
 4131:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4132:             if ($mime_type =~ m{^image/}) {
 4133: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4134:             }  
 4135: 	}
 4136:     }
 4137:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4138:         if (ref($mimetype)) {
 4139:             if ($$mimetype eq '') {
 4140:                 my $mm = new File::MMagic;
 4141:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4142:                 $$mimetype = $type;
 4143:             }
 4144:         }
 4145:     }
 4146:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4147:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4148:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4149:                                                        $allfiles,$codebase);
 4150:             unless ($parse_result eq 'ok') {
 4151:                 &logthis('Failed to parse '.$filepath.$file.
 4152: 	   	         ' for embedded media: '.$parse_result); 
 4153:             }
 4154:         }
 4155:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4156:         my $format = $env{'form.scantron_format'};
 4157:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4158:     }
 4159:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4160:         my $input = $filepath.'/'.$file;
 4161:         my $output = $filepath.'/'.'tn-'.$file;
 4162:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4163:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4164:         system({$args[0]} @args);
 4165:         if (-e $filepath.'/'.'tn-'.$file) {
 4166:             $fetchthumb  = 1; 
 4167:         }
 4168:     }
 4169:  
 4170: # Notify homeserver to grep it
 4171: #
 4172:     my $docuhome=&homeserver($docuname,$docudom);	
 4173:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4174:     if ($fetchresult eq 'ok') {
 4175:         if ($fetchthumb) {
 4176:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4177:             if ($thumbresult ne 'ok') {
 4178:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4179:                          $docuhome.': '.$thumbresult);
 4180:             }
 4181:         }
 4182: #
 4183: # Return the URL to it
 4184:         return '/uploaded/'.$path.$file;
 4185:     } else {
 4186:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4187: 		 ': '.$fetchresult);
 4188:         return '/adm/notfound.html';
 4189:     }
 4190: }
 4191: 
 4192: sub extract_embedded_items {
 4193:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4194:     my @state = ();
 4195:     my (%lastids,%related,%shockwave,%flashvars);
 4196:     my %javafiles = (
 4197:                       codebase => '',
 4198:                       code => '',
 4199:                       archive => ''
 4200:                     );
 4201:     my %mediafiles = (
 4202:                       src => '',
 4203:                       movie => '',
 4204:                      );
 4205:     my $p;
 4206:     if ($content) {
 4207:         $p = HTML::LCParser->new($content);
 4208:     } else {
 4209:         $p = HTML::LCParser->new($fullpath);
 4210:     }
 4211:     while (my $t=$p->get_token()) {
 4212: 	if ($t->[0] eq 'S') {
 4213: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4214: 	    push(@state, $tagname);
 4215:             if (lc($tagname) eq 'allow') {
 4216:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4217:             }
 4218: 	    if (lc($tagname) eq 'img') {
 4219: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4220: 	    }
 4221: 	    if (lc($tagname) eq 'a') {
 4222:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4223:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4224:                 }
 4225: 	    }
 4226:             if (lc($tagname) eq 'script') {
 4227:                 my $src;
 4228:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4229:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4230:                 } else {
 4231:                     if ($attr->{'src'} ne '') {
 4232:                         $src = $attr->{'src'};
 4233:                         &add_filetype($allfiles,$src,'src');
 4234:                     }
 4235:                 }
 4236:                 my $text = $p->get_trimmed_text();
 4237:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4238:                     my @swfargs = split(/,/,$1);
 4239:                     foreach my $item (@swfargs) {
 4240:                         $item =~ s/["']//g;
 4241:                         $item =~ s/^\s+//;
 4242:                         $item =~ s/\s+$//;
 4243:                     }
 4244:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4245:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4246:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4247:                         } else {
 4248:                             $related{$swfargs[0]} = [$swfargs[2]];
 4249:                         }
 4250:                     }
 4251:                 }
 4252:             }
 4253:             if (lc($tagname) eq 'link') {
 4254:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4255:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4256:                 }
 4257:             }
 4258: 	    if (lc($tagname) eq 'object' ||
 4259: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4260: 		foreach my $item (keys(%javafiles)) {
 4261: 		    $javafiles{$item} = '';
 4262: 		}
 4263:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4264:                     $lastids{lc($tagname)} = $attr->{'id'};
 4265:                 }
 4266: 	    }
 4267: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4268: 		my $name = lc($attr->{'name'});
 4269: 		foreach my $item (keys(%javafiles)) {
 4270: 		    if ($name eq $item) {
 4271: 			$javafiles{$item} = $attr->{'value'};
 4272: 			last;
 4273: 		    }
 4274: 		}
 4275:                 my $pathfrom;
 4276: 		foreach my $item (keys(%mediafiles)) {
 4277: 		    if ($name eq $item) {
 4278:                         $pathfrom = $attr->{'value'};
 4279:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4280: 			&add_filetype($allfiles,$pathfrom,$name);
 4281: 			last;
 4282: 		    }
 4283: 		}
 4284:                 if ($name eq 'flashvars') {
 4285:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4286:                 }
 4287:                 if ($pathfrom ne '') {
 4288:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4289:                                          $pathfrom);
 4290:                 }
 4291: 	    }
 4292: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4293: 		foreach my $item (keys(%javafiles)) {
 4294: 		    if ($attr->{$item}) {
 4295: 			$javafiles{$item} = $attr->{$item};
 4296: 			last;
 4297: 		    }
 4298: 		}
 4299: 		foreach my $item (keys(%mediafiles)) {
 4300: 		    if ($attr->{$item}) {
 4301: 			&add_filetype($allfiles,$attr->{$item},$item);
 4302: 			last;
 4303: 		    }
 4304: 		}
 4305:                 if (lc($tagname) eq 'embed') {
 4306:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4307:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4308:                                              $attr->{'src'});
 4309:                     }
 4310:                 }
 4311: 	    }
 4312:             if (lc($tagname) eq 'iframe') {
 4313:                 my $src = $attr->{'src'} ;
 4314:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4315:                     &add_filetype($allfiles,$src,'src');
 4316:                 } elsif ($src =~ m{^/}) {
 4317:                     if ($env{'request.course.id'}) {
 4318:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4319:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4320:                         my $url = &hreflocation('',$fullpath);
 4321:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4322:                             my $relpath = $1;
 4323:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4324:                                 &add_filetype($allfiles,$1,'src');
 4325:                             }
 4326:                         }
 4327:                     }
 4328:                 }
 4329:             }
 4330:             if ($t->[4] =~ m{/>$}) {
 4331:                 pop(@state);
 4332:             }
 4333: 	} elsif ($t->[0] eq 'E') {
 4334: 	    my ($tagname) = ($t->[1]);
 4335: 	    if ($javafiles{'codebase'} ne '') {
 4336: 		$javafiles{'codebase'} .= '/';
 4337: 	    }  
 4338: 	    if (lc($tagname) eq 'applet' ||
 4339: 		lc($tagname) eq 'object' ||
 4340: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4341: 		) {
 4342: 		foreach my $item (keys(%javafiles)) {
 4343: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4344: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4345: 			&add_filetype($allfiles,$file,$item);
 4346: 		    }
 4347: 		}
 4348: 	    } 
 4349: 	    pop @state;
 4350: 	}
 4351:     }
 4352:     foreach my $id (sort(keys(%flashvars))) {
 4353:         if ($shockwave{$id} ne '') {
 4354:             my @pairs = split(/\&/,$flashvars{$id});
 4355:             foreach my $pair (@pairs) {
 4356:                 my ($key,$value) = split(/\=/,$pair);
 4357:                 if ($key eq 'thumb') {
 4358:                     &add_filetype($allfiles,$value,$key);
 4359:                 } elsif ($key eq 'content') {
 4360:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4361:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4362:                     if ($ext ne '') {
 4363:                         &add_filetype($allfiles,$path.$value,$ext);
 4364:                     }
 4365:                 }
 4366:             }
 4367:         }
 4368:     }
 4369:     return 'ok';
 4370: }
 4371: 
 4372: sub add_filetype {
 4373:     my ($allfiles,$file,$type)=@_;
 4374:     if (exists($allfiles->{$file})) {
 4375: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4376: 	    push(@{$allfiles->{$file}}, &escape($type));
 4377: 	}
 4378:     } else {
 4379: 	@{$allfiles->{$file}} = (&escape($type));
 4380:     }
 4381: }
 4382: 
 4383: sub embedded_dependency {
 4384:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4385:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4386:         if (($identifier ne '') &&
 4387:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4388:             ($pathfrom ne '')) {
 4389:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4390:             foreach my $dep (@{$related->{$identifier}}) {
 4391:                 &add_filetype($allfiles,$path.$dep,'object');
 4392:             }
 4393:         }
 4394:     }
 4395:     return;
 4396: }
 4397: 
 4398: sub bubblesheet_converter {
 4399:     my ($cdom,$fullpath,$config,$format) = @_;
 4400:     if ((&domain($cdom) ne '') &&
 4401:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4402:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4403:         my (%csvcols,%csvoptions);
 4404:         if (ref($config->{'fields'}) eq 'HASH') {  
 4405:             %csvcols = %{$config->{'fields'}};
 4406:         }
 4407:         if (ref($config->{'options'}) eq 'HASH') {
 4408:             %csvoptions = %{$config->{'options'}};
 4409:         }
 4410:         my %csvbynum = reverse(%csvcols);
 4411:         my %scantronconf = &get_scantron_config($format,$cdom);
 4412:         if (keys(%scantronconf)) {
 4413:             my %bynum = (
 4414:                           $scantronconf{CODEstart} => 'CODEstart',
 4415:                           $scantronconf{IDstart}   => 'IDstart',
 4416:                           $scantronconf{PaperID}   => 'PaperID',
 4417:                           $scantronconf{FirstName} => 'FirstName',
 4418:                           $scantronconf{LastName}  => 'LastName',
 4419:                           $scantronconf{Qstart}    => 'Qstart',
 4420:                         );
 4421:             my @ordered;
 4422:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4423:                 push(@ordered,$bynum{$item});
 4424:             }
 4425:             my %mapstart = (
 4426:                               CODEstart => 'CODE',
 4427:                               IDstart   => 'ID',
 4428:                               PaperID   => 'PaperID',
 4429:                               FirstName => 'FirstName',
 4430:                               LastName  => 'LastName',
 4431:                               Qstart    => 'FirstQuestion',
 4432:                            );
 4433:             my %maplength = (
 4434:                               CODEstart => 'CODElength',
 4435:                               IDstart   => 'IDlength',
 4436:                               PaperID   => 'PaperIDlength',
 4437:                               FirstName => 'FirstNamelength',
 4438:                               LastName  => 'LastNamelength',
 4439:             );
 4440:             if (open(my $fh,'<',$fullpath)) {
 4441:                 my $output;
 4442:                 my %lettdig = &letter_to_digits();
 4443:                 my %diglett = reverse(%lettdig);
 4444:                 my $numletts = scalar(keys(%lettdig));
 4445:                 my $num = 0;
 4446:                 while (my $line=<$fh>) {
 4447:                     $num ++;
 4448:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4449:                     $line =~ s{[\r\n]+$}{};
 4450:                     my %found;
 4451:                     my @values = split(/,/,$line);
 4452:                     my ($qstart,$record);
 4453:                     for (my $i=0; $i<@values; $i++) {
 4454:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4455:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4456:                             if ($values[$i] eq '') {
 4457:                                 $values[$i] = $scantronconf{'Qoff'};
 4458:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4459:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4460:                                     $values[$i] = $lettdig{uc($values[$i])};
 4461:                                 }
 4462:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4463:                                 if ($values[$i] =~ /^[0-9]$/) {
 4464:                                     $values[$i] = $diglett{$values[$i]};
 4465:                                 }
 4466:                             } else {
 4467:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4468:                                     my $digit;
 4469:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4470:                                         $digit = $lettdig{uc($values[$i])}-1;
 4471:                                         if ($values[$i] eq 'J') {
 4472:                                             $digit += $numletts;
 4473:                                         }
 4474:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4475:                                         $digit = $values[$i]-1;
 4476:                                         if ($values[$i] eq '0') {
 4477:                                             $digit += $numletts;
 4478:                                         }
 4479:                                     }
 4480:                                     my $qval='';
 4481:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4482:                                         if ($j == $digit) {
 4483:                                             $qval .= $scantronconf{'Qon'};
 4484:                                         } else {
 4485:                                             $qval .= $scantronconf{'Qoff'};
 4486:                                         }
 4487:                                     }
 4488:                                     $values[$i] = $qval;
 4489:                                 }
 4490:                             }
 4491:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4492:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4493:                             }
 4494:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4495:                             if ($numblank > 0) {
 4496:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4497:                             }
 4498:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4499:                                 $qstart = $i;
 4500:                                 $found{$csvbynum{$i}} = $values[$i];
 4501:                             } else {
 4502:                                 $found{'FirstQuestion'} .= $values[$i];
 4503:                             }
 4504:                         } elsif (exists($csvbynum{$i})) {
 4505:                             if ($csvoptions{'rem'}) {
 4506:                                 $values[$i] =~ s/^\s+//;
 4507:                             }
 4508:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4509:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4510:                                     $values[$i] = '0'.$values[$i];
 4511:                                 }
 4512:                             }
 4513:                             $found{$csvbynum{$i}} = $values[$i];
 4514:                         }
 4515:                     }
 4516:                     foreach my $item (@ordered) {
 4517:                         my $currlength = 1+length($record);
 4518:                         my $numspaces = $scantronconf{$item} - $currlength;
 4519:                         if ($numspaces > 0) {
 4520:                             $record .= (' ' x $numspaces);
 4521:                         }
 4522:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4523:                             unless ($item eq 'Qstart') {
 4524:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4525:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4526:                                 }
 4527:                             }
 4528:                             $record .= $found{$mapstart{$item}};
 4529:                         }
 4530:                     }
 4531:                     $output .= "$record\n";
 4532:                 }
 4533:                 close($fh);
 4534:                 if ($output) {
 4535:                     if (open(my $fh,'>',$fullpath)) {
 4536:                         print $fh $output;
 4537:                         close($fh);
 4538:                     }
 4539:                 }
 4540:             }
 4541:         }
 4542:         return;
 4543:     }
 4544: }
 4545: 
 4546: sub letter_to_digits {
 4547:     my %lettdig = (
 4548:                     A => 1,
 4549:                     B => 2,
 4550:                     C => 3,
 4551:                     D => 4,
 4552:                     E => 5,
 4553:                     F => 6,
 4554:                     G => 7,
 4555:                     H => 8,
 4556:                     I => 9,
 4557:                     J => 0,
 4558:                   );
 4559:     return %lettdig;
 4560: }
 4561: 
 4562: sub get_scantron_config {
 4563:     my ($which,$cdom) = @_;
 4564:     my @lines = &get_scantronformat_file($cdom);
 4565:     my %config;
 4566:     #FIXME probably should move to XML it has already gotten a bit much now
 4567:     foreach my $line (@lines) {
 4568:         my ($name,$descrip)=split(/:/,$line);
 4569:         if ($name ne $which ) { next; }
 4570:         chomp($line);
 4571:         my @config=split(/:/,$line);
 4572:         $config{'name'}=$config[0];
 4573:         $config{'description'}=$config[1];
 4574:         $config{'CODElocation'}=$config[2];
 4575:         $config{'CODEstart'}=$config[3];
 4576:         $config{'CODElength'}=$config[4];
 4577:         $config{'IDstart'}=$config[5];
 4578:         $config{'IDlength'}=$config[6];
 4579:         $config{'Qstart'}=$config[7];
 4580:         $config{'Qlength'}=$config[8];
 4581:         $config{'Qoff'}=$config[9];
 4582:         $config{'Qon'}=$config[10];
 4583:         $config{'PaperID'}=$config[11];
 4584:         $config{'PaperIDlength'}=$config[12];
 4585:         $config{'FirstName'}=$config[13];
 4586:         $config{'FirstNamelength'}=$config[14];
 4587:         $config{'LastName'}=$config[15];
 4588:         $config{'LastNamelength'}=$config[16];
 4589:         $config{'BubblesPerRow'}=$config[17];
 4590:         last;
 4591:     }
 4592:     return %config;
 4593: }
 4594: 
 4595: sub get_scantronformat_file {
 4596:     my ($cdom) = @_;
 4597:     if ($cdom eq '') {
 4598:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4599:     }
 4600:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4601:     my $gottab = 0;
 4602:     my @lines;
 4603:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4604:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4605:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4606:             if ($formatfile ne '-1') {
 4607:                 @lines = split("\n",$formatfile,-1);
 4608:                 $gottab = 1;
 4609:             }
 4610:         }
 4611:     }
 4612:     if (!$gottab) {
 4613:         my $confname = $cdom.'-domainconfig';
 4614:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4615:         my $formatfile = &getfile($default);
 4616:         if ($formatfile ne '-1') {
 4617:             @lines = split("\n",$formatfile,-1);
 4618:             $gottab = 1;
 4619:         }
 4620:     }
 4621:     if (!$gottab) {
 4622:         my @domains = &current_machine_domains();
 4623:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4624:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4625:                 @lines = <$fh>;
 4626:                 close($fh);
 4627:             }
 4628:         } else {
 4629:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4630:                 @lines = <$fh>;
 4631:                 close($fh);
 4632:             }
 4633:         }
 4634:     }
 4635:     return @lines;
 4636: }
 4637: 
 4638: sub removeuploadedurl {
 4639:     my ($url)=@_;	
 4640:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4641:     return &removeuserfile($uname,$udom,$fname);
 4642: }
 4643: 
 4644: sub removeuserfile {
 4645:     my ($docuname,$docudom,$fname)=@_;
 4646:     my $home=&homeserver($docuname,$docudom);    
 4647:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4648:     if ($result eq 'ok') {	
 4649:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4650:             my $metafile = $fname.'.meta';
 4651:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4652: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4653:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4654:             my $sqlresult = 
 4655:                 &update_portfolio_table($docuname,$docudom,$file,
 4656:                                         'portfolio_metadata',$group,
 4657:                                         'delete');
 4658:         }
 4659:     }
 4660:     return $result;
 4661: }
 4662: 
 4663: sub mkdiruserfile {
 4664:     my ($docuname,$docudom,$dir)=@_;
 4665:     my $home=&homeserver($docuname,$docudom);
 4666:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4667: }
 4668: 
 4669: sub renameuserfile {
 4670:     my ($docuname,$docudom,$old,$new)=@_;
 4671:     my $home=&homeserver($docuname,$docudom);
 4672:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4673:                         &escape("$old").':'.&escape("$new"),$home);
 4674:     if ($result eq 'ok') {
 4675:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4676:             my $oldmeta = $old.'.meta';
 4677:             my $newmeta = $new.'.meta';
 4678:             my $metaresult = 
 4679:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4680: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4681:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4682:             my $sqlresult = 
 4683:                 &update_portfolio_table($docuname,$docudom,$file,
 4684:                                         'portfolio_metadata',$group,
 4685:                                         'delete');
 4686:         }
 4687:     }
 4688:     return $result;
 4689: }
 4690: 
 4691: # ------------------------------------------------------------------------- Log
 4692: 
 4693: sub log {
 4694:     my ($dom,$nam,$hom,$what)=@_;
 4695:     return critical("log:$dom:$nam:$what",$hom);
 4696: }
 4697: 
 4698: # ------------------------------------------------------------------ Course Log
 4699: #
 4700: # This routine flushes several buffers of non-mission-critical nature
 4701: #
 4702: 
 4703: sub flushcourselogs {
 4704:     &logthis('Flushing log buffers');
 4705: #
 4706: # course logs
 4707: # This is a log of all transactions in a course, which can be used
 4708: # for data mining purposes
 4709: #
 4710: # It also collects the courseid database, which lists last transaction
 4711: # times and course titles for all courseids
 4712: #
 4713:     my %courseidbuffer=();
 4714:     foreach my $crsid (keys(%courselogs)) {
 4715:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4716: 		          &escape($courselogs{$crsid}),
 4717: 		          $coursehombuf{$crsid}) eq 'ok') {
 4718: 	    delete $courselogs{$crsid};
 4719:         } else {
 4720:             &logthis('Failed to flush log buffer for '.$crsid);
 4721:             if (length($courselogs{$crsid})>40000) {
 4722:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4723:                         " exceeded maximum size, deleting.</font>");
 4724:                delete $courselogs{$crsid};
 4725:             }
 4726:         }
 4727:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4728:             'description' => $coursedescrbuf{$crsid},
 4729:             'inst_code'    => $courseinstcodebuf{$crsid},
 4730:             'type'        => $coursetypebuf{$crsid},
 4731:             'owner'       => $courseownerbuf{$crsid},
 4732:         };
 4733:     }
 4734: #
 4735: # Write course id database (reverse lookup) to homeserver of courses 
 4736: # Is used in pickcourse
 4737: #
 4738:     foreach my $crs_home (keys(%courseidbuffer)) {
 4739:         my $response = &courseidput(&host_domain($crs_home),
 4740:                                     $courseidbuffer{$crs_home},
 4741:                                     $crs_home,'timeonly');
 4742:     }
 4743: #
 4744: # File accesses
 4745: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4746: #
 4747:     foreach my $entry (keys(%accesshash)) {
 4748:         if ($entry =~ /___count$/) {
 4749:             my ($dom,$name);
 4750:             ($dom,$name,undef)=
 4751: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4752:             if (! defined($dom) || $dom eq '' || 
 4753:                 ! defined($name) || $name eq '') {
 4754:                 my $cid = $env{'request.course.id'};
 4755:                 $dom  = $env{'request.'.$cid.'.domain'};
 4756:                 $name = $env{'request.'.$cid.'.num'};
 4757:             }
 4758:             my $value = $accesshash{$entry};
 4759:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4760:             my %temphash=($url => $value);
 4761:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4762:             if ($result eq 'ok') {
 4763:                 delete $accesshash{$entry};
 4764:             }
 4765:         } else {
 4766:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4767:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4768:             my %temphash=($entry => $accesshash{$entry});
 4769:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4770:                 delete $accesshash{$entry};
 4771:             }
 4772:         }
 4773:     }
 4774: #
 4775: # Roles
 4776: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4777: #
 4778:     foreach my $entry (keys(%userrolehash)) {
 4779:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4780: 	    split(/\:/,$entry);
 4781:         if (&Apache::lonnet::put('nohist_userroles',
 4782:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4783:                 $rudom,$runame) eq 'ok') {
 4784: 	    delete $userrolehash{$entry};
 4785:         }
 4786:     }
 4787: #
 4788: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4789: #
 4790:     my %domrolebuffer = ();
 4791:     foreach my $entry (keys(%domainrolehash)) {
 4792:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4793:         if ($domrolebuffer{$rudom}) {
 4794:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4795:                       '='.&escape($domainrolehash{$entry});
 4796:         } else {
 4797:             $domrolebuffer{$rudom}.=&escape($entry).
 4798:                       '='.&escape($domainrolehash{$entry});
 4799:         }
 4800:         delete $domainrolehash{$entry};
 4801:     }
 4802:     foreach my $dom (keys(%domrolebuffer)) {
 4803: 	my %servers;
 4804: 	if (defined(&domain($dom,'primary'))) {
 4805: 	    my $primary=&domain($dom,'primary');
 4806: 	    my $hostname=&hostname($primary);
 4807: 	    $servers{$primary} = $hostname;
 4808: 	} else { 
 4809: 	    %servers = &get_servers($dom,'library');
 4810: 	}
 4811: 	foreach my $tryserver (keys(%servers)) {
 4812: 	    if (&reply('domroleput:'.$dom.':'.
 4813: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4814: 		last;
 4815: 	    } else {  
 4816: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4817: 	    }
 4818:         }
 4819:     }
 4820:     $dumpcount++;
 4821: }
 4822: 
 4823: sub courselog {
 4824:     my $what=shift;
 4825:     $what=time.':'.$what;
 4826:     unless ($env{'request.course.id'}) { return ''; }
 4827:     $coursedombuf{$env{'request.course.id'}}=
 4828:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4829:     $coursenumbuf{$env{'request.course.id'}}=
 4830:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4831:     $coursehombuf{$env{'request.course.id'}}=
 4832:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4833:     $coursedescrbuf{$env{'request.course.id'}}=
 4834:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4835:     $courseinstcodebuf{$env{'request.course.id'}}=
 4836:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4837:     $courseownerbuf{$env{'request.course.id'}}=
 4838:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4839:     $coursetypebuf{$env{'request.course.id'}}=
 4840:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4841:     if (defined $courselogs{$env{'request.course.id'}}) {
 4842: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4843:     } else {
 4844: 	$courselogs{$env{'request.course.id'}}.=$what;
 4845:     }
 4846:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4847: 	&flushcourselogs();
 4848:     }
 4849: }
 4850: 
 4851: sub courseacclog {
 4852:     my $fnsymb=shift;
 4853:     unless ($env{'request.course.id'}) { return ''; }
 4854:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4855:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4856:         $what.=':POST';
 4857:         # FIXME: Probably ought to escape things....
 4858: 	foreach my $key (keys(%env)) {
 4859:             if ($key=~/^form\.(.*)/) {
 4860:                 my $formitem = $1;
 4861:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4862:                     $what.=':'.$formitem.'='.$env{$key};
 4863:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4864:                     $what.=':'.$formitem.'='.$env{$key};
 4865:                 }
 4866:             }
 4867:         }
 4868:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4869:         # FIXME: We should not be depending on a form parameter that someone
 4870:         # editing lonsearchcat.pm might change in the future.
 4871:         if ($env{'form.phase'} eq 'course_search') {
 4872:             $what.= ':POST';
 4873:             # FIXME: Probably ought to escape things....
 4874:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4875:                                  'crsdiscuss') {
 4876:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4877:             }
 4878:         }
 4879:     }
 4880:     &courselog($what);
 4881: }
 4882: 
 4883: sub countacc {
 4884:     my $url=&declutter(shift);
 4885:     return if (! defined($url) || $url eq '');
 4886:     unless ($env{'request.course.id'}) { return ''; }
 4887: #
 4888: # Mark that this url was used in this course
 4889: #
 4890:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4891: #
 4892: # Increase the access count for this resource in this child process
 4893: #
 4894:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4895:     $accesshash{$key}++;
 4896: }
 4897: 
 4898: sub linklog {
 4899:     my ($from,$to)=@_;
 4900:     $from=&declutter($from);
 4901:     $to=&declutter($to);
 4902:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4903:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4904: }
 4905: 
 4906: sub statslog {
 4907:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4908:     if ($users<2) { return; }
 4909:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4910:             'course'       => $env{'request.course.id'},
 4911:             'sections'     => '"all"',
 4912:             'num_students' => $users,
 4913:             'part'         => $part,
 4914:             'symb'         => $symb,
 4915:             'mean_tries'   => $av_attempts,
 4916:             'deg_of_diff'  => $degdiff});
 4917:     foreach my $key (keys(%dynstore)) {
 4918:         $accesshash{$key}=$dynstore{$key};
 4919:     }
 4920: }
 4921:   
 4922: sub userrolelog {
 4923:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4924:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4925:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4926:        $userrolehash
 4927:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4928:                     =$tend.':'.$tstart;
 4929:     }
 4930:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4931:        $userrolehash
 4932:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4933:                     =$tend.':'.$tstart;
 4934:     }
 4935:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4936:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4937:        $domainrolehash
 4938:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4939:                     = $tend.':'.$tstart;
 4940:     }
 4941: }
 4942: 
 4943: sub courserolelog {
 4944:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4945:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4946:         my $cdom = $1;
 4947:         my $cnum = $2;
 4948:         my $sec = $3;
 4949:         my $namespace = 'rolelog';
 4950:         my %storehash = (
 4951:                            role    => $trole,
 4952:                            start   => $tstart,
 4953:                            end     => $tend,
 4954:                            selfenroll => $selfenroll,
 4955:                            context    => $context,
 4956:                         );
 4957:         if ($trole eq 'gr') {
 4958:             $namespace = 'groupslog';
 4959:             $storehash{'group'} = $sec;
 4960:         } else {
 4961:             $storehash{'section'} = $sec;
 4962:         }
 4963:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4964:                    $domain,$cnum,$cdom);
 4965:         if (($trole ne 'st') || ($sec ne '')) {
 4966:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4967:         }
 4968:     }
 4969:     return;
 4970: }
 4971: 
 4972: sub domainrolelog {
 4973:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4974:     if ($area =~ m{^/($match_domain)/$}) {
 4975:         my $cdom = $1;
 4976:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4977:         my $namespace = 'rolelog';
 4978:         my %storehash = (
 4979:                            role    => $trole,
 4980:                            start   => $tstart,
 4981:                            end     => $tend,
 4982:                            context => $context,
 4983:                         );
 4984:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4985:                    $domain,$domconfiguser,$cdom);
 4986:     }
 4987:     return;
 4988: 
 4989: }
 4990: 
 4991: sub coauthorrolelog {
 4992:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4993:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4994:         my $audom = $1;
 4995:         my $auname = $2;
 4996:         my $namespace = 'rolelog';
 4997:         my %storehash = (
 4998:                            role    => $trole,
 4999:                            start   => $tstart,
 5000:                            end     => $tend,
 5001:                            context => $context,
 5002:                         );
 5003:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5004:                    $domain,$auname,$audom);
 5005:     }
 5006:     return;
 5007: }
 5008: 
 5009: sub get_course_adv_roles {
 5010:     my ($cid,$codes) = @_;
 5011:     $cid=$env{'request.course.id'} unless (defined($cid));
 5012:     my %coursehash=&coursedescription($cid);
 5013:     my $crstype = &Apache::loncommon::course_type($cid);
 5014:     my %nothide=();
 5015:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5016:         if ($user !~ /:/) {
 5017: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5018:         } else {
 5019:             $nothide{$user}=1;
 5020:         }
 5021:     }
 5022:     my @possdoms = ($coursehash{'domain'});
 5023:     if ($coursehash{'checkforpriv'}) {
 5024:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5025:     }
 5026:     my %returnhash=();
 5027:     my %dumphash=
 5028:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5029:     my $now=time;
 5030:     my %privileged;
 5031:     foreach my $entry (keys(%dumphash)) {
 5032: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5033:         if (($tstart) && ($tstart<0)) { next; }
 5034:         if (($tend) && ($tend<$now)) { next; }
 5035:         if (($tstart) && ($now<$tstart)) { next; }
 5036:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5037: 	if ($username eq '' || $domain eq '') { next; }
 5038:         if ((&privileged($username,$domain,\@possdoms)) &&
 5039:             (!$nothide{$username.':'.$domain})) { next; }
 5040: 	if ($role eq 'cr') { next; }
 5041:         if ($codes) {
 5042:             if ($section) { $role .= ':'.$section; }
 5043:             if ($returnhash{$role}) {
 5044:                 $returnhash{$role}.=','.$username.':'.$domain;
 5045:             } else {
 5046:                 $returnhash{$role}=$username.':'.$domain;
 5047:             }
 5048:         } else {
 5049:             my $key=&plaintext($role,$crstype);
 5050:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5051:             if ($returnhash{$key}) {
 5052: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5053:             } else {
 5054:                 $returnhash{$key}=$username.':'.$domain;
 5055:             }
 5056:         }
 5057:     }
 5058:     return %returnhash;
 5059: }
 5060: 
 5061: sub get_my_roles {
 5062:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5063:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5064:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5065:     my (%dumphash,%nothide);
 5066:     if ($context eq 'userroles') {
 5067:         %dumphash = &dump('roles',$udom,$uname);
 5068:     } else {
 5069:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5070:         if ($hidepriv) {
 5071:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5072:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5073:                 if ($user !~ /:/) {
 5074:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5075:                 } else {
 5076:                     $nothide{$user} = 1;
 5077:                 }
 5078:             }
 5079:         }
 5080:     }
 5081:     my %returnhash=();
 5082:     my $now=time;
 5083:     my %privileged;
 5084:     foreach my $entry (keys(%dumphash)) {
 5085:         my ($role,$tend,$tstart);
 5086:         if ($context eq 'userroles') {
 5087:             next if ($entry =~ /^rolesdef/);
 5088: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5089:         } else {
 5090:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5091:         }
 5092:         if (($tstart) && ($tstart<0)) { next; }
 5093:         my $status = 'active';
 5094:         if (($tend) && ($tend<=$now)) {
 5095:             $status = 'previous';
 5096:         } 
 5097:         if (($tstart) && ($now<$tstart)) {
 5098:             $status = 'future';
 5099:         }
 5100:         if (ref($types) eq 'ARRAY') {
 5101:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5102:                 next;
 5103:             } 
 5104:         } else {
 5105:             if ($status ne 'active') {
 5106:                 next;
 5107:             }
 5108:         }
 5109:         my ($rolecode,$username,$domain,$section,$area);
 5110:         if ($context eq 'userroles') {
 5111:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5112:             (undef,$domain,$username,$section) = split(/\//,$area);
 5113:         } else {
 5114:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5115:         }
 5116:         if (ref($roledoms) eq 'ARRAY') {
 5117:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5118:                 next;
 5119:             }
 5120:         }
 5121:         if (ref($roles) eq 'ARRAY') {
 5122:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5123:                 if ($role =~ /^cr\//) {
 5124:                     if (!grep(/^cr$/,@{$roles})) {
 5125:                         next;
 5126:                     }
 5127:                 } elsif ($role =~ /^gr\//) {
 5128:                     if (!grep(/^gr$/,@{$roles})) {
 5129:                         next;
 5130:                     }
 5131:                 } else {
 5132:                     next;
 5133:                 }
 5134:             }
 5135:         }
 5136:         if ($hidepriv) {
 5137:             my @privroles = ('dc','su');
 5138:             if ($context eq 'userroles') {
 5139:                 next if (grep(/^\Q$role\E$/,@privroles));
 5140:             } else {
 5141:                 my $possdoms = [$domain];
 5142:                 if (ref($roledoms) eq 'ARRAY') {
 5143:                    push(@{$possdoms},@{$roledoms}); 
 5144:                 }
 5145:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5146:                     if (!$nothide{$username.':'.$domain}) {
 5147:                         next;
 5148:                     }
 5149:                 }
 5150:             }
 5151:         }
 5152:         if ($withsec) {
 5153:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5154:                 $tstart.':'.$tend;
 5155:         } else {
 5156:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5157:         }
 5158:     }
 5159:     return %returnhash;
 5160: }
 5161: 
 5162: sub get_all_adhocroles {
 5163:     my ($dom) = @_;
 5164:     my @roles_by_num = ();
 5165:     my %domdefaults = &get_domain_defaults($dom);
 5166:     my (%description,%access_in_dom,%access_info);
 5167:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5168:         my $count = 0;
 5169:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5170:         my %ordered;
 5171:         foreach my $role (sort(keys(%domcurrent))) {
 5172:             my ($order,$desc,$access_in_dom);
 5173:             if (ref($domcurrent{$role}) eq 'HASH') {
 5174:                 $order = $domcurrent{$role}{'order'};
 5175:                 $desc = $domcurrent{$role}{'desc'};
 5176:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5177:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5178:             }
 5179:             if ($order eq '') {
 5180:                 $order = $count;
 5181:             }
 5182:             $ordered{$order} = $role;
 5183:             if ($desc ne '') {
 5184:                 $description{$role} = $desc;
 5185:             } else {
 5186:                 $description{$role}= $role;
 5187:             }
 5188:             $count++;
 5189:         }
 5190:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5191:             push(@roles_by_num,$ordered{$item});
 5192:         }
 5193:     }
 5194:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5195: }
 5196: 
 5197: sub get_my_adhocroles {
 5198:     my ($cid,$checkreg) = @_;
 5199:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5200:     if ($env{'request.course.id'} eq $cid) {
 5201:         $cdom = $env{'course.'.$cid.'.domain'};
 5202:         $cnum = $env{'course.'.$cid.'.num'};
 5203:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5204:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5205:         $cdom = $1;
 5206:         $cnum = $2;
 5207:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5208:                                      $cdom,$cnum);
 5209:     }
 5210:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5211:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5212:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5213:         if ($rosterhash{$user} ne '') {
 5214:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5215:             return ([],{}) if ($type eq 'auto');
 5216:         }
 5217:     }
 5218:     if (($cdom ne '') && ($cnum ne ''))  {
 5219:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5220:             my $then=$env{'user.login.time'};
 5221:             my $update=$env{'user.update.time'};
 5222:             if (!$update) {
 5223:                 $update = $then;
 5224:             }
 5225:             my @liveroles;
 5226:             foreach my $role ('dh','da') {
 5227:                 if ($env{"user.role.$role./$cdom/"}) {
 5228:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5229:                     my $limit = $update;
 5230:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5231:                         $limit = $then;
 5232:                     }
 5233:                     my $activerole = 1;
 5234:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5235:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5236:                     if ($activerole) {
 5237:                         push(@liveroles,$role);
 5238:                     }
 5239:                 }
 5240:             }
 5241:             if (@liveroles) {
 5242:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5243:                     my ($accessref,$accessinfo,%access_in_dom);
 5244:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5245:                     if (ref($roles_by_num) eq 'ARRAY') {
 5246:                         if (@{$roles_by_num}) {
 5247:                             my %settings;
 5248:                             if ($env{'request.course.id'} eq $cid) {
 5249:                                 foreach my $envkey (keys(%env)) {
 5250:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5251:                                         $settings{$1} = $env{$envkey};
 5252:                                     }
 5253:                                 }
 5254:                             } else {
 5255:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5256:                             }
 5257:                             my %setincrs;
 5258:                             if ($settings{'internal.adhocaccess'}) {
 5259:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5260:                             }
 5261:                             my @statuses;
 5262:                             if ($env{'environment.inststatus'}) {
 5263:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5264:                             }
 5265:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5266:                             if (ref($accessref) eq 'HASH') {
 5267:                                 %access_in_dom = %{$accessref};
 5268:                             }
 5269:                             foreach my $role (@{$roles_by_num}) {
 5270:                                 my ($curraccess,@okstatus,@personnel);
 5271:                                 if ($setincrs{$role}) {
 5272:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5273:                                     if ($curraccess eq 'status') {
 5274:                                         @okstatus = split(/\&/,$rest);
 5275:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5276:                                         @personnel = split(/\&/,$rest);
 5277:                                     }
 5278:                                 } else {
 5279:                                     $curraccess = $access_in_dom{$role};
 5280:                                     if (ref($accessinfo) eq 'HASH') {
 5281:                                         if ($curraccess eq 'status') {
 5282:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5283:                                                 @okstatus = @{$accessinfo->{$role}};
 5284:                                             }
 5285:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5286:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5287:                                                 @personnel = @{$accessinfo->{$role}};
 5288:                                             }
 5289:                                         }
 5290:                                     }
 5291:                                 }
 5292:                                 if ($curraccess eq 'none') {
 5293:                                     next;
 5294:                                 } elsif ($curraccess eq 'all') {
 5295:                                     push(@possroles,$role);
 5296:                                 } elsif ($curraccess eq 'dh') {
 5297:                                     if (grep(/^dh$/,@liveroles)) {
 5298:                                         push(@possroles,$role);
 5299:                                     } else {
 5300:                                         next;
 5301:                                     }
 5302:                                 } elsif ($curraccess eq 'da') {
 5303:                                     if (grep(/^da$/,@liveroles)) {
 5304:                                         push(@possroles,$role);
 5305:                                     } else {
 5306:                                         next;
 5307:                                     }
 5308:                                 } elsif ($curraccess eq 'status') {
 5309:                                     if (@okstatus) {
 5310:                                         if (!@statuses) {
 5311:                                             if (grep(/^default$/,@okstatus)) {
 5312:                                                 push(@possroles,$role);
 5313:                                             }
 5314:                                         } else {
 5315:                                             foreach my $status (@okstatus) {
 5316:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5317:                                                     push(@possroles,$role);
 5318:                                                     last;
 5319:                                                 }
 5320:                                             }
 5321:                                         }
 5322:                                     }
 5323:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5324:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5325:                                         if ($curraccess eq 'exc') {
 5326:                                             push(@possroles,$role);
 5327:                                         }
 5328:                                     } elsif ($curraccess eq 'inc') {
 5329:                                         push(@possroles,$role);
 5330:                                     }
 5331:                                 }
 5332:                             }
 5333:                         }
 5334:                     }
 5335:                 }
 5336:             }
 5337:         }
 5338:     }
 5339:     unless (ref($description) eq 'HASH') {
 5340:         if (ref($roles_by_num) eq 'ARRAY') {
 5341:             my %desc;
 5342:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5343:             $description = \%desc;
 5344:         } else {
 5345:             $description = {};
 5346:         }
 5347:     }
 5348:     return (\@possroles,$description);
 5349: }
 5350: 
 5351: # ----------------------------------------------------- Frontpage Announcements
 5352: #
 5353: #
 5354: 
 5355: sub postannounce {
 5356:     my ($server,$text)=@_;
 5357:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5358:     unless ($text=~/\w/) { $text=''; }
 5359:     return &reply('setannounce:'.&escape($text),$server);
 5360: }
 5361: 
 5362: sub getannounce {
 5363: 
 5364:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5365: 	my $announcement='';
 5366: 	while (my $line = <$fh>) { $announcement .= $line; }
 5367: 	close($fh);
 5368: 	if ($announcement=~/\w/) { 
 5369: 	    return 
 5370:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5371:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5372: 	} else {
 5373: 	    return '';
 5374: 	}
 5375:     } else {
 5376: 	return '';
 5377:     }
 5378: }
 5379: 
 5380: # ---------------------------------------------------------- Course ID routines
 5381: # Deal with domain's nohist_courseid.db files
 5382: #
 5383: 
 5384: sub courseidput {
 5385:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5386:     return unless (ref($storehash) eq 'HASH');
 5387:     my $outcome;
 5388:     if ($caller eq 'timeonly') {
 5389:         my $cids = '';
 5390:         foreach my $item (keys(%$storehash)) {
 5391:             $cids.=&escape($item).'&';
 5392:         }
 5393:         $cids=~s/\&$//;
 5394:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5395:                           $coursehome);       
 5396:     } else {
 5397:         my $items = '';
 5398:         foreach my $item (keys(%$storehash)) {
 5399:             $items.= &escape($item).'='.
 5400:                      &freeze_escape($$storehash{$item}).'&';
 5401:         }
 5402:         $items=~s/\&$//;
 5403:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5404:                           $coursehome);
 5405:     }
 5406:     if ($outcome eq 'unknown_cmd') {
 5407:         my $what;
 5408:         foreach my $cid (keys(%$storehash)) {
 5409:             $what .= &escape($cid).'=';
 5410:             foreach my $item ('description','inst_code','owner','type') {
 5411:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5412:             }
 5413:             $what =~ s/\:$/&/;
 5414:         }
 5415:         $what =~ s/\&$//;  
 5416:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5417:     } else {
 5418:         return $outcome;
 5419:     }
 5420: }
 5421: 
 5422: sub courseiddump {
 5423:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5424:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5425:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5426:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5427:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5428:     my $as_hash = 1;
 5429:     my %returnhash;
 5430:     if (!$domfilter) { $domfilter=''; }
 5431:     my %libserv = &all_library();
 5432:     foreach my $tryserver (keys(%libserv)) {
 5433:         if ( (  $hostidflag == 1 
 5434: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5435: 	     || (!defined($hostidflag)) ) {
 5436: 
 5437: 	    if (($domfilter eq '') ||
 5438: 		(&host_domain($tryserver) eq $domfilter)) {
 5439:                 my $rep;
 5440:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5441:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5442:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5443:                                 &escape($descfilter), &escape($instcodefilter), 
 5444:                                 &escape($ownerfilter), &escape($coursefilter),
 5445:                                 &escape($typefilter), &escape($regexp_ok), 
 5446:                                 $as_hash, &escape($selfenrollonly), 
 5447:                                 &escape($catfilter), $showhidden, $caller, 
 5448:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5449:                                 &escape($createdbefore), &escape($createdafter), 
 5450:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5451:                                 $reqcrsdom,&escape($reqinstcode))));
 5452:                 } else {
 5453:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5454:                              $sincefilter.':'.&escape($descfilter).':'.
 5455:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5456:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5457:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5458:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5459:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5460:                              &escape($cc_clone).':'.$cloneonly.':'.
 5461:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5462:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5463:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5464:                 }
 5465:                      
 5466:                 my @pairs=split(/\&/,$rep);
 5467:                 foreach my $item (@pairs) {
 5468:                     my ($key,$value)=split(/\=/,$item,2);
 5469:                     $key = &unescape($key);
 5470:                     next if ($key =~ /^error: 2 /);
 5471:                     my $result = &thaw_unescape($value);
 5472:                     if (ref($result) eq 'HASH') {
 5473:                         $returnhash{$key}=$result;
 5474:                     } else {
 5475:                         my @responses = split(/:/,$value);
 5476:                         my @items = ('description','inst_code','owner','type');
 5477:                         for (my $i=0; $i<@responses; $i++) {
 5478:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5479:                         }
 5480:                     }
 5481:                 }
 5482:             }
 5483:         }
 5484:     }
 5485:     return %returnhash;
 5486: }
 5487: 
 5488: sub courselastaccess {
 5489:     my ($cdom,$cnum,$hostidref) = @_;
 5490:     my %returnhash;
 5491:     if ($cdom && $cnum) {
 5492:         my $chome = &homeserver($cnum,$cdom);
 5493:         if ($chome ne 'no_host') {
 5494:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5495:             &extract_lastaccess(\%returnhash,$rep);
 5496:         }
 5497:     } else {
 5498:         if (!$cdom) { $cdom=''; }
 5499:         my %libserv = &all_library();
 5500:         foreach my $tryserver (keys(%libserv)) {
 5501:             if (ref($hostidref) eq 'ARRAY') {
 5502:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5503:             } 
 5504:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5505:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5506:                 &extract_lastaccess(\%returnhash,$rep);
 5507:             }
 5508:         }
 5509:     }
 5510:     return %returnhash;
 5511: }
 5512: 
 5513: sub extract_lastaccess {
 5514:     my ($returnhash,$rep) = @_;
 5515:     if (ref($returnhash) eq 'HASH') {
 5516:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5517:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5518:                  $rep eq '') {
 5519:             my @pairs=split(/\&/,$rep);
 5520:             foreach my $item (@pairs) {
 5521:                 my ($key,$value)=split(/\=/,$item,2);
 5522:                 $key = &unescape($key);
 5523:                 next if ($key =~ /^error: 2 /);
 5524:                 $returnhash->{$key} = &thaw_unescape($value);
 5525:             }
 5526:         }
 5527:     }
 5528:     return;
 5529: }
 5530: 
 5531: # ---------------------------------------------------------- DC e-mail
 5532: 
 5533: sub dcmailput {
 5534:     my ($domain,$msgid,$message,$server)=@_;
 5535:     my $status = &Apache::lonnet::critical(
 5536:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5537:        &escape($message),$server);
 5538:     return $status;
 5539: }
 5540: 
 5541: sub dcmaildump {
 5542:     my ($dom,$startdate,$enddate,$senders) = @_;
 5543:     my %returnhash=();
 5544: 
 5545:     if (defined(&domain($dom,'primary'))) {
 5546:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5547:                                                          &escape($enddate).':';
 5548: 	my @esc_senders=map { &escape($_)} @$senders;
 5549: 	$cmd.=&escape(join('&',@esc_senders));
 5550: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5551:             my ($key,$value) = split(/\=/,$line,2);
 5552:             if (($key) && ($value)) {
 5553:                 $returnhash{&unescape($key)} = &unescape($value);
 5554:             }
 5555:         }
 5556:     }
 5557:     return %returnhash;
 5558: }
 5559: # ---------------------------------------------------------- Domain roles
 5560: 
 5561: sub get_domain_roles {
 5562:     my ($dom,$roles,$startdate,$enddate)=@_;
 5563:     if ((!defined($startdate)) || ($startdate eq '')) {
 5564:         $startdate = '.';
 5565:     }
 5566:     if ((!defined($enddate)) || ($enddate eq '')) {
 5567:         $enddate = '.';
 5568:     }
 5569:     my $rolelist;
 5570:     if (ref($roles) eq 'ARRAY') {
 5571:         $rolelist = join('&',@{$roles});
 5572:     }
 5573:     my %personnel = ();
 5574: 
 5575:     my %servers = &get_servers($dom,'library');
 5576:     foreach my $tryserver (keys(%servers)) {
 5577: 	%{$personnel{$tryserver}}=();
 5578: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5579: 					    &escape($startdate).':'.
 5580: 					    &escape($enddate).':'.
 5581: 					    &escape($rolelist), $tryserver))) {
 5582: 	    my ($key,$value) = split(/\=/,$line,2);
 5583: 	    if (($key) && ($value)) {
 5584: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5585: 	    }
 5586: 	}
 5587:     }
 5588:     return %personnel;
 5589: }
 5590: 
 5591: sub get_active_domroles {
 5592:     my ($dom,$roles) = @_;
 5593:     return () unless (ref($roles) eq 'ARRAY');
 5594:     my $now = time;
 5595:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5596:     my %domroles;
 5597:     foreach my $server (keys(%dompersonnel)) {
 5598:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5599:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5600:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5601:         }
 5602:     }
 5603:     return %domroles;
 5604: }
 5605: 
 5606: # ----------------------------------------------------------- Interval timing 
 5607: 
 5608: {
 5609: # Caches needed for speedup of navmaps
 5610: # We don't want to cache this for very long at all (5 seconds at most)
 5611: # 
 5612: # The user for whom we cache
 5613: my $cachedkey='';
 5614: # The cached times for this user
 5615: my %cachedtimes=();
 5616: # When this was last done
 5617: my $cachedtime='';
 5618: 
 5619: sub load_all_first_access {
 5620:     my ($uname,$udom,$ignorecache)=@_;
 5621:     if (($cachedkey eq $uname.':'.$udom) &&
 5622:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5623:         (!$ignorecache)) {
 5624:         return;
 5625:     }
 5626:     $cachedtime=time;
 5627:     $cachedkey=$uname.':'.$udom;
 5628:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5629: }
 5630: 
 5631: sub get_first_access {
 5632:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5633:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5634:     if ($argsymb) { $symb=$argsymb; }
 5635:     my ($map,$id,$res)=&decode_symb($symb);
 5636:     if ($argmap) { $map = $argmap; }
 5637:     if ($type eq 'course') {
 5638: 	$res='course';
 5639:     } elsif ($type eq 'map') {
 5640: 	$res=&symbread($map);
 5641:     } else {
 5642: 	$res=$symb;
 5643:     }
 5644:     &load_all_first_access($uname,$udom,$ignorecache);
 5645:     return $cachedtimes{"$courseid\0$res"};
 5646: }
 5647: 
 5648: sub set_first_access {
 5649:     my ($type,$interval)=@_;
 5650:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5651:     my ($map,$id,$res)=&decode_symb($symb);
 5652:     if ($type eq 'course') {
 5653: 	$res='course';
 5654:     } elsif ($type eq 'map') {
 5655: 	$res=&symbread($map);
 5656:     } else {
 5657: 	$res=$symb;
 5658:     }
 5659:     $cachedkey='';
 5660:     my $firstaccess=&get_first_access($type,$symb,$map);
 5661:     if ($firstaccess) {
 5662:         &logthis("First access time already set ($firstaccess) when attempting ".
 5663:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5664:                  "in $courseid");
 5665:         return 'already_set';
 5666:     } else {
 5667:         my $start = time;
 5668: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5669:                           $udom,$uname);
 5670:         if ($putres eq 'ok') {
 5671:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5672:                  $udom,$uname); 
 5673:             &appenv(
 5674:                      {
 5675:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5676:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5677:                      }
 5678:                   );
 5679:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5680:                 $cachedtimes{"$courseid\0$res"} = $start;
 5681:             }
 5682:         } elsif ($putres ne 'refused') {
 5683:             &logthis("Result: $putres when attempting to set first access time ".
 5684:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5685:         }
 5686:         return $putres;
 5687:     }
 5688:     return 'already_set';
 5689: }
 5690: }
 5691: 
 5692: # --------------------------------------------- Set Expire Date for Spreadsheet
 5693: 
 5694: sub expirespread {
 5695:     my ($uname,$udom,$stype,$usymb)=@_;
 5696:     my $cid=$env{'request.course.id'}; 
 5697:     if ($cid) {
 5698:        my $now=time;
 5699:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5700:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5701:                             $env{'course.'.$cid.'.num'}.
 5702: 	        	    ':nohist_expirationdates:'.
 5703:                             &escape($key).'='.$now,
 5704:                             $env{'course.'.$cid.'.home'})
 5705:     }
 5706:     return 'ok';
 5707: }
 5708: 
 5709: # ----------------------------------------------------- Devalidate Spreadsheets
 5710: 
 5711: sub devalidate {
 5712:     my ($symb,$uname,$udom)=@_;
 5713:     my $cid=$env{'request.course.id'}; 
 5714:     if ($cid) {
 5715:         # delete the stored spreadsheets for
 5716:         # - the student level sheet of this user in course's homespace
 5717:         # - the assessment level sheet for this resource 
 5718:         #   for this user in user's homespace
 5719: 	# - current conditional state info
 5720: 	my $key=$uname.':'.$udom.':';
 5721:         my $status=
 5722: 	    &del('nohist_calculatedsheets',
 5723: 		 [$key.'studentcalc:'],
 5724: 		 $env{'course.'.$cid.'.domain'},
 5725: 		 $env{'course.'.$cid.'.num'})
 5726: 		.' '.
 5727: 	    &del('nohist_calculatedsheets_'.$cid,
 5728: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5729:         unless ($status eq 'ok ok') {
 5730:            &logthis('Could not devalidate spreadsheet '.
 5731:                     $uname.' at '.$udom.' for '.
 5732: 		    $symb.': '.$status);
 5733:         }
 5734: 	&delenv('user.state.'.$cid);
 5735:     }
 5736: }
 5737: 
 5738: sub get_scalar {
 5739:     my ($string,$end) = @_;
 5740:     my $value;
 5741:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5742: 	$value = $1;
 5743:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5744: 	$value = $1;
 5745:     }
 5746:     return &unescape($value);
 5747: }
 5748: 
 5749: sub array2str {
 5750:   my (@array) = @_;
 5751:   my $result=&arrayref2str(\@array);
 5752:   $result=~s/^__ARRAY_REF__//;
 5753:   $result=~s/__END_ARRAY_REF__$//;
 5754:   return $result;
 5755: }
 5756: 
 5757: sub arrayref2str {
 5758:   my ($arrayref) = @_;
 5759:   my $result='__ARRAY_REF__';
 5760:   foreach my $elem (@$arrayref) {
 5761:     if(ref($elem) eq 'ARRAY') {
 5762:       $result.=&arrayref2str($elem).'&';
 5763:     } elsif(ref($elem) eq 'HASH') {
 5764:       $result.=&hashref2str($elem).'&';
 5765:     } elsif(ref($elem)) {
 5766:       #print("Got a ref of ".(ref($elem))." skipping.");
 5767:     } else {
 5768:       $result.=&escape($elem).'&';
 5769:     }
 5770:   }
 5771:   $result=~s/\&$//;
 5772:   $result .= '__END_ARRAY_REF__';
 5773:   return $result;
 5774: }
 5775: 
 5776: sub hash2str {
 5777:   my (%hash) = @_;
 5778:   my $result=&hashref2str(\%hash);
 5779:   $result=~s/^__HASH_REF__//;
 5780:   $result=~s/__END_HASH_REF__$//;
 5781:   return $result;
 5782: }
 5783: 
 5784: sub hashref2str {
 5785:   my ($hashref)=@_;
 5786:   my $result='__HASH_REF__';
 5787:   foreach my $key (sort(keys(%$hashref))) {
 5788:     if (ref($key) eq 'ARRAY') {
 5789:       $result.=&arrayref2str($key).'=';
 5790:     } elsif (ref($key) eq 'HASH') {
 5791:       $result.=&hashref2str($key).'=';
 5792:     } elsif (ref($key)) {
 5793:       $result.='=';
 5794:       #print("Got a ref of ".(ref($key))." skipping.");
 5795:     } else {
 5796: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5797:     }
 5798: 
 5799:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5800:       $result.=&arrayref2str($hashref->{$key}).'&';
 5801:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5802:       $result.=&hashref2str($hashref->{$key}).'&';
 5803:     } elsif(ref($hashref->{$key})) {
 5804:        $result.='&';
 5805:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5806:     } else {
 5807:       $result.=&escape($hashref->{$key}).'&';
 5808:     }
 5809:   }
 5810:   $result=~s/\&$//;
 5811:   $result .= '__END_HASH_REF__';
 5812:   return $result;
 5813: }
 5814: 
 5815: sub str2hash {
 5816:     my ($string)=@_;
 5817:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5818:     return %$hash;
 5819: }
 5820: 
 5821: sub str2hashref {
 5822:   my ($string) = @_;
 5823: 
 5824:   my %hash;
 5825: 
 5826:   if($string !~ /^__HASH_REF__/) {
 5827:       if (! ($string eq '' || !defined($string))) {
 5828: 	  $hash{'error'}='Not hash reference';
 5829:       }
 5830:       return (\%hash, $string);
 5831:   }
 5832: 
 5833:   $string =~ s/^__HASH_REF__//;
 5834: 
 5835:   while($string !~ /^__END_HASH_REF__/) {
 5836:       #key
 5837:       my $key='';
 5838:       if($string =~ /^__HASH_REF__/) {
 5839:           ($key, $string)=&str2hashref($string);
 5840:           if(defined($key->{'error'})) {
 5841:               $hash{'error'}='Bad data';
 5842:               return (\%hash, $string);
 5843:           }
 5844:       } elsif($string =~ /^__ARRAY_REF__/) {
 5845:           ($key, $string)=&str2arrayref($string);
 5846:           if($key->[0] eq 'Array reference error') {
 5847:               $hash{'error'}='Bad data';
 5848:               return (\%hash, $string);
 5849:           }
 5850:       } else {
 5851:           $string =~ s/^(.*?)=//;
 5852: 	  $key=&unescape($1);
 5853:       }
 5854:       $string =~ s/^=//;
 5855: 
 5856:       #value
 5857:       my $value='';
 5858:       if($string =~ /^__HASH_REF__/) {
 5859:           ($value, $string)=&str2hashref($string);
 5860:           if(defined($value->{'error'})) {
 5861:               $hash{'error'}='Bad data';
 5862:               return (\%hash, $string);
 5863:           }
 5864:       } elsif($string =~ /^__ARRAY_REF__/) {
 5865:           ($value, $string)=&str2arrayref($string);
 5866:           if($value->[0] eq 'Array reference error') {
 5867:               $hash{'error'}='Bad data';
 5868:               return (\%hash, $string);
 5869:           }
 5870:       } else {
 5871: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5872:       }
 5873:       $string =~ s/^&//;
 5874: 
 5875:       $hash{$key}=$value;
 5876:   }
 5877: 
 5878:   $string =~ s/^__END_HASH_REF__//;
 5879: 
 5880:   return (\%hash, $string);
 5881: }
 5882: 
 5883: sub str2array {
 5884:     my ($string)=@_;
 5885:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5886:     return @$array;
 5887: }
 5888: 
 5889: sub str2arrayref {
 5890:   my ($string) = @_;
 5891:   my @array;
 5892: 
 5893:   if($string !~ /^__ARRAY_REF__/) {
 5894:       if (! ($string eq '' || !defined($string))) {
 5895: 	  $array[0]='Array reference error';
 5896:       }
 5897:       return (\@array, $string);
 5898:   }
 5899: 
 5900:   $string =~ s/^__ARRAY_REF__//;
 5901: 
 5902:   while($string !~ /^__END_ARRAY_REF__/) {
 5903:       my $value='';
 5904:       if($string =~ /^__HASH_REF__/) {
 5905:           ($value, $string)=&str2hashref($string);
 5906:           if(defined($value->{'error'})) {
 5907:               $array[0] ='Array reference error';
 5908:               return (\@array, $string);
 5909:           }
 5910:       } elsif($string =~ /^__ARRAY_REF__/) {
 5911:           ($value, $string)=&str2arrayref($string);
 5912:           if($value->[0] eq 'Array reference error') {
 5913:               $array[0] ='Array reference error';
 5914:               return (\@array, $string);
 5915:           }
 5916:       } else {
 5917: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5918:       }
 5919:       $string =~ s/^&//;
 5920: 
 5921:       push(@array, $value);
 5922:   }
 5923: 
 5924:   $string =~ s/^__END_ARRAY_REF__//;
 5925: 
 5926:   return (\@array, $string);
 5927: }
 5928: 
 5929: # -------------------------------------------------------------------Temp Store
 5930: 
 5931: sub tmpreset {
 5932:   my ($symb,$namespace,$domain,$stuname) = @_;
 5933:   if (!$symb) {
 5934:     $symb=&symbread();
 5935:     if (!$symb) { $symb= $env{'request.url'}; }
 5936:   }
 5937:   $symb=escape($symb);
 5938: 
 5939:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5940:   $namespace=~s/\//\_/g;
 5941:   $namespace=~s/\W//g;
 5942: 
 5943:   if (!$domain) { $domain=$env{'user.domain'}; }
 5944:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5945:   if ($domain eq 'public' && $stuname eq 'public') {
 5946:       $stuname=$ENV{'REMOTE_ADDR'};
 5947:   }
 5948:   my $path=LONCAPA::tempdir();
 5949:   my %hash;
 5950:   if (tie(%hash,'GDBM_File',
 5951: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5952: 	  &GDBM_WRCREAT(),0640)) {
 5953:     foreach my $key (keys(%hash)) {
 5954:       if ($key=~ /:$symb/) {
 5955: 	delete($hash{$key});
 5956:       }
 5957:     }
 5958:   }
 5959: }
 5960: 
 5961: sub tmpstore {
 5962:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5963: 
 5964:   if (!$symb) {
 5965:     $symb=&symbread();
 5966:     if (!$symb) { $symb= $env{'request.url'}; }
 5967:   }
 5968:   $symb=escape($symb);
 5969: 
 5970:   if (!$namespace) {
 5971:     # I don't think we would ever want to store this for a course.
 5972:     # it seems this will only be used if we don't have a course.
 5973:     #$namespace=$env{'request.course.id'};
 5974:     #if (!$namespace) {
 5975:       $namespace=$env{'request.state'};
 5976:     #}
 5977:   }
 5978:   $namespace=~s/\//\_/g;
 5979:   $namespace=~s/\W//g;
 5980:   if (!$domain) { $domain=$env{'user.domain'}; }
 5981:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5982:   if ($domain eq 'public' && $stuname eq 'public') {
 5983:       $stuname=$ENV{'REMOTE_ADDR'};
 5984:   }
 5985:   my $now=time;
 5986:   my %hash;
 5987:   my $path=LONCAPA::tempdir();
 5988:   if (tie(%hash,'GDBM_File',
 5989: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5990: 	  &GDBM_WRCREAT(),0640)) {
 5991:     $hash{"version:$symb"}++;
 5992:     my $version=$hash{"version:$symb"};
 5993:     my $allkeys=''; 
 5994:     foreach my $key (keys(%$storehash)) {
 5995:       $allkeys.=$key.':';
 5996:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5997:     }
 5998:     $hash{"$version:$symb:timestamp"}=$now;
 5999:     $allkeys.='timestamp';
 6000:     $hash{"$version:keys:$symb"}=$allkeys;
 6001:     if (untie(%hash)) {
 6002:       return 'ok';
 6003:     } else {
 6004:       return "error:$!";
 6005:     }
 6006:   } else {
 6007:     return "error:$!";
 6008:   }
 6009: }
 6010: 
 6011: # -----------------------------------------------------------------Temp Restore
 6012: 
 6013: sub tmprestore {
 6014:   my ($symb,$namespace,$domain,$stuname) = @_;
 6015: 
 6016:   if (!$symb) {
 6017:     $symb=&symbread();
 6018:     if (!$symb) { $symb= $env{'request.url'}; }
 6019:   }
 6020:   $symb=escape($symb);
 6021: 
 6022:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6023: 
 6024:   if (!$domain) { $domain=$env{'user.domain'}; }
 6025:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6026:   if ($domain eq 'public' && $stuname eq 'public') {
 6027:       $stuname=$ENV{'REMOTE_ADDR'};
 6028:   }
 6029:   my %returnhash;
 6030:   $namespace=~s/\//\_/g;
 6031:   $namespace=~s/\W//g;
 6032:   my %hash;
 6033:   my $path=LONCAPA::tempdir();
 6034:   if (tie(%hash,'GDBM_File',
 6035: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6036: 	  &GDBM_READER(),0640)) {
 6037:     my $version=$hash{"version:$symb"};
 6038:     $returnhash{'version'}=$version;
 6039:     my $scope;
 6040:     for ($scope=1;$scope<=$version;$scope++) {
 6041:       my $vkeys=$hash{"$scope:keys:$symb"};
 6042:       my @keys=split(/:/,$vkeys);
 6043:       my $key;
 6044:       $returnhash{"$scope:keys"}=$vkeys;
 6045:       foreach $key (@keys) {
 6046: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6047: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6048:       }
 6049:     }
 6050:     if (!(untie(%hash))) {
 6051:       return "error:$!";
 6052:     }
 6053:   } else {
 6054:     return "error:$!";
 6055:   }
 6056:   return %returnhash;
 6057: }
 6058: 
 6059: # ----------------------------------------------------------------------- Store
 6060: 
 6061: sub store {
 6062:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6063:     my $home='';
 6064: 
 6065:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6066: 
 6067:     $symb=&symbclean($symb);
 6068:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6069: 
 6070:     if (!$domain) { $domain=$env{'user.domain'}; }
 6071:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6072: 
 6073:     &devalidate($symb,$stuname,$domain);
 6074: 
 6075:     $symb=escape($symb);
 6076:     if (!$namespace) { 
 6077:        unless ($namespace=$env{'request.course.id'}) { 
 6078:           return ''; 
 6079:        } 
 6080:     }
 6081:     if (!$home) { $home=$env{'user.home'}; }
 6082: 
 6083:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6084:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6085: 
 6086:     my $namevalue='';
 6087:     foreach my $key (keys(%$storehash)) {
 6088:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6089:     }
 6090:     $namevalue=~s/\&$//;
 6091:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6092:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6093: }
 6094: 
 6095: # -------------------------------------------------------------- Critical Store
 6096: 
 6097: sub cstore {
 6098:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6099:     my $home='';
 6100: 
 6101:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6102: 
 6103:     $symb=&symbclean($symb);
 6104:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6105: 
 6106:     if (!$domain) { $domain=$env{'user.domain'}; }
 6107:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6108: 
 6109:     &devalidate($symb,$stuname,$domain);
 6110: 
 6111:     $symb=escape($symb);
 6112:     if (!$namespace) { 
 6113:        unless ($namespace=$env{'request.course.id'}) { 
 6114:           return ''; 
 6115:        } 
 6116:     }
 6117:     if (!$home) { $home=$env{'user.home'}; }
 6118: 
 6119:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6120:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6121: 
 6122:     my $namevalue='';
 6123:     foreach my $key (keys(%$storehash)) {
 6124:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6125:     }
 6126:     $namevalue=~s/\&$//;
 6127:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6128:     return critical
 6129:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6130: }
 6131: 
 6132: # --------------------------------------------------------------------- Restore
 6133: 
 6134: sub restore {
 6135:     my ($symb,$namespace,$domain,$stuname) = @_;
 6136:     my $home='';
 6137: 
 6138:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6139: 
 6140:     if (!$symb) {
 6141:         return if ($namespace eq 'courserequests');
 6142:         unless ($symb=escape(&symbread())) { return ''; }
 6143:     } else {
 6144:         unless ($namespace eq 'courserequests') {
 6145:             $symb=&escape(&symbclean($symb));
 6146:         }
 6147:     }
 6148:     if (!$namespace) { 
 6149:        unless ($namespace=$env{'request.course.id'}) { 
 6150:           return ''; 
 6151:        } 
 6152:     }
 6153:     if (!$domain) { $domain=$env{'user.domain'}; }
 6154:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6155:     if (!$home) { $home=$env{'user.home'}; }
 6156:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6157: 
 6158:     my %returnhash=();
 6159:     foreach my $line (split(/\&/,$answer)) {
 6160: 	my ($name,$value)=split(/\=/,$line);
 6161:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6162:     }
 6163:     my $version;
 6164:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6165:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6166:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6167:        }
 6168:     }
 6169:     return %returnhash;
 6170: }
 6171: 
 6172: # ---------------------------------------------------------- Course Description
 6173: #
 6174: #  
 6175: 
 6176: sub coursedescription {
 6177:     my ($courseid,$args)=@_;
 6178:     $courseid=~s/^\///;
 6179:     $courseid=~s/\_/\//g;
 6180:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6181:     my $chome=&homeserver($cnum,$cdomain);
 6182:     my $normalid=$cdomain.'_'.$cnum;
 6183:     # need to always cache even if we get errors otherwise we keep 
 6184:     # trying and trying and trying to get the course description.
 6185:     my %envhash=();
 6186:     my %returnhash=();
 6187:     
 6188:     my $expiretime=600;
 6189:     if ($env{'request.course.id'} eq $normalid) {
 6190: 	$expiretime=120;
 6191:     }
 6192: 
 6193:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6194:     if (!$args->{'freshen_cache'}
 6195: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6196: 	foreach my $key (keys(%env)) {
 6197: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6198: 	    my ($setting) = $1;
 6199: 	    $returnhash{$setting} = $env{$key};
 6200: 	}
 6201: 	return %returnhash;
 6202:     }
 6203: 
 6204:     # get the data again
 6205: 
 6206:     if (!$args->{'one_time'}) {
 6207: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6208:     }
 6209: 
 6210:     if ($chome ne 'no_host') {
 6211:        %returnhash=&dump('environment',$cdomain,$cnum);
 6212:        if (!exists($returnhash{'con_lost'})) {
 6213: 	   my $username = $env{'user.name'}; # Defult username
 6214: 	   if(defined $args->{'user'}) {
 6215: 	       $username = $args->{'user'};
 6216: 	   }
 6217:            $returnhash{'home'}= $chome;
 6218: 	   $returnhash{'domain'} = $cdomain;
 6219: 	   $returnhash{'num'} = $cnum;
 6220:            if (!defined($returnhash{'type'})) {
 6221:                $returnhash{'type'} = 'Course';
 6222:            }
 6223:            while (my ($name,$value) = each %returnhash) {
 6224:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6225:            }
 6226:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6227:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6228: 	       $username.'_'.$cdomain.'_'.$cnum;
 6229:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6230:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6231:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6232:        }
 6233:     }
 6234:     if (!$args->{'one_time'}) {
 6235: 	&appenv(\%envhash);
 6236:     }
 6237:     return %returnhash;
 6238: }
 6239: 
 6240: sub update_released_required {
 6241:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6242:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6243:         $cid = $env{'request.course.id'};
 6244:         $cdom = $env{'course.'.$cid.'.domain'};
 6245:         $cnum = $env{'course.'.$cid.'.num'};
 6246:         $chome = $env{'course.'.$cid.'.home'};
 6247:     }
 6248:     if ($needsrelease) {
 6249:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6250:         my $needsupdate;
 6251:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6252:             $needsupdate = 1;
 6253:         } else {
 6254:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6255:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6256:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6257:                 $needsupdate = 1;
 6258:             }
 6259:         }
 6260:         if ($needsupdate) {
 6261:             my %needshash = (
 6262:                              'internal.releaserequired' => $needsrelease,
 6263:                             );
 6264:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6265:             if ($putresult eq 'ok') {
 6266:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6267:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6268:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6269:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6270:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6271:                 }
 6272:             }
 6273:         }
 6274:     }
 6275:     return;
 6276: }
 6277: 
 6278: # -------------------------------------------------See if a user is privileged
 6279: 
 6280: sub privileged {
 6281:     my ($username,$domain,$possdomains,$possroles)=@_;
 6282:     my $now = time;
 6283:     my $roles;
 6284:     if (ref($possroles) eq 'ARRAY') {
 6285:         $roles = $possroles; 
 6286:     } else {
 6287:         $roles = ['dc','su'];
 6288:     }
 6289:     if (ref($possdomains) eq 'ARRAY') {
 6290:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6291:         foreach my $dom (@{$possdomains}) {
 6292:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6293:                 (ref($privileged{$dom}) eq 'HASH')) {
 6294:                 foreach my $role (@{$roles}) {
 6295:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6296:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6297:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6298:                             return 1 unless (($end && $end < $now) ||
 6299:                                              ($start && $start > $now));
 6300:                         }
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     } else {
 6306:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6307:         my $now = time;
 6308: 
 6309:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6310:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6311:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6312:                 return 1 unless ($tend && $tend < $now) 
 6313:                         or ($tstart && $tstart > $now);
 6314:             }
 6315:         }
 6316:     }
 6317:     return 0;
 6318: }
 6319: 
 6320: sub privileged_by_domain {
 6321:     my ($domains,$roles) = @_;
 6322:     my %privileged = ();
 6323:     my $cachetime = 60*60*24;
 6324:     my $now = time;
 6325:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6326:         return %privileged;
 6327:     }
 6328:     foreach my $dom (@{$domains}) {
 6329:         next if (ref($privileged{$dom}) eq 'HASH');
 6330:         my $needroles;
 6331:         foreach my $role (@{$roles}) {
 6332:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6333:             if (defined($cached)) {
 6334:                 if (ref($result) eq 'HASH') {
 6335:                     $privileged{$dom}{$role} = $result;
 6336:                 }
 6337:             } else {
 6338:                 $needroles = 1;
 6339:             }
 6340:         }
 6341:         if ($needroles) {
 6342:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6343:             $privileged{$dom} = {};
 6344:             foreach my $server (keys(%dompersonnel)) {
 6345:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6346:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6347:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6348:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6349:                         next if ($end && $end < $now);
 6350:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6351:                             $dompersonnel{$server}{$item};
 6352:                     }
 6353:                 }
 6354:             }
 6355:             if (ref($privileged{$dom}) eq 'HASH') {
 6356:                 foreach my $role (@{$roles}) {
 6357:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6358:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6359:                     } else {
 6360:                         my %hash = ();
 6361:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6362:                     }
 6363:                 }
 6364:             }
 6365:         }
 6366:     }
 6367:     return %privileged;
 6368: }
 6369: 
 6370: # -------------------------------------------------------- Get user privileges
 6371: 
 6372: sub rolesinit {
 6373:     my ($domain, $username) = @_;
 6374:     my %userroles = ('user.login.time' => time);
 6375:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6376: 
 6377:     # firstaccess and timerinterval are related to timed maps/resources. 
 6378:     # also, blocking can be triggered by an activating timer
 6379:     # it's saved in the user's %env.
 6380:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6381:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6382:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6383:         %timerintchk, %timerintenv);
 6384: 
 6385:     foreach my $key (keys(%firstaccess)) {
 6386:         my ($cid, $rest) = split(/\0/, $key);
 6387:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6388:     }
 6389: 
 6390:     foreach my $key (keys(%timerinterval)) {
 6391:         my ($cid,$rest) = split(/\0/,$key);
 6392:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6393:     }
 6394: 
 6395:     my %allroles=();
 6396:     my %allgroups=();
 6397: 
 6398:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6399:         my $role = $rolesdump{$area};
 6400:         $area =~ s/\_\w\w$//;
 6401: 
 6402:         my ($trole, $tend, $tstart, $group_privs);
 6403: 
 6404:         if ($role =~ /^cr/) {
 6405:         # Custom role, defined by a user 
 6406:         # e.g., user.role.cr/msu/smith/mynewrole
 6407:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6408:                 $trole = $1;
 6409:                 ($tend, $tstart) = split('_', $2);
 6410:             } else {
 6411:                 $trole = $role;
 6412:             }
 6413:         } elsif ($role =~ m|^gr/|) {
 6414:         # Role of member in a group, defined within a course/community
 6415:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6416:             ($trole, $tend, $tstart) = split(/_/, $role);
 6417:             next if $tstart eq '-1';
 6418:             ($trole, $group_privs) = split(/\//, $trole);
 6419:             $group_privs = &unescape($group_privs);
 6420:         } else {
 6421:         # Just a normal role, defined in roles.tab
 6422:             ($trole, $tend, $tstart) = split(/_/,$role);
 6423:         }
 6424: 
 6425:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6426:                  $username);
 6427:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6428: 
 6429:         # role expired or not available yet?
 6430:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6431:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6432: 
 6433:         next if $area eq '' or $trole eq '';
 6434: 
 6435:         my $spec = "$trole.$area";
 6436:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6437: 
 6438:         if ($trole =~ /^cr\//) {
 6439:         # Custom role, defined by a user
 6440:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6441:         } elsif ($trole eq 'gr') {
 6442:         # Role of a member in a group, defined within a course/community
 6443:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6444:             next;
 6445:         } else {
 6446:         # Normal role, defined in roles.tab
 6447:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6448:         }
 6449: 
 6450:         my $cid = $tdomain.'_'.$trest;
 6451:         unless ($firstaccchk{$cid}) {
 6452:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6453:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6454:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6455:                         $coursetimerstarts{$cid}{$item}; 
 6456:                 }
 6457:             }
 6458:             $firstaccchk{$cid} = 1;
 6459:         }
 6460:         unless ($timerintchk{$cid}) {
 6461:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6462:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6463:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6464:                        $coursetimerintervals{$cid}{$item};
 6465:                 }
 6466:             }
 6467:             $timerintchk{$cid} = 1;
 6468:         }
 6469:     }
 6470: 
 6471:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6472:                                                           \%allroles, \%allgroups);
 6473:     $env{'user.adv'} = $userroles{'user.adv'};
 6474:     $env{'user.rar'} = $userroles{'user.rar'};
 6475: 
 6476:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6477: }
 6478: 
 6479: sub set_arearole {
 6480:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6481:     unless ($nolog) {
 6482: # log the associated role with the area
 6483:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6484:     }
 6485:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6486: }
 6487: 
 6488: sub custom_roleprivs {
 6489:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6490:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6491:     my $homsvr = &homeserver($rauthor,$rdomain);
 6492:     if (&hostname($homsvr) ne '') {
 6493:         my ($rdummy,$roledef)=
 6494:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6495:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6496:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6497:             if (defined($syspriv)) {
 6498:                 if ($trest =~ /^$match_community$/) {
 6499:                     $syspriv =~ s/bre\&S//; 
 6500:                 }
 6501:                 $$allroles{'cm./'}.=':'.$syspriv;
 6502:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6503:             }
 6504:             if ($tdomain ne '') {
 6505:                 if (defined($dompriv)) {
 6506:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6507:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6508:                 }
 6509:                 if (($trest ne '') && (defined($coursepriv))) {
 6510:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6511:                         my $rolename = $1;
 6512:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6513:                     }
 6514:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6515:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6516:                 }
 6517:             }
 6518:         }
 6519:     }
 6520: }
 6521: 
 6522: sub course_adhocrole_privs {
 6523:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6524:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6525:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6526:         my (%currprivs,%storeprivs);
 6527:         foreach my $item (split(/:/,$coursepriv)) {
 6528:             my ($priv,$restrict) = split(/\&/,$item);
 6529:             $currprivs{$priv} = $restrict;
 6530:         }
 6531:         my (%possadd,%possremove,%full);
 6532:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6533:             my ($priv,$restrict)=split(/\&/,$item);
 6534:             $full{$priv} = $restrict;
 6535:         }
 6536:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6537:              next if ($item eq '');
 6538:              my ($rule,$rest) = split(/=/,$item);
 6539:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6540:              foreach my $priv (split(/:/,$rest)) {
 6541:                  if ($priv ne '') {
 6542:                      if ($rule eq 'off') {
 6543:                          $possremove{$priv} = 1;
 6544:                      } else {
 6545:                          $possadd{$priv} = 1;
 6546:                      }
 6547:                  }
 6548:              }
 6549:          }
 6550:          foreach my $priv (sort(keys(%full))) {
 6551:              if (exists($currprivs{$priv})) {
 6552:                  unless (exists($possremove{$priv})) {
 6553:                      $storeprivs{$priv} = $currprivs{$priv};
 6554:                  }
 6555:              } elsif (exists($possadd{$priv})) {
 6556:                  $storeprivs{$priv} = $full{$priv};
 6557:              }
 6558:          }
 6559:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6560:      }
 6561:      return $coursepriv;
 6562: }
 6563: 
 6564: sub group_roleprivs {
 6565:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6566:     my $access = 1;
 6567:     my $now = time;
 6568:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6569:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6570:     if ($access) {
 6571:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6572:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6573:     }
 6574: }
 6575: 
 6576: sub standard_roleprivs {
 6577:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6578:     if (defined($pr{$trole.':s'})) {
 6579:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6580:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6581:     }
 6582:     if ($tdomain ne '') {
 6583:         if (defined($pr{$trole.':d'})) {
 6584:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6585:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6586:         }
 6587:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6588:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6589:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6590:         }
 6591:     }
 6592: }
 6593: 
 6594: sub set_userprivs {
 6595:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6596:     my $author=0;
 6597:     my $adv=0;
 6598:     my $rar=0;
 6599:     my %grouproles = ();
 6600:     if (keys(%{$allgroups}) > 0) {
 6601:         my @groupkeys; 
 6602:         foreach my $role (keys(%{$allroles})) {
 6603:             push(@groupkeys,$role);
 6604:         }
 6605:         if (ref($groups_roles) eq 'HASH') {
 6606:             foreach my $key (keys(%{$groups_roles})) {
 6607:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6608:                     push(@groupkeys,$key);
 6609:                 }
 6610:             }
 6611:         }
 6612:         if (@groupkeys > 0) {
 6613:             foreach my $role (@groupkeys) {
 6614:                 my ($trole,$area,$sec,$extendedarea);
 6615:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6616:                     $trole = $1;
 6617:                     $area = $2;
 6618:                     $sec = $3;
 6619:                     $extendedarea = $area.$sec;
 6620:                     if (exists($$allgroups{$area})) {
 6621:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6622:                             my $spec = $trole.'.'.$extendedarea;
 6623:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6624:                                                 $$allgroups{$area}{$group};
 6625:                         }
 6626:                     }
 6627:                 }
 6628:             }
 6629:         }
 6630:     }
 6631:     foreach my $group (keys(%grouproles)) {
 6632:         $$allroles{$group} = $grouproles{$group};
 6633:     }
 6634:     foreach my $role (keys(%{$allroles})) {
 6635:         my %thesepriv;
 6636:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6637:         foreach my $item (split(/:/,$$allroles{$role})) {
 6638:             if ($item ne '') {
 6639:                 my ($privilege,$restrictions)=split(/&/,$item);
 6640:                 if ($restrictions eq '') {
 6641:                     $thesepriv{$privilege}='F';
 6642:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6643:                     $thesepriv{$privilege}.=$restrictions;
 6644:                 }
 6645:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6646:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6647:             }
 6648:         }
 6649:         my $thesestr='';
 6650:         foreach my $priv (sort(keys(%thesepriv))) {
 6651: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6652: 	}
 6653:         $userroles->{'user.priv.'.$role} = $thesestr;
 6654:     }
 6655:     return ($author,$adv,$rar);
 6656: }
 6657: 
 6658: sub role_status {
 6659:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6660:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6661:         my ($one,$two) = split(m{\./},$rolekey,2);
 6662:         (undef,undef,$$role) = split(/\./,$one,3);
 6663:         unless (!defined($$role) || $$role eq '') {
 6664:             $$where = '/'.$two;
 6665:             $$trolecode=$$role.'.'.$$where;
 6666:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6667:             $$tstatus='is';
 6668:             if ($$tstart && $$tstart>$update) {
 6669:                 $$tstatus='future';
 6670:                 if ($$tstart<$now) {
 6671:                     if ($$tstart && $$tstart>$refresh) {
 6672:                         if (($$where ne '') && ($$role ne '')) {
 6673:                             my (%allroles,%allgroups,$group_privs,
 6674:                                 %groups_roles,@rolecodes);
 6675:                             my %userroles = (
 6676:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6677:                             );
 6678:                             @rolecodes = ('cm'); 
 6679:                             my $spec=$$role.'.'.$$where;
 6680:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6681:                             if ($$role =~ /^cr\//) {
 6682:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6683:                                 push(@rolecodes,'cr');
 6684:                             } elsif ($$role eq 'gr') {
 6685:                                 push(@rolecodes,$$role);
 6686:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6687:                                                     $env{'user.name'});
 6688:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6689:                                 (undef,my $group_privs) = split(/\//,$trole);
 6690:                                 $group_privs = &unescape($group_privs);
 6691:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6692:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6693:                                 &get_groups_roles($tdomain,$trest,
 6694:                                                   \%course_roles,\@rolecodes,
 6695:                                                   \%groups_roles);
 6696:                             } else {
 6697:                                 push(@rolecodes,$$role);
 6698:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6699:                             }
 6700:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6701:                                                                    \%groups_roles);
 6702:                             &appenv(\%userroles,\@rolecodes);
 6703:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6704:                         }
 6705:                     }
 6706:                     $$tstatus = 'is';
 6707:                 }
 6708:             }
 6709:             if ($$tend) {
 6710:                 if ($$tend<$update) {
 6711:                     $$tstatus='expired';
 6712:                 } elsif ($$tend<$now) {
 6713:                     $$tstatus='will_not';
 6714:                 }
 6715:             }
 6716:         }
 6717:     }
 6718: }
 6719: 
 6720: sub get_groups_roles {
 6721:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6722:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6723:                   (ref($rolecodes) eq 'ARRAY') && 
 6724:                   (ref($groups_roles) eq 'HASH')); 
 6725:     if (keys(%{$cdom_courseroles}) > 0) {
 6726:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6727:         if ($cdom ne '' && $cnum ne '') {
 6728:             foreach my $key (keys(%{$cdom_courseroles})) {
 6729:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6730:                     my $crsrole = $1;
 6731:                     my $crssec = $2;
 6732:                     if ($crsrole =~ /^cr/) {
 6733:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6734:                             push(@{$rolecodes},'cr');
 6735:                         }
 6736:                     } else {
 6737:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6738:                             push(@{$rolecodes},$crsrole);
 6739:                         }
 6740:                     }
 6741:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6742:                     if ($crssec ne '') {
 6743:                         $rolekey .= "/$crssec";
 6744:                     }
 6745:                     $rolekey .= './';
 6746:                     $groups_roles->{$rolekey} = $rolecodes;
 6747:                 }
 6748:             }
 6749:         }
 6750:     }
 6751:     return;
 6752: }
 6753: 
 6754: sub delete_env_groupprivs {
 6755:     my ($where,$courseroles,$possroles) = @_;
 6756:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6757:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6758:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6759:         %{$courseroles->{$udom}} =
 6760:             &get_my_roles('','','userroles',['active'],
 6761:                           $possroles,[$udom],1);
 6762:     }
 6763:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6764:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6765:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6766:             my $area = '/'.$cdom.'/'.$cnum;
 6767:             my $privkey = "user.priv.$crsrole.$area";
 6768:             if ($crssec ne '') {
 6769:                 $privkey .= '/'.$crssec;
 6770:             }
 6771:             $privkey .= ".$area/$group";
 6772:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6773:         }
 6774:     }
 6775:     return;
 6776: }
 6777: 
 6778: sub check_adhoc_privs {
 6779:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6780:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6781:     if ($sec) {
 6782:         $cckey .= '/'.$sec;
 6783:     } 
 6784:     my $setprivs;
 6785:     if ($env{$cckey}) {
 6786:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6787:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6788:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6789:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6790:             $setprivs = 1;
 6791:         }
 6792:     } else {
 6793:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6794:         $setprivs = 1;
 6795:     }
 6796:     return $setprivs;
 6797: }
 6798: 
 6799: sub set_adhoc_privileges {
 6800: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6801:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6802:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6803:     if ($sec ne '') {
 6804:         $area .= '/'.$sec;
 6805:     }
 6806:     my $spec = $role.'.'.$area;
 6807:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6808:                                   $env{'user.name'},1);
 6809:     my %rolehash = ();
 6810:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6811:         my $rolename = $1;
 6812:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6813:         my %domdef = &get_domain_defaults($dcdom);
 6814:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6815:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6816:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6817:             }
 6818:         }
 6819:     } else {
 6820:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6821:     }
 6822:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6823:     &appenv(\%userroles,[$role,'cm']);
 6824:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6825:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6826:             ($caller eq 'tiny')) {
 6827:         &appenv( {'request.role'        => $spec,
 6828:                   'request.role.domain' => $dcdom,
 6829:                   'request.course.sec'  => $sec,
 6830:                  }
 6831:                );
 6832:         my $tadv=0;
 6833:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6834:         &appenv({'request.role.adv'    => $tadv});
 6835:     }
 6836: }
 6837: 
 6838: # --------------------------------------------------------------- get interface
 6839: 
 6840: sub get {
 6841:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6842:    my $items='';
 6843:    foreach my $item (@$storearr) {
 6844:        $items.=&escape($item).'&';
 6845:    }
 6846:    $items=~s/\&$//;
 6847:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6848:    if (!$uname) { $uname=$env{'user.name'}; }
 6849:    my $uhome=&homeserver($uname,$udomain);
 6850: 
 6851:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6852:    my @pairs=split(/\&/,$rep);
 6853:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6854:      return @pairs;
 6855:    }
 6856:    my %returnhash=();
 6857:    my $i=0;
 6858:    foreach my $item (@$storearr) {
 6859:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6860:       $i++;
 6861:    }
 6862:    return %returnhash;
 6863: }
 6864: 
 6865: # --------------------------------------------------------------- del interface
 6866: 
 6867: sub del {
 6868:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6869:    my $items='';
 6870:    foreach my $item (@$storearr) {
 6871:        $items.=&escape($item).'&';
 6872:    }
 6873: 
 6874:    $items=~s/\&$//;
 6875:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6876:    if (!$uname) { $uname=$env{'user.name'}; }
 6877:    my $uhome=&homeserver($uname,$udomain);
 6878:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6879: }
 6880: 
 6881: # -------------------------------------------------------------- dump interface
 6882: 
 6883: sub unserialize {
 6884:     my ($rep, $escapedkeys) = @_;
 6885: 
 6886:     return {} if $rep =~ /^error/;
 6887: 
 6888:     my %returnhash=();
 6889: 	foreach my $item (split(/\&/,$rep)) {
 6890: 	    my ($key, $value) = split(/=/, $item, 2);
 6891: 	    $key = unescape($key) unless $escapedkeys;
 6892: 	    next if $key =~ /^error: 2 /;
 6893: 	    $returnhash{$key} = &thaw_unescape($value);
 6894: 	}
 6895:     #return %returnhash;
 6896:     return \%returnhash;
 6897: }        
 6898: 
 6899: # see Lond::dump_with_regexp
 6900: # if $escapedkeys hash keys won't get unescaped.
 6901: sub dump {
 6902:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6904:     if (!$uname) { $uname=$env{'user.name'}; }
 6905:     my $uhome=&homeserver($uname,$udomain);
 6906: 
 6907:     if ($regexp) {
 6908:         $regexp=&escape($regexp);
 6909:     } else {
 6910:         $regexp='.';
 6911:     }
 6912:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6913:         # user is hosted on this machine
 6914:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6915:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6916:         return %{unserialize($reply, $escapedkeys)};
 6917:     }
 6918:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6919:     my @pairs=split(/\&/,$rep);
 6920:     my %returnhash=();
 6921:     if (!($rep =~ /^error/ )) {
 6922: 	foreach my $item (@pairs) {
 6923: 	    my ($key,$value)=split(/=/,$item,2);
 6924:         $key = unescape($key) unless $escapedkeys;
 6925:         #$key = &unescape($key);
 6926: 	    next if ($key =~ /^error: 2 /);
 6927: 	    $returnhash{$key}=&thaw_unescape($value);
 6928: 	}
 6929:     }
 6930:     return %returnhash;
 6931: }
 6932: 
 6933: 
 6934: # --------------------------------------------------------- dumpstore interface
 6935: 
 6936: sub dumpstore {
 6937:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6938:    # same as dump but keys must be escaped. They may contain colon separated
 6939:    # lists of values that may themself contain colons (e.g. symbs).
 6940:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6941: }
 6942: 
 6943: # -------------------------------------------------------------- keys interface
 6944: 
 6945: sub getkeys {
 6946:    my ($namespace,$udomain,$uname)=@_;
 6947:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6948:    if (!$uname) { $uname=$env{'user.name'}; }
 6949:    my $uhome=&homeserver($uname,$udomain);
 6950:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6951:    my @keyarray=();
 6952:    foreach my $key (split(/\&/,$rep)) {
 6953:       next if ($key =~ /^error: 2 /);
 6954:       push(@keyarray,&unescape($key));
 6955:    }
 6956:    return @keyarray;
 6957: }
 6958: 
 6959: # --------------------------------------------------------------- currentdump
 6960: sub currentdump {
 6961:    my ($courseid,$sdom,$sname)=@_;
 6962:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6963:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6964:    $sname    = $env{'user.name'}         if (! defined($sname));
 6965:    my $uhome = &homeserver($sname,$sdom);
 6966:    my $rep;
 6967: 
 6968:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6969:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6970:                    $courseid)));
 6971:    } else {
 6972:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6973:    }
 6974: 
 6975:    return if ($rep =~ /^(error:|no_such_host)/);
 6976:    #
 6977:    my %returnhash=();
 6978:    #
 6979:    if ($rep eq 'unknown_cmd') {
 6980:        # an old lond will not know currentdump
 6981:        # Do a dump and make it look like a currentdump
 6982:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6983:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6984:        my %hash = @tmp;
 6985:        @tmp=();
 6986:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6987:    } else {
 6988:        my @pairs=split(/\&/,$rep);
 6989:        foreach my $pair (@pairs) {
 6990:            my ($key,$value)=split(/=/,$pair,2);
 6991:            my ($symb,$param) = split(/:/,$key);
 6992:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6993:                                                         &thaw_unescape($value);
 6994:        }
 6995:    }
 6996:    return %returnhash;
 6997: }
 6998: 
 6999: sub convert_dump_to_currentdump{
 7000:     my %hash = %{shift()};
 7001:     my %returnhash;
 7002:     # Code ripped from lond, essentially.  The only difference
 7003:     # here is the unescaping done by lonnet::dump().  Conceivably
 7004:     # we might run in to problems with parameter names =~ /^v\./
 7005:     while (my ($key,$value) = each(%hash)) {
 7006:         my ($v,$symb,$param) = split(/:/,$key);
 7007: 	$symb  = &unescape($symb);
 7008: 	$param = &unescape($param);
 7009:         next if ($v eq 'version' || $symb eq 'keys');
 7010:         next if (exists($returnhash{$symb}) &&
 7011:                  exists($returnhash{$symb}->{$param}) &&
 7012:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7013:         $returnhash{$symb}->{$param}=$value;
 7014:         $returnhash{$symb}->{'v.'.$param}=$v;
 7015:     }
 7016:     #
 7017:     # Remove all of the keys in the hashes which keep track of
 7018:     # the version of the parameter.
 7019:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7020:         # use a foreach because we are going to delete from the hash.
 7021:         foreach my $key (keys(%$param_hash)) {
 7022:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7023:         }
 7024:     }
 7025:     return \%returnhash;
 7026: }
 7027: 
 7028: # ------------------------------------------------------ critical inc interface
 7029: 
 7030: sub cinc {
 7031:     return &inc(@_,'critical');
 7032: }
 7033: 
 7034: # --------------------------------------------------------------- inc interface
 7035: 
 7036: sub inc {
 7037:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7038:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7039:     if (!$uname) { $uname=$env{'user.name'}; }
 7040:     my $uhome=&homeserver($uname,$udomain);
 7041:     my $items='';
 7042:     if (! ref($store)) {
 7043:         # got a single value, so use that instead
 7044:         $items = &escape($store).'=&';
 7045:     } elsif (ref($store) eq 'SCALAR') {
 7046:         $items = &escape($$store).'=&';        
 7047:     } elsif (ref($store) eq 'ARRAY') {
 7048:         $items = join('=&',map {&escape($_);} @{$store});
 7049:     } elsif (ref($store) eq 'HASH') {
 7050:         while (my($key,$value) = each(%{$store})) {
 7051:             $items.= &escape($key).'='.&escape($value).'&';
 7052:         }
 7053:     }
 7054:     $items=~s/\&$//;
 7055:     if ($critical) {
 7056: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7057:     } else {
 7058: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7059:     }
 7060: }
 7061: 
 7062: # --------------------------------------------------------------- put interface
 7063: 
 7064: sub put {
 7065:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7067:    if (!$uname) { $uname=$env{'user.name'}; }
 7068:    my $uhome=&homeserver($uname,$udomain);
 7069:    my $items='';
 7070:    foreach my $item (keys(%$storehash)) {
 7071:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7072:    }
 7073:    $items=~s/\&$//;
 7074:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7075: }
 7076: 
 7077: # ------------------------------------------------------------ newput interface
 7078: 
 7079: sub newput {
 7080:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7081:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7082:    if (!$uname) { $uname=$env{'user.name'}; }
 7083:    my $uhome=&homeserver($uname,$udomain);
 7084:    my $items='';
 7085:    foreach my $key (keys(%$storehash)) {
 7086:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7087:    }
 7088:    $items=~s/\&$//;
 7089:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7090: }
 7091: 
 7092: # ---------------------------------------------------------  putstore interface
 7093: 
 7094: sub putstore {
 7095:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7097:    if (!$uname) { $uname=$env{'user.name'}; }
 7098:    my $uhome=&homeserver($uname,$udomain);
 7099:    my $items='';
 7100:    foreach my $key (keys(%$storehash)) {
 7101:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7102:    }
 7103:    $items=~s/\&$//;
 7104:    my $esc_symb=&escape($symb);
 7105:    my $esc_v=&escape($version);
 7106:    my $reply =
 7107:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7108: 	      $uhome);
 7109:    if (($tolog) && ($reply eq 'ok')) {
 7110:        my $namevalue='';
 7111:        foreach my $key (keys(%{$storehash})) {
 7112:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7113:        }
 7114:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7115:                      '&host='.&escape($perlvar{'lonHostID'}).
 7116:                      '&version='.$esc_v.
 7117:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7118:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7119:    }
 7120:    if ($reply eq 'unknown_cmd') {
 7121:        # gfall back to way things use to be done
 7122:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7123: 			    $uname);
 7124:    }
 7125:    return $reply;
 7126: }
 7127: 
 7128: sub old_putstore {
 7129:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7130:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7131:     if (!$uname) { $uname=$env{'user.name'}; }
 7132:     my $uhome=&homeserver($uname,$udomain);
 7133:     my %newstorehash;
 7134:     foreach my $item (keys(%$storehash)) {
 7135: 	my $key = $version.':'.&escape($symb).':'.$item;
 7136: 	$newstorehash{$key} = $storehash->{$item};
 7137:     }
 7138:     my $items='';
 7139:     my %allitems = ();
 7140:     foreach my $item (keys(%newstorehash)) {
 7141: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7142: 	    my $key = $1.':keys:'.$2;
 7143: 	    $allitems{$key} .= $3.':';
 7144: 	}
 7145: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7146:     }
 7147:     foreach my $item (keys(%allitems)) {
 7148: 	$allitems{$item} =~ s/\:$//;
 7149: 	$items.= $item.'='.$allitems{$item}.'&';
 7150:     }
 7151:     $items=~s/\&$//;
 7152:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7153: }
 7154: 
 7155: # ------------------------------------------------------ critical put interface
 7156: 
 7157: sub cput {
 7158:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7160:    if (!$uname) { $uname=$env{'user.name'}; }
 7161:    my $uhome=&homeserver($uname,$udomain);
 7162:    my $items='';
 7163:    foreach my $item (keys(%$storehash)) {
 7164:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7165:    }
 7166:    $items=~s/\&$//;
 7167:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7168: }
 7169: 
 7170: # -------------------------------------------------------------- eget interface
 7171: 
 7172: sub eget {
 7173:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7174:    my $items='';
 7175:    foreach my $item (@$storearr) {
 7176:        $items.=&escape($item).'&';
 7177:    }
 7178:    $items=~s/\&$//;
 7179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7180:    if (!$uname) { $uname=$env{'user.name'}; }
 7181:    my $uhome=&homeserver($uname,$udomain);
 7182:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7183:    my @pairs=split(/\&/,$rep);
 7184:    my %returnhash=();
 7185:    my $i=0;
 7186:    foreach my $item (@$storearr) {
 7187:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7188:       $i++;
 7189:    }
 7190:    return %returnhash;
 7191: }
 7192: 
 7193: # ------------------------------------------------------------ tmpput interface
 7194: sub tmpput {
 7195:     my ($storehash,$server,$context)=@_;
 7196:     my $items='';
 7197:     foreach my $item (keys(%$storehash)) {
 7198: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7199:     }
 7200:     $items=~s/\&$//;
 7201:     if (defined($context)) {
 7202:         $items .= ':'.&escape($context);
 7203:     }
 7204:     return &reply("tmpput:$items",$server);
 7205: }
 7206: 
 7207: # ------------------------------------------------------------ tmpget interface
 7208: sub tmpget {
 7209:     my ($token,$server)=@_;
 7210:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7211:     my $rep=&reply("tmpget:$token",$server);
 7212:     my %returnhash;
 7213:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7214:         return %returnhash;
 7215:     }
 7216:     foreach my $item (split(/\&/,$rep)) {
 7217: 	my ($key,$value)=split(/=/,$item);
 7218: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7219:     }
 7220:     return %returnhash;
 7221: }
 7222: 
 7223: # ------------------------------------------------------------ tmpdel interface
 7224: sub tmpdel {
 7225:     my ($token,$server)=@_;
 7226:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7227:     return &reply("tmpdel:$token",$server);
 7228: }
 7229: 
 7230: # ------------------------------------------------------------ get_timebased_id 
 7231: 
 7232: sub get_timebased_id {
 7233:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7234:         $maxtries) = @_;
 7235:     my ($newid,$error,$dellock);
 7236:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7237:         return ('','ok','invalid call to get suffix');
 7238:     }
 7239: 
 7240: # set defaults for any optional args for which values were not supplied
 7241:     if ($who eq '') {
 7242:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7243:     }
 7244:     if (!$locktries) {
 7245:         $locktries = 3;
 7246:     }
 7247:     if (!$maxtries) {
 7248:         $maxtries = 10;
 7249:     }
 7250:     
 7251:     if (($cdom eq '') || ($cnum eq '')) {
 7252:         if ($env{'request.course.id'}) {
 7253:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7254:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7255:         }
 7256:         if (($cdom eq '') || ($cnum eq '')) {
 7257:             return ('','ok','call to get suffix not in course context');
 7258:         }
 7259:     }
 7260: 
 7261: # construct locking item
 7262:     my $lockhash = {
 7263:                       $prefix."\0".'locked_'.$keyid => $who,
 7264:                    };
 7265:     my $tries = 0;
 7266: 
 7267: # attempt to get lock on nohist_$namespace file
 7268:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7269:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7270:         $tries ++;
 7271:         sleep 1;
 7272:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7273:     }
 7274: 
 7275: # attempt to get unique identifier, based on current timestamp
 7276:     if ($gotlock eq 'ok') {
 7277:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7278:         my $id = time;
 7279:         $newid = $id;
 7280:         if ($idtype eq 'addcode') {
 7281:             $newid .= &sixnum_code();
 7282:         }
 7283:         my $idtries = 0;
 7284:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7285:             if ($idtype eq 'concat') {
 7286:                 $newid = $id.$idtries;
 7287:             } elsif ($idtype eq 'addcode') {
 7288:                 $newid = $newid.&sixnum_code();
 7289:             } else {
 7290:                 $newid ++;
 7291:             }
 7292:             $idtries ++;
 7293:         }
 7294:         if (!exists($inuse{$prefix."\0".$newid})) {
 7295:             my %new_item =  (
 7296:                               $prefix."\0".$newid => $who,
 7297:                             );
 7298:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7299:                                                  $cdom,$cnum);
 7300:             if ($putresult ne 'ok') {
 7301:                 undef($newid);
 7302:                 $error = 'error saving new item: '.$putresult;
 7303:             }
 7304:         } else {
 7305:              undef($newid);
 7306:              $error = ('error: no unique suffix available for the new item ');
 7307:         }
 7308: #  remove lock
 7309:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7310:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7311:     } else {
 7312:         $error = "error: could not obtain lockfile\n";
 7313:         $dellock = 'ok';
 7314:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7315:             $dellock = 'nolock';
 7316:         }
 7317:     }
 7318:     return ($newid,$dellock,$error);
 7319: }
 7320: 
 7321: sub sixnum_code {
 7322:     my $code;
 7323:     for (0..6) {
 7324:         $code .= int( rand(9) );
 7325:     }
 7326:     return $code;
 7327: }
 7328: 
 7329: # -------------------------------------------------- portfolio access checking
 7330: 
 7331: sub portfolio_access {
 7332:     my ($requrl,$clientip) = @_;
 7333:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7334:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7335:     if ($result) {
 7336:         my %setters;
 7337:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7338:             my ($startblock,$endblock) =
 7339:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7340:             if ($startblock && $endblock) {
 7341:                 return 'B';
 7342:             }
 7343:         } else {
 7344:             my ($startblock,$endblock) =
 7345:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7346:             if ($startblock && $endblock) {
 7347:                 return 'B';
 7348:             }
 7349:         }
 7350:     }
 7351:     if ($result eq 'ok') {
 7352:        return 'F';
 7353:     } elsif ($result =~ /^[^:]+:guest_/) {
 7354:        return 'A';
 7355:     }
 7356:     return '';
 7357: }
 7358: 
 7359: sub get_portfolio_access {
 7360:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7361: 
 7362:     if (!ref($access_hash)) {
 7363: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7364: 	my %access_controls = &get_access_controls($current_perms,$group,
 7365: 						   $file_name);
 7366: 	$access_hash = $access_controls{$file_name};
 7367:     }
 7368: 
 7369:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7370:     my $now = time;
 7371:     if (ref($access_hash) eq 'HASH') {
 7372:         foreach my $key (keys(%{$access_hash})) {
 7373:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7374:             if ($start > $now) {
 7375:                 next;
 7376:             }
 7377:             if ($end && $end<$now) {
 7378:                 next;
 7379:             }
 7380:             if ($scope eq 'public') {
 7381:                 $public = $key;
 7382:                 last;
 7383:             } elsif ($scope eq 'guest') {
 7384:                 $guest = $key;
 7385:             } elsif ($scope eq 'domains') {
 7386:                 push(@domains,$key);
 7387:             } elsif ($scope eq 'users') {
 7388:                 push(@users,$key);
 7389:             } elsif ($scope eq 'course') {
 7390:                 push(@courses,$key);
 7391:             } elsif ($scope eq 'group') {
 7392:                 push(@groups,$key);
 7393:             } elsif ($scope eq 'ip') {
 7394:                 push(@ips,$key);
 7395:             }
 7396:         }
 7397:         if ($public) {
 7398:             return 'ok';
 7399:         } elsif (@ips > 0) {
 7400:             my $allowed;
 7401:             foreach my $ipkey (@ips) {
 7402:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7403:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7404:                         $allowed = 1;
 7405:                         last; 
 7406:                     }
 7407:                 }
 7408:             }
 7409:             if ($allowed) {
 7410:                 return 'ok';
 7411:             }
 7412:         }
 7413:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7414:             if ($guest) {
 7415:                 return $guest;
 7416:             }
 7417:         } else {
 7418:             if (@domains > 0) {
 7419:                 foreach my $domkey (@domains) {
 7420:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7421:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7422:                             return 'ok';
 7423:                         }
 7424:                     }
 7425:                 }
 7426:             }
 7427:             if (@users > 0) {
 7428:                 foreach my $userkey (@users) {
 7429:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7430:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7431:                             if (ref($item) eq 'HASH') {
 7432:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7433:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7434:                                     return 'ok';
 7435:                                 }
 7436:                             }
 7437:                         }
 7438:                     } 
 7439:                 }
 7440:             }
 7441:             my %roleshash;
 7442:             my @courses_and_groups = @courses;
 7443:             push(@courses_and_groups,@groups); 
 7444:             if (@courses_and_groups > 0) {
 7445:                 my (%allgroups,%allroles); 
 7446:                 my ($start,$end,$role,$sec,$group);
 7447:                 foreach my $envkey (%env) {
 7448:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7449:                         my $cid = $2.'_'.$3; 
 7450:                         if ($1 eq 'gr') {
 7451:                             $group = $4;
 7452:                             $allgroups{$cid}{$group} = $env{$envkey};
 7453:                         } else {
 7454:                             if ($4 eq '') {
 7455:                                 $sec = 'none';
 7456:                             } else {
 7457:                                 $sec = $4;
 7458:                             }
 7459:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7460:                         }
 7461:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7462:                         my $cid = $2.'_'.$3;
 7463:                         if ($4 eq '') {
 7464:                             $sec = 'none';
 7465:                         } else {
 7466:                             $sec = $4;
 7467:                         }
 7468:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7469:                     }
 7470:                 }
 7471:                 if (keys(%allroles) == 0) {
 7472:                     return;
 7473:                 }
 7474:                 foreach my $key (@courses_and_groups) {
 7475:                     my %content = %{$$access_hash{$key}};
 7476:                     my $cnum = $content{'number'};
 7477:                     my $cdom = $content{'domain'};
 7478:                     my $cid = $cdom.'_'.$cnum;
 7479:                     if (!exists($allroles{$cid})) {
 7480:                         next;
 7481:                     }    
 7482:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7483:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7484:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7485:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7486:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7487:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7488:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7489:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7490:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7491:                                         if (grep/^all$/,@sections) {
 7492:                                             return 'ok';
 7493:                                         } else {
 7494:                                             if (grep/^$sec$/,@sections) {
 7495:                                                 return 'ok';
 7496:                                             }
 7497:                                         }
 7498:                                     }
 7499:                                 }
 7500:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7501:                                     if (grep/^none$/,@groups) {
 7502:                                         return 'ok';
 7503:                                     }
 7504:                                 } else {
 7505:                                     if (grep/^all$/,@groups) {
 7506:                                         return 'ok';
 7507:                                     } 
 7508:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7509:                                         if (grep/^$group$/,@groups) {
 7510:                                             return 'ok';
 7511:                                         }
 7512:                                     }
 7513:                                 } 
 7514:                             }
 7515:                         }
 7516:                     }
 7517:                 }
 7518:             }
 7519:             if ($guest) {
 7520:                 return $guest;
 7521:             }
 7522:         }
 7523:     }
 7524:     return;
 7525: }
 7526: 
 7527: sub course_group_datechecker {
 7528:     my ($dates,$now,$status) = @_;
 7529:     my ($start,$end) = split(/\./,$dates);
 7530:     if (!$start && !$end) {
 7531:         return 'ok';
 7532:     }
 7533:     if (grep/^active$/,@{$status}) {
 7534:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7535:             return 'ok';
 7536:         }
 7537:     }
 7538:     if (grep/^previous$/,@{$status}) {
 7539:         if ($end > $now ) {
 7540:             return 'ok';
 7541:         }
 7542:     }
 7543:     if (grep/^future$/,@{$status}) {
 7544:         if ($start > $now) {
 7545:             return 'ok';
 7546:         }
 7547:     }
 7548:     return; 
 7549: }
 7550: 
 7551: sub parse_portfolio_url {
 7552:     my ($url) = @_;
 7553: 
 7554:     my ($type,$udom,$unum,$group,$file_name);
 7555:     
 7556:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7557: 	$type = 1;
 7558:         $udom = $1;
 7559:         $unum = $2;
 7560:         $file_name = $3;
 7561:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7562: 	$type = 2;
 7563:         $udom = $1;
 7564:         $unum = $2;
 7565:         $group = $3;
 7566:         $file_name = $3.'/'.$4;
 7567:     }
 7568:     if (wantarray) {
 7569: 	return ($type,$udom,$unum,$file_name,$group);
 7570:     }
 7571:     return $type;
 7572: }
 7573: 
 7574: sub is_portfolio_url {
 7575:     my ($url) = @_;
 7576:     return scalar(&parse_portfolio_url($url));
 7577: }
 7578: 
 7579: sub is_portfolio_file {
 7580:     my ($file) = @_;
 7581:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7582:         return 1;
 7583:     }
 7584:     return;
 7585: }
 7586: 
 7587: sub usertools_access {
 7588:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7589:     my ($access,%tools);
 7590:     if ($context eq '') {
 7591:         $context = 'tools';
 7592:     }
 7593:     if ($context eq 'requestcourses') {
 7594:         %tools = (
 7595:                       official   => 1,
 7596:                       unofficial => 1,
 7597:                       community  => 1,
 7598:                       textbook   => 1,
 7599:                       placement  => 1,
 7600:                       lti        => 1,
 7601:                  );
 7602:     } elsif ($context eq 'requestauthor') {
 7603:         %tools = (
 7604:                       requestauthor => 1,
 7605:                  );
 7606:     } else {
 7607:         %tools = (
 7608:                       aboutme   => 1,
 7609:                       blog      => 1,
 7610:                       webdav    => 1,
 7611:                       portfolio => 1,
 7612:                  );
 7613:     }
 7614:     return if (!defined($tools{$tool}));
 7615: 
 7616:     if (($udom eq '') || ($uname eq '')) {
 7617:         $udom = $env{'user.domain'};
 7618:         $uname = $env{'user.name'};
 7619:     }
 7620: 
 7621:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7622:         if ($action ne 'reload') {
 7623:             if ($context eq 'requestcourses') {
 7624:                 return $env{'environment.canrequest.'.$tool};
 7625:             } elsif ($context eq 'requestauthor') {
 7626:                 return $env{'environment.canrequest.author'};
 7627:             } else {
 7628:                 return $env{'environment.availabletools.'.$tool};
 7629:             }
 7630:         }
 7631:     }
 7632: 
 7633:     my ($toolstatus,$inststatus,$envkey);
 7634:     if ($context eq 'requestauthor') {
 7635:         $envkey = $context; 
 7636:     } else {
 7637:         $envkey = $context.'.'.$tool;
 7638:     }
 7639: 
 7640:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7641:          ($action ne 'reload')) {
 7642:         $toolstatus = $env{'environment.'.$envkey};
 7643:         $inststatus = $env{'environment.inststatus'};
 7644:     } else {
 7645:         if (ref($userenvref) eq 'HASH') {
 7646:             $toolstatus = $userenvref->{$envkey};
 7647:             $inststatus = $userenvref->{'inststatus'};
 7648:         } else {
 7649:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7650:             $toolstatus = $userenv{$envkey};
 7651:             $inststatus = $userenv{'inststatus'};
 7652:         }
 7653:     }
 7654: 
 7655:     if ($toolstatus ne '') {
 7656:         if ($toolstatus) {
 7657:             $access = 1;
 7658:         } else {
 7659:             $access = 0;
 7660:         }
 7661:         return $access;
 7662:     }
 7663: 
 7664:     my ($is_adv,%domdef);
 7665:     if (ref($is_advref) eq 'HASH') {
 7666:         $is_adv = $is_advref->{'is_adv'};
 7667:     } else {
 7668:         $is_adv = &is_advanced_user($udom,$uname);
 7669:     }
 7670:     if (ref($domdefref) eq 'HASH') {
 7671:         %domdef = %{$domdefref};
 7672:     } else {
 7673:         %domdef = &get_domain_defaults($udom);
 7674:     }
 7675:     if (ref($domdef{$tool}) eq 'HASH') {
 7676:         if ($is_adv) {
 7677:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7678:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7679:                     $access = 1;
 7680:                 } else {
 7681:                     $access = 0;
 7682:                 }
 7683:                 return $access;
 7684:             }
 7685:         }
 7686:         if ($inststatus ne '') {
 7687:             my ($hasaccess,$hasnoaccess);
 7688:             foreach my $affiliation (split(/:/,$inststatus)) {
 7689:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7690:                     if ($domdef{$tool}{$affiliation}) {
 7691:                         $hasaccess = 1;
 7692:                     } else {
 7693:                         $hasnoaccess = 1;
 7694:                     }
 7695:                 }
 7696:             }
 7697:             if ($hasaccess || $hasnoaccess) {
 7698:                 if ($hasaccess) {
 7699:                     $access = 1;
 7700:                 } elsif ($hasnoaccess) {
 7701:                     $access = 0; 
 7702:                 }
 7703:                 return $access;
 7704:             }
 7705:         } else {
 7706:             if ($domdef{$tool}{'default'} ne '') {
 7707:                 if ($domdef{$tool}{'default'}) {
 7708:                     $access = 1;
 7709:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7710:                     $access = 0;
 7711:                 }
 7712:                 return $access;
 7713:             }
 7714:         }
 7715:     } else {
 7716:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7717:             $access = 1;
 7718:         } else {
 7719:             $access = 0;
 7720:         }
 7721:         return $access;
 7722:     }
 7723: }
 7724: 
 7725: sub is_course_owner {
 7726:     my ($cdom,$cnum,$udom,$uname) = @_;
 7727:     if (($udom eq '') || ($uname eq '')) {
 7728:         $udom = $env{'user.domain'};
 7729:         $uname = $env{'user.name'};
 7730:     }
 7731:     unless (($udom eq '') || ($uname eq '')) {
 7732:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7733:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7734:                 return 1;
 7735:             } else {
 7736:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7737:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7738:                     return 1;
 7739:                 }
 7740:             }
 7741:         }
 7742:     }
 7743:     return;
 7744: }
 7745: 
 7746: sub is_advanced_user {
 7747:     my ($udom,$uname) = @_;
 7748:     if ($udom ne '' && $uname ne '') {
 7749:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7750:             if (wantarray) {
 7751:                 return ($env{'user.adv'},$env{'user.author'});
 7752:             } else {
 7753:                 return $env{'user.adv'};
 7754:             }
 7755:         }
 7756:     }
 7757:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7758:     my %allroles;
 7759:     my ($is_adv,$is_author);
 7760:     foreach my $role (keys(%roleshash)) {
 7761:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7762:         my $area = '/'.$tdomain.'/'.$trest;
 7763:         if ($sec ne '') {
 7764:             $area .= '/'.$sec;
 7765:         }
 7766:         if (($area ne '') && ($trole ne '')) {
 7767:             my $spec=$trole.'.'.$area;
 7768:             if ($trole =~ /^cr\//) {
 7769:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7770:             } elsif ($trole ne 'gr') {
 7771:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7772:             }
 7773:             if ($trole eq 'au') {
 7774:                 $is_author = 1;
 7775:             }
 7776:         }
 7777:     }
 7778:     foreach my $role (keys(%allroles)) {
 7779:         last if ($is_adv);
 7780:         foreach my $item (split(/:/,$allroles{$role})) {
 7781:             if ($item ne '') {
 7782:                 my ($privilege,$restrictions)=split(/&/,$item);
 7783:                 if ($privilege eq 'adv') {
 7784:                     $is_adv = 1;
 7785:                     last;
 7786:                 }
 7787:             }
 7788:         }
 7789:     }
 7790:     if (wantarray) {
 7791:         return ($is_adv,$is_author);
 7792:     }
 7793:     return $is_adv;
 7794: }
 7795: 
 7796: sub check_can_request {
 7797:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7798:     my $canreq = 0;
 7799:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7800:         $uname = $env{'user.name'};
 7801:         $udom = $env{'user.domain'};
 7802:     }
 7803:     my ($types,$typename) = &Apache::loncommon::course_types();
 7804:     my @options = ('approval','validate','autolimit');
 7805:     my $optregex = join('|',@options);
 7806:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7807:         foreach my $type (@{$types}) {
 7808:             if (&usertools_access($uname,$udom,$type,undef,
 7809:                                   'requestcourses')) {
 7810:                 $canreq ++;
 7811:                 if (ref($request_domains) eq 'HASH') {
 7812:                     push(@{$request_domains->{$type}},$udom);
 7813:                 }
 7814:                 if ($dom eq $udom) {
 7815:                     $can_request->{$type} = 1;
 7816:                 }
 7817:             }
 7818:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7819:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7820:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7821:                 if (@curr > 0) {
 7822:                     foreach my $item (@curr) {
 7823:                         if (ref($request_domains) eq 'HASH') {
 7824:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7825:                             if ($otherdom ne '') {
 7826:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7827:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7828:                                         push(@{$request_domains->{$type}},$otherdom);
 7829:                                     }
 7830:                                 } else {
 7831:                                     push(@{$request_domains->{$type}},$otherdom);
 7832:                                 }
 7833:                             }
 7834:                         }
 7835:                     }
 7836:                     unless ($dom eq $env{'user.domain'}) {
 7837:                         $canreq ++;
 7838:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7839:                             $can_request->{$type} = 1;
 7840:                         }
 7841:                     }
 7842:                 }
 7843:             }
 7844:         }
 7845:     }
 7846:     return $canreq;
 7847: }
 7848: 
 7849: # ---------------------------------------------- Custom access rule evaluation
 7850: 
 7851: sub customaccess {
 7852:     my ($priv,$uri)=@_;
 7853:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7854:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7855:     $udom = &LONCAPA::clean_domain($udom);
 7856:     $ucrs = &LONCAPA::clean_username($ucrs);
 7857:     my $access=0;
 7858:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7859: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7860: 	if ($type eq 'user') {
 7861: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7862: 		my ($tdom,$tuname)=split(m{/},$scope);
 7863: 		if ($tdom) {
 7864: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7865: 		}
 7866: 		if ($tuname) {
 7867: 		    if ($tuname ne $env{'user.name'}) { next; }
 7868: 		}
 7869: 		$access=($effect eq 'allow');
 7870: 		last;
 7871: 	    }
 7872: 	} else {
 7873: 	    if ($role) {
 7874: 		if ($role ne $urole) { next; }
 7875: 	    }
 7876: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7877: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7878: 		if ($tdom) {
 7879: 		    if ($tdom ne $udom) { next; }
 7880: 		}
 7881: 		if ($tcrs) {
 7882: 		    if ($tcrs ne $ucrs) { next; }
 7883: 		}
 7884: 		if ($tsec) {
 7885: 		    if ($tsec ne $usec) { next; }
 7886: 		}
 7887: 		$access=($effect eq 'allow');
 7888: 		last;
 7889: 	    }
 7890: 	    if ($realm eq '' && $role eq '') {
 7891: 		$access=($effect eq 'allow');
 7892: 	    }
 7893: 	}
 7894:     }
 7895:     return $access;
 7896: }
 7897: 
 7898: # ------------------------------------------------- Check for a user privilege
 7899: 
 7900: sub allowed {
 7901:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7902:     my $ver_orguri=$uri;
 7903:     $uri=&deversion($uri);
 7904:     my $orguri=$uri;
 7905:     $uri=&declutter($uri);
 7906: 
 7907:     if ($priv eq 'evb') {
 7908: # Evade communication block restrictions for specified role in a course
 7909:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7910:             return $1;
 7911:         } else {
 7912:             return;
 7913:         }
 7914:     }
 7915: 
 7916:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7917: # Free bre access to adm and meta resources
 7918:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7919: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7920: 	&& ($priv eq 'bre')) {
 7921: 	return 'F';
 7922:     }
 7923: 
 7924: # Free bre access to user's own portfolio contents
 7925:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7926:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7927: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7928:         my %setters;
 7929:         my ($startblock,$endblock) = 
 7930:             &Apache::loncommon::blockcheck(\%setters,'port');
 7931:         if ($startblock && $endblock) {
 7932:             return 'B';
 7933:         } else {
 7934:             return 'F';
 7935:         }
 7936:     }
 7937: 
 7938: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7939:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7940:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7941:         if (exists($env{'request.course.id'})) {
 7942:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7943:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7944:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7945:                 my $courseprivid=$env{'request.course.id'};
 7946:                 $courseprivid=~s/\_/\//;
 7947:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7948:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7949:                     return $1; 
 7950:                 } else {
 7951:                     if ($env{'request.course.sec'}) {
 7952:                         $courseprivid.='/'.$env{'request.course.sec'};
 7953:                     }
 7954:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7955:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7956:                         return $2;
 7957:                     }
 7958:                 }
 7959:             }
 7960:         }
 7961:     }
 7962: 
 7963: # Free bre to public access
 7964: 
 7965:     if ($priv eq 'bre') {
 7966:         my $copyright;
 7967:         unless ($uri =~ /ext\.tool/) {
 7968:             $copyright=&metadata($uri,'copyright');
 7969:         }
 7970: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7971:            return 'F'; 
 7972:         }
 7973:         if ($copyright eq 'priv') {
 7974:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7975: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7976: 		return '';
 7977:             }
 7978:         }
 7979:         if ($copyright eq 'domain') {
 7980:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7981: 	    unless (($env{'user.domain'} eq $1) ||
 7982:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7983: 		return '';
 7984:             }
 7985:         }
 7986:         if ($env{'request.role'}=~ /li\.\//) {
 7987:             # Library role, so allow browsing of resources in this domain.
 7988:             return 'F';
 7989:         }
 7990:         if ($copyright eq 'custom') {
 7991: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7992:         }
 7993:     }
 7994:     # Domain coordinator is trying to create a course
 7995:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7996:         # uri is the requested domain in this case.
 7997:         # comparison to 'request.role.domain' shows if the user has selected
 7998:         # a role of dc for the domain in question.
 7999:         return 'F' if ($uri eq $env{'request.role.domain'});
 8000:     }
 8001: 
 8002:     my $thisallowed='';
 8003:     my $statecond=0;
 8004:     my $courseprivid='';
 8005: 
 8006:     my $ownaccess;
 8007:     # Community Coordinator or Assistant Co-author browsing resource space.
 8008:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8009:         if ($uri eq '') {
 8010:             $ownaccess = 1;
 8011:         } else {
 8012:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8013:                 my $udom = $env{'user.domain'};
 8014:                 my $uname = $env{'user.name'};
 8015:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8016:                     $ownaccess = 1;
 8017:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8018:                     unless ($uri =~ m{\.\./}) {
 8019:                         $ownaccess = 1;
 8020:                     }
 8021:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8022:                     my $now = time;
 8023:                     if ($uri =~ m{^([^/]+)/?$}) {
 8024:                         my $adom = $1;
 8025:                         foreach my $key (keys(%env)) {
 8026:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8027:                                 my ($start,$end) = split('.',$env{$key});
 8028:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8029:                                     $ownaccess = 1;
 8030:                                     last;
 8031:                                 }
 8032:                             }
 8033:                         }
 8034:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8035:                         my $adom = $1;
 8036:                         my $aname = $2;
 8037:                         foreach my $role ('ca','aa') { 
 8038:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8039:                                 my ($start,$end) =
 8040:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8041:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8042:                                     $ownaccess = 1;
 8043:                                     last;
 8044:                                 }
 8045:                             }
 8046:                         }
 8047:                     }
 8048:                 }
 8049:             }
 8050:         }
 8051:     }
 8052: 
 8053: # Course
 8054: 
 8055:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8056:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8057:             $thisallowed.=$1;
 8058:         }
 8059:     }
 8060: 
 8061: # Domain
 8062: 
 8063:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8064:        =~/\Q$priv\E\&([^\:]*)/) {
 8065:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8066:             $thisallowed.=$1;
 8067:         }
 8068:     }
 8069: 
 8070: # User who is not author or co-author might still be able to edit
 8071: # resource of an author in the domain (e.g., if Domain Coordinator).
 8072:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8073:         (&allowed('mdc',$env{'request.course.id'}))) {
 8074:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8075:             $thisallowed.=$1;
 8076:         }
 8077:     }
 8078: 
 8079: # Course: uri itself is a course
 8080:     my $courseuri=$uri;
 8081:     $courseuri=~s/\_(\d)/\/$1/;
 8082:     $courseuri=~s/^([^\/])/\/$1/;
 8083: 
 8084:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8085:        =~/\Q$priv\E\&([^\:]*)/) {
 8086:         if ($priv eq 'mip') {
 8087:             my $rem = $1;
 8088:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8089:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8090:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8091:                 if ($cdom ne '') {
 8092:                     my %passwdconf = &Apache::lonnet::get_passwdconf($cdom);
 8093:                     if ($passwdconf{'crsownerchg'}) {
 8094:                         $thisallowed.=$rem;
 8095:                     }
 8096:                 }
 8097:             }
 8098:         } else {
 8099:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8100:                 $thisallowed.=$1;
 8101:             }
 8102:         }
 8103:     }
 8104: 
 8105: # URI is an uploaded document for this course, default permissions don't matter
 8106: # not allowing 'edit' access (editupload) to uploaded course docs
 8107:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8108: 	$thisallowed='';
 8109:         my ($match)=&is_on_map($uri);
 8110:         if ($match) {
 8111:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8112:                   =~/\Q$priv\E\&([^\:]*)/) {
 8113:                 my $value = $1;
 8114:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8115:                 if ($deeplinkblock) {
 8116:                     $thisallowed='D';
 8117:                 } elsif ($noblockcheck) {
 8118:                     $thisallowed.=$value;
 8119:                 } else {
 8120:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8121:                     if (@blockers > 0) {
 8122:                         $thisallowed = 'B';
 8123:                     } else {
 8124:                         $thisallowed.=$value;
 8125:                     }
 8126:                 }
 8127:             }
 8128:         } else {
 8129:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8130:             if ($refuri) {
 8131:                 if ($refuri =~ m|^/adm/|) {
 8132:                     $thisallowed='F';
 8133:                 } else {
 8134:                     $refuri=&declutter($refuri);
 8135:                     my ($match) = &is_on_map($refuri);
 8136:                     if ($match) {
 8137:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8138:                         if ($deeplinkblock) {
 8139:                             $thisallowed='D';
 8140:                         } elsif ($noblockcheck) {
 8141:                             $thisallowed='F';
 8142:                         } else {
 8143:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8144:                             if (@blockers > 0) {
 8145:                                 $thisallowed = 'B';
 8146:                             } else {
 8147:                                 $thisallowed='F';
 8148:                             }
 8149:                         }
 8150:                     }
 8151:                 }
 8152:             }
 8153:         }
 8154:     }
 8155: 
 8156:     if ($priv eq 'bre'
 8157: 	&& $thisallowed ne 'F' 
 8158: 	&& $thisallowed ne '2'
 8159: 	&& &is_portfolio_url($uri)) {
 8160: 	$thisallowed = &portfolio_access($uri,$clientip);
 8161:     }
 8162: 
 8163: # Full access at system, domain or course-wide level? Exit.
 8164:     if ($thisallowed=~/F/) {
 8165: 	return 'F';
 8166:     }
 8167: 
 8168: # If this is generating or modifying users, exit with special codes
 8169: 
 8170:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8171: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8172: 	    my ($audom,$auname)=split('/',$uri);
 8173: # no author name given, so this just checks on the general right to make a co-author in this domain
 8174: 	    unless ($auname) { return $thisallowed; }
 8175: # an author name is given, so we are about to actually make a co-author for a certain account
 8176: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8177: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8178: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8179: 	}
 8180: 	return $thisallowed;
 8181:     }
 8182: #
 8183: # Gathered so far: system, domain and course wide privileges
 8184: #
 8185: # Course: See if uri or referer is an individual resource that is part of 
 8186: # the course
 8187: 
 8188:     if ($env{'request.course.id'}) {
 8189: 
 8190: # If this is modifying password (internal auth) domains must match for user and user's role.
 8191: 
 8192:         if ($priv eq 'mip') {
 8193:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8194:                 return $thisallowed;
 8195:             } else {
 8196:                 return '';
 8197:             }
 8198:         }
 8199: 
 8200:        $courseprivid=$env{'request.course.id'};
 8201:        if ($env{'request.course.sec'}) {
 8202:           $courseprivid.='/'.$env{'request.course.sec'};
 8203:        }
 8204:        $courseprivid=~s/\_/\//;
 8205:        my $checkreferer=1;
 8206:        my ($match,$cond)=&is_on_map($uri);
 8207:        if ($match) {
 8208:            $statecond=$cond;
 8209:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8210:                =~/\Q$priv\E\&([^\:]*)/) {
 8211:                my $value = $1;
 8212:                if ($priv eq 'bre') {
 8213:                    if ($noblockcheck) {
 8214:                        $thisallowed.=$value;
 8215:                    } else {
 8216:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8217:                        if (@blockers > 0) {
 8218:                            $thisallowed = 'B';
 8219:                        } else {
 8220:                            $thisallowed.=$value;
 8221:                        }
 8222:                    }
 8223:                } else {
 8224:                    $thisallowed.=$value;
 8225:                }
 8226:                $checkreferer=0;
 8227:            }
 8228:        }
 8229:        
 8230:        if ($checkreferer) {
 8231: 	  my $refuri=$env{'httpref.'.$orguri};
 8232:             unless ($refuri) {
 8233:                 foreach my $key (keys(%env)) {
 8234: 		    if ($key=~/^httpref\..*\*/) {
 8235: 			my $pattern=$key;
 8236:                         $pattern=~s/^httpref\.\/res\///;
 8237:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8238:                         $pattern=~s/\//\\\//g;
 8239:                         if ($orguri=~/$pattern/) {
 8240: 			    $refuri=$env{$key};
 8241:                         }
 8242:                     }
 8243:                 }
 8244:             }
 8245: 
 8246:          if ($refuri) { 
 8247: 	  $refuri=&declutter($refuri);
 8248:           my ($match,$cond)=&is_on_map($refuri);
 8249:             if ($match) {
 8250:               my $refstatecond=$cond;
 8251:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8252:                   =~/\Q$priv\E\&([^\:]*)/) {
 8253:                   my $value = $1;
 8254:                   if ($priv eq 'bre') {
 8255:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8256:                       if ($deeplinkblock) {
 8257:                           $thisallowed = 'D';
 8258:                       } elsif ($noblockcheck) {
 8259:                           $thisallowed.=$value;
 8260:                       } else {
 8261:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8262:                           if (@blockers > 0) {
 8263:                               $thisallowed = 'B';
 8264:                           } else {
 8265:                               $thisallowed.=$value;
 8266:                           }
 8267:                       }
 8268:                   } else {
 8269:                       $thisallowed.=$value;
 8270:                   }
 8271:                   $uri=$refuri;
 8272:                   $statecond=$refstatecond;
 8273:               }
 8274:           }
 8275:         }
 8276:        }
 8277:    }
 8278: 
 8279: #
 8280: # Gathered now: all privileges that could apply, and condition number
 8281: # 
 8282: #
 8283: # Full or no access?
 8284: #
 8285: 
 8286:     if ($thisallowed=~/F/) {
 8287: 	return 'F';
 8288:     }
 8289: 
 8290:     unless ($thisallowed) {
 8291:         return '';
 8292:     }
 8293: 
 8294: # Restrictions exist, deal with them
 8295: #
 8296: #   C:according to course preferences
 8297: #   R:according to resource settings
 8298: #   L:unless locked
 8299: #   X:according to user session state
 8300: #
 8301: 
 8302: # Possibly locked functionality, check all courses
 8303: # Locks might take effect only after 10 minutes cache expiration for other
 8304: # courses, and 2 minutes for current course
 8305: 
 8306:     my $envkey;
 8307:     if ($thisallowed=~/L/) {
 8308:         foreach $envkey (keys(%env)) {
 8309:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8310:                my $courseid=$2;
 8311:                my $roleid=$1.'.'.$2;
 8312:                $courseid=~s/^\///;
 8313:                my $expiretime=600;
 8314:                if ($env{'request.role'} eq $roleid) {
 8315: 		  $expiretime=120;
 8316:                }
 8317: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8318:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8319:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8320: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8321:                }
 8322:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8323:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8324: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8325:                        &log($env{'user.domain'},$env{'user.name'},
 8326:                             $env{'user.home'},
 8327:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8328:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8329:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8330: 		       return '';
 8331:                    }
 8332:                }
 8333:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8334:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8335: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8336:                        &log($env{'user.domain'},$env{'user.name'},
 8337:                             $env{'user.home'},
 8338:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8339:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8340:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8341: 		       return '';
 8342:                    }
 8343:                }
 8344: 	   }
 8345:        }
 8346:     }
 8347:    
 8348: #
 8349: # Rest of the restrictions depend on selected course
 8350: #
 8351: 
 8352:     unless ($env{'request.course.id'}) {
 8353: 	if ($thisallowed eq 'A') {
 8354: 	    return 'A';
 8355:         } elsif ($thisallowed eq 'B') {
 8356:             return 'B';
 8357: 	} else {
 8358: 	    return '1';
 8359: 	}
 8360:     }
 8361: 
 8362: #
 8363: # Now user is definitely in a course
 8364: #
 8365: 
 8366: 
 8367: # Course preferences
 8368: 
 8369:    if ($thisallowed=~/C/) {
 8370:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8371:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8372:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8373: 	   =~/\Q$rolecode\E/) {
 8374: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8375: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8376: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8377: 			$env{'request.course.id'});
 8378: 	   }
 8379:            return '';
 8380:        }
 8381: 
 8382:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8383: 	   =~/\Q$unamedom\E/) {
 8384: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8385: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8386: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8387: 			$env{'request.course.id'});
 8388: 	   }
 8389:            return '';
 8390:        }
 8391:    }
 8392: 
 8393: # Resource preferences
 8394: 
 8395:    if ($thisallowed=~/R/) {
 8396:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8397:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8398: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8399: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8400: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8401: 	   }
 8402: 	   return '';
 8403:        }
 8404:    }
 8405: 
 8406: # Restricted by state or randomout?
 8407: 
 8408:    if ($thisallowed=~/X/) {
 8409:       if ($env{'acc.randomout'}) {
 8410: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8411:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8412:             return ''; 
 8413:          }
 8414:       }
 8415:       if (&condval($statecond)) {
 8416: 	 return '2';
 8417:       } else {
 8418:          return '';
 8419:       }
 8420:    }
 8421: 
 8422:     if ($thisallowed eq 'A') {
 8423: 	return 'A';
 8424:     } elsif ($thisallowed eq 'B') {
 8425:         return 'B';
 8426:     } elsif ($thisallowed eq 'D') {
 8427:         return 'D';
 8428:     }
 8429:    return 'F';
 8430: }
 8431: 
 8432: # ------------------------------------------- Check construction space access
 8433: 
 8434: sub constructaccess {
 8435:     my ($url,$setpriv)=@_;
 8436: 
 8437: # We do not allow editing of previous versions of files
 8438:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8439: 
 8440: # Get username and domain from URL
 8441:     my ($ownername,$ownerdomain,$ownerhome);
 8442: 
 8443:     ($ownerdomain,$ownername) =
 8444:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8445: 
 8446: # The URL does not really point to any authorspace, forget it
 8447:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8448: 
 8449: # Now we need to see if the user has access to the authorspace of
 8450: # $ownername at $ownerdomain
 8451: 
 8452:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8453: # Real author for this?
 8454:        $ownerhome = $env{'user.home'};
 8455:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8456:           return ($ownername,$ownerdomain,$ownerhome);
 8457:        }
 8458:     } else {
 8459: # Co-author for this?
 8460:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8461:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8462:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8463:             return ($ownername,$ownerdomain,$ownerhome);
 8464:         }
 8465:         if ($env{'request.course.id'}) {
 8466:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8467:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8468:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8469:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8470:                     return ($ownername,$ownerdomain,$ownerhome);
 8471:                 }
 8472:             }
 8473:         }
 8474:     }
 8475: 
 8476: # We don't have any access right now. If we are not possibly going to do anything about this,
 8477: # we might as well leave
 8478:    unless ($setpriv) { return ''; }
 8479: 
 8480: # Backdoor access?
 8481:     my $allowed=&allowed('eco',$ownerdomain);
 8482: # Nope
 8483:     unless ($allowed) { return ''; }
 8484: # Looks like we may have access, but could be locked by the owner of the construction space
 8485:     if ($allowed eq 'U') {
 8486:         my %blocked=&get('environment',['domcoord.author'],
 8487:                          $ownerdomain,$ownername);
 8488: # Is blocked by owner
 8489:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8490:     }
 8491:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8492: # Grant temporary access
 8493:         my $then=$env{'user.login.time'};
 8494:         my $update=$env{'user.update.time'};
 8495:         if (!$update) { $update = $then; }
 8496:         my $refresh=$env{'user.refresh.time'};
 8497:         if (!$refresh) { $refresh = $update; }
 8498:         my $now = time;
 8499:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8500:                            $now,'ca','constructaccess');
 8501:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8502:         return($ownername,$ownerdomain,$ownerhome);
 8503:     }
 8504: # No business here
 8505:     return '';
 8506: }
 8507: 
 8508: # ----------------------------------------------------------- Content Blocking
 8509: 
 8510: {
 8511: # Caches for faster Course Contents display where content blocking
 8512: # is in operation (i.e., interval param set) for timed quiz.
 8513: #
 8514: # User for whom data are being temporarily cached.
 8515: my $cacheduser='';
 8516: # Cached blockers for this user (a hash of blocking items). 
 8517: my %cachedblockers=();
 8518: # When the data were last cached.
 8519: my $cachedlast='';
 8520: 
 8521: sub load_all_blockers {
 8522:     my ($uname,$udom,$blocks)=@_;
 8523:     if (($uname ne '') && ($udom ne '')) { 
 8524:         if (($cacheduser eq $uname.':'.$udom) &&
 8525:             (abs($cachedlast-time)<5)) {
 8526:             return;
 8527:         }
 8528:     }
 8529:     $cachedlast=time;
 8530:     $cacheduser=$uname.':'.$udom;
 8531:     %cachedblockers = &get_commblock_resources($blocks);
 8532: }
 8533: 
 8534: sub get_comm_blocks {
 8535:     my ($cdom,$cnum) = @_;
 8536:     if ($cdom eq '' || $cnum eq '') {
 8537:         return unless ($env{'request.course.id'});
 8538:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8539:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8540:     }
 8541:     my %commblocks;
 8542:     my $hashid=$cdom.'_'.$cnum;
 8543:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8544:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8545:         %commblocks = %{$blocksref};
 8546:     } else {
 8547:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8548:         my $cachetime = 600;
 8549:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8550:     }
 8551:     return %commblocks;
 8552: }
 8553: 
 8554: sub get_commblock_resources {
 8555:     my ($blocks) = @_;
 8556:     my %blockers = ();
 8557:     return %blockers unless ($env{'request.course.id'});
 8558:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8559:     my %commblocks;
 8560:     if (ref($blocks) eq 'HASH') {
 8561:         %commblocks = %{$blocks};
 8562:     } else {
 8563:         %commblocks = &get_comm_blocks();
 8564:     }
 8565:     return %blockers unless (keys(%commblocks) > 0); 
 8566:     my $navmap = Apache::lonnavmaps::navmap->new();
 8567:     return %blockers unless (ref($navmap));
 8568:     my $now = time;
 8569:     foreach my $block (keys(%commblocks)) {
 8570:         if ($block =~ /^(\d+)____(\d+)$/) {
 8571:             my ($start,$end) = ($1,$2);
 8572:             if ($start <= $now && $end >= $now) {
 8573:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8574:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8575:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8576:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8577:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8578:                             }
 8579:                         }
 8580:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8581:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8582:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8583:                             }
 8584:                         }
 8585:                     }
 8586:                 }
 8587:             }
 8588:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8589:             my $item = $1;
 8590:             my @to_test;
 8591:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8592:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8593:                     my @interval;
 8594:                     my $type = 'map';
 8595:                     if ($item eq 'course') {
 8596:                         $type = 'course';
 8597:                         @interval=&EXT("resource.0.interval");
 8598:                     } else {
 8599:                         if ($item =~ /___\d+___/) {
 8600:                             $type = 'resource';
 8601:                             @interval=&EXT("resource.0.interval",$item);
 8602:                             if (ref($navmap)) {                        
 8603:                                 my $res = $navmap->getBySymb($item); 
 8604:                                 push(@to_test,$res);
 8605:                             }
 8606:                         } else {
 8607:                             my $mapsymb = &symbread($item,1);
 8608:                             if ($mapsymb) {
 8609:                                 if (ref($navmap)) {
 8610:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8611:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8612:                                     foreach my $res (@to_test) {
 8613:                                         my $symb = $res->symb();
 8614:                                         next if ($symb eq $mapsymb);
 8615:                                         if ($symb ne '') {
 8616:                                             @interval=&EXT("resource.0.interval",$symb);
 8617:                                             if ($interval[1] eq 'map') {
 8618:                                                 last;
 8619:                                             }
 8620:                                         }
 8621:                                     }
 8622:                                 }
 8623:                             }
 8624:                         }
 8625:                     }
 8626:                     if ($interval[0] =~ /^(\d+)/) {
 8627:                         my $timelimit = $1; 
 8628:                         my $first_access;
 8629:                         if ($type eq 'resource') {
 8630:                             $first_access=&get_first_access($interval[1],$item);
 8631:                         } elsif ($type eq 'map') {
 8632:                             $first_access=&get_first_access($interval[1],undef,$item);
 8633:                         } else {
 8634:                             $first_access=&get_first_access($interval[1]);
 8635:                         }
 8636:                         if ($first_access) {
 8637:                             my $timesup = $first_access+$timelimit;
 8638:                             if ($timesup > $now) {
 8639:                                 my $activeblock;
 8640:                                 foreach my $res (@to_test) {
 8641:                                     if ($res->answerable()) {
 8642:                                         $activeblock = 1;
 8643:                                         last;
 8644:                                     }
 8645:                                 }
 8646:                                 if ($activeblock) {
 8647:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8648:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8649:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8650:                                          }
 8651:                                     }
 8652:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8653:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8654:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8655:                                         }
 8656:                                     }
 8657:                                 }
 8658:                             }
 8659:                         }
 8660:                     }
 8661:                 }
 8662:             }
 8663:         }
 8664:     }
 8665:     return %blockers;
 8666: }
 8667: 
 8668: sub has_comm_blocking {
 8669:     my ($priv,$symb,$uri,$blocks) = @_;
 8670:     my @blockers;
 8671:     return unless ($env{'request.course.id'});
 8672:     return unless ($priv eq 'bre');
 8673:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8674:     return if ($env{'request.state'} eq 'construct');
 8675:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8676:     return unless (keys(%cachedblockers) > 0);
 8677:     my (%possibles,@symbs);
 8678:     if (!$symb) {
 8679:         $symb = &symbread($uri,1,1,1,\%possibles);
 8680:     }
 8681:     if ($symb) {
 8682:         @symbs = ($symb);
 8683:     } elsif (keys(%possibles)) { 
 8684:         @symbs = keys(%possibles);
 8685:     }
 8686:     my $noblock;
 8687:     foreach my $symb (@symbs) {
 8688:         last if ($noblock);
 8689:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8690:         foreach my $block (keys(%cachedblockers)) {
 8691:             if ($block =~ /^firstaccess____(.+)$/) {
 8692:                 my $item = $1;
 8693:                 if (($item eq $map) || ($item eq $symb)) {
 8694:                     $noblock = 1;
 8695:                     last;
 8696:                 }
 8697:             }
 8698:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8699:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8700:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8701:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8702:                             push(@blockers,$block);
 8703:                         }
 8704:                     }
 8705:                 }
 8706:             }
 8707:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8708:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8709:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8710:                         push(@blockers,$block);
 8711:                     }
 8712:                 }
 8713:             }
 8714:         }
 8715:     }
 8716:     return if ($noblock);
 8717:     return @blockers;
 8718: }
 8719: }
 8720: 
 8721: sub deeplink_check {
 8722:     my ($priv,$symb,$uri) = @_;
 8723:     return unless ($env{'request.course.id'});
 8724:     return unless ($priv eq 'bre');
 8725:     return if ($env{'request.state'} eq 'construct');
 8726:     return if ($env{'request.role.adv'});
 8727:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8728:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8729:     my (%possibles,@symbs);
 8730:     if (!$symb) {
 8731:         $symb = &symbread($uri,1,1,1,\%possibles);
 8732:     }
 8733:     if ($symb) {
 8734:         @symbs = ($symb);
 8735:     } elsif (keys(%possibles)) {
 8736:         @symbs = keys(%possibles);
 8737:     }
 8738: 
 8739:     my ($login,$switchrole,$allow);
 8740:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8741:         my $key = $1;
 8742:         my $tinyurl;
 8743:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8744:         if (defined($cached)) {
 8745:              $tinyurl = $result;
 8746:         } else {
 8747:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8748:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8749:              if ($currtiny{$key} ne '') {
 8750:                  $tinyurl = $currtiny{$key};
 8751:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8752:              }
 8753:         }
 8754:         if ($tinyurl ne '') {
 8755:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8756:             if ($cnumreq eq $cnum) {
 8757:                 $login = $posslogin;
 8758:             } else {
 8759:                 $switchrole = 1;
 8760:             }
 8761:         }
 8762:     }
 8763:     foreach my $symb (@symbs) {
 8764:         last if ($allow);
 8765:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8766:         if ($deeplink eq '') {
 8767:             $allow = 1;
 8768:         } else {
 8769:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8770:             if ($access eq 'any') {
 8771:                 $allow = 1;
 8772:             } elsif ($login) {
 8773:                 if ($access eq 'only') {
 8774:                     if ($scope eq 'res') {
 8775:                         if ($symb eq $login) {
 8776:                             $allow = 1;
 8777:                         }
 8778:                     } elsif ($scope eq 'map') {
 8779: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8780:                     } elsif ($scope eq 'rec') {
 8781: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8782:                     }
 8783:                 } else {
 8784:                     my ($acctype,$item) = split(/:/,$access);
 8785:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8786:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8787:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8788:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8789:                                 $allow = 1;
 8790:                             }
 8791:                         }
 8792:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8793:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8794:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8795:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8796:                                 $allow = 1;
 8797:                             }
 8798:                         }
 8799:                     }
 8800:                 }
 8801:             }
 8802:         }
 8803:     }
 8804:     return if ($allow);
 8805:     return 1;
 8806: }
 8807: 
 8808: # -------------------------------- Deversion and split uri into path an filename   
 8809: 
 8810: #
 8811: #   Removes the version from a URI and
 8812: #   splits it in to its filename and path to the filename.
 8813: #   Seems like File::Basename could have done this more clearly.
 8814: #   Parameters:
 8815: #      $uri   - input URI
 8816: #   Returns:
 8817: #     Two element list consisting of 
 8818: #     $pathname  - the URI up to and excluding the trailing /
 8819: #     $filename  - The part of the URI following the last /
 8820: #  NOTE:
 8821: #    Another realization of this is simply:
 8822: #    use File::Basename;
 8823: #    ...
 8824: #    $uri = shift;
 8825: #    $filename = basename($uri);
 8826: #    $path     = dirname($uri);
 8827: #    return ($filename, $path);
 8828: #
 8829: #     The implementation below is probably faster however.
 8830: #
 8831: sub split_uri_for_cond {
 8832:     my $uri=&deversion(&declutter(shift));
 8833:     my @uriparts=split(/\//,$uri);
 8834:     my $filename=pop(@uriparts);
 8835:     my $pathname=join('/',@uriparts);
 8836:     return ($pathname,$filename);
 8837: }
 8838: # --------------------------------------------------- Is a resource on the map?
 8839: 
 8840: sub is_on_map {
 8841:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8842:     #Trying to find the conditional for the file
 8843:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8844: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8845:     if ($match) {
 8846: 	return (1,$1);
 8847:     } else {
 8848: 	return (0,0);
 8849:     }
 8850: }
 8851: 
 8852: # --------------------------------------------------------- Get symb from alias
 8853: 
 8854: sub get_symb_from_alias {
 8855:     my $symb=shift;
 8856:     my ($map,$resid,$url)=&decode_symb($symb);
 8857: # Already is a symb
 8858:     if ($url) { return $symb; }
 8859: # Must be an alias
 8860:     my $aliassymb='';
 8861:     my %bighash;
 8862:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8863:                             &GDBM_READER(),0640)) {
 8864:         my $rid=$bighash{'mapalias_'.$symb};
 8865: 	if ($rid) {
 8866: 	    my ($mapid,$resid)=split(/\./,$rid);
 8867: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8868: 				    $resid,$bighash{'src_'.$rid});
 8869: 	}
 8870:         untie %bighash;
 8871:     }
 8872:     return $aliassymb;
 8873: }
 8874: 
 8875: # ----------------------------------------------------------------- Define Role
 8876: 
 8877: sub definerole {
 8878:   if (allowed('mcr','/')) {
 8879:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8880:     foreach my $role (split(':',$sysrole)) {
 8881: 	my ($crole,$cqual)=split(/\&/,$role);
 8882:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8883:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8884: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8885:                return "refused:s:$crole&$cqual"; 
 8886:             }
 8887:         }
 8888:     }
 8889:     foreach my $role (split(':',$domrole)) {
 8890: 	my ($crole,$cqual)=split(/\&/,$role);
 8891:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8892:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8893: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8894:                return "refused:d:$crole&$cqual"; 
 8895:             }
 8896:         }
 8897:     }
 8898:     foreach my $role (split(':',$courole)) {
 8899: 	my ($crole,$cqual)=split(/\&/,$role);
 8900:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8901:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8902: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8903:                return "refused:c:$crole&$cqual"; 
 8904:             }
 8905:         }
 8906:     }
 8907:     my $uhome;
 8908:     if (($uname ne '') && ($udom ne '')) {
 8909:         $uhome = &homeserver($uname,$udom);
 8910:         return $uhome if ($uhome eq 'no_host');
 8911:     } else {
 8912:         $uname = $env{'user.name'};
 8913:         $udom = $env{'user.domain'};
 8914:         $uhome = $env{'user.home'};
 8915:     }
 8916:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8917:                 "$udom:$uname:rolesdef_$rolename=".
 8918:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8919:     return reply($command,$uhome);
 8920:   } else {
 8921:     return 'refused';
 8922:   }
 8923: }
 8924: 
 8925: # ---------------- Make a metadata query against the network of library servers
 8926: 
 8927: sub metadata_query {
 8928:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8929:     my %rhash;
 8930:     my %libserv = &all_library();
 8931:     my @server_list = (defined($server_array) ? @$server_array
 8932:                                               : keys(%libserv) );
 8933:     for my $server (@server_list) {
 8934:         my $domains = ''; 
 8935:         if (ref($domains_hash) eq 'HASH') {
 8936:             $domains = $domains_hash->{$server}; 
 8937:         }
 8938: 	unless ($custom or $customshow) {
 8939: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8940: 	    $rhash{$server}=$reply;
 8941: 	}
 8942: 	else {
 8943: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8944: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8945: 			     $server);
 8946: 	    $rhash{$server}=$reply;
 8947: 	}
 8948:     }
 8949:     return \%rhash;
 8950: }
 8951: 
 8952: # ----------------------------------------- Send log queries and wait for reply
 8953: 
 8954: sub log_query {
 8955:     my ($uname,$udom,$query,%filters)=@_;
 8956:     my $uhome=&homeserver($uname,$udom);
 8957:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8958:     my $uhost=&hostname($uhome);
 8959:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8960:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8961:                        $uhome);
 8962:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8963:     return get_query_reply($queryid);
 8964: }
 8965: 
 8966: # -------------------------- Update MySQL table for portfolio file
 8967: 
 8968: sub update_portfolio_table {
 8969:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8970:     if ($group ne '') {
 8971:         $file_name =~s /^\Q$group\E//;
 8972:     }
 8973:     my $homeserver = &homeserver($uname,$udom);
 8974:     my $queryid=
 8975:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8976:                ':'.&escape($file_name).':'.$action,$homeserver);
 8977:     my $reply = &get_query_reply($queryid);
 8978:     return $reply;
 8979: }
 8980: 
 8981: # -------------------------- Update MySQL allusers table
 8982: 
 8983: sub update_allusers_table {
 8984:     my ($uname,$udom,$names) = @_;
 8985:     my $homeserver = &homeserver($uname,$udom);
 8986:     my $queryid=
 8987:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8988:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8989:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8990:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8991:                'generation='.&escape($names->{'generation'}).'%%'.
 8992:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8993:                'id='.&escape($names->{'id'}),$homeserver);
 8994:     return;
 8995: }
 8996: 
 8997: # ------- Request retrieval of institutional classlists for course(s)
 8998: 
 8999: sub fetch_enrollment_query {
 9000:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9001:     my ($homeserver,$sleep,$loopmax);
 9002:     my $maxtries = 1;
 9003:     if ($context eq 'automated') {
 9004:         $homeserver = $perlvar{'lonHostID'};
 9005:         $sleep = 2;
 9006:         $loopmax = 100;
 9007:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9008:     } else {
 9009:         $homeserver = &homeserver($cnum,$dom);
 9010:     }
 9011:     my $host=&hostname($homeserver);
 9012:     my $cmd = '';
 9013:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9014:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9015:     }
 9016:     $cmd =~ s/%%$//;
 9017:     $cmd = &escape($cmd);
 9018:     my $query = 'fetchenrollment';
 9019:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9020:     unless ($queryid=~/^\Q$host\E\_/) { 
 9021:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9022:         return 'error: '.$queryid;
 9023:     }
 9024:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9025:     my $tries = 1;
 9026:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9027:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9028:         $tries ++;
 9029:     }
 9030:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9031:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9032:     } else {
 9033:         my @responses = split(/:/,$reply);
 9034:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9035:             foreach my $line (@responses) {
 9036:                 my ($key,$value) = split(/=/,$line,2);
 9037:                 $$replyref{$key} = $value;
 9038:             }
 9039:         } else {
 9040:             my $pathname = LONCAPA::tempdir();
 9041:             foreach my $line (@responses) {
 9042:                 my ($key,$value) = split(/=/,$line);
 9043:                 $$replyref{$key} = $value;
 9044:                 if ($value > 0) {
 9045:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9046:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9047:                         my $destname = $pathname.'/'.$filename;
 9048:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9049:                         if ($xml_classlist =~ /^error/) {
 9050:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9051:                         } else {
 9052:                             if ( open(FILE,">",$destname) ) {
 9053:                                 print FILE &unescape($xml_classlist);
 9054:                                 close(FILE);
 9055:                             } else {
 9056:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9057:                             }
 9058:                         }
 9059:                     }
 9060:                 }
 9061:             }
 9062:         }
 9063:         return 'ok';
 9064:     }
 9065:     return 'error';
 9066: }
 9067: 
 9068: sub get_query_reply {
 9069:     my ($queryid,$sleep,$loopmax) = @_;;
 9070:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9071:         $sleep = 0.2;
 9072:     }
 9073:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9074:         $loopmax = 100;
 9075:     }
 9076:     my $replyfile=LONCAPA::tempdir().$queryid;
 9077:     my $reply='';
 9078:     for (1..$loopmax) {
 9079: 	sleep($sleep);
 9080:         if (-e $replyfile.'.end') {
 9081: 	    if (open(my $fh,"<",$replyfile)) {
 9082: 		$reply = join('',<$fh>);
 9083: 		close($fh);
 9084: 	   } else { return 'error: reply_file_error'; }
 9085:            return &unescape($reply);
 9086: 	}
 9087:     }
 9088:     return 'timeout:'.$queryid;
 9089: }
 9090: 
 9091: sub courselog_query {
 9092: #
 9093: # possible filters:
 9094: # url: url or symb
 9095: # username
 9096: # domain
 9097: # action: view, submit, grade
 9098: # start: timestamp
 9099: # end: timestamp
 9100: #
 9101:     my (%filters)=@_;
 9102:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9103:     if ($filters{'url'}) {
 9104: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9105:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9106:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9107:     }
 9108:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9109:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9110:     return &log_query($cname,$cdom,'courselog',%filters);
 9111: }
 9112: 
 9113: sub userlog_query {
 9114: #
 9115: # possible filters:
 9116: # action: log check role
 9117: # start: timestamp
 9118: # end: timestamp
 9119: #
 9120:     my ($uname,$udom,%filters)=@_;
 9121:     return &log_query($uname,$udom,'userlog',%filters);
 9122: }
 9123: 
 9124: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9125: 
 9126: sub auto_run {
 9127:     my ($cnum,$cdom) = @_;
 9128:     my $response = 0;
 9129:     my $settings;
 9130:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9131:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9132:         $settings = $domconfig{'autoenroll'};
 9133:         if ($settings->{'run'} eq '1') {
 9134:             $response = 1;
 9135:         }
 9136:     } else {
 9137:         my $homeserver;
 9138:         if (&is_course($cdom,$cnum)) {
 9139:             $homeserver = &homeserver($cnum,$cdom);
 9140:         } else {
 9141:             $homeserver = &domain($cdom,'primary');
 9142:         }
 9143:         if ($homeserver ne 'no_host') {
 9144:             $response = &reply('autorun:'.$cdom,$homeserver);
 9145:         }
 9146:     }
 9147:     return $response;
 9148: }
 9149: 
 9150: sub auto_get_sections {
 9151:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9152:     my $homeserver;
 9153:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9154:         $homeserver = &homeserver($cnum,$cdom);
 9155:     }
 9156:     if (!defined($homeserver)) { 
 9157:         if ($cdom =~ /^$match_domain$/) {
 9158:             $homeserver = &domain($cdom,'primary');
 9159:         }
 9160:     }
 9161:     my @secs;
 9162:     if (defined($homeserver)) {
 9163:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9164:         unless ($response eq 'refused') {
 9165:             @secs = split(/:/,$response);
 9166:         }
 9167:     }
 9168:     return @secs;
 9169: }
 9170: 
 9171: sub auto_new_course {
 9172:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9173:     my $homeserver = &homeserver($cnum,$cdom);
 9174:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9175:     return $response;
 9176: }
 9177: 
 9178: sub auto_validate_courseID {
 9179:     my ($cnum,$cdom,$inst_course_id) = @_;
 9180:     my $homeserver = &homeserver($cnum,$cdom);
 9181:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9182:     return $response;
 9183: }
 9184: 
 9185: sub auto_validate_instcode {
 9186:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9187:     my ($homeserver,$response);
 9188:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9189:         $homeserver = &homeserver($cnum,$cdom);
 9190:     }
 9191:     if (!defined($homeserver)) {
 9192:         if ($cdom =~ /^$match_domain$/) {
 9193:             $homeserver = &domain($cdom,'primary');
 9194:         }
 9195:     }
 9196:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9197:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9198:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9199:     return ($outcome,$description,$defaultcredits);
 9200: }
 9201: 
 9202: sub auto_create_password {
 9203:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9204:     my ($homeserver,$response);
 9205:     my $create_passwd = 0;
 9206:     my $authchk = '';
 9207:     if ($udom =~ /^$match_domain$/) {
 9208:         $homeserver = &domain($udom,'primary');
 9209:     }
 9210:     if ($homeserver eq '') {
 9211:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9212:             $homeserver = &homeserver($cnum,$cdom);
 9213:         }
 9214:     }
 9215:     if ($homeserver eq '') {
 9216:         $authchk = 'nodomain';
 9217:     } else {
 9218:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9219:         if ($response eq 'refused') {
 9220:             $authchk = 'refused';
 9221:         } else {
 9222:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9223:         }
 9224:     }
 9225:     return ($authparam,$create_passwd,$authchk);
 9226: }
 9227: 
 9228: sub auto_photo_permission {
 9229:     my ($cnum,$cdom,$students) = @_;
 9230:     my $homeserver = &homeserver($cnum,$cdom);
 9231:     my ($outcome,$perm_reqd,$conditions) = 
 9232: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9233:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9234: 	return (undef,undef);
 9235:     }
 9236:     return ($outcome,$perm_reqd,$conditions);
 9237: }
 9238: 
 9239: sub auto_checkphotos {
 9240:     my ($uname,$udom,$pid) = @_;
 9241:     my $homeserver = &homeserver($uname,$udom);
 9242:     my ($result,$resulttype);
 9243:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9244: 				   &escape($uname).':'.&escape($pid),
 9245: 				   $homeserver));
 9246:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9247: 	return (undef,undef);
 9248:     }
 9249:     if ($outcome) {
 9250:         ($result,$resulttype) = split(/:/,$outcome);
 9251:     } 
 9252:     return ($result,$resulttype);
 9253: }
 9254: 
 9255: sub auto_photochoice {
 9256:     my ($cnum,$cdom) = @_;
 9257:     my $homeserver = &homeserver($cnum,$cdom);
 9258:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9259: 						       &escape($cdom),
 9260: 						       $homeserver)));
 9261:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9262: 	return (undef,undef);
 9263:     }
 9264:     return ($update,$comment);
 9265: }
 9266: 
 9267: sub auto_photoupdate {
 9268:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9269:     my $homeserver = &homeserver($cnum,$dom);
 9270:     my $host=&hostname($homeserver);
 9271:     my $cmd = '';
 9272:     my $maxtries = 1;
 9273:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9274:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9275:     }
 9276:     $cmd =~ s/%%$//;
 9277:     $cmd = &escape($cmd);
 9278:     my $query = 'institutionalphotos';
 9279:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9280:     unless ($queryid=~/^\Q$host\E\_/) {
 9281:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9282:         return 'error: '.$queryid;
 9283:     }
 9284:     my $reply = &get_query_reply($queryid);
 9285:     my $tries = 1;
 9286:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9287:         $reply = &get_query_reply($queryid);
 9288:         $tries ++;
 9289:     }
 9290:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9291:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9292:     } else {
 9293:         my @responses = split(/:/,$reply);
 9294:         my $outcome = shift(@responses); 
 9295:         foreach my $item (@responses) {
 9296:             my ($key,$value) = split(/=/,$item);
 9297:             $$photo{$key} = $value;
 9298:         }
 9299:         return $outcome;
 9300:     }
 9301:     return 'error';
 9302: }
 9303: 
 9304: sub auto_instcode_format {
 9305:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9306: 	$cat_order) = @_;
 9307:     my $courses = '';
 9308:     my @homeservers;
 9309:     if ($caller eq 'global') {
 9310: 	my %servers = &get_servers($codedom,'library');
 9311: 	foreach my $tryserver (keys(%servers)) {
 9312: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9313: 		push(@homeservers,$tryserver);
 9314: 	    }
 9315:         }
 9316:     } elsif ($caller eq 'requests') {
 9317:         if ($codedom =~ /^$match_domain$/) {
 9318:             my $chome = &domain($codedom,'primary');
 9319:             unless ($chome eq 'no_host') {
 9320:                 push(@homeservers,$chome);
 9321:             }
 9322:         }
 9323:     } else {
 9324:         push(@homeservers,&homeserver($caller,$codedom));
 9325:     }
 9326:     foreach my $code (keys(%{$instcodes})) {
 9327:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9328:     }
 9329:     chop($courses);
 9330:     my $ok_response = 0;
 9331:     my $response;
 9332:     while (@homeservers > 0 && $ok_response == 0) {
 9333:         my $server = shift(@homeservers); 
 9334:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9335:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9336:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9337: 		split(/:/,$response);
 9338:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9339:             push(@{$codetitles},&str2array($codetitles_str));
 9340:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9341:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9342:             $ok_response = 1;
 9343:         }
 9344:     }
 9345:     if ($ok_response) {
 9346:         return 'ok';
 9347:     } else {
 9348:         return $response;
 9349:     }
 9350: }
 9351: 
 9352: sub auto_instcode_defaults {
 9353:     my ($domain,$returnhash,$code_order) = @_;
 9354:     my @homeservers;
 9355: 
 9356:     my %servers = &get_servers($domain,'library');
 9357:     foreach my $tryserver (keys(%servers)) {
 9358: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9359: 	    push(@homeservers,$tryserver);
 9360: 	}
 9361:     }
 9362: 
 9363:     my $response;
 9364:     foreach my $server (@homeservers) {
 9365:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9366:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9367: 	
 9368: 	foreach my $pair (split(/\&/,$response)) {
 9369: 	    my ($name,$value)=split(/\=/,$pair);
 9370: 	    if ($name eq 'code_order') {
 9371: 		@{$code_order} = split(/\&/,&unescape($value));
 9372: 	    } else {
 9373: 		$returnhash->{&unescape($name)}=&unescape($value);
 9374: 	    }
 9375: 	}
 9376: 	return 'ok';
 9377:     }
 9378: 
 9379:     return $response;
 9380: }
 9381: 
 9382: sub auto_possible_instcodes {
 9383:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9384:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9385:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9386:         return;
 9387:     }
 9388:     my (@homeservers,$uhome);
 9389:     if (defined(&domain($domain,'primary'))) {
 9390:         $uhome=&domain($domain,'primary');
 9391:         push(@homeservers,&domain($domain,'primary'));
 9392:     } else {
 9393:         my %servers = &get_servers($domain,'library');
 9394:         foreach my $tryserver (keys(%servers)) {
 9395:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9396:                 push(@homeservers,$tryserver);
 9397:             }
 9398:         }
 9399:     }
 9400:     my $response;
 9401:     foreach my $server (@homeservers) {
 9402:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9403:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9404:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9405:             split(':',$response);
 9406:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9407:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9408:         foreach my $item (split('&',$cat_title)) {   
 9409:             my ($name,$value)=split('=',$item);
 9410:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9411:         }
 9412:         foreach my $item (split('&',$cat_order)) {
 9413:             my ($name,$value)=split('=',$item);
 9414:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9415:         }
 9416:         return 'ok';
 9417:     }
 9418:     return $response;
 9419: }
 9420: 
 9421: sub auto_courserequest_checks {
 9422:     my ($dom) = @_;
 9423:     my ($homeserver,%validations);
 9424:     if ($dom =~ /^$match_domain$/) {
 9425:         $homeserver = &domain($dom,'primary');
 9426:     }
 9427:     unless ($homeserver eq 'no_host') {
 9428:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9429:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9430:             my @items = split(/&/,$response);
 9431:             foreach my $item (@items) {
 9432:                 my ($key,$value) = split('=',$item);
 9433:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9434:             }
 9435:         }
 9436:     }
 9437:     return %validations; 
 9438: }
 9439: 
 9440: sub auto_courserequest_validation {
 9441:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9442:     my ($homeserver,$response);
 9443:     if ($dom =~ /^$match_domain$/) {
 9444:         $homeserver = &domain($dom,'primary');
 9445:     }
 9446:     unless ($homeserver eq 'no_host') {
 9447:         my $customdata;
 9448:         if (ref($custominfo) eq 'HASH') {
 9449:             $customdata = &freeze_escape($custominfo);
 9450:         }
 9451:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9452:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9453:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9454:                                     $customdata,$homeserver));
 9455:     }
 9456:     return $response;
 9457: }
 9458: 
 9459: sub auto_validate_class_sec {
 9460:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9461:     my $homeserver = &homeserver($cnum,$cdom);
 9462:     my $ownerlist;
 9463:     if (ref($owners) eq 'ARRAY') {
 9464:         $ownerlist = join(',',@{$owners});
 9465:     } else {
 9466:         $ownerlist = $owners;
 9467:     }
 9468:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9469:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9470:     return $response;
 9471: }
 9472: 
 9473: sub auto_validate_instclasses {
 9474:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9475:     my ($homeserver,%validations);
 9476:     $homeserver = &homeserver($cnum,$cdom);
 9477:     unless ($homeserver eq 'no_host') {
 9478:         my $ownerlist;
 9479:         if (ref($owners) eq 'ARRAY') {
 9480:             $ownerlist = join(',',@{$owners});
 9481:         } else {
 9482:             $ownerlist = $owners;
 9483:         }
 9484:         if (ref($classesref) eq 'HASH') {
 9485:             my $classes = &freeze_escape($classesref);
 9486:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9487:                                 ':'.$cdom.':'.$classes,$homeserver);
 9488:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9489:                 my @items = split(/&/,$response);
 9490:                 foreach my $item (@items) {
 9491:                     my ($key,$value) = split('=',$item);
 9492:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9493:                 }
 9494:             }
 9495:         }
 9496:     }
 9497:     return %validations;
 9498: }
 9499: 
 9500: sub auto_crsreq_update {
 9501:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9502:         $code,$accessstart,$accessend,$inbound) = @_;
 9503:     my ($homeserver,%crsreqresponse);
 9504:     if ($cdom =~ /^$match_domain$/) {
 9505:         $homeserver = &domain($cdom,'primary');
 9506:     }
 9507:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9508:         my $info;
 9509:         if (ref($inbound) eq 'HASH') {
 9510:             $info = &freeze_escape($inbound);
 9511:         }
 9512:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9513:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9514:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9515:                             &escape($title).':'.&escape($code).':'.
 9516:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9517:                             $homeserver);
 9518:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9519:             my @items = split(/&/,$response);
 9520:             foreach my $item (@items) {
 9521:                 my ($key,$value) = split('=',$item);
 9522:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9523:             }
 9524:         }
 9525:     }
 9526:     return \%crsreqresponse;
 9527: }
 9528: 
 9529: sub auto_export_grades {
 9530:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9531:     my ($homeserver,%exportresponse);
 9532:     if ($cdom =~ /^$match_domain$/) {
 9533:         $homeserver = &domain($cdom,'primary');
 9534:     }
 9535:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9536:         my $info;
 9537:         if (ref($inforef) eq 'HASH') {
 9538:             $info = &freeze_escape($inforef);
 9539:         }
 9540:         if (ref($gradesref) eq 'HASH') {
 9541:             my $grades = &freeze_escape($gradesref);
 9542:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9543:                                 $info.':'.$grades,$homeserver);
 9544:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9545:                 my @items = split(/&/,$response);
 9546:                 foreach my $item (@items) {
 9547:                     my ($key,$value) = split('=',$item);
 9548:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9549:                 }
 9550:             }
 9551:         }
 9552:     }
 9553:     return \%exportresponse;
 9554: }
 9555: 
 9556: sub check_instcode_cloning {
 9557:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9558:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9559:         return;
 9560:     }
 9561:     my $canclone;
 9562:     if (@{$code_order} > 0) {
 9563:         my $instcoderegexp ='^';
 9564:         my @clonecodes = split(/\&/,$cloner);
 9565:         foreach my $item (@{$code_order}) {
 9566:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9567:                 foreach my $pair (@clonecodes) {
 9568:                     my ($key,$val) = split(/\=/,$pair,2);
 9569:                     $val = &unescape($val);
 9570:                     if ($key eq $item) {
 9571:                         $instcoderegexp .= '('.$val.')';
 9572:                         last;
 9573:                     }
 9574:                 }
 9575:             } else {
 9576:                 $instcoderegexp .= $codedefaults->{$item};
 9577:             }
 9578:         }
 9579:         $instcoderegexp .= '$';
 9580:         my (@from,@to);
 9581:         eval {
 9582:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9583:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9584:         };
 9585:         if ((@from > 0) && (@to > 0)) {
 9586:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9587:             if (!@diffs) {
 9588:                 $canclone = 1;
 9589:             }
 9590:         }
 9591:     }
 9592:     return $canclone;
 9593: }
 9594: 
 9595: sub default_instcode_cloning {
 9596:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9597:     my (%codedefaults,@code_order,$canclone);
 9598:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9599:         %codedefaults = %{$codedefaultsref};
 9600:         @code_order = @{$codeorderref};
 9601:     } elsif ($clonedom) {
 9602:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9603:     }
 9604:     if (($domdefclone) && (@code_order)) {
 9605:         my @clonecodes = split(/\+/,$domdefclone);
 9606:         my $instcoderegexp ='^';
 9607:         foreach my $item (@code_order) {
 9608:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9609:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9610:             } else {
 9611:                 $instcoderegexp .= $codedefaults{$item};
 9612:             }
 9613:         }
 9614:         $instcoderegexp .= '$';
 9615:         my (@from,@to);
 9616:         eval {
 9617:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9618:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9619:         };
 9620:         if ((@from > 0) && (@to > 0)) {
 9621:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9622:             if (!@diffs) {
 9623:                 $canclone = 1;
 9624:             }
 9625:         }
 9626:     }
 9627:     return $canclone;
 9628: }
 9629: 
 9630: # ------------------------------------------------------- Course Group routines
 9631: 
 9632: sub get_coursegroups {
 9633:     my ($cdom,$cnum,$group,$namespace) = @_;
 9634:     return(&dump($namespace,$cdom,$cnum,$group));
 9635: }
 9636: 
 9637: sub modify_coursegroup {
 9638:     my ($cdom,$cnum,$groupsettings) = @_;
 9639:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9640: }
 9641: 
 9642: sub toggle_coursegroup_status {
 9643:     my ($cdom,$cnum,$group,$action) = @_;
 9644:     my ($from_namespace,$to_namespace);
 9645:     if ($action eq 'delete') {
 9646:         $from_namespace = 'coursegroups';
 9647:         $to_namespace = 'deleted_groups';
 9648:     } else {
 9649:         $from_namespace = 'deleted_groups';
 9650:         $to_namespace = 'coursegroups';
 9651:     }
 9652:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9653:     if (my $tmp = &error(%curr_group)) {
 9654:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9655:         return ('read error',$tmp);
 9656:     } else {
 9657:         my %savedsettings = %curr_group; 
 9658:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9659:         my $deloutcome;
 9660:         if ($result eq 'ok') {
 9661:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9662:         } else {
 9663:             return ('write error',$result);
 9664:         }
 9665:         if ($deloutcome eq 'ok') {
 9666:             return 'ok';
 9667:         } else {
 9668:             return ('delete error',$deloutcome);
 9669:         }
 9670:     }
 9671: }
 9672: 
 9673: sub modify_group_roles {
 9674:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9675:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9676:     my $role = 'gr/'.&escape($userprivs);
 9677:     my ($uname,$udom) = split(/:/,$user);
 9678:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9679:     if ($result eq 'ok') {
 9680:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9681:     }
 9682:     return $result;
 9683: }
 9684: 
 9685: sub modify_coursegroup_membership {
 9686:     my ($cdom,$cnum,$membership) = @_;
 9687:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9688:     return $result;
 9689: }
 9690: 
 9691: sub get_active_groups {
 9692:     my ($udom,$uname,$cdom,$cnum) = @_;
 9693:     my $now = time;
 9694:     my %groups = ();
 9695:     foreach my $key (keys(%env)) {
 9696:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9697:             my ($start,$end) = split(/\./,$env{$key});
 9698:             if (($end!=0) && ($end<$now)) { next; }
 9699:             if (($start!=0) && ($start>$now)) { next; }
 9700:             if ($1 eq $cdom && $2 eq $cnum) {
 9701:                 $groups{$3} = $env{$key} ;
 9702:             }
 9703:         }
 9704:     }
 9705:     return %groups;
 9706: }
 9707: 
 9708: sub get_group_membership {
 9709:     my ($cdom,$cnum,$group) = @_;
 9710:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9711: }
 9712: 
 9713: sub get_users_groups {
 9714:     my ($udom,$uname,$courseid) = @_;
 9715:     my @usersgroups;
 9716:     my $cachetime=1800;
 9717: 
 9718:     my $hashid="$udom:$uname:$courseid";
 9719:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9720:     if (defined($cached)) {
 9721:         @usersgroups = split(/:/,$grouplist);
 9722:     } else {  
 9723:         $grouplist = '';
 9724:         my $courseurl = &courseid_to_courseurl($courseid);
 9725:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9726:         my $access_end = $env{'course.'.$courseid.
 9727:                               '.default_enrollment_end_date'};
 9728:         my $now = time;
 9729:         foreach my $key (keys(%roleshash)) {
 9730:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9731:                 my $group = $1;
 9732:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9733:                     my $start = $2;
 9734:                     my $end = $1;
 9735:                     if ($start == -1) { next; } # deleted from group
 9736:                     if (($start!=0) && ($start>$now)) { next; }
 9737:                     if (($end!=0) && ($end<$now)) {
 9738:                         if ($access_end && $access_end < $now) {
 9739:                             if ($access_end - $end < 86400) {
 9740:                                 push(@usersgroups,$group);
 9741:                             }
 9742:                         }
 9743:                         next;
 9744:                     }
 9745:                     push(@usersgroups,$group);
 9746:                 }
 9747:             }
 9748:         }
 9749:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9750:         $grouplist = join(':',@usersgroups);
 9751:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9752:     }
 9753:     return @usersgroups;
 9754: }
 9755: 
 9756: sub devalidate_getgroups_cache {
 9757:     my ($udom,$uname,$cdom,$cnum)=@_;
 9758:     my $courseid = $cdom.'_'.$cnum;
 9759: 
 9760:     my $hashid="$udom:$uname:$courseid";
 9761:     &devalidate_cache_new('getgroups',$hashid);
 9762: }
 9763: 
 9764: # ------------------------------------------------------------------ Plain Text
 9765: 
 9766: sub plaintext {
 9767:     my ($short,$type,$cid,$forcedefault) = @_;
 9768:     if ($short =~ m{^cr/}) {
 9769: 	return (split('/',$short))[-1];
 9770:     }
 9771:     if (!defined($cid)) {
 9772:         $cid = $env{'request.course.id'};
 9773:     }
 9774:     my %rolenames = (
 9775:                       Course    => 'std',
 9776:                       Community => 'alt1',
 9777:                       Placement => 'std',
 9778:                     );
 9779:     if ($cid ne '') {
 9780:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9781:             unless ($forcedefault) {
 9782:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9783:                 &Apache::lonlocal::mt_escape(\$roletext);
 9784:                 return &Apache::lonlocal::mt($roletext);
 9785:             }
 9786:         }
 9787:     }
 9788:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9789:         (defined($rolenames{$type})) && 
 9790:         (defined($prp{$short}{$rolenames{$type}}))) {
 9791:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9792:     } elsif ($cid ne '') {
 9793:         my $crstype = $env{'course.'.$cid.'.type'};
 9794:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9795:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9796:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9797:         }
 9798:     }
 9799:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9800: }
 9801: 
 9802: # ----------------------------------------------------------------- Assign Role
 9803: 
 9804: sub assignrole {
 9805:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9806:         $context)=@_;
 9807:     my $mrole;
 9808:     if ($role =~ /^cr\//) {
 9809:         my $cwosec=$url;
 9810:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9811: 	unless (&allowed('ccr',$cwosec)) {
 9812:            my $refused = 1;
 9813:            if ($context eq 'requestcourses') {
 9814:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9815:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9816:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9817:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9818:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9819:                            if ($crsenv{'internal.courseowner'} eq
 9820:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9821:                                $refused = '';
 9822:                            }
 9823:                        }
 9824:                    }
 9825:                }
 9826:            }
 9827:            if ($refused) {
 9828:                &logthis('Refused custom assignrole: '.
 9829:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9830:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9831:                return 'refused';
 9832:            }
 9833:         }
 9834:         $mrole='cr';
 9835:     } elsif ($role =~ /^gr\//) {
 9836:         my $cwogrp=$url;
 9837:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9838:         unless (&allowed('mdg',$cwogrp)) {
 9839:             &logthis('Refused group assignrole: '.
 9840:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9841:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9842:             return 'refused';
 9843:         }
 9844:         $mrole='gr';
 9845:     } else {
 9846:         my $cwosec=$url;
 9847:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9848:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9849:             my $refused;
 9850:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9851:                 if (!(&allowed('c'.$role,$url))) {
 9852:                     $refused = 1;
 9853:                 }
 9854:             } else {
 9855:                 $refused = 1;
 9856:             }
 9857:             if ($refused) {
 9858:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9859:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9860:                     my %crsenv;
 9861:                     if ($role eq 'cc' || $role eq 'co') {
 9862:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9863:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9864:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9865:                                 if ($crsenv{'internal.courseowner'} eq 
 9866:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9867:                                     $refused = '';
 9868:                                 }
 9869:                             }
 9870:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9871:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9872:                                 if ($crsenv{'internal.courseowner'} eq 
 9873:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9874:                                     $refused = '';
 9875:                                 }
 9876:                             }
 9877:                         }
 9878:                     }
 9879:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9880:                     if ($role eq 'st') {
 9881:                         $refused = '';
 9882:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9883:                         $refused = '';
 9884:                     }
 9885:                 } elsif ($context eq 'requestcourses') {
 9886:                     my @possroles = ('st','ta','ep','in','cc','co');
 9887:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9888:                         my $wrongcc;
 9889:                         if ($cnum =~ /^$match_community$/) {
 9890:                             $wrongcc = 1 if ($role eq 'cc');
 9891:                         } else {
 9892:                             $wrongcc = 1 if ($role eq 'co');
 9893:                         }
 9894:                         unless ($wrongcc) {
 9895:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9896:                             if ($crsenv{'internal.courseowner'} eq 
 9897:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9898:                                 $refused = '';
 9899:                             }
 9900:                         }
 9901:                     }
 9902:                 } elsif ($context eq 'requestauthor') {
 9903:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9904:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9905:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9906:                             $refused = '';
 9907:                         } else {
 9908:                             my %domdefaults = &get_domain_defaults($udom);
 9909:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9910:                                 my $checkbystatus;
 9911:                                 if ($env{'user.adv'}) { 
 9912:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9913:                                     if ($disposition eq 'automatic') {
 9914:                                         $refused = '';
 9915:                                     } elsif ($disposition eq '') {
 9916:                                         $checkbystatus = 1;
 9917:                                     } 
 9918:                                 } else {
 9919:                                     $checkbystatus = 1;
 9920:                                 }
 9921:                                 if ($checkbystatus) {
 9922:                                     if ($env{'environment.inststatus'}) {
 9923:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9924:                                         foreach my $type (@inststatuses) {
 9925:                                             if (($type ne '') &&
 9926:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9927:                                                 $refused = '';
 9928:                                             }
 9929:                                         }
 9930:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9931:                                         $refused = '';
 9932:                                     }
 9933:                                 }
 9934:                             }
 9935:                         }
 9936:                     }
 9937:                 }
 9938:                 if ($refused) {
 9939:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9940:                              ' '.$role.' '.$end.' '.$start.' by '.
 9941: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9942:                     return 'refused';
 9943:                 }
 9944:             }
 9945:         } elsif ($role eq 'au') {
 9946:             if ($url ne '/'.$udom.'/') {
 9947:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9948:                          ' to assign author role for '.$uname.':'.$udom.
 9949:                          ' in domain: '.$url.' refused (wrong domain).');
 9950:                 return 'refused';
 9951:             }
 9952:         }
 9953:         $mrole=$role;
 9954:     }
 9955:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9956:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9957:     if ($end) { $command.='_'.$end; }
 9958:     if ($start) {
 9959: 	if ($end) { 
 9960:            $command.='_'.$start; 
 9961:         } else {
 9962:            $command.='_0_'.$start;
 9963:         }
 9964:     }
 9965:     my $origstart = $start;
 9966:     my $origend = $end;
 9967:     my $delflag;
 9968: # actually delete
 9969:     if ($deleteflag) {
 9970: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9971: # modify command to delete the role
 9972:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9973:                 "$udom:$uname:$url".'_'."$mrole";
 9974: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9975: # set start and finish to negative values for userrolelog
 9976:            $start=-1;
 9977:            $end=-1;
 9978:            $delflag = 1;
 9979:         }
 9980:     }
 9981: # send command
 9982:     my $answer=&reply($command,&homeserver($uname,$udom));
 9983: # log new user role if status is ok
 9984:     if ($answer eq 'ok') {
 9985: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9986:         if (($role eq 'cc') || ($role eq 'in') ||
 9987:             ($role eq 'ep') || ($role eq 'ad') ||
 9988:             ($role eq 'ta') || ($role eq 'st') ||
 9989:             ($role=~/^cr/) || ($role eq 'gr') ||
 9990:             ($role eq 'co')) {
 9991: # for course roles, perform group memberships changes triggered by role change.
 9992:             unless ($role =~ /^gr/) {
 9993:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9994:                                                  $origstart,$selfenroll,$context);
 9995:             }
 9996:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9997:                            $selfenroll,$context);
 9998:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9999:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10000:                  ($role eq 'da')) {
10001:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10002:                            $context);
10003:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10004:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10005:                              $context); 
10006:         }
10007:         if ($role eq 'cc') {
10008:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10009:         }
10010:     }
10011:     return $answer;
10012: }
10013: 
10014: sub autoupdate_coowners {
10015:     my ($url,$end,$start,$uname,$udom) = @_;
10016:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10017:     if (($cdom ne '') && ($cnum ne '')) {
10018:         my $now = time;
10019:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10020:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10021:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10022:             my $instcode = $coursehash{'internal.coursecode'};
10023:             if ($instcode ne '') {
10024:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10025:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10026:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10027:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10028:                         if ($result eq 'valid') {
10029:                             if ($coursehash{'internal.co-owners'}) {
10030:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10031:                                     push(@newcoowners,$coowner);
10032:                                 }
10033:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10034:                                     push(@newcoowners,$uname.':'.$udom);
10035:                                 }
10036:                                 @newcoowners = sort(@newcoowners);
10037:                             } else {
10038:                                 push(@newcoowners,$uname.':'.$udom);
10039:                             }
10040:                         } else {
10041:                             if ($coursehash{'internal.co-owners'}) {
10042:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10043:                                     unless ($coowner eq $uname.':'.$udom) {
10044:                                         push(@newcoowners,$coowner);
10045:                                     }
10046:                                 }
10047:                                 unless (@newcoowners > 0) {
10048:                                     $delcoowners = 1;
10049:                                     $coowners = '';
10050:                                 }
10051:                             }
10052:                         }
10053:                         if (@newcoowners || $delcoowners) {
10054:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10055:                                             $delcoowners,@newcoowners);
10056:                         }
10057:                     }
10058:                 }
10059:             }
10060:         }
10061:     }
10062: }
10063: 
10064: sub store_coowners {
10065:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10066:     my $cid = $cdom.'_'.$cnum;
10067:     my ($coowners,$delresult,$putresult);
10068:     if (@newcoowners) {
10069:         $coowners = join(',',@newcoowners);
10070:         my %coownershash = (
10071:                             'internal.co-owners' => $coowners,
10072:                            );
10073:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10074:         if ($putresult eq 'ok') {
10075:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10076:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10077:             }
10078:         }
10079:     }
10080:     if ($delcoowners) {
10081:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10082:         if ($delresult eq 'ok') {
10083:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10084:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10085:             }
10086:         }
10087:     }
10088:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10089:         my %crsinfo =
10090:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10091:         if (ref($crsinfo{$cid}) eq 'HASH') {
10092:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10093:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10094:         }
10095:     }
10096: }
10097: 
10098: # -------------------------------------------------- Modify user authentication
10099: # Overrides without validation
10100: 
10101: sub modifyuserauth {
10102:     my ($udom,$uname,$umode,$upass)=@_;
10103:     my $uhome=&homeserver($uname,$udom);
10104:     my $allowed;
10105:     if (&allowed('mau',$udom)) {
10106:         $allowed = 1;
10107:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10108:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10109:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10110:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10111:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10112:         if (($cdom ne '') && ($cnum ne '')) {
10113:             my $is_owner = &is_course_owner($cdom,$cnum);
10114:             if ($is_owner) {
10115:                 $allowed = 1;
10116:             }
10117:         }
10118:     }
10119:     unless ($allowed) { return 'refused'; }
10120:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10121:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10122:              ' in domain '.$env{'request.role.domain'});  
10123:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10124: 		     &escape($upass),$uhome);
10125:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10126:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10127:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10128:     &log($udom,,$uname,$uhome,
10129:         'Authentication changed by '.$env{'user.domain'}.', '.
10130:                                      $env{'user.name'}.', '.$umode.
10131:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10132:     unless ($reply eq 'ok') {
10133:         &logthis('Authentication mode error: '.$reply);
10134: 	return 'error: '.$reply;
10135:     }   
10136:     return 'ok';
10137: }
10138: 
10139: # --------------------------------------------------------------- Modify a user
10140: 
10141: sub modifyuser {
10142:     my ($udom,    $uname, $uid,
10143:         $umode,   $upass, $first,
10144:         $middle,  $last,  $gene,
10145:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10146:     $udom= &LONCAPA::clean_domain($udom);
10147:     $uname=&LONCAPA::clean_username($uname);
10148:     my $showcandelete = 'none';
10149:     if (ref($candelete) eq 'ARRAY') {
10150:         if (@{$candelete} > 0) {
10151:             $showcandelete = join(', ',@{$candelete});
10152:         }
10153:     }
10154:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10155:              $umode.', '.$first.', '.$middle.', '.
10156: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10157:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10158:                                      ' desiredhome not specified'). 
10159:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10160:              ' in domain '.$env{'request.role.domain'});
10161:     my $uhome=&homeserver($uname,$udom,'true');
10162:     my $newuser;
10163:     if ($uhome eq 'no_host') {
10164:         $newuser = 1;
10165:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10166:                 ($umode eq 'lti')) {
10167:             return 'error: more information needed to create new user';
10168:         }
10169:     }
10170: # ----------------------------------------------------------------- Create User
10171:     if (($uhome eq 'no_host') && 
10172: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10173:         my $unhome='';
10174:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10175:             $unhome = $desiredhome;
10176: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10177: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10178:         } else { # load balancing routine for determining $unhome
10179:             my $loadm=10000000;
10180: 	    my %servers = &get_servers($udom,'library');
10181: 	    foreach my $tryserver (keys(%servers)) {
10182: 		my $answer=reply('load',$tryserver);
10183: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10184: 		    $loadm=$answer;
10185: 		    $unhome=$tryserver;
10186: 		}
10187: 	    }
10188:         }
10189:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10190: 	    return 'error: unable to find a home server for '.$uname.
10191:                    ' in domain '.$udom;
10192:         }
10193:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10194:                          &escape($upass),$unhome);
10195: 	unless ($reply eq 'ok') {
10196:             return 'error: '.$reply;
10197:         }   
10198:         $uhome=&homeserver($uname,$udom,'true');
10199:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10200: 	    return 'error: unable verify users home machine.';
10201:         }
10202:     }   # End of creation of new user
10203: # ---------------------------------------------------------------------- Add ID
10204:     if ($uid) {
10205:        $uid=~tr/A-Z/a-z/;
10206:        my %uidhash=&idrget($udom,$uname);
10207:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10208:          && (!$forceid)) {
10209: 	  unless ($uid eq $uidhash{$uname}) {
10210: 	      return 'error: user id "'.$uid.'" does not match '.
10211:                   'current user id "'.$uidhash{$uname}.'".';
10212:           }
10213:        } else {
10214: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10215:        }
10216:     }
10217: # -------------------------------------------------------------- Add names, etc
10218:     my @tmp=&get('environment',
10219: 		   ['firstname','middlename','lastname','generation','id',
10220:                     'permanentemail','inststatus'],
10221: 		   $udom,$uname);
10222:     my (%names,%oldnames);
10223:     if ($tmp[0] =~ m/^error:.*/) { 
10224:         %names=(); 
10225:     } else {
10226:         %names = @tmp;
10227:         %oldnames = %names;
10228:     }
10229: #
10230: # If name, email and/or uid are blank (e.g., because an uploaded file
10231: # of users did not contain them), do not overwrite existing values
10232: # unless field is in $candelete array ref.  
10233: #
10234: 
10235:     my @fields = ('firstname','middlename','lastname','generation',
10236:                   'permanentemail','id');
10237:     my %newvalues;
10238:     if (ref($candelete) eq 'ARRAY') {
10239:         foreach my $field (@fields) {
10240:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10241:                 if ($field eq 'firstname') {
10242:                     $names{$field} = $first;
10243:                 } elsif ($field eq 'middlename') {
10244:                     $names{$field} = $middle;
10245:                 } elsif ($field eq 'lastname') {
10246:                     $names{$field} = $last;
10247:                 } elsif ($field eq 'generation') { 
10248:                     $names{$field} = $gene;
10249:                 } elsif ($field eq 'permanentemail') {
10250:                     $names{$field} = $email;
10251:                 } elsif ($field eq 'id') {
10252:                     $names{$field}  = $uid;
10253:                 }
10254:             }
10255:         }
10256:     }
10257:     if ($first)  { $names{'firstname'}  = $first; }
10258:     if (defined($middle)) { $names{'middlename'} = $middle; }
10259:     if ($last)   { $names{'lastname'}   = $last; }
10260:     if (defined($gene))   { $names{'generation'} = $gene; }
10261:     if ($email) {
10262:        $email=~s/[^\w\@\.\-\,]//gs;
10263:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10264:     }
10265:     if ($uid) { $names{'id'}  = $uid; }
10266:     if (defined($inststatus)) {
10267:         $names{'inststatus'} = '';
10268:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10269:         if (ref($usertypes) eq 'HASH') {
10270:             my @okstatuses; 
10271:             foreach my $item (split(/:/,$inststatus)) {
10272:                 if (defined($usertypes->{$item})) {
10273:                     push(@okstatuses,$item);  
10274:                 }
10275:             }
10276:             if (@okstatuses) {
10277:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10278:             }
10279:         }
10280:     }
10281:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10282:                  $umode.', '.$first.', '.$middle.', '.
10283:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10284:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10285:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10286:     } else {
10287:         $logmsg .= ' during self creation';
10288:     }
10289:     my $changed;
10290:     if ($newuser) {
10291:         $changed = 1;
10292:     } else {
10293:         foreach my $field (@fields) {
10294:             if ($names{$field} ne $oldnames{$field}) {
10295:                 $changed = 1;
10296:                 last;
10297:             }
10298:         }
10299:     }
10300:     unless ($changed) {
10301:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10302:         &logthis($logmsg);
10303:         return 'ok';
10304:     }
10305:     my $reply = &put('environment', \%names, $udom,$uname);
10306:     if ($reply ne 'ok') { 
10307:         return 'error: '.$reply;
10308:     }
10309:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10310:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10311:     }
10312:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10313:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10314:     $logmsg = 'Success modifying user '.$logmsg;
10315:     &logthis($logmsg);
10316:     return 'ok';
10317: }
10318: 
10319: # -------------------------------------------------------------- Modify student
10320: 
10321: sub modifystudent {
10322:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10323:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10324:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10325:     if (!$cid) {
10326: 	unless ($cid=$env{'request.course.id'}) {
10327: 	    return 'not_in_class';
10328: 	}
10329:     }
10330: # --------------------------------------------------------------- Make the user
10331:     my $reply=&modifyuser
10332: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10333:          $desiredhome,$email,$inststatus);
10334:     unless ($reply eq 'ok') { return $reply; }
10335:     # This will cause &modify_student_enrollment to get the uid from the
10336:     # student's environment
10337:     $uid = undef if (!$forceid);
10338:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10339:                                         $gene,$usec,$end,$start,$type,$locktype,
10340:                                         $cid,$selfenroll,$context,$credits,$instsec);
10341:     return $reply;
10342: }
10343: 
10344: sub modify_student_enrollment {
10345:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10346:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10347:     my ($cdom,$cnum,$chome);
10348:     if (!$cid) {
10349: 	unless ($cid=$env{'request.course.id'}) {
10350: 	    return 'not_in_class';
10351: 	}
10352: 	$cdom=$env{'course.'.$cid.'.domain'};
10353: 	$cnum=$env{'course.'.$cid.'.num'};
10354:     } else {
10355: 	($cdom,$cnum)=split(/_/,$cid);
10356:     }
10357:     $chome=$env{'course.'.$cid.'.home'};
10358:     if (!$chome) {
10359: 	$chome=&homeserver($cnum,$cdom);
10360:     }
10361:     if (!$chome) { return 'unknown_course'; }
10362:     # Make sure the user exists
10363:     my $uhome=&homeserver($uname,$udom);
10364:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10365: 	return 'error: no such user';
10366:     }
10367:     # Get student data if we were not given enough information
10368:     if (!defined($first)  || $first  eq '' || 
10369:         !defined($last)   || $last   eq '' || 
10370:         !defined($uid)    || $uid    eq '' || 
10371:         !defined($middle) || $middle eq '' || 
10372:         !defined($gene)   || $gene   eq '') {
10373:         # They did not supply us with enough data to enroll the student, so
10374:         # we need to pick up more information.
10375:         my %tmp = &get('environment',
10376:                        ['firstname','middlename','lastname', 'generation','id']
10377:                        ,$udom,$uname);
10378: 
10379:         #foreach my $key (keys(%tmp)) {
10380:         #    &logthis("key $key = ".$tmp{$key});
10381:         #}
10382:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10383:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10384:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10385:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10386:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10387:     }
10388:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10389:     my $user = "$uname:$udom";
10390:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10391:     my $reply=cput('classlist',
10392: 		   {$user => 
10393: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10394: 		   $cdom,$cnum);
10395:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10396:         &devalidate_getsection_cache($udom,$uname,$cid);
10397:     } else { 
10398: 	return 'error: '.$reply;
10399:     }
10400:     # Add student role to user
10401:     my $uurl='/'.$cid;
10402:     $uurl=~s/\_/\//g;
10403:     if ($usec) {
10404: 	$uurl.='/'.$usec;
10405:     }
10406:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10407:                              $selfenroll,$context);
10408:     if ($result ne 'ok') {
10409:         if ($old_entry{$user} ne '') {
10410:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10411:         } else {
10412:             $reply = &del('classlist',[$user],$cdom,$cnum);
10413:         }
10414:     }
10415:     return $result; 
10416: }
10417: 
10418: sub format_name {
10419:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10420:     my $name;
10421:     if ($first ne 'lastname') {
10422: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10423:     } else {
10424: 	if ($lastname=~/\S/) {
10425: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10426: 	    $name=~s/\s+,/,/;
10427: 	} else {
10428: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10429: 	}
10430:     }
10431:     $name=~s/^\s+//;
10432:     $name=~s/\s+$//;
10433:     $name=~s/\s+/ /g;
10434:     return $name;
10435: }
10436: 
10437: # ------------------------------------------------- Write to course preferences
10438: 
10439: sub writecoursepref {
10440:     my ($courseid,%prefs)=@_;
10441:     $courseid=~s/^\///;
10442:     $courseid=~s/\_/\//g;
10443:     my ($cdomain,$cnum)=split(/\//,$courseid);
10444:     my $chome=homeserver($cnum,$cdomain);
10445:     if (($chome eq '') || ($chome eq 'no_host')) { 
10446: 	return 'error: no such course';
10447:     }
10448:     my $cstring='';
10449:     foreach my $pref (keys(%prefs)) {
10450: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10451:     }
10452:     $cstring=~s/\&$//;
10453:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10454: }
10455: 
10456: # ---------------------------------------------------------- Make/modify course
10457: 
10458: sub createcourse {
10459:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10460:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10461:     $url=&declutter($url);
10462:     my $cid='';
10463:     if ($context eq 'requestcourses') {
10464:         my $can_create = 0;
10465:         my ($ownername,$ownerdom) = split(':',$course_owner);
10466:         if ($udom eq $ownerdom) {
10467:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10468:                                   $context)) {
10469:                 $can_create = 1;
10470:             }
10471:         } else {
10472:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10473:                                            $category);
10474:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10475:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10476:                 if (@curr > 0) {
10477:                     my @options = qw(approval validate autolimit);
10478:                     my $optregex = join('|',@options);
10479:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10480:                         $can_create = 1;
10481:                     }
10482:                 }
10483:             }
10484:         }
10485:         if ($can_create) {
10486:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10487:                 unless (&allowed('ccc',$udom)) {
10488:                     return 'refused'; 
10489:                 }
10490:             }
10491:         } else {
10492:             return 'refused';
10493:         }
10494:     } elsif (!&allowed('ccc',$udom)) {
10495:         return 'refused';
10496:     }
10497: # --------------------------------------------------------------- Get Unique ID
10498:     my $uname;
10499:     if ($cnum =~ /^$match_courseid$/) {
10500:         my $chome=&homeserver($cnum,$udom,'true');
10501:         if (($chome eq '') || ($chome eq 'no_host')) {
10502:             $uname = $cnum;
10503:         } else {
10504:             $uname = &generate_coursenum($udom,$crstype);
10505:         }
10506:     } else {
10507:         $uname = &generate_coursenum($udom,$crstype);
10508:     }
10509:     return $uname if ($uname =~ /^error/);
10510: # -------------------------------------------------- Check supplied server name
10511:     if (!defined($course_server)) {
10512:         if (defined(&domain($udom,'primary'))) {
10513:             $course_server = &domain($udom,'primary');
10514:         } else {
10515:             $course_server = $env{'user.home'}; 
10516:         }
10517:     }
10518:     my %host_servers =
10519:         &Apache::lonnet::get_servers($udom,'library');
10520:     unless ($host_servers{$course_server}) {
10521:         return 'error: invalid home server for course: '.$course_server;
10522:     }
10523: # ------------------------------------------------------------- Make the course
10524:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10525:                       $course_server);
10526:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10527:     my $uhome=&homeserver($uname,$udom,'true');
10528:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10529: 	return 'error: no such course';
10530:     }
10531: # ----------------------------------------------------------------- Course made
10532: # log existence
10533:     my $now = time;
10534:     my $newcourse = {
10535:                     $udom.'_'.$uname => {
10536:                                      description => $description,
10537:                                      inst_code   => $inst_code,
10538:                                      owner       => $course_owner,
10539:                                      type        => $crstype,
10540:                                      creator     => $env{'user.name'}.':'.
10541:                                                     $env{'user.domain'},
10542:                                      created     => $now,
10543:                                      context     => $context,
10544:                                                 },
10545:                     };
10546:     &courseidput($udom,$newcourse,$uhome,'notime');
10547: # set toplevel url
10548:     my $topurl=$url;
10549:     unless ($nonstandard) {
10550: # ------------------------------------------ For standard courses, make top url
10551:         my $mapurl=&clutter($url);
10552:         if ($mapurl eq '/res/') { $mapurl=''; }
10553:         $env{'form.initmap'}=(<<ENDINITMAP);
10554: <map>
10555: <resource id="1" type="start"></resource>
10556: <resource id="2" src="$mapurl"></resource>
10557: <resource id="3" type="finish"></resource>
10558: <link index="1" from="1" to="2"></link>
10559: <link index="2" from="2" to="3"></link>
10560: </map>
10561: ENDINITMAP
10562:         $topurl=&declutter(
10563:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10564:                           );
10565:     }
10566: # ----------------------------------------------------------- Write preferences
10567:     &writecoursepref($udom.'_'.$uname,
10568:                      ('description'              => $description,
10569:                       'url'                      => $topurl,
10570:                       'internal.creator'         => $env{'user.name'}.':'.
10571:                                                     $env{'user.domain'},
10572:                       'internal.created'         => $now,
10573:                       'internal.creationcontext' => $context)
10574:                     );
10575:     return '/'.$udom.'/'.$uname;
10576: }
10577: 
10578: # ------------------------------------------------------------------- Create ID
10579: sub generate_coursenum {
10580:     my ($udom,$crstype) = @_;
10581:     my $domdesc = &domain($udom);
10582:     return 'error: invalid domain' if ($domdesc eq '');
10583:     my $first;
10584:     if ($crstype eq 'Community') {
10585:         $first = '0';
10586:     } else {
10587:         $first = int(1+rand(9)); 
10588:     } 
10589:     my $uname=$first.
10590:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10591:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10592:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10593: # ----------------------------------------------- Make sure that does not exist
10594:     my $uhome=&homeserver($uname,$udom,'true');
10595:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10596:         if ($crstype eq 'Community') {
10597:             $first = '0';
10598:         } else {
10599:             $first = int(1+rand(9));
10600:         }
10601:         $uname=$first.
10602:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10603:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10604:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10605:         $uhome=&homeserver($uname,$udom,'true');
10606:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10607:             return 'error: unable to generate unique course-ID';
10608:         }
10609:     }
10610:     return $uname;
10611: }
10612: 
10613: sub is_course {
10614:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10615:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10616: 
10617:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10618:     my $uhome=&homeserver($cnum,$cdom);
10619:     my $iscourse;
10620:     if (grep { $_ eq $uhome } current_machine_ids()) {
10621:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10622:     } else {
10623:         my $hashid = $cdom.':'.$cnum;
10624:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10625:         unless (defined($cached)) {
10626:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10627:                                         $cnum,undef,undef,'.');
10628:             $iscourse = 0;
10629:             if (exists($courses{$cdom.'_'.$cnum})) {
10630:                 $iscourse = 1;
10631:             }
10632:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10633:         }
10634:     }
10635:     return unless ($iscourse);
10636:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10637: }
10638: 
10639: sub store_userdata {
10640:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10641:     my $result;
10642:     if ($datakey ne '') {
10643:         if (ref($storehash) eq 'HASH') {
10644:             if ($udom eq '' || $uname eq '') {
10645:                 $udom = $env{'user.domain'};
10646:                 $uname = $env{'user.name'};
10647:             }
10648:             my $uhome=&homeserver($uname,$udom);
10649:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10650:                 $result = 'error: no_host';
10651:             } else {
10652:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10653:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10654: 
10655:                 my $namevalue='';
10656:                 foreach my $key (keys(%{$storehash})) {
10657:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10658:                 }
10659:                 $namevalue=~s/\&$//;
10660:                 unless ($namespace eq 'courserequests') {
10661:                     $datakey = &escape($datakey);
10662:                 }
10663:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10664:                                   $namevalue,$uhome);
10665:             }
10666:         } else {
10667:             $result = 'error: data to store was not a hash reference'; 
10668:         }
10669:     } else {
10670:         $result= 'error: invalid requestkey'; 
10671:     }
10672:     return $result;
10673: }
10674: 
10675: # ---------------------------------------------------------- Assign Custom Role
10676: 
10677: sub assigncustomrole {
10678:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10679:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10680:                        $end,$start,$deleteflag,$selfenroll,$context);
10681: }
10682: 
10683: # ----------------------------------------------------------------- Revoke Role
10684: 
10685: sub revokerole {
10686:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10687:     my $now=time;
10688:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10689: }
10690: 
10691: # ---------------------------------------------------------- Revoke Custom Role
10692: 
10693: sub revokecustomrole {
10694:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10695:     my $now=time;
10696:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10697:            $deleteflag,$selfenroll,$context);
10698: }
10699: 
10700: # ------------------------------------------------------------ Disk usage
10701: sub diskusage {
10702:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10703:     $directorypath =~ s/\/$//;
10704:     my $listing=&reply('du2:'.&escape($directorypath).':'
10705:                        .&escape($getpropath).':'.&escape($uname).':'
10706:                        .&escape($udom),homeserver($uname,$udom));
10707:     if ($listing eq 'unknown_cmd') {
10708:         if ($getpropath) {
10709:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10710:         }
10711:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10712:     }
10713:     return $listing;
10714: }
10715: 
10716: sub is_locked {
10717:     my ($file_name, $domain, $user, $which) = @_;
10718:     my @check;
10719:     my $is_locked;
10720:     push (@check,$file_name);
10721:     my %locked = &get('file_permissions',\@check,
10722: 		      $env{'user.domain'},$env{'user.name'});
10723:     my ($tmp)=keys(%locked);
10724:     if ($tmp=~/^error:/) { undef(%locked); }
10725:     
10726:     if (ref($locked{$file_name}) eq 'ARRAY') {
10727:         $is_locked = 'false';
10728:         foreach my $entry (@{$locked{$file_name}}) {
10729:            if (ref($entry) eq 'ARRAY') {
10730:                $is_locked = 'true';
10731:                if (ref($which) eq 'ARRAY') {
10732:                    push(@{$which},$entry);
10733:                } else {
10734:                    last;
10735:                }
10736:            }
10737:        }
10738:     } else {
10739:         $is_locked = 'false';
10740:     }
10741:     return $is_locked;
10742: }
10743: 
10744: sub declutter_portfile {
10745:     my ($file) = @_;
10746:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10747:     return $file;
10748: }
10749: 
10750: # ------------------------------------------------------------- Mark as Read Only
10751: 
10752: sub mark_as_readonly {
10753:     my ($domain,$user,$files,$what) = @_;
10754:     my %current_permissions = &dump('file_permissions',$domain,$user);
10755:     my ($tmp)=keys(%current_permissions);
10756:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10757:     foreach my $file (@{$files}) {
10758: 	$file = &declutter_portfile($file);
10759:         push(@{$current_permissions{$file}},$what);
10760:     }
10761:     &put('file_permissions',\%current_permissions,$domain,$user);
10762:     return;
10763: }
10764: 
10765: # ------------------------------------------------------------Save Selected Files
10766: 
10767: sub save_selected_files {
10768:     my ($user, $path, @files) = @_;
10769:     my $filename = $user."savedfiles";
10770:     my @other_files = &files_not_in_path($user, $path);
10771:     open (OUT,'>',LONCAPA::tempdir().$filename);
10772:     foreach my $file (@files) {
10773:         print (OUT $env{'form.currentpath'}.$file."\n");
10774:     }
10775:     foreach my $file (@other_files) {
10776:         print (OUT $file."\n");
10777:     }
10778:     close (OUT);
10779:     return 'ok';
10780: }
10781: 
10782: sub clear_selected_files {
10783:     my ($user) = @_;
10784:     my $filename = $user."savedfiles";
10785:     open (OUT,'>',LONCAPA::tempdir().$filename);
10786:     print (OUT undef);
10787:     close (OUT);
10788:     return ("ok");    
10789: }
10790: 
10791: sub files_in_path {
10792:     my ($user, $path) = @_;
10793:     my $filename = $user."savedfiles";
10794:     my %return_files;
10795:     open (IN,'<',LONCAPA::tempdir().$filename);
10796:     while (my $line_in = <IN>) {
10797:         chomp ($line_in);
10798:         my @paths_and_file = split (m!/!, $line_in);
10799:         my $file_part = pop (@paths_and_file);
10800:         my $path_part = join ('/', @paths_and_file);
10801:         $path_part.='/';
10802:         my $path_and_file = $path_part.$file_part;
10803:         if ($path_part eq $path) {
10804:             $return_files{$file_part}= 'selected';
10805:         }
10806:     }
10807:     close (IN);
10808:     return (\%return_files);
10809: }
10810: 
10811: # called in portfolio select mode, to show files selected NOT in current directory
10812: sub files_not_in_path {
10813:     my ($user, $path) = @_;
10814:     my $filename = $user."savedfiles";
10815:     my @return_files;
10816:     my $path_part;
10817:     open(IN, '<',LONCAPA::tempdir().$filename);
10818:     while (my $line = <IN>) {
10819:         #ok, I know it's clunky, but I want it to work
10820:         my @paths_and_file = split(m|/|, $line);
10821:         my $file_part = pop(@paths_and_file);
10822:         chomp($file_part);
10823:         my $path_part = join('/', @paths_and_file);
10824:         $path_part .= '/';
10825:         my $path_and_file = $path_part.$file_part;
10826:         if ($path_part ne $path) {
10827:             push(@return_files, ($path_and_file));
10828:         }
10829:     }
10830:     close(OUT);
10831:     return (@return_files);
10832: }
10833: 
10834: #------------------------------Submitted/Handedback Portfolio Files Versioning
10835:  
10836: sub portfiles_versioning {
10837:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10838:     my $portfolio_root = '/userfiles/portfolio';
10839:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10840:     foreach my $file (@{$portfiles}) {
10841:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10842:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10843:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10844:         my $getpropath = 1;
10845:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10846:                                              $stu_name,$getpropath);
10847:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10848:         my $new_answer = 
10849:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10850:         if ($new_answer ne 'problem getting file') {
10851:             push(@{$versioned_portfiles}, $directory.$new_answer);
10852:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10853:                               [$symb,$env{'request.course.id'},'graded']);
10854:         }
10855:     }
10856: }
10857: 
10858: sub get_next_version {
10859:     my ($answer_name, $answer_ext, $dir_list) = @_;
10860:     my $version;
10861:     if (ref($dir_list) eq 'ARRAY') {
10862:         foreach my $row (@{$dir_list}) {
10863:             my ($file) = split(/\&/,$row,2);
10864:             my ($file_name,$file_version,$file_ext) =
10865:                 &file_name_version_ext($file);
10866:             if (($file_name eq $answer_name) &&
10867:                 ($file_ext eq $answer_ext)) {
10868:                      # gets here if filename and extension match,
10869:                      # regardless of version
10870:                 if ($file_version ne '') {
10871:                     # a versioned file is found  so save it for later
10872:                     if ($file_version > $version) {
10873:                         $version = $file_version;
10874:                     }
10875:                 }
10876:             }
10877:         }
10878:     }
10879:     $version ++;
10880:     return($version);
10881: }
10882: 
10883: sub version_selected_portfile {
10884:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10885:     my ($answer_name,$answer_ver,$answer_ext) =
10886:         &file_name_version_ext($file_name);
10887:     my $new_answer;
10888:     $env{'form.copy'} =
10889:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10890:     if($env{'form.copy'} eq '-1') {
10891:         $new_answer = 'problem getting file';
10892:     } else {
10893:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10894:         my $copy_result = 
10895:             &finishuserfileupload($stu_name,$domain,'copy',
10896:                                   '/portfolio'.$directory.$new_answer);
10897:     }
10898:     undef($env{'form.copy'});
10899:     return ($new_answer);
10900: }
10901: 
10902: sub file_name_version_ext {
10903:     my ($file)=@_;
10904:     my @file_parts = split(/\./, $file);
10905:     my ($name,$version,$ext);
10906:     if (@file_parts > 1) {
10907:         $ext=pop(@file_parts);
10908:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10909:             $version=pop(@file_parts);
10910:         }
10911:         $name=join('.',@file_parts);
10912:     } else {
10913:         $name=join('.',@file_parts);
10914:     }
10915:     return($name,$version,$ext);
10916: }
10917: 
10918: #----------------------------------------------Get portfolio file permissions
10919: 
10920: sub get_portfile_permissions {
10921:     my ($domain,$user) = @_;
10922:     my %current_permissions = &dump('file_permissions',$domain,$user);
10923:     my ($tmp)=keys(%current_permissions);
10924:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10925:     return \%current_permissions;
10926: }
10927: 
10928: #---------------------------------------------Get portfolio file access controls
10929: 
10930: sub get_access_controls {
10931:     my ($current_permissions,$group,$file) = @_;
10932:     my %access;
10933:     my $real_file = $file;
10934:     $file =~ s/\.meta$//;
10935:     if (defined($file)) {
10936:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10937:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10938:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10939:             }
10940:         }
10941:     } else {
10942:         foreach my $key (keys(%{$current_permissions})) {
10943:             if ($key =~ /\0accesscontrol$/) {
10944:                 if (defined($group)) {
10945:                     if ($key !~ m-^\Q$group\E/-) {
10946:                         next;
10947:                     }
10948:                 }
10949:                 my ($fullpath) = split(/\0/,$key);
10950:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10951:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10952:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10953:                     }
10954:                 }
10955:             }
10956:         }
10957:     }
10958:     return %access;
10959: }
10960: 
10961: sub modify_access_controls {
10962:     my ($file_name,$changes,$domain,$user)=@_;
10963:     my ($outcome,$deloutcome);
10964:     my %store_permissions;
10965:     my %new_values;
10966:     my %new_control;
10967:     my %translation;
10968:     my @deletions = ();
10969:     my $now = time;
10970:     if (exists($$changes{'activate'})) {
10971:         if (ref($$changes{'activate'}) eq 'HASH') {
10972:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10973:             my $numnew = scalar(@newitems);
10974:             for (my $i=0; $i<$numnew; $i++) {
10975:                 my $newkey = $newitems[$i];
10976:                 my $newid = &Apache::loncommon::get_cgi_id();
10977:                 if ($newkey =~ /^\d+:/) { 
10978:                     $newkey =~ s/^(\d+)/$newid/;
10979:                     $translation{$1} = $newid;
10980:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10981:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10982:                     $translation{$1} = $newid;
10983:                 }
10984:                 $new_values{$file_name."\0".$newkey} = 
10985:                                           $$changes{'activate'}{$newitems[$i]};
10986:                 $new_control{$newkey} = $now;
10987:             }
10988:         }
10989:     }
10990:     my %todelete;
10991:     my %changed_items;
10992:     foreach my $action ('delete','update') {
10993:         if (exists($$changes{$action})) {
10994:             if (ref($$changes{$action}) eq 'HASH') {
10995:                 foreach my $key (keys(%{$$changes{$action}})) {
10996:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10997:                     if ($action eq 'delete') { 
10998:                         $todelete{$itemnum} = 1;
10999:                     } else {
11000:                         $changed_items{$itemnum} = $key;
11001:                     }
11002:                 }
11003:             }
11004:         }
11005:     }
11006:     # get lock on access controls for file.
11007:     my $lockhash = {
11008:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11009:                                                        ':'.$env{'user.domain'},
11010:                    }; 
11011:     my $tries = 0;
11012:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11013:    
11014:     while (($gotlock ne 'ok') && $tries < 10) {
11015:         $tries ++;
11016:         sleep(0.1);
11017:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11018:     }
11019:     if ($gotlock eq 'ok') {
11020:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11021:         my ($tmp)=keys(%curr_permissions);
11022:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11023:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11024:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11025:             if (ref($curr_controls) eq 'HASH') {
11026:                 foreach my $control_item (keys(%{$curr_controls})) {
11027:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11028:                     if (defined($todelete{$itemnum})) {
11029:                         push(@deletions,$file_name."\0".$control_item);
11030:                     } else {
11031:                         if (defined($changed_items{$itemnum})) {
11032:                             $new_control{$changed_items{$itemnum}} = $now;
11033:                             push(@deletions,$file_name."\0".$control_item);
11034:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11035:                         } else {
11036:                             $new_control{$control_item} = $$curr_controls{$control_item};
11037:                         }
11038:                     }
11039:                 }
11040:             }
11041:         }
11042:         my ($group);
11043:         if (&is_course($domain,$user)) {
11044:             ($group,my $file) = split(/\//,$file_name,2);
11045:         }
11046:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11047:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11048:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11049:         #  remove lock
11050:         my @del_lock = ($file_name."\0".'locked_access_records');
11051:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11052:         my $sqlresult =
11053:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11054:                                     $group);
11055:     } else {
11056:         $outcome = "error: could not obtain lockfile\n";  
11057:     }
11058:     return ($outcome,$deloutcome,\%new_values,\%translation);
11059: }
11060: 
11061: sub make_public_indefinitely {
11062:     my (@requrl) = @_;
11063:     return &automated_portfile_access('public',\@requrl);
11064: }
11065: 
11066: sub automated_portfile_access {
11067:     my ($accesstype,$addsref,$delsref,$info) = @_;
11068:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11069:         return 'invalid';
11070:     }
11071:     my %urls;
11072:     if (ref($addsref) eq 'ARRAY') {
11073:         foreach my $requrl (@{$addsref}) {
11074:             if (&is_portfolio_url($requrl)) {
11075:                 unless (exists($urls{$requrl})) {
11076:                     $urls{$requrl} = 'add';
11077:                 }
11078:             }
11079:         }
11080:     }
11081:     if (ref($delsref) eq 'ARRAY') {
11082:         foreach my $requrl (@{$delsref}) { 
11083:             if (&is_portfolio_url($requrl)) {
11084:                 unless (exists($urls{$requrl})) {
11085:                     $urls{$requrl} = 'delete'; 
11086:                 }
11087:             }
11088:         }
11089:     }
11090:     unless (keys(%urls)) {
11091:         return 'invalid';
11092:     }
11093:     my $ip;
11094:     if ($accesstype eq 'ip') {
11095:         if (ref($info) eq 'HASH') {
11096:             if ($info->{'ip'} ne '') {
11097:                 $ip = $info->{'ip'};
11098:             }
11099:         }
11100:         if ($ip eq '') {
11101:             return 'invalid';
11102:         }
11103:     }
11104:     my $errors;
11105:     my $now = time;
11106:     my %current_perms;
11107:     foreach my $requrl (sort(keys(%urls))) {
11108:         my $action;
11109:         if ($urls{$requrl} eq 'add') {
11110:             $action = 'activate';
11111:         } else {
11112:             $action = 'none';
11113:         }
11114:         my $aclnum = 0;
11115:         my (undef,$udom,$unum,$file_name,$group) =
11116:             &parse_portfolio_url($requrl);
11117:         unless (exists($current_perms{$unum.':'.$udom})) {
11118:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11119:         }
11120:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11121:                                                    $group,$file_name);
11122:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11123:             my ($num,$scope,$end,$start) = 
11124:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11125:             if ($scope eq $accesstype) {
11126:                 if (($start <= $now) && ($end == 0)) {
11127:                     if ($accesstype eq 'ip') {
11128:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11129:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11130:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11131:                                     if ($urls{$requrl} eq 'add') {
11132:                                         $action = 'none';
11133:                                         last;
11134:                                     } else {
11135:                                         $action = 'delete';
11136:                                         $aclnum = $num;
11137:                                         last;
11138:                                     }
11139:                                 }
11140:                             }
11141:                         }
11142:                     } elsif ($accesstype eq 'public') {
11143:                         if ($urls{$requrl} eq 'add') {
11144:                             $action = 'none';
11145:                             last;
11146:                         } else {
11147:                             $action = 'delete';
11148:                             $aclnum = $num;
11149:                             last;
11150:                         }
11151:                     }
11152:                 } elsif ($accesstype eq 'public') {
11153:                     $action = 'update';
11154:                     $aclnum = $num;
11155:                     last;
11156:                 }
11157:             }
11158:         }
11159:         if ($action eq 'none') {
11160:             next;
11161:         } else {
11162:             my %changes;
11163:             my $newend = 0;
11164:             my $newstart = $now;
11165:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11166:             $changes{$action}{$newkey} = {
11167:                 type => $accesstype,
11168:                 time => {
11169:                     start => $newstart,
11170:                     end   => $newend,
11171:                 },
11172:             };
11173:             if ($accesstype eq 'ip') {
11174:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11175:             }
11176:             my ($outcome,$deloutcome,$new_values,$translation) =
11177:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11178:             unless ($outcome eq 'ok') {
11179:                 $errors .= $outcome.' ';
11180:             }
11181:         }
11182:     }
11183:     if ($errors) {
11184:         $errors =~ s/\s$//;
11185:         return $errors;
11186:     } else {
11187:         return 'ok';
11188:     }
11189: }
11190: 
11191: #------------------------------------------------------Get Marked as Read Only
11192: 
11193: sub get_marked_as_readonly {
11194:     my ($domain,$user,$what,$group) = @_;
11195:     my $current_permissions = &get_portfile_permissions($domain,$user);
11196:     my @readonly_files;
11197:     my $cmp1=$what;
11198:     if (ref($what)) { $cmp1=join('',@{$what}) };
11199:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11200:         if (defined($group)) {
11201:             if ($file_name !~ m-^\Q$group\E/-) {
11202:                 next;
11203:             }
11204:         }
11205:         if (ref($value) eq "ARRAY"){
11206:             foreach my $stored_what (@{$value}) {
11207:                 my $cmp2=$stored_what;
11208:                 if (ref($stored_what) eq 'ARRAY') {
11209:                     $cmp2=join('',@{$stored_what});
11210:                 }
11211:                 if ($cmp1 eq $cmp2) {
11212:                     push(@readonly_files, $file_name);
11213:                     last;
11214:                 } elsif (!defined($what)) {
11215:                     push(@readonly_files, $file_name);
11216:                     last;
11217:                 }
11218:             }
11219:         }
11220:     }
11221:     return @readonly_files;
11222: }
11223: #-----------------------------------------------------------Get Marked as Read Only Hash
11224: 
11225: sub get_marked_as_readonly_hash {
11226:     my ($current_permissions,$group,$what) = @_;
11227:     my %readonly_files;
11228:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11229:         if (defined($group)) {
11230:             if ($file_name !~ m-^\Q$group\E/-) {
11231:                 next;
11232:             }
11233:         }
11234:         if (ref($value) eq "ARRAY"){
11235:             foreach my $stored_what (@{$value}) {
11236:                 if (ref($stored_what) eq 'ARRAY') {
11237:                     foreach my $lock_descriptor(@{$stored_what}) {
11238:                         if ($lock_descriptor eq 'graded') {
11239:                             $readonly_files{$file_name} = 'graded';
11240:                         } elsif ($lock_descriptor eq 'handback') {
11241:                             $readonly_files{$file_name} = 'handback';
11242:                         } else {
11243:                             if (!exists($readonly_files{$file_name})) {
11244:                                 $readonly_files{$file_name} = 'locked';
11245:                             }
11246:                         }
11247:                     }
11248:                 } 
11249:             }
11250:         } 
11251:     }
11252:     return %readonly_files;
11253: }
11254: # ------------------------------------------------------------ Unmark as Read Only
11255: 
11256: sub unmark_as_readonly {
11257:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11258:     # for portfolio submissions, $what contains [$symb,$crsid] 
11259:     my ($domain,$user,$what,$file_name,$group) = @_;
11260:     $file_name = &declutter_portfile($file_name);
11261:     my $symb_crs = $what;
11262:     if (ref($what)) { $symb_crs=join('',@$what); }
11263:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11264:     my ($tmp)=keys(%current_permissions);
11265:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11266:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11267:     foreach my $file (@readonly_files) {
11268: 	my $clean_file = &declutter_portfile($file);
11269: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11270: 	my $current_locks = $current_permissions{$file};
11271:         my @new_locks;
11272:         my @del_keys;
11273:         if (ref($current_locks) eq "ARRAY"){
11274:             foreach my $locker (@{$current_locks}) {
11275:                 my $compare=$locker;
11276:                 if (ref($locker) eq 'ARRAY') {
11277:                     $compare=join('',@{$locker});
11278:                     if ($compare ne $symb_crs) {
11279:                         push(@new_locks, $locker);
11280:                     }
11281:                 }
11282:             }
11283:             if (scalar(@new_locks) > 0) {
11284:                 $current_permissions{$file} = \@new_locks;
11285:             } else {
11286:                 push(@del_keys, $file);
11287:                 &del('file_permissions',\@del_keys, $domain, $user);
11288:                 delete($current_permissions{$file});
11289:             }
11290:         }
11291:     }
11292:     &put('file_permissions',\%current_permissions,$domain,$user);
11293:     return;
11294: }
11295: 
11296: # ------------------------------------------------------------ Directory lister
11297: 
11298: sub dirlist {
11299:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11300:     $uri=~s/^\///;
11301:     $uri=~s/\/$//;
11302:     my ($udom, $uname);
11303:     if ($getuserdir) {
11304:         $udom = $userdomain;
11305:         $uname = $username;
11306:     } else {
11307:         (undef,$udom,$uname)=split(/\//,$uri);
11308:         if(defined($userdomain)) {
11309:             $udom = $userdomain;
11310:         }
11311:         if(defined($username)) {
11312:             $uname = $username;
11313:         }
11314:     }
11315:     my ($dirRoot,$listing,@listing_results);
11316: 
11317:     $dirRoot = $perlvar{'lonDocRoot'};
11318:     if (defined($getpropath)) {
11319:         $dirRoot = &propath($udom,$uname);
11320:         $dirRoot =~ s/\/$//;
11321:     } elsif (defined($getuserdir)) {
11322:         my $subdir=$uname.'__';
11323:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11324:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11325:                    ."/$udom/$subdir/$uname";
11326:     } elsif (defined($alternateRoot)) {
11327:         $dirRoot = $alternateRoot;
11328:     }
11329: 
11330:     if($udom) {
11331:         if($uname) {
11332:             my $uhome = &homeserver($uname,$udom);
11333:             if ($uhome eq 'no_host') {
11334:                 return ([],'no_host');
11335:             }
11336:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11337:                               .$getuserdir.':'.&escape($dirRoot)
11338:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11339:             if ($listing eq 'unknown_cmd') {
11340:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11341:             } else {
11342:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11343:             }
11344:             if ($listing eq 'unknown_cmd') {
11345:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11346:                 @listing_results = split(/:/,$listing);
11347:             } else {
11348:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11349:             }
11350:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11351:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11352:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11353:                 return ([],$listing);
11354:             } else {
11355:                 return (\@listing_results);
11356:             }
11357:         } elsif(!$alternateRoot) {
11358:             my (%allusers,%listerror);
11359: 	    my %servers = &get_servers($udom,'library');
11360:  	    foreach my $tryserver (keys(%servers)) {
11361:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11362:                                   &escape($udom),$tryserver);
11363:                 if ($listing eq 'unknown_cmd') {
11364: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11365: 				      $udom, $tryserver);
11366:                 } else {
11367:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11368:                 }
11369: 		if ($listing eq 'unknown_cmd') {
11370: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11371: 				      $udom, $tryserver);
11372: 		    @listing_results = split(/:/,$listing);
11373: 		} else {
11374: 		    @listing_results =
11375: 			map { &unescape($_); } split(/:/,$listing);
11376: 		}
11377:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11378:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11379:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11380:                     $listerror{$tryserver} = $listing;
11381:                 } else {
11382: 		    foreach my $line (@listing_results) {
11383: 			my ($entry) = split(/&/,$line,2);
11384: 			$allusers{$entry} = 1;
11385: 		    }
11386: 		}
11387:             }
11388:             my @alluserslist=();
11389:             foreach my $user (sort(keys(%allusers))) {
11390:                 push(@alluserslist,$user.'&user');
11391:             }
11392: 
11393:             if (!%listerror) {
11394:                 # no errors
11395:                 return (\@alluserslist);
11396:             } elsif (scalar(keys(%servers)) == 1) {
11397:                 # one library server, one error 
11398:                 my ($key) = keys(%listerror);
11399:                 return (\@alluserslist, $listerror{$key});
11400:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11401:                 # con_lost indicates that we might miss data from at least one
11402:                 # library server
11403:                 return (\@alluserslist, 'con_lost');
11404:             } else {
11405:                 # multiple library servers and no con_lost -> data should be
11406:                 # complete. 
11407:                 return (\@alluserslist);
11408:             }
11409: 
11410:         } else {
11411:             return ([],'missing username');
11412:         }
11413:     } elsif(!defined($getpropath)) {
11414:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11415:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11416:         return (\@all_domains);
11417:     } else {
11418:         return ([],'missing domain');
11419:     }
11420: }
11421: 
11422: # --------------------------------------------- GetFileTimestamp
11423: # This function utilizes dirlist and returns the date stamp for
11424: # when it was last modified.  It will also return an error of -1
11425: # if an error occurs
11426: 
11427: sub GetFileTimestamp {
11428:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11429:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11430:     $studentName   = &LONCAPA::clean_username($studentName);
11431:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11432:                                     undef,$getuserdir);
11433:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11434:         return -1;
11435:     }
11436:     if (ref($fileref) eq 'ARRAY') {
11437:         my @stats = split('&',$fileref->[0]);
11438:         # @stats contains first the filename, then the stat output
11439:         return $stats[10]; # so this is 10 instead of 9.
11440:     } else {
11441:         return -1;
11442:     }
11443: }
11444: 
11445: sub stat_file {
11446:     my ($uri) = @_;
11447:     $uri = &clutter_with_no_wrapper($uri);
11448: 
11449:     my ($udom,$uname,$file);
11450:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11451: 	($udom,$uname,$file) =
11452: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11453: 	$file = 'userfiles/'.$file;
11454:     }
11455:     if ($uri =~ m-^/res/-) {
11456: 	($udom,$uname) = 
11457: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11458: 	$file = $uri;
11459:     }
11460: 
11461:     if (!$udom || !$uname || !$file) {
11462: 	# unable to handle the uri
11463: 	return ();
11464:     }
11465:     my $getpropath;
11466:     if ($file =~ /^userfiles\//) {
11467:         $getpropath = 1;
11468:     }
11469:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11470:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11471:         return ();
11472:     } else {
11473:         if (ref($listref) eq 'ARRAY') {
11474:             my @stats = split('&',$listref->[0]);
11475: 	    shift(@stats); #filename is first
11476: 	    return @stats;
11477:         }
11478:     }
11479:     return ();
11480: }
11481: 
11482: # --------------------------------------------------------- recursedirs
11483: # Recursive function to traverse either a specific user's Authoring Space
11484: # or corresponding Published Resource Space, and populate the hash ref:
11485: # $dirhashref with URLs of all directories, and if $filehashref hash
11486: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11487: # or .rights files in resource space, and .meta, .save, .log, and .bak
11488: # files in Authoring Space.
11489: #
11490: # Inputs:
11491: #
11492: # $is_home - true if current server is home server for user's space
11493: # $context - either: priv, or res respectively for Authoring or Resource Space.
11494: # $docroot - Document root (i.e., /home/httpd/html
11495: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11496: # $relpath - Current path (relative to top level).
11497: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11498: # $filehashref - reference to hash to populate with URLs of files (Optional)
11499: #
11500: # Returns: nothing
11501: #
11502: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11503: #
11504: # Currently used by interface/londocs.pm to create linked select boxes for
11505: # directory and filename to import a Course "Author" resource into a course, and
11506: # also to create linked select boxes for Authoring Space and Directory to choose
11507: # save location for creation of a new "standard" problem from the Course Editor.
11508: #
11509: 
11510: sub recursedirs {
11511:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11512:     return unless (ref($dirhashref) eq 'HASH');
11513:     my $currpath = $docroot.$toppath;
11514:     if ($relpath) {
11515:         $currpath .= "/$relpath";
11516:     }
11517:     my $savefile;
11518:     if (ref($filehashref)) {
11519:         $savefile = 1;
11520:     }
11521:     if ($is_home) {
11522:         if (opendir(my $dirh,$currpath)) {
11523:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11524:                 next if ($item eq '');
11525:                 if (-d "$currpath/$item") {
11526:                     my $newpath;
11527:                     if ($relpath) {
11528:                         $newpath = "$relpath/$item";
11529:                     } else {
11530:                         $newpath = $item;
11531:                     }
11532:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11533:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11534:                 } elsif ($savefile) {
11535:                     if ($context eq 'priv') {
11536:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11537:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11538:                         }
11539:                     } else {
11540:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11541:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11542:                         }
11543:                     }
11544:                 }
11545:             }
11546:             closedir($dirh);
11547:         }
11548:     } else {
11549:         my ($dirlistref,$listerror) =
11550:             &dirlist($toppath.$relpath);
11551:         my @dir_lines;
11552:         my $dirptr=16384;
11553:         if (ref($dirlistref) eq 'ARRAY') {
11554:             foreach my $dir_line (sort
11555:                               {
11556:                                   my ($afile)=split('&',$a,2);
11557:                                   my ($bfile)=split('&',$b,2);
11558:                                   return (lc($afile) cmp lc($bfile));
11559:                               } (@{$dirlistref})) {
11560:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11561:                     split(/\&/,$dir_line,16);
11562:                 $item =~ s/\s+$//;
11563:                 next if (($item =~ /^\.\.?$/) || ($obs));
11564:                 if ($dirptr&$testdir) {
11565:                     my $newpath;
11566:                     if ($relpath) {
11567:                         $newpath = "$relpath/$item";
11568:                     } else {
11569:                         $relpath = '/';
11570:                         $newpath = $item;
11571:                     }
11572:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11573:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11574:                 } elsif ($savefile) {
11575:                     if ($context eq 'priv') {
11576:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11577:                             $filehashref->{$relpath}{$item} = 1;
11578:                         }
11579:                     } else {
11580:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11581:                             $filehashref->{$relpath}{$item} = 1;
11582:                         }
11583:                     }
11584:                 }
11585:             }
11586:         }
11587:     }
11588:     return;
11589: }
11590: 
11591: # -------------------------------------------------------- Value of a Condition
11592: 
11593: # gets the value of a specific preevaluated condition
11594: #    stored in the string  $env{user.state.<cid>}
11595: # or looks up a condition reference in the bighash and if if hasn't
11596: # already been evaluated recurses into docondval to get the value of
11597: # the condition, then memoizing it to 
11598: #   $env{user.state.<cid>.<condition>}
11599: sub directcondval {
11600:     my $number=shift;
11601:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11602: 	&Apache::lonuserstate::evalstate();
11603:     }
11604:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11605: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11606:     } elsif ($number =~ /^_/) {
11607: 	my $sub_condition;
11608: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11609: 		&GDBM_READER(),0640)) {
11610: 	    $sub_condition=$bighash{'conditions'.$number};
11611: 	    untie(%bighash);
11612: 	}
11613: 	my $value = &docondval($sub_condition);
11614: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11615: 	return $value;
11616:     }
11617:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11618:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11619:     } else {
11620:        return 2;
11621:     }
11622: }
11623: 
11624: # get the collection of conditions for this resource
11625: sub condval {
11626:     my $condidx=shift;
11627:     my $allpathcond='';
11628:     foreach my $cond (split(/\|/,$condidx)) {
11629: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11630: 	    $allpathcond.=
11631: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11632: 	}
11633:     }
11634:     $allpathcond=~s/\|$//;
11635:     return &docondval($allpathcond);
11636: }
11637: 
11638: #evaluates an expression of conditions
11639: sub docondval {
11640:     my ($allpathcond) = @_;
11641:     my $result=0;
11642:     if ($env{'request.course.id'}
11643: 	&& defined($allpathcond)) {
11644: 	my $operand='|';
11645: 	my @stack;
11646: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11647: 	    if ($chunk eq '(') {
11648: 		push @stack,($operand,$result);
11649: 	    } elsif ($chunk eq ')') {
11650: 		my $before=pop @stack;
11651: 		if (pop @stack eq '&') {
11652: 		    $result=$result>$before?$before:$result;
11653: 		} else {
11654: 		    $result=$result>$before?$result:$before;
11655: 		}
11656: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11657: 		$operand=$chunk;
11658: 	    } else {
11659: 		my $new=directcondval($chunk);
11660: 		if ($operand eq '&') {
11661: 		    $result=$result>$new?$new:$result;
11662: 		} else {
11663: 		    $result=$result>$new?$result:$new;
11664: 		}
11665: 	    }
11666: 	}
11667:     }
11668:     return $result;
11669: }
11670: 
11671: # ---------------------------------------------------- Devalidate courseresdata
11672: 
11673: sub devalidatecourseresdata {
11674:     my ($coursenum,$coursedomain)=@_;
11675:     my $hashid=$coursenum.':'.$coursedomain;
11676:     &devalidate_cache_new('courseres',$hashid);
11677: }
11678: 
11679: 
11680: # --------------------------------------------------- Course Resourcedata Query
11681: #
11682: #  Parameters:
11683: #      $coursenum    - Number of the course.
11684: #      $coursedomain - Domain at which the course was created.
11685: #  Returns:
11686: #     A hash of the course parameters along (I think) with timestamps
11687: #     and version info.
11688: 
11689: sub get_courseresdata {
11690:     my ($coursenum,$coursedomain)=@_;
11691:     my $coursehom=&homeserver($coursenum,$coursedomain);
11692:     my $hashid=$coursenum.':'.$coursedomain;
11693:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11694:     my %dumpreply;
11695:     unless (defined($cached)) {
11696: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11697: 	$result=\%dumpreply;
11698: 	my ($tmp) = keys(%dumpreply);
11699: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11700: 	    &do_cache_new('courseres',$hashid,$result,600);
11701: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11702: 	    return $tmp;
11703: 	} elsif ($tmp =~ /^(error)/) {
11704: 	    $result=undef;
11705: 	    &do_cache_new('courseres',$hashid,$result,600);
11706: 	}
11707:     }
11708:     return $result;
11709: }
11710: 
11711: sub devalidateuserresdata {
11712:     my ($uname,$udom)=@_;
11713:     my $hashid="$udom:$uname";
11714:     &devalidate_cache_new('userres',$hashid);
11715: }
11716: 
11717: sub get_userresdata {
11718:     my ($uname,$udom)=@_;
11719:     #most student don\'t have any data set, check if there is some data
11720:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11721: 
11722:     my $hashid="$udom:$uname";
11723:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11724:     if (!defined($cached)) {
11725: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11726: 	$result=\%resourcedata;
11727: 	&do_cache_new('userres',$hashid,$result,600);
11728:     }
11729:     my ($tmp)=keys(%$result);
11730:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11731: 	return $result;
11732:     }
11733:     #error 2 occurs when the .db doesn't exist
11734:     if ($tmp!~/error: 2 /) {
11735:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11736: 	    &logthis("<font color=\"blue\">WARNING:".
11737: 		     " Trying to get resource data for ".
11738: 		     $uname." at ".$udom.": ".
11739: 		     $tmp."</font>");
11740:         }
11741:     } elsif ($tmp=~/error: 2 /) {
11742: 	#&EXT_cache_set($udom,$uname);
11743: 	&do_cache_new('userres',$hashid,undef,600);
11744: 	undef($tmp); # not really an error so don't send it back
11745:     }
11746:     return $tmp;
11747: }
11748: #----------------------------------------------- resdata - return resource data
11749: #  Purpose:
11750: #    Return resource data for either users or for a course.
11751: #  Parameters:
11752: #     $name      - Course/user name.
11753: #     $domain    - Name of the domain the user/course is registered on.
11754: #     $type      - Type of thing $name is (must be 'course' or 'user')
11755: #     $mapp      - decluttered URL of enclosing map  
11756: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11757: #     $recurseup - Ref to array of map URLs, starting with map containing
11758: #                  $mapp up through hierarchy of nested maps to top level map.  
11759: #     $courseid  - CourseID (first part of param identifier).
11760: #     $modifier  - Middle part of param identifier.
11761: #     $what      - Last part of param identifier.
11762: #     @which     - Array of names of resources desired.
11763: #  Returns:
11764: #     The value of the first reasource in @which that is found in the
11765: #     resource hash.
11766: #  Exceptional Conditions:
11767: #     If the $type passed in is not valid (not the string 'course' or 
11768: #     'user', an undefined  reference is returned.
11769: #     If none of the resources are found, an undef is returned
11770: sub resdata {
11771:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11772:         $modifier,$what,@which)=@_;
11773:     my $result;
11774:     if ($type eq 'course') {
11775: 	$result=&get_courseresdata($name,$domain);
11776:     } elsif ($type eq 'user') {
11777: 	$result=&get_userresdata($name,$domain);
11778:     }
11779:     if (!ref($result)) { return $result; }    
11780:     foreach my $item (@which) {
11781:         if ($item->[1] eq 'course') {
11782:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11783:                 unless ($$recursed) {
11784:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11785:                     $$recursed = 1;
11786:                 }
11787:                 foreach my $item (@${recurseup}) {
11788:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11789:                     last if (defined($result->{$norecursechk}));
11790:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11791:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11792:                 }
11793:             }
11794:         }
11795:         if (defined($result->{$item->[0]})) {
11796: 	    return [$result->{$item->[0]},$item->[1]];
11797: 	}
11798:     }
11799:     return undef;
11800: }
11801: 
11802: sub get_domain_lti {
11803:     my ($cdom,$context) = @_;
11804:     my ($name,%lti);
11805:     if ($context eq 'consumer') {
11806:         $name = 'ltitools';
11807:     } elsif ($context eq 'provider') {
11808:         $name = 'lti';
11809:     } else {
11810:         return %lti;
11811:     }
11812:     my ($result,$cached)=&is_cached_new($name,$cdom);
11813:     if (defined($cached)) {
11814:         if (ref($result) eq 'HASH') {
11815:             %lti = %{$result};
11816:         }
11817:     } else {
11818:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11819:         if (ref($domconfig{$name}) eq 'HASH') {
11820:             %lti = %{$domconfig{$name}};
11821:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11822:             if (ref($encdomconfig{$name}) eq 'HASH') {
11823:                 foreach my $id (keys(%lti)) {
11824:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11825:                         foreach my $item ('key','secret') {
11826:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11827:                         }
11828:                     }
11829:                 }
11830:             }
11831:         }
11832:         my $cachetime = 24*60*60;
11833:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11834:     }
11835:     return %lti;
11836: }
11837: 
11838: sub get_numsuppfiles {
11839:     my ($cnum,$cdom,$ignorecache)=@_;
11840:     my $hashid=$cnum.':'.$cdom;
11841:     my ($suppcount,$cached);
11842:     unless ($ignorecache) {
11843:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11844:     }
11845:     unless (defined($cached)) {
11846:         my $chome=&homeserver($cnum,$cdom);
11847:         unless ($chome eq 'no_host') {
11848:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11849:             my $suppmap = 'supplemental.sequence';
11850:             ($suppcount,$supptools,$errors) =
11851:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11852:                                                          $supptools,$errors);
11853:         }
11854:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11855:     }
11856:     return $suppcount;
11857: }
11858: 
11859: #
11860: # EXT resource caching routines
11861: #
11862: 
11863: {
11864: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11865: #
11866: # The course for which we cache
11867: my $cachedmapkey='';
11868: # The cached recursive maps for this course
11869: my %cachedmaps=();
11870: # When this was last done
11871: my $cachedmaptime='';
11872: 
11873: sub clear_EXT_cache_status {
11874:     &delenv('cache.EXT.');
11875: }
11876: 
11877: sub EXT_cache_status {
11878:     my ($target_domain,$target_user) = @_;
11879:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11880:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11881:         # We know already the user has no data
11882:         return 1;
11883:     } else {
11884:         return 0;
11885:     }
11886: }
11887: 
11888: sub EXT_cache_set {
11889:     my ($target_domain,$target_user) = @_;
11890:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11891:     #&appenv({$cachename => time});
11892: }
11893: 
11894: # --------------------------------------------------------- Value of a Variable
11895: sub EXT {
11896: 
11897:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11898:     unless ($varname) { return ''; }
11899:     #get real user name/domain, courseid and symb
11900:     my $courseid;
11901:     my $publicuser;
11902:     if ($symbparm) {
11903: 	$symbparm=&get_symb_from_alias($symbparm);
11904:     }
11905:     if (!($uname && $udom)) {
11906:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11907:       if (!$symbparm) {	$symbparm=$cursymb; }
11908:     } else {
11909: 	$courseid=$env{'request.course.id'};
11910:     }
11911:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11912:     my $rest;
11913:     if (defined($therest[0])) {
11914:        $rest=join('.',@therest);
11915:     } else {
11916:        $rest='';
11917:     }
11918: 
11919:     my $qualifierrest=$qualifier;
11920:     if ($rest) { $qualifierrest.='.'.$rest; }
11921:     my $spacequalifierrest=$space;
11922:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11923:     if ($realm eq 'user') {
11924: # --------------------------------------------------------------- user.resource
11925: 	if ($space eq 'resource') {
11926: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11927: 		  || defined($Apache::lonhomework::parsing_a_task))
11928: 		 &&
11929: 		 ($symbparm eq &symbread()) ) {	
11930: 		# if we are in the middle of processing the resource the
11931: 		# get the value we are planning on committing
11932:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11933:                     return $Apache::lonhomework::results{$qualifierrest};
11934:                 } else {
11935:                     return $Apache::lonhomework::history{$qualifierrest};
11936:                 }
11937: 	    } else {
11938: 		my %restored;
11939: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11940: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11941: 		} else {
11942: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11943: 		}
11944: 		return $restored{$qualifierrest};
11945: 	    }
11946: # ----------------------------------------------------------------- user.access
11947:         } elsif ($space eq 'access') {
11948: 	    # FIXME - not supporting calls for a specific user
11949:             return &allowed($qualifier,$rest);
11950: # ------------------------------------------ user.preferences, user.environment
11951:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11952: 	    if (($uname eq $env{'user.name'}) &&
11953: 		($udom eq $env{'user.domain'})) {
11954: 		return $env{join('.',('environment',$qualifierrest))};
11955: 	    } else {
11956: 		my %returnhash;
11957: 		if (!$publicuser) {
11958: 		    %returnhash=&userenvironment($udom,$uname,
11959: 						 $qualifierrest);
11960: 		}
11961: 		return $returnhash{$qualifierrest};
11962: 	    }
11963: # ----------------------------------------------------------------- user.course
11964:         } elsif ($space eq 'course') {
11965: 	    # FIXME - not supporting calls for a specific user
11966:             return $env{join('.',('request.course',$qualifier))};
11967: # ------------------------------------------------------------------- user.role
11968:         } elsif ($space eq 'role') {
11969: 	    # FIXME - not supporting calls for a specific user
11970:             my ($role,$where)=split(/\./,$env{'request.role'});
11971:             if ($qualifier eq 'value') {
11972: 		return $role;
11973:             } elsif ($qualifier eq 'extent') {
11974:                 return $where;
11975:             }
11976: # ----------------------------------------------------------------- user.domain
11977:         } elsif ($space eq 'domain') {
11978:             return $udom;
11979: # ------------------------------------------------------------------- user.name
11980:         } elsif ($space eq 'name') {
11981:             return $uname;
11982: # ---------------------------------------------------- Any other user namespace
11983:         } else {
11984: 	    my %reply;
11985: 	    if (!$publicuser) {
11986: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11987: 	    }
11988: 	    return $reply{$qualifierrest};
11989:         }
11990:     } elsif ($realm eq 'query') {
11991: # ---------------------------------------------- pull stuff out of query string
11992:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11993: 						[$spacequalifierrest]);
11994: 	return $env{'form.'.$spacequalifierrest}; 
11995:    } elsif ($realm eq 'request') {
11996: # ------------------------------------------------------------- request.browser
11997:         if ($space eq 'browser') {
11998:             return $env{'browser.'.$qualifier};
11999: # ------------------------------------------------------------ request.filename
12000:         } else {
12001:             return $env{'request.'.$spacequalifierrest};
12002:         }
12003:     } elsif ($realm eq 'course') {
12004: # ---------------------------------------------------------- course.description
12005:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12006:     } elsif ($realm eq 'resource') {
12007: 
12008: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12009: 	    if (!$symbparm) { $symbparm=&symbread(); }
12010: 	}
12011: 
12012:         if ($qualifier eq '') {
12013: 	    if ($space eq 'title') {
12014: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12015: 	        return &gettitle($symbparm);
12016: 	    }
12017: 	
12018: 	    if ($space eq 'map') {
12019: 	        my ($map) = &decode_symb($symbparm);
12020: 	        return &symbread($map);
12021: 	    }
12022:             if ($space eq 'maptitle') {
12023:                 my ($map) = &decode_symb($symbparm);
12024:                 return &gettitle($map);
12025:             }
12026: 	    if ($space eq 'filename') {
12027: 	        if ($symbparm) {
12028: 		    return &clutter((&decode_symb($symbparm))[2]);
12029: 	        }
12030: 	        return &hreflocation('',$env{'request.filename'});
12031: 	    }
12032: 
12033:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12034:                 if ($space eq 'visibleparts') {
12035:                     my $navmap = Apache::lonnavmaps::navmap->new();
12036:                     my $item;
12037:                     if (ref($navmap)) {
12038:                         my $res = $navmap->getBySymb($symbparm);
12039:                         my $parts = $res->parts();
12040:                         if (ref($parts) eq 'ARRAY') {
12041:                             $item = join(',',@{$parts});
12042:                         }
12043:                         undef($navmap);
12044:                     }
12045:                     return $item;
12046:                 }
12047:             }
12048:         }
12049: 
12050: 	my ($section, $group, @groups, @recurseup, $recursed);
12051: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12052:         if (($courseid eq '') && ($cid)) {
12053:             $courseid = $cid;
12054:         }
12055: 	if (($symbparm && $courseid) && 
12056: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12057: 
12058: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12059: 
12060: # ----------------------------------------------------- Cascading lookup scheme
12061: 	    my $symbp=$symbparm;
12062: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12063: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12064:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12065: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12066: 	    if (($env{'user.name'} eq $uname) &&
12067: 		($env{'user.domain'} eq $udom)) {
12068: 		$section=$env{'request.course.sec'};
12069:                 @groups = split(/:/,$env{'request.course.groups'});  
12070:                 @groups=&sort_course_groups($courseid,@groups); 
12071: 	    } else {
12072: 		if (! defined($usection)) {
12073: 		    $section=&getsection($udom,$uname,$courseid);
12074: 		} else {
12075: 		    $section = $usection;
12076: 		}
12077:                 @groups = &get_users_groups($udom,$uname,$courseid);
12078: 	    }
12079: 
12080: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12081: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12082:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12083: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12084: 
12085: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12086: 	    my $courselevelr=$courseid.'.'.$symbparm;
12087:             $courseleveli=$courseid.'.'.$recurseparm;
12088: 	    $courselevelm=$courseid.'.'.$mapparm;
12089: 
12090: # ----------------------------------------------------------- first, check user
12091: 
12092: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12093:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12094: 				       ([$courselevelr,'resource'],
12095: 					[$courselevelm,'map'     ],
12096:                                         [$courseleveli,'map'     ],
12097: 					[$courselevel, 'course'  ]));
12098: 	    if (defined($userreply)) { return &get_reply($userreply); }
12099: 
12100: # ------------------------------------------------ second, check some of course
12101:             my $coursereply;
12102:             if (@groups > 0) {
12103:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12104:                                        $recurseparm,$mapparm,$spacequalifierrest,
12105:                                        $mapp,\$recursed,\@recurseup);
12106:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12107:             }
12108: 
12109: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12110: 				  $env{'course.'.$courseid.'.domain'},
12111: 				  'course',$mapp,\$recursed,\@recurseup,
12112:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12113: 				  ([$seclevelr,   'resource'],
12114: 				   [$seclevelm,   'map'     ],
12115:                                    [$secleveli,   'map'     ],
12116: 				   [$seclevel,    'course'  ],
12117: 				   [$courselevelr,'resource']));
12118: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12119: 
12120: # ------------------------------------------------------ third, check map parms
12121: 	    my %parmhash=();
12122: 	    my $thisparm='';
12123: 	    if (tie(%parmhash,'GDBM_File',
12124: 		    $env{'request.course.fn'}.'_parms.db',
12125: 		    &GDBM_READER(),0640)) {
12126: 		$thisparm=$parmhash{$symbparm};
12127: 		untie(%parmhash);
12128: 	    }
12129: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12130: 	}
12131: # ------------------------------------------ fourth, look in resource metadata
12132:  
12133:         my $what = $spacequalifierrest;
12134: 	$what=~s/\./\_/;
12135: 	my $filename;
12136: 	if (!$symbparm) { $symbparm=&symbread(); }
12137: 	if ($symbparm) {
12138: 	    $filename=(&decode_symb($symbparm))[2];
12139: 	} else {
12140: 	    $filename=$env{'request.filename'};
12141: 	}
12142:         my $toolsymb;
12143:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12144:             $toolsymb = $symbparm;
12145:         }
12146: 	my $metadata=&metadata($filename,$what,$toolsymb);
12147: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12148: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12149: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12150: 
12151: # ----------------------------------------------- fifth, look in rest of course
12152: 	if ($symbparm && defined($courseid) && 
12153: 	    $courseid eq $env{'request.course.id'}) {
12154: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12155: 				     $env{'course.'.$courseid.'.domain'},
12156: 				     'course',$mapp,\$recursed,\@recurseup,
12157:                                      $courseid,'.',$spacequalifierrest,
12158: 				     ([$courselevelm,'map'   ],
12159:                                       [$courseleveli,'map'   ],
12160: 				      [$courselevel, 'course']));
12161: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12162: 	}
12163: # ------------------------------------------------------------------ Cascade up
12164: 	unless ($space eq '0') {
12165: 	    my @parts=split(/_/,$space);
12166: 	    my $id=pop(@parts);
12167: 	    my $part=join('_',@parts);
12168: 	    if ($part eq '') { $part='0'; }
12169: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12170: 				 $symbparm,$udom,$uname,$section,1);
12171: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12172: 	}
12173: 	if ($recurse) { return undef; }
12174: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12175: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12176: # ---------------------------------------------------- Any other user namespace
12177:     } elsif ($realm eq 'environment') {
12178: # ----------------------------------------------------------------- environment
12179: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12180: 	    return $env{'environment.'.$spacequalifierrest};
12181: 	} else {
12182: 	    if ($uname eq 'anonymous' && $udom eq '') {
12183: 		return '';
12184: 	    }
12185: 	    my %returnhash=&userenvironment($udom,$uname,
12186: 					    $spacequalifierrest);
12187: 	    return $returnhash{$spacequalifierrest};
12188: 	}
12189:     } elsif ($realm eq 'system') {
12190: # ----------------------------------------------------------------- system.time
12191: 	if ($space eq 'time') {
12192: 	    return time;
12193:         }
12194:     } elsif ($realm eq 'server') {
12195: # ----------------------------------------------------------------- system.time
12196: 	if ($space eq 'name') {
12197: 	    return $ENV{'SERVER_NAME'};
12198:         }
12199:     }
12200:     return '';
12201: }
12202: 
12203: sub get_reply {
12204:     my ($reply_value) = @_;
12205:     if (ref($reply_value) eq 'ARRAY') {
12206:         if (wantarray) {
12207: 	    return @$reply_value;
12208:         }
12209:         return $reply_value->[0];
12210:     } else {
12211:         return $reply_value;
12212:     }
12213: }
12214: 
12215: sub check_group_parms {
12216:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12217:         $recursed,$recurseupref) = @_;
12218:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12219:                   [$what,'course']);
12220:     my $coursereply;
12221:     foreach my $group (@{$groups}) {
12222:         my @groupitems = ();
12223:         foreach my $level (@levels) {
12224:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12225:              push(@groupitems,[$item,$level->[1]]);
12226:         }
12227:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12228:                                    $env{'course.'.$courseid.'.domain'},
12229:                                    'course',$mapp,$recursed,$recurseupref,
12230:                                    $courseid,'.['.$group.'].',$what,
12231:                                    @groupitems);
12232:         last if (defined($coursereply));
12233:     }
12234:     return $coursereply;
12235: }
12236: 
12237: sub get_map_hierarchy {
12238:     my ($mapname,$courseid) = @_;
12239:     my @recurseup = ();
12240:     if ($mapname) {
12241:         if (($cachedmapkey eq $courseid) &&
12242:             (abs($cachedmaptime-time)<5)) {
12243:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12244:                 return @{$cachedmaps{$mapname}};
12245:             }
12246:         }
12247:         my $navmap = Apache::lonnavmaps::navmap->new();
12248:         if (ref($navmap)) {
12249:             @recurseup = $navmap->recurseup_maps($mapname);
12250:             undef($navmap);
12251:             $cachedmaps{$mapname} = \@recurseup;
12252:             $cachedmaptime=time;
12253:             $cachedmapkey=$courseid;
12254:         }
12255:     }
12256:     return @recurseup;
12257: }
12258: 
12259: }
12260: 
12261: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12262:     my ($courseid,@groups) = @_;
12263:     @groups = sort(@groups);
12264:     return @groups;
12265: }
12266: 
12267: sub packages_tab_default {
12268:     my ($uri,$varname,$toolsymb)=@_;
12269:     my (undef,$part,$name)=split(/\./,$varname);
12270: 
12271:     my (@extension,@specifics,$do_default);
12272:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12273: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12274: 	if ($pack_type eq 'default') {
12275: 	    $do_default=1;
12276: 	} elsif ($pack_type eq 'extension') {
12277: 	    push(@extension,[$package,$pack_type,$pack_part]);
12278: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12279: 	    # only look at packages defaults for packages that this id is
12280: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12281: 	}
12282:     }
12283:     # first look for a package that matches the requested part id
12284:     foreach my $package (@specifics) {
12285: 	my (undef,$pack_type,$pack_part)=@{$package};
12286: 	next if ($pack_part ne $part);
12287: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12288: 	    return $packagetab{"$pack_type&$name&default"};
12289: 	}
12290:     }
12291:     # look for any possible matching non extension_ package
12292:     foreach my $package (@specifics) {
12293: 	my (undef,$pack_type,$pack_part)=@{$package};
12294: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12295: 	    return $packagetab{"$pack_type&$name&default"};
12296: 	}
12297: 	if ($pack_type eq 'part') { $pack_part='0'; }
12298: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12299: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12300: 	}
12301:     }
12302:     # look for any posible extension_ match
12303:     foreach my $package (@extension) {
12304: 	my ($package,$pack_type)=@{$package};
12305: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12306: 	    return $packagetab{"$pack_type&$name&default"};
12307: 	}
12308: 	if (defined($packagetab{$package."&$name&default"})) {
12309: 	    return $packagetab{$package."&$name&default"};
12310: 	}
12311:     }
12312:     # look for a global default setting
12313:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12314: 	return $packagetab{"default&$name&default"};
12315:     }
12316:     return undef;
12317: }
12318: 
12319: sub add_prefix_and_part {
12320:     my ($prefix,$part)=@_;
12321:     my $keyroot;
12322:     if (defined($prefix) && $prefix !~ /^__/) {
12323: 	# prefix that has a part already
12324: 	$keyroot=$prefix;
12325:     } elsif (defined($prefix)) {
12326: 	# prefix that is missing a part
12327: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12328:     } else {
12329: 	# no prefix at all
12330: 	if (defined($part)) { $keyroot='_'.$part; }
12331:     }
12332:     return $keyroot;
12333: }
12334: 
12335: # ---------------------------------------------------------------- Get metadata
12336: 
12337: my %metaentry;
12338: my %importedpartids;
12339: my %importedrespids;
12340: sub metadata {
12341:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12342:     $uri=&declutter($uri);
12343:     # if it is a non metadata possible uri return quickly
12344:     if (($uri eq '') || 
12345: 	(($uri =~ m|^/*adm/|) && 
12346: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12347:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12348: 	return undef;
12349:     }
12350:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12351: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12352: 	return undef;
12353:     }
12354:     my $filename=$uri;
12355:     $uri=~s/\.meta$//;
12356: #
12357: # Is the metadata already cached?
12358: # Look at timestamp of caching
12359: # Everything is cached by the main uri, libraries are never directly cached
12360: #
12361:     if (!defined($liburi)) {
12362: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12363: 	if (defined($cached)) { return $result->{':'.$what}; }
12364:     }
12365: 
12366: #
12367: # If the uri is for an external tool the file from
12368: # which metadata should be retrieved depends on whether
12369: # the tool had been configured to be gradable (set in the Course
12370: # Editor or Resource Editor).
12371: #
12372: # If a valid symb has been included as the third arg in the call
12373: # to &metadata() that can be used to retrieve the value of
12374: # parameter_0_gradable set for the resource, and included in the
12375: # uploaded map containing the tool. The value is retrieved via
12376: # &EXT(), if a valid symb is available.  Otherwise the value of
12377: # gradable in the exttool_$marker.db file for the tool instance
12378: # is retrieved via &get().
12379: #
12380: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12381: # hiddenresource and encrypturl (during course initialization)
12382: # the map-level parameter for resource.0.gradable included in the 
12383: # uploaded map containing the tool will not yet have been stored
12384: # in the user_course_parms.db file for the user's session, so in 
12385: # this case fall back to retrieving gradable status from the
12386: # exttool_$marker.db file.
12387: #
12388: # In order to avoid an infinite loop, &metadata() will return
12389: # before a call to &EXT(), if the uri is for an external tool
12390: # and the $what for which metadata is being requested is
12391: # parameter_0_gradable or 0_gradable.
12392: #
12393: 
12394:     if ($uri =~ /ext\.tool$/) {
12395:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12396:             return;
12397:         } else {
12398:             my ($checked,$use_passback);
12399:             if ($toolsymb ne '') {
12400:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12401:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12402:                     $checked = 1;
12403:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12404:                         $use_passback = 1;
12405:                     }
12406:                 }
12407:             }
12408:             unless ($checked) {
12409:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12410:                 $marker=~s/\D//g;
12411:                 if ($marker) {
12412:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12413:                     $use_passback = $toolsettings{'gradable'};
12414:                 }
12415:             }
12416:             if ($use_passback) {
12417:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12418:             } else {
12419:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12420:             }
12421:         }
12422:     }
12423: 
12424:     {
12425: # Imported parts would go here
12426:         my @origfiletagids=();
12427:         my $importedparts=0;
12428: 
12429: # Imported responseids would go here
12430:         my $importedresponses=0;
12431: #
12432: # Is this a recursive call for a library?
12433: #
12434: #	if (! exists($metacache{$uri})) {
12435: #	    $metacache{$uri}={};
12436: #	}
12437: 	my $cachetime = 60*60;
12438:         if ($liburi) {
12439: 	    $liburi=&declutter($liburi);
12440:             $filename=$liburi;
12441:         } else {
12442: 	    &devalidate_cache_new('meta',$uri);
12443: 	    undef(%metaentry);
12444: 	}
12445:         my %metathesekeys=();
12446:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12447: 	my $metastring;
12448: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12449: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12450: 	    $metastring = 
12451: 		&Apache::lonnet::ssi_body($which,
12452: 					  ('grade_target' => 'meta'));
12453: 	    $cachetime = 1; # only want this cached in the child not long term
12454: 	} elsif (($uri !~ m -^(editupload)/-) && 
12455:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12456: 	    my $file=&filelocation('',&clutter($filename));
12457: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12458: 	    $metastring=&getfile($file);
12459: 	}
12460:         my $parser=HTML::LCParser->new(\$metastring);
12461:         my $token;
12462:         undef %metathesekeys;
12463:         while ($token=$parser->get_token) {
12464: 	    if ($token->[0] eq 'S') {
12465: 		if (defined($token->[2]->{'package'})) {
12466: #
12467: # This is a package - get package info
12468: #
12469: 		    my $package=$token->[2]->{'package'};
12470: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12471: 		    if (defined($token->[2]->{'id'})) { 
12472: 			$keyroot.='_'.$token->[2]->{'id'}; 
12473: 		    }
12474: 		    if ($metaentry{':packages'}) {
12475: 			$metaentry{':packages'}.=','.$package.$keyroot;
12476: 		    } else {
12477: 			$metaentry{':packages'}=$package.$keyroot;
12478: 		    }
12479: 		    foreach my $pack_entry (keys(%packagetab)) {
12480: 			my $part=$keyroot;
12481: 			$part=~s/^\_//;
12482: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12483: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12484: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12485: 			    # ignore package.tab specified default values
12486:                             # here &package_tab_default() will fetch those
12487: 			    if ($subp eq 'default') { next; }
12488: 			    my $value=$packagetab{$pack_entry};
12489: 			    my $unikey;
12490: 			    if ($pack =~ /_0$/) {
12491: 				$unikey='parameter_0_'.$name;
12492: 				$part=0;
12493: 			    } else {
12494: 				$unikey='parameter'.$keyroot.'_'.$name;
12495: 			    }
12496: 			    if ($subp eq 'display') {
12497: 				$value.=' [Part: '.$part.']';
12498: 			    }
12499: 			    $metaentry{':'.$unikey.'.part'}=$part;
12500: 			    $metathesekeys{$unikey}=1;
12501: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12502: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12503: 			    }
12504: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12505: 				$metaentry{':'.$unikey}=
12506: 				    $metaentry{':'.$unikey.'.default'};
12507: 			    }
12508: 			}
12509: 		    }
12510: 		} else {
12511: #
12512: # This is not a package - some other kind of start tag
12513: #
12514: 		    my $entry=$token->[1];
12515: 		    my $unikey='';
12516: 
12517: 		    if ($entry eq 'import') {
12518: #
12519: # Importing a library here
12520: #
12521:                         my $location=$parser->get_text('/import');
12522:                         my $dir=$filename;
12523:                         $dir=~s|[^/]*$||;
12524:                         $location=&filelocation($dir,$location);
12525: 
12526:                         my $importid=$token->[2]->{'id'};
12527:                         my $importmode=$token->[2]->{'importmode'};
12528: #
12529: # Check metadata for imported file to
12530: # see if it contained response items
12531: #
12532:                         my ($origfile,@libfilekeys);
12533:                         my %currmetaentry = %metaentry;
12534:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12535:                                                            $depthcount+1));
12536:                         if (grep(/^responseorder$/,@libfilekeys)) {
12537:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12538:                                                              undef,$depthcount+1);
12539:                             if ($libresponseorder ne '') {
12540:                                 if ($#origfiletagids<0) {
12541:                                     undef(%importedrespids);
12542:                                     undef(%importedpartids);
12543:                                 }
12544:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12545:                                 if (@respids) {
12546:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12547:                                 }
12548:                                 if ($importedrespids{$importid} ne '') {
12549:                                     $importedresponses = 1;
12550: # We need to get the original file and the imported file to get the response order correct
12551: # Load and inspect original file
12552:                                     if ($#origfiletagids<0) {
12553:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12554:                                         $origfile=&getfile($origfilelocation);
12555:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12556:                                     }
12557:                                 }
12558:                             }
12559:                         }
12560: # Do not overwrite contents of %metaentry hash for resource itself with 
12561: # hash populated for imported library file
12562:                         %metaentry = %currmetaentry;
12563:                         undef(%currmetaentry);
12564:                         if ($importmode eq 'part') {
12565: # Import as part(s)
12566:                            $importedparts=1;
12567: # We need to get the original file and the imported file to get the part order correct
12568: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12569: # Load and inspect original file if we didn't do that already
12570:                            if ($#origfiletagids<0) {
12571:                                undef(%importedrespids);
12572:                                undef(%importedpartids);
12573:                                if ($origfile eq '') {
12574:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12575:                                    $origfile=&getfile($origfilelocation);
12576:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12577:                                }
12578:                            }
12579:                            my @impfilepartids;
12580: # If <partorder> tag is included in metadata for the imported file
12581: # get the parts in the imported file from that.
12582:                            if (grep(/^partorder$/,@libfilekeys)) {
12583:                                %currmetaentry = %metaentry;
12584:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12585:                                                             $depthcount+1);
12586:                                %metaentry = %currmetaentry;
12587:                                undef(%currmetaentry);
12588:                                if ($libpartorder ne '') {
12589:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12590:                                }
12591:                            } else {
12592: # If no <partorder> tag available, load and inspect imported file
12593:                                my $impfile=&getfile($location);
12594:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12595:                            }
12596:                            if ($#impfilepartids>=0) {
12597: # This problem had parts
12598:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12599:                            } else {
12600: # Importing by turning a single problem into a problem part
12601: # It gets the import-tags ID as part-ID
12602:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12603:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12604:                            }
12605:                         } else {
12606: # Import as problem or as normal import
12607:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12608:                             unless ($importmode eq 'problem') {
12609: # Normal import
12610:                                 if (defined($token->[2]->{'id'})) {
12611:                                     $unikey.='_'.$token->[2]->{'id'};
12612:                                 }
12613:                             }
12614: # Check metadata for imported file to
12615: # see if it contained parts
12616:                             if (grep(/^partorder$/,@libfilekeys)) {
12617:                                 %currmetaentry = %metaentry;
12618:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12619:                                                              $depthcount+1);
12620:                                 %metaentry = %currmetaentry;
12621:                                 undef(%currmetaentry);
12622:                                 if ($libpartorder ne '') {
12623:                                     $importedparts = 1;
12624:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12625:                                 }
12626:                             }
12627:                         }
12628: 			if ($depthcount<20) {
12629: 			    my $metadata = 
12630: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12631: 					  $depthcount+1);
12632: 			    foreach my $meta (split(',',$metadata)) {
12633: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12634: 				$metathesekeys{$meta}=1;
12635: 			    }
12636:                         }
12637: 		    } else {
12638: #
12639: # Not importing, some other kind of non-package, non-library start tag
12640: # 
12641:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12642:                         if (defined($token->[2]->{'id'})) {
12643:                             $unikey.='_'.$token->[2]->{'id'};
12644:                         }
12645: 			if (defined($token->[2]->{'name'})) { 
12646: 			    $unikey.='_'.$token->[2]->{'name'}; 
12647: 			}
12648: 			$metathesekeys{$unikey}=1;
12649: 			foreach my $param (@{$token->[3]}) {
12650: 			    $metaentry{':'.$unikey.'.'.$param} =
12651: 				$token->[2]->{$param};
12652: 			}
12653: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12654: 			my $default=$metaentry{':'.$unikey.'.default'};
12655: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12656: 		 # only ws inside the tag, and not in default, so use default
12657: 		 # as value
12658: 			    $metaentry{':'.$unikey}=$default;
12659: 			} elsif ( $internaltext =~ /\S/ ) {
12660: 		  # something interesting inside the tag
12661: 			    $metaentry{':'.$unikey}=$internaltext;
12662: 			} else {
12663: 		  # no interesting values, don't set a default
12664: 			}
12665: # end of not-a-package not-a-library import
12666: 		    }
12667: # end of not-a-package start tag
12668: 		}
12669: # the next is the end of "start tag"
12670: 	    }
12671: 	}
12672: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12673: 	$extension = lc($extension);
12674: 	if ($extension eq 'htm') { $extension='html'; }
12675: 
12676: 	foreach my $key (keys(%packagetab)) {
12677: 	    #no specific packages #how's our extension
12678: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12679: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12680: 					 \%metathesekeys);
12681: 	}
12682: 
12683: 	if (!exists($metaentry{':packages'})
12684: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12685: 	    foreach my $key (keys(%packagetab)) {
12686: 		#no specific packages well let's get default then
12687: 		if ($key!~/^default&/) { next; }
12688: 		&metadata_create_package_def($uri,$key,'default',
12689: 					     \%metathesekeys);
12690: 	    }
12691: 	}
12692: # are there custom rights to evaluate
12693: 	if ($metaentry{':copyright'} eq 'custom') {
12694: 
12695:     #
12696:     # Importing a rights file here
12697:     #
12698: 	    unless ($depthcount) {
12699: 		my $location=$metaentry{':customdistributionfile'};
12700: 		my $dir=$filename;
12701: 		$dir=~s|[^/]*$||;
12702: 		$location=&filelocation($dir,$location);
12703: 		my $rights_metadata =
12704: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12705: 			      $depthcount+1);
12706: 		foreach my $rights (split(',',$rights_metadata)) {
12707: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12708: 		    $metathesekeys{$rights}=1;
12709: 		}
12710: 	    }
12711: 	}
12712: 	# uniqifiy package listing
12713: 	my %seen;
12714: 	my @uniq_packages =
12715: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12716: 	$metaentry{':packages'} = join(',',@uniq_packages);
12717: 
12718:         if (($importedresponses) || ($importedparts)) {
12719:             if ($importedparts) {
12720: # We had imported parts and need to rebuild partorder
12721:                 $metaentry{':partorder'}='';
12722:                 $metathesekeys{'partorder'}=1;
12723:             }
12724:             if ($importedresponses) {
12725: # We had imported responses and need to rebuil responseorder
12726:                 $metaentry{':responseorder'}='';
12727:                 $metathesekeys{'responseorder'}=1;
12728:             }
12729:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12730:                 my $origid = $origfiletagids[$index+1];
12731:                 if ($origfiletagids[$index] eq 'part') {
12732: # Original part, part of the problem
12733:                     if ($importedparts) {
12734:                         $metaentry{':partorder'}.=','.$origid;
12735:                     }
12736:                 } elsif ($origfiletagids[$index] eq 'import') {
12737:                     if ($importedparts) {
12738: # We have imported parts at this position
12739:                         if ($importedpartids{$origid} ne '') {
12740:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12741:                         }
12742:                     }
12743:                     if ($importedresponses) {
12744: # We have imported responses at this position
12745:                         if ($importedrespids{$origid} ne '') {
12746:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12747:                         }
12748:                     }
12749:                 } else {
12750: # Original response item, part of the problem
12751:                     if ($importedresponses) {
12752:                         $metaentry{':responseorder'}.=','.$origid;
12753:                     }
12754:                 }
12755:             }
12756:             if ($importedparts) {
12757:                 $metaentry{':partorder'}=~s/^\,//;
12758:             }
12759:             if ($importedresponses) {
12760:                 $metaentry{':responseorder'}=~s/^\,//;
12761:             }
12762:         }
12763: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12764: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12765: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12766:         unless ($liburi) {
12767: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12768:         }
12769: # this is the end of "was not already recently cached
12770:     }
12771:     return $metaentry{':'.$what};
12772: }
12773: 
12774: sub metadata_create_package_def {
12775:     my ($uri,$key,$package,$metathesekeys)=@_;
12776:     my ($pack,$name,$subp)=split(/\&/,$key);
12777:     if ($subp eq 'default') { next; }
12778:     
12779:     if (defined($metaentry{':packages'})) {
12780: 	$metaentry{':packages'}.=','.$package;
12781:     } else {
12782: 	$metaentry{':packages'}=$package;
12783:     }
12784:     my $value=$packagetab{$key};
12785:     my $unikey;
12786:     $unikey='parameter_0_'.$name;
12787:     $metaentry{':'.$unikey.'.part'}=0;
12788:     $$metathesekeys{$unikey}=1;
12789:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12790: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12791:     }
12792:     if (defined($metaentry{':'.$unikey.'.default'})) {
12793: 	$metaentry{':'.$unikey}=
12794: 	    $metaentry{':'.$unikey.'.default'};
12795:     }
12796: }
12797: 
12798: sub metadata_generate_part0 {
12799:     my ($metadata,$metacache,$uri) = @_;
12800:     my %allnames;
12801:     foreach my $metakey (keys(%$metadata)) {
12802: 	if ($metakey=~/^parameter\_(.*)/) {
12803: 	  my $part=$$metacache{':'.$metakey.'.part'};
12804: 	  my $name=$$metacache{':'.$metakey.'.name'};
12805: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12806: 	    $allnames{$name}=$part;
12807: 	  }
12808: 	}
12809:     }
12810:     foreach my $name (keys(%allnames)) {
12811:       $$metadata{"parameter_0_$name"}=1;
12812:       my $key=":parameter_0_$name";
12813:       $$metacache{"$key.part"}='0';
12814:       $$metacache{"$key.name"}=$name;
12815:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12816: 					   $allnames{$name}.'_'.$name.
12817: 					   '.type'};
12818:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12819: 			     '.display'};
12820:       my $expr='[Part: '.$allnames{$name}.']';
12821:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12822:       $$metacache{"$key.display"}=$olddis;
12823:     }
12824: }
12825: 
12826: # ------------------------------------------------------ Devalidate title cache
12827: 
12828: sub devalidate_title_cache {
12829:     my ($url)=@_;
12830:     if (!$env{'request.course.id'}) { return; }
12831:     my $symb=&symbread($url);
12832:     if (!$symb) { return; }
12833:     my $key=$env{'request.course.id'}."\0".$symb;
12834:     &devalidate_cache_new('title',$key);
12835: }
12836: 
12837: # ------------------------------------------------- Get the title of a course
12838: 
12839: sub current_course_title {
12840:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12841: }
12842: # ------------------------------------------------- Get the title of a resource
12843: 
12844: sub gettitle {
12845:     my $urlsymb=shift;
12846:     my $symb=&symbread($urlsymb);
12847:     if ($symb) {
12848: 	my $key=$env{'request.course.id'}."\0".$symb;
12849: 	my ($result,$cached)=&is_cached_new('title',$key);
12850: 	if (defined($cached)) { 
12851: 	    return $result;
12852: 	}
12853: 	my ($map,$resid,$url)=&decode_symb($symb);
12854: 	my $title='';
12855: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12856: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12857: 	} else {
12858: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12859: 		    &GDBM_READER(),0640)) {
12860: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12861: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12862: 		untie(%bighash);
12863: 	    }
12864: 	}
12865: 	$title=~s/\&colon\;/\:/gs;
12866: 	if ($title) {
12867: # Remember both $symb and $title for dynamic metadata
12868:             $accesshash{$symb.'___crstitle'}=$title;
12869:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12870: # Cache this title and then return it
12871: 	    return &do_cache_new('title',$key,$title,600);
12872: 	}
12873: 	$urlsymb=$url;
12874:     }
12875:     my $title=&metadata($urlsymb,'title');
12876:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12877:     return $title;
12878: }
12879: 
12880: sub get_slot {
12881:     my ($which,$cnum,$cdom)=@_;
12882:     if (!$cnum || !$cdom) {
12883: 	(undef,my $courseid)=&whichuser();
12884: 	$cdom=$env{'course.'.$courseid.'.domain'};
12885: 	$cnum=$env{'course.'.$courseid.'.num'};
12886:     }
12887:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12888:     my %slotinfo;
12889:     if (exists($remembered{$key})) {
12890: 	$slotinfo{$which} = $remembered{$key};
12891:     } else {
12892: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12893: 	&Apache::lonhomework::showhash(%slotinfo);
12894: 	my ($tmp)=keys(%slotinfo);
12895: 	if ($tmp=~/^error:/) { return (); }
12896: 	$remembered{$key} = $slotinfo{$which};
12897:     }
12898:     if (ref($slotinfo{$which}) eq 'HASH') {
12899: 	return %{$slotinfo{$which}};
12900:     }
12901:     return $slotinfo{$which};
12902: }
12903: 
12904: sub get_reservable_slots {
12905:     my ($cnum,$cdom,$uname,$udom) = @_;
12906:     my $now = time;
12907:     my $reservable_info;
12908:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12909:     if (exists($remembered{$key})) {
12910:         $reservable_info = $remembered{$key};
12911:     } else {
12912:         my %resv;
12913:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12914:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12915:         $reservable_info = \%resv;
12916:         $remembered{$key} = $reservable_info;
12917:     }
12918:     return $reservable_info;
12919: }
12920: 
12921: sub get_course_slots {
12922:     my ($cnum,$cdom) = @_;
12923:     my $hashid=$cnum.':'.$cdom;
12924:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12925:     if (defined($cached)) {
12926:         if (ref($result) eq 'HASH') {
12927:             return %{$result};
12928:         }
12929:     } else {
12930:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12931:         my ($tmp) = keys(%slots);
12932:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12933:             &do_cache_new('allslots',$hashid,\%slots,600);
12934:             return %slots;
12935:         }
12936:     }
12937:     return;
12938: }
12939: 
12940: sub devalidate_slots_cache {
12941:     my ($cnum,$cdom)=@_;
12942:     my $hashid=$cnum.':'.$cdom;
12943:     &devalidate_cache_new('allslots',$hashid);
12944: }
12945: 
12946: sub get_coursechange {
12947:     my ($cdom,$cnum) = @_;
12948:     if ($cdom eq '' || $cnum eq '') {
12949:         return unless ($env{'request.course.id'});
12950:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12951:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12952:     }
12953:     my $hashid=$cdom.'_'.$cnum;
12954:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12955:     if ((defined($cached)) && ($change ne '')) {
12956:         return $change;
12957:     } else {
12958:         my %crshash;
12959:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12960:         if ($crshash{'internal.contentchange'} eq '') {
12961:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12962:             if ($change eq '') {
12963:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12964:                 $change = $crshash{'internal.created'};
12965:             }
12966:         } else {
12967:             $change = $crshash{'internal.contentchange'};
12968:         }
12969:         my $cachetime = 600;
12970:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12971:     }
12972:     return $change;
12973: }
12974: 
12975: sub devalidate_coursechange_cache {
12976:     my ($cnum,$cdom)=@_;
12977:     my $hashid=$cnum.':'.$cdom;
12978:     &devalidate_cache_new('crschange',$hashid);
12979: }
12980: 
12981: # ------------------------------------------------- Update symbolic store links
12982: 
12983: sub symblist {
12984:     my ($mapname,%newhash)=@_;
12985:     $mapname=&deversion(&declutter($mapname));
12986:     my %hash;
12987:     if (($env{'request.course.fn'}) && (%newhash)) {
12988:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12989:                       &GDBM_WRCREAT(),0640)) {
12990: 	    foreach my $url (keys(%newhash)) {
12991: 		next if ($url eq 'last_known'
12992: 			 && $env{'form.no_update_last_known'});
12993: 		$hash{declutter($url)}=&encode_symb($mapname,
12994: 						    $newhash{$url}->[1],
12995: 						    $newhash{$url}->[0]);
12996:             }
12997:             if (untie(%hash)) {
12998: 		return 'ok';
12999:             }
13000:         }
13001:     }
13002:     return 'error';
13003: }
13004: 
13005: # --------------------------------------------------------------- Verify a symb
13006: 
13007: sub symbverify {
13008:     my ($symb,$thisurl,$encstate)=@_;
13009:     my $thisfn=$thisurl;
13010:     $thisfn=&declutter($thisfn);
13011: # direct jump to resource in page or to a sequence - will construct own symbs
13012:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13013: # check URL part
13014:     my ($map,$resid,$url)=&decode_symb($symb);
13015: 
13016:     unless ($url eq $thisfn) { return 0; }
13017: 
13018:     $symb=&symbclean($symb);
13019:     $thisurl=&deversion($thisurl);
13020:     $thisfn=&deversion($thisfn);
13021: 
13022:     my %bighash;
13023:     my $okay=0;
13024: 
13025:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13026:                             &GDBM_READER(),0640)) {
13027:         my $noclutter;
13028:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13029:             $thisurl =~ s/\?.+$//;
13030:             if ($map =~ m{^uploaded/.+\.page$}) {
13031:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13032:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13033:                 $noclutter = 1;
13034:             }
13035:         }
13036:         my $ids;
13037:         if ($noclutter) {
13038:             $ids=$bighash{'ids_'.$thisurl};
13039:         } else {
13040:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13041:         }
13042:         unless ($ids) {
13043:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13044:             $ids=$bighash{$idkey};
13045:         }
13046:         if ($ids) {
13047: # ------------------------------------------------------------------- Has ID(s)
13048:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13049:                 $symb =~ s/\?.+$//;
13050:             }
13051: 	    foreach my $id (split(/\,/,$ids)) {
13052: 	       my ($mapid,$resid)=split(/\./,$id);
13053:                if (
13054:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13055:    eq $symb) {
13056:                    if (ref($encstate)) {
13057:                        $$encstate = $bighash{'encrypted_'.$id};
13058:                    }
13059: 		   if (($env{'request.role.adv'}) ||
13060: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13061:                        ($thisurl eq '/adm/navmaps')) {
13062: 		       $okay=1;
13063:                        last;
13064: 		   }
13065: 	       }
13066: 	   }
13067:         }
13068: 	untie(%bighash);
13069:     }
13070:     return $okay;
13071: }
13072: 
13073: # --------------------------------------------------------------- Clean-up symb
13074: 
13075: sub symbclean {
13076:     my $symb=shift;
13077:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13078: # remove version from map
13079:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13080: 
13081: # remove version from URL
13082:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13083: 
13084: # remove wrapper
13085: 
13086:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13087:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13088:     return $symb;
13089: }
13090: 
13091: # ---------------------------------------------- Split symb to find map and url
13092: 
13093: sub encode_symb {
13094:     my ($map,$resid,$url)=@_;
13095:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13096: }
13097: 
13098: sub decode_symb {
13099:     my $symb=shift;
13100:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13101:     my ($map,$resid,$url)=split(/___/,$symb);
13102:     return (&fixversion($map),$resid,&fixversion($url));
13103: }
13104: 
13105: sub fixversion {
13106:     my $fn=shift;
13107:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13108:     my %bighash;
13109:     my $uri=&clutter($fn);
13110:     my $key=$env{'request.course.id'}.'_'.$uri;
13111: # is this cached?
13112:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13113:     if (defined($cached)) { return $result; }
13114: # unfortunately not cached, or expired
13115:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13116: 	    &GDBM_READER(),0640)) {
13117:  	if ($bighash{'version_'.$uri}) {
13118:  	    my $version=$bighash{'version_'.$uri};
13119:  	    unless (($version eq 'mostrecent') || 
13120: 		    ($version==&getversion($uri))) {
13121:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13122:  	    }
13123:  	}
13124:  	untie %bighash;
13125:     }
13126:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13127: }
13128: 
13129: sub deversion {
13130:     my $url=shift;
13131:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13132:     return $url;
13133: }
13134: 
13135: # ------------------------------------------------------ Return symb list entry
13136: 
13137: sub symbread {
13138:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13139:     my $cache_str='request.symbread.cached.'.$thisfn;
13140:     if (defined($env{$cache_str})) {
13141:         if ($ignorecachednull) {
13142:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13143:         } else {
13144:             return $env{$cache_str};
13145:         }
13146:     }
13147: # no filename provided? try from environment
13148:     unless ($thisfn) {
13149:         if ($env{'request.symb'}) {
13150: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13151: 	}
13152: 	$thisfn=$env{'request.filename'};
13153:     }
13154:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13155: # is that filename actually a symb? Verify, clean, and return
13156:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13157: 	if (&symbverify($thisfn,$1)) {
13158: 	    return $env{$cache_str}=&symbclean($thisfn);
13159: 	}
13160:     }
13161:     $thisfn=declutter($thisfn);
13162:     my %hash;
13163:     my %bighash;
13164:     my $syval='';
13165:     if (($env{'request.course.fn'}) && ($thisfn)) {
13166:         my $targetfn = $thisfn;
13167:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13168:             $targetfn = 'adm/wrapper/'.$thisfn;
13169:         }
13170: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13171: 	    $targetfn=$1;
13172: 	}
13173:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13174:                       &GDBM_READER(),0640)) {
13175: 	    $syval=$hash{$targetfn};
13176:             untie(%hash);
13177:         }
13178: # ---------------------------------------------------------- There was an entry
13179:         if ($syval) {
13180: 	    #unless ($syval=~/\_\d+$/) {
13181: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13182: 		    #&appenv({'request.ambiguous' => $thisfn});
13183: 		    #return $env{$cache_str}='';
13184: 		#}    
13185: 		#$syval.=$1;
13186: 	    #}
13187:         } else {
13188: # ------------------------------------------------------- Was not in symb table
13189:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13190:                             &GDBM_READER(),0640)) {
13191: # ---------------------------------------------- Get ID(s) for current resource
13192:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13193:               unless ($ids) { 
13194:                  $ids=$bighash{'ids_/'.$thisfn};
13195:               }
13196:               unless ($ids) {
13197: # alias?
13198: 		  $ids=$bighash{'mapalias_'.$thisfn};
13199:               }
13200:               if ($ids) {
13201: # ------------------------------------------------------------------- Has ID(s)
13202:                  my @possibilities=split(/\,/,$ids);
13203:                  if ($#possibilities==0) {
13204: # ----------------------------------------------- There is only one possibility
13205: 		     my ($mapid,$resid)=split(/\./,$ids);
13206: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13207: 						    $resid,$thisfn);
13208:                      if (ref($possibles) eq 'HASH') {
13209:                          $possibles->{$syval} = 1;    
13210:                      }
13211:                      if ($checkforblock) {
13212:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13213:                          if (@blockers) {
13214:                              $syval = '';
13215:                              return;
13216:                          }
13217:                      }
13218:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13219: # ------------------------------------------ There is more than one possibility
13220:                      my $realpossible=0;
13221:                      foreach my $id (@possibilities) {
13222: 			 my $file=$bighash{'src_'.$id};
13223:                          my $canaccess;
13224:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13225:                              $canaccess = 1;
13226:                          } else { 
13227:                              $canaccess = &allowed('bre',$file);
13228:                          }
13229:                          if ($canaccess) {
13230:          		     my ($mapid,$resid)=split(/\./,$id);
13231:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13232:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13233: 						             $resid,$thisfn);
13234:                                  if (ref($possibles) eq 'HASH') {
13235:                                      $possibles->{$syval} = 1;
13236:                                  }
13237:                                  if ($checkforblock) {
13238:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13239:                                      unless (@blockers > 0) {
13240:                                          $syval = $poss_syval;
13241:                                          $realpossible++;
13242:                                      }
13243:                                  } else {
13244:                                      $syval = $poss_syval;
13245:                                      $realpossible++;
13246:                                  }
13247:                              }
13248: 			 }
13249:                      }
13250: 		     if ($realpossible!=1) { $syval=''; }
13251:                  } else {
13252:                      $syval='';
13253:                  }
13254: 	      }
13255:               untie(%bighash);
13256:            }
13257:         }
13258:         if ($syval) {
13259: 	    return $env{$cache_str}=$syval;
13260:         }
13261:     }
13262:     &appenv({'request.ambiguous' => $thisfn});
13263:     return $env{$cache_str}='';
13264: }
13265: 
13266: # ---------------------------------------------------------- Return random seed
13267: 
13268: sub numval {
13269:     my $txt=shift;
13270:     $txt=~tr/A-J/0-9/;
13271:     $txt=~tr/a-j/0-9/;
13272:     $txt=~tr/K-T/0-9/;
13273:     $txt=~tr/k-t/0-9/;
13274:     $txt=~tr/U-Z/0-5/;
13275:     $txt=~tr/u-z/0-5/;
13276:     $txt=~s/\D//g;
13277:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13278:     return int($txt);
13279: }
13280: 
13281: sub numval2 {
13282:     my $txt=shift;
13283:     $txt=~tr/A-J/0-9/;
13284:     $txt=~tr/a-j/0-9/;
13285:     $txt=~tr/K-T/0-9/;
13286:     $txt=~tr/k-t/0-9/;
13287:     $txt=~tr/U-Z/0-5/;
13288:     $txt=~tr/u-z/0-5/;
13289:     $txt=~s/\D//g;
13290:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13291:     my $total;
13292:     foreach my $val (@txts) { $total+=$val; }
13293:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13294:     return int($total);
13295: }
13296: 
13297: sub numval3 {
13298:     use integer;
13299:     my $txt=shift;
13300:     $txt=~tr/A-J/0-9/;
13301:     $txt=~tr/a-j/0-9/;
13302:     $txt=~tr/K-T/0-9/;
13303:     $txt=~tr/k-t/0-9/;
13304:     $txt=~tr/U-Z/0-5/;
13305:     $txt=~tr/u-z/0-5/;
13306:     $txt=~s/\D//g;
13307:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13308:     my $total;
13309:     foreach my $val (@txts) { $total+=$val; }
13310:     if ($_64bit) { $total=(($total<<32)>>32); }
13311:     return $total;
13312: }
13313: 
13314: sub digest {
13315:     my ($data)=@_;
13316:     my $digest=&Digest::MD5::md5($data);
13317:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13318:     my ($e,$f);
13319:     {
13320:         use integer;
13321:         $e=($a+$b);
13322:         $f=($c+$d);
13323:         if ($_64bit) {
13324:             $e=(($e<<32)>>32);
13325:             $f=(($f<<32)>>32);
13326:         }
13327:     }
13328:     if (wantarray) {
13329: 	return ($e,$f);
13330:     } else {
13331: 	my $g;
13332: 	{
13333: 	    use integer;
13334: 	    $g=($e+$f);
13335: 	    if ($_64bit) {
13336: 		$g=(($g<<32)>>32);
13337: 	    }
13338: 	}
13339: 	return $g;
13340:     }
13341: }
13342: 
13343: sub latest_rnd_algorithm_id {
13344:     return '64bit5';
13345: }
13346: 
13347: sub get_rand_alg {
13348:     my ($courseid)=@_;
13349:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13350:     if ($courseid) {
13351: 	return $env{"course.$courseid.rndseed"};
13352:     }
13353:     return &latest_rnd_algorithm_id();
13354: }
13355: 
13356: sub validCODE {
13357:     my ($CODE)=@_;
13358:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13359:     return 0;
13360: }
13361: 
13362: sub getCODE {
13363:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13364:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13365: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13366: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13367: 	return $Apache::lonhomework::history{'resource.CODE'};
13368:     }
13369:     return undef;
13370: }
13371: #
13372: #  Determines the random seed for a specific context:
13373: #
13374: # parameters:
13375: #   symb      - in course context the symb for the seed.
13376: #   course_id - The course id of the form domain_coursenum.
13377: #   domain    - Domain for the user.
13378: #   course    - Course for the user.
13379: #   cenv      - environment of the course.
13380: #
13381: # NOTE:
13382: #   All parameters are picked out of the environment if missing
13383: #   or not defined.
13384: #   If a symb cannot be determined the current time is used instead.
13385: #
13386: #  For a given well defined symb, courside, domain, username,
13387: #  and course environment, the seed is reproducible.
13388: #
13389: sub rndseed {
13390:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13391:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13392:     if (!defined($symb)) {
13393: 	unless ($symb=$wsymb) { return time; }
13394:     }
13395:     if (!defined $courseid) { 
13396: 	$courseid=$wcourseid; 
13397:     }
13398:     if (!defined $domain) { $domain=$wdomain; }
13399:     if (!defined $username) { $username=$wusername }
13400: 
13401:     my $which;
13402:     if (defined($cenv->{'rndseed'})) {
13403: 	$which = $cenv->{'rndseed'};
13404:     } else {
13405: 	$which =&get_rand_alg($courseid);
13406:     }
13407:     if (defined(&getCODE())) {
13408: 
13409: 	if ($which eq '64bit5') {
13410: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13411: 	} elsif ($which eq '64bit4') {
13412: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13413: 	} else {
13414: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13415: 	}
13416:     } elsif ($which eq '64bit5') {
13417: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13418:     } elsif ($which eq '64bit4') {
13419: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13420:     } elsif ($which eq '64bit3') {
13421: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13422:     } elsif ($which eq '64bit2') {
13423: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13424:     } elsif ($which eq '64bit') {
13425: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13426:     }
13427:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13428: }
13429: 
13430: sub rndseed_32bit {
13431:     my ($symb,$courseid,$domain,$username)=@_;
13432:     {
13433: 	use integer;
13434: 	my $symbchck=unpack("%32C*",$symb) << 27;
13435: 	my $symbseed=numval($symb) << 22;
13436: 	my $namechck=unpack("%32C*",$username) << 17;
13437: 	my $nameseed=numval($username) << 12;
13438: 	my $domainseed=unpack("%32C*",$domain) << 7;
13439: 	my $courseseed=unpack("%32C*",$courseid);
13440: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13441: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13442: 	#&logthis("rndseed :$num:$symb");
13443: 	if ($_64bit) { $num=(($num<<32)>>32); }
13444: 	return $num;
13445:     }
13446: }
13447: 
13448: sub rndseed_64bit {
13449:     my ($symb,$courseid,$domain,$username)=@_;
13450:     {
13451: 	use integer;
13452: 	my $symbchck=unpack("%32S*",$symb) << 21;
13453: 	my $symbseed=numval($symb) << 10;
13454: 	my $namechck=unpack("%32S*",$username);
13455: 	
13456: 	my $nameseed=numval($username) << 21;
13457: 	my $domainseed=unpack("%32S*",$domain) << 10;
13458: 	my $courseseed=unpack("%32S*",$courseid);
13459: 	
13460: 	my $num1=$symbchck+$symbseed+$namechck;
13461: 	my $num2=$nameseed+$domainseed+$courseseed;
13462: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13463: 	#&logthis("rndseed :$num:$symb");
13464: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13465: 	return "$num1,$num2";
13466:     }
13467: }
13468: 
13469: sub rndseed_64bit2 {
13470:     my ($symb,$courseid,$domain,$username)=@_;
13471:     {
13472: 	use integer;
13473: 	# strings need to be an even # of cahracters long, it it is odd the
13474:         # last characters gets thrown away
13475: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13476: 	my $symbseed=numval($symb) << 10;
13477: 	my $namechck=unpack("%32S*",$username.' ');
13478: 	
13479: 	my $nameseed=numval($username) << 21;
13480: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13481: 	my $courseseed=unpack("%32S*",$courseid.' ');
13482: 	
13483: 	my $num1=$symbchck+$symbseed+$namechck;
13484: 	my $num2=$nameseed+$domainseed+$courseseed;
13485: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13486: 	#&logthis("rndseed :$num:$symb");
13487: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13488: 	return "$num1,$num2";
13489:     }
13490: }
13491: 
13492: sub rndseed_64bit3 {
13493:     my ($symb,$courseid,$domain,$username)=@_;
13494:     {
13495: 	use integer;
13496: 	# strings need to be an even # of cahracters long, it it is odd the
13497:         # last characters gets thrown away
13498: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13499: 	my $symbseed=numval2($symb) << 10;
13500: 	my $namechck=unpack("%32S*",$username.' ');
13501: 	
13502: 	my $nameseed=numval2($username) << 21;
13503: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13504: 	my $courseseed=unpack("%32S*",$courseid.' ');
13505: 	
13506: 	my $num1=$symbchck+$symbseed+$namechck;
13507: 	my $num2=$nameseed+$domainseed+$courseseed;
13508: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13509: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13510: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13511: 	
13512: 	return "$num1:$num2";
13513:     }
13514: }
13515: 
13516: sub rndseed_64bit4 {
13517:     my ($symb,$courseid,$domain,$username)=@_;
13518:     {
13519: 	use integer;
13520: 	# strings need to be an even # of cahracters long, it it is odd the
13521:         # last characters gets thrown away
13522: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13523: 	my $symbseed=numval3($symb) << 10;
13524: 	my $namechck=unpack("%32S*",$username.' ');
13525: 	
13526: 	my $nameseed=numval3($username) << 21;
13527: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13528: 	my $courseseed=unpack("%32S*",$courseid.' ');
13529: 	
13530: 	my $num1=$symbchck+$symbseed+$namechck;
13531: 	my $num2=$nameseed+$domainseed+$courseseed;
13532: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13533: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13534: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13535: 	
13536: 	return "$num1:$num2";
13537:     }
13538: }
13539: 
13540: sub rndseed_64bit5 {
13541:     my ($symb,$courseid,$domain,$username)=@_;
13542:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13543:     return "$num1:$num2";
13544: }
13545: 
13546: sub rndseed_CODE_64bit {
13547:     my ($symb,$courseid,$domain,$username)=@_;
13548:     {
13549: 	use integer;
13550: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13551: 	my $symbseed=numval2($symb);
13552: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13553: 	my $CODEseed=numval(&getCODE());
13554: 	my $courseseed=unpack("%32S*",$courseid.' ');
13555: 	my $num1=$symbseed+$CODEchck;
13556: 	my $num2=$CODEseed+$courseseed+$symbchck;
13557: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13558: 	#&logthis("rndseed :$num1:$num2:$symb");
13559: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13560: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13561: 	return "$num1:$num2";
13562:     }
13563: }
13564: 
13565: sub rndseed_CODE_64bit4 {
13566:     my ($symb,$courseid,$domain,$username)=@_;
13567:     {
13568: 	use integer;
13569: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13570: 	my $symbseed=numval3($symb);
13571: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13572: 	my $CODEseed=numval3(&getCODE());
13573: 	my $courseseed=unpack("%32S*",$courseid.' ');
13574: 	my $num1=$symbseed+$CODEchck;
13575: 	my $num2=$CODEseed+$courseseed+$symbchck;
13576: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13577: 	#&logthis("rndseed :$num1:$num2:$symb");
13578: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13579: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13580: 	return "$num1:$num2";
13581:     }
13582: }
13583: 
13584: sub rndseed_CODE_64bit5 {
13585:     my ($symb,$courseid,$domain,$username)=@_;
13586:     my $code = &getCODE();
13587:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13588:     return "$num1:$num2";
13589: }
13590: 
13591: sub setup_random_from_rndseed {
13592:     my ($rndseed)=@_;
13593:     if ($rndseed =~/([,:])/) {
13594:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13595:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13596:             &Math::Random::random_set_seed_from_phrase($rndseed);
13597:         } else {
13598:             &Math::Random::random_set_seed($num1,$num2);
13599:         }
13600:     } else {
13601: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13602:     }
13603: }
13604: 
13605: sub latest_receipt_algorithm_id {
13606:     return 'receipt3';
13607: }
13608: 
13609: sub recunique {
13610:     my $fucourseid=shift;
13611:     my $unique;
13612:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13613: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13614: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13615:     } else {
13616: 	$unique=$perlvar{'lonReceipt'};
13617:     }
13618:     return unpack("%32C*",$unique);
13619: }
13620: 
13621: sub recprefix {
13622:     my $fucourseid=shift;
13623:     my $prefix;
13624:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13625: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13626: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13627:     } else {
13628: 	$prefix=$perlvar{'lonHostID'};
13629:     }
13630:     return unpack("%32C*",$prefix);
13631: }
13632: 
13633: sub ireceipt {
13634:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13635: 
13636:     my $return =&recprefix($fucourseid).'-';
13637: 
13638:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13639: 	$env{'request.state'} eq 'construct') {
13640: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13641: 	return $return;
13642:     }
13643: 
13644:     my $cuname=unpack("%32C*",$funame);
13645:     my $cudom=unpack("%32C*",$fudom);
13646:     my $cucourseid=unpack("%32C*",$fucourseid);
13647:     my $cusymb=unpack("%32C*",$fusymb);
13648:     my $cunique=&recunique($fucourseid);
13649:     my $cpart=unpack("%32S*",$part);
13650:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13651: 
13652: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13653: 			       
13654: 	$return.= ($cunique%$cuname+
13655: 		   $cunique%$cudom+
13656: 		   $cusymb%$cuname+
13657: 		   $cusymb%$cudom+
13658: 		   $cucourseid%$cuname+
13659: 		   $cucourseid%$cudom+
13660: 		   $cpart%$cuname+
13661: 		   $cpart%$cudom);
13662:     } else {
13663: 	$return.= ($cunique%$cuname+
13664: 		   $cunique%$cudom+
13665: 		   $cusymb%$cuname+
13666: 		   $cusymb%$cudom+
13667: 		   $cucourseid%$cuname+
13668: 		   $cucourseid%$cudom);
13669:     }
13670:     return $return;
13671: }
13672: 
13673: sub receipt {
13674:     my ($part)=@_;
13675:     my ($symb,$courseid,$domain,$name) = &whichuser();
13676:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13677: }
13678: 
13679: sub whichuser {
13680:     my ($passedsymb)=@_;
13681:     my ($symb,$courseid,$domain,$name,$publicuser);
13682:     if (defined($env{'form.grade_symb'})) {
13683: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13684: 	my $allowed=&allowed('vgr',$tmp_courseid);
13685: 	if (!$allowed &&
13686: 	    exists($env{'request.course.sec'}) &&
13687: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13688: 	    $allowed=&allowed('vgr',$tmp_courseid.
13689: 			      '/'.$env{'request.course.sec'});
13690: 	}
13691: 	if ($allowed) {
13692: 	    ($symb)=&get_env_multiple('form.grade_symb');
13693: 	    $courseid=$tmp_courseid;
13694: 	    ($domain)=&get_env_multiple('form.grade_domain');
13695: 	    ($name)=&get_env_multiple('form.grade_username');
13696: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13697: 	}
13698:     }
13699:     if (!$passedsymb) {
13700: 	$symb=&symbread();
13701:     } else {
13702: 	$symb=$passedsymb;
13703:     }
13704:     $courseid=$env{'request.course.id'};
13705:     $domain=$env{'user.domain'};
13706:     $name=$env{'user.name'};
13707:     if ($name eq 'public' && $domain eq 'public') {
13708: 	if (!defined($env{'form.username'})) {
13709: 	    $env{'form.username'}.=time.rand(10000000);
13710: 	}
13711: 	$name.=$env{'form.username'};
13712:     }
13713:     return ($symb,$courseid,$domain,$name,$publicuser);
13714: 
13715: }
13716: 
13717: # ------------------------------------------------------------ Serves up a file
13718: # returns either the contents of the file or 
13719: # -1 if the file doesn't exist
13720: #
13721: # if the target is a file that was uploaded via DOCS, 
13722: # a check will be made to see if a current copy exists on the local server,
13723: # if it does this will be served, otherwise a copy will be retrieved from
13724: # the home server for the course and stored in /home/httpd/html/userfiles on
13725: # the local server.   
13726: 
13727: sub getfile {
13728:     my ($file) = @_;
13729:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13730:     &repcopy($file);
13731:     return &readfile($file);
13732: }
13733: 
13734: sub repcopy_userfile {
13735:     my ($file)=@_;
13736:     my $londocroot = $perlvar{'lonDocRoot'};
13737:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13738:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13739:     my ($cdom,$cnum,$filename) = 
13740: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13741:     my $uri="/uploaded/$cdom/$cnum/$filename";
13742:     if (-e "$file") {
13743: # we already have a local copy, check it out
13744: 	my @fileinfo = stat($file);
13745: 	my $rtncode;
13746: 	my $info;
13747: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13748: 	if ($lwpresp ne 'ok') {
13749: # there is no such file anymore, even though we had a local copy
13750: 	    if ($rtncode eq '404') {
13751: 		unlink($file);
13752: 	    }
13753: 	    return -1;
13754: 	}
13755: 	if ($info < $fileinfo[9]) {
13756: # nice, the file we have is up-to-date, just say okay
13757: 	    return 'ok';
13758: 	} else {
13759: # the file is outdated, get rid of it
13760: 	    unlink($file);
13761: 	}
13762:     }
13763: # one way or the other, at this point, we don't have the file
13764: # construct the correct path for the file
13765:     my @parts = ($cdom,$cnum); 
13766:     if ($filename =~ m|^(.+)/[^/]+$|) {
13767: 	push @parts, split(/\//,$1);
13768:     }
13769:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13770:     foreach my $part (@parts) {
13771: 	$path .= '/'.$part;
13772: 	if (!-e $path) {
13773: 	    mkdir($path,0770);
13774: 	}
13775:     }
13776: # now the path exists for sure
13777: # get a user agent
13778:     my $transferfile=$file.'.in.transfer';
13779: # FIXME: this should flock
13780:     if (-e $transferfile) { return 'ok'; }
13781:     my $request;
13782:     $uri=~s/^\///;
13783:     my $homeserver = &homeserver($cnum,$cdom);
13784:     my $hostname = &hostname($homeserver);
13785:     my $protocol = $protocol{$homeserver};
13786:     $protocol = 'http' if ($protocol ne 'https');
13787:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13788:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13789: # did it work?
13790:     if ($response->is_error()) {
13791: 	unlink($transferfile);
13792: 	&logthis("Userfile repcopy failed for $uri");
13793: 	return -1;
13794:     }
13795: # worked, rename the transfer file
13796:     rename($transferfile,$file);
13797:     return 'ok';
13798: }
13799: 
13800: sub tokenwrapper {
13801:     my $uri=shift;
13802:     $uri=~s|^https?\://([^/]+)||;
13803:     $uri=~s|^/||;
13804:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13805:     my $token=$1;
13806:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13807:     if ($udom && $uname && $file) {
13808: 	$file=~s|(\?\.*)*$||;
13809:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13810:         my $homeserver = &homeserver($uname,$udom);
13811:         my $hostname = &hostname($homeserver);
13812:         my $protocol = $protocol{$homeserver};
13813:         $protocol = 'http' if ($protocol ne 'https');
13814:         return $protocol.'://'.$hostname.'/'.$uri.
13815:                (($uri=~/\?/)?'&':'?').'token='.$token.
13816:                                '&tokenissued='.$perlvar{'lonHostID'};
13817:     } else {
13818:         return '/adm/notfound.html';
13819:     }
13820: }
13821: 
13822: # call with reqtype HEAD: get last modification time
13823: # call with reqtype GET: get the file contents
13824: # Do not call this with reqtype GET for large files! It loads everything into memory
13825: #
13826: sub getuploaded {
13827:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13828:     $uri=~s/^\///;
13829:     my $homeserver = &homeserver($cnum,$cdom);
13830:     my $hostname = &hostname($homeserver);
13831:     my $protocol = $protocol{$homeserver};
13832:     $protocol = 'http' if ($protocol ne 'https');
13833:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13834:     my $request=new HTTP::Request($reqtype,$uri);
13835:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13836:     $$rtncode = $response->code;
13837:     if (! $response->is_success()) {
13838: 	return 'failed';
13839:     }      
13840:     if ($reqtype eq 'HEAD') {
13841: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13842:     } elsif ($reqtype eq 'GET') {
13843: 	$$info = $response->content;
13844:     }
13845:     return 'ok';
13846: }
13847: 
13848: sub readfile {
13849:     my $file = shift;
13850:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13851:     my $fh;
13852:     open($fh,"<",$file);
13853:     my $a='';
13854:     while (my $line = <$fh>) { $a .= $line; }
13855:     return $a;
13856: }
13857: 
13858: sub filelocation {
13859:     my ($dir,$file) = @_;
13860:     my $location;
13861:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13862: 
13863:     if ($file =~ m-^/adm/-) {
13864: 	$file=~s-^/adm/wrapper/-/-;
13865: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13866:     }
13867: 
13868:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13869:         $location = $file;
13870:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13871:         my ($udom,$uname,$filename)=
13872:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13873:         my $home=&homeserver($uname,$udom);
13874:         my $is_me=0;
13875:         my @ids=&current_machine_ids();
13876:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13877:         if ($is_me) {
13878:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13879:         } else {
13880:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13881:   	      $udom.'/'.$uname.'/'.$filename;
13882:         }
13883:     } elsif ($file =~ m-^/adm/-) {
13884: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13885:     } else {
13886:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13887:         $file=~s:^/(res|priv)/:/:;
13888:         my $space=$1;
13889:         if ( !( $file =~ m:^/:) ) {
13890:             $location = $dir. '/'.$file;
13891:         } else {
13892:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13893:         }
13894:     }
13895:     $location=~s://+:/:g; # remove duplicate /
13896:     while ($location=~m{/\.\./}) {
13897: 	if ($location =~ m{/[^/]+/\.\./}) {
13898: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13899: 	} else {
13900: 	    $location=~ s{/\.\./}{/}g;
13901: 	}
13902:     } #remove dir/..
13903:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13904:     return $location;
13905: }
13906: 
13907: sub hreflocation {
13908:     my ($dir,$file)=@_;
13909:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13910: 	$file=filelocation($dir,$file);
13911:     } elsif ($file=~m-^/adm/-) {
13912: 	$file=~s-^/adm/wrapper/-/-;
13913: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13914:     }
13915:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13916: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13917:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13918: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13919: 	        {/uploaded/$1/$2/}x;
13920:     }
13921:     if ($file=~ m{^/userfiles/}) {
13922: 	$file =~ s{^/userfiles/}{/uploaded/};
13923:     }
13924:     return $file;
13925: }
13926: 
13927: 
13928: 
13929: 
13930: 
13931: sub current_machine_domains {
13932:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13933: }
13934: 
13935: sub machine_domains {
13936:     my ($hostname) = @_;
13937:     my @domains;
13938:     my %hostname = &all_hostnames();
13939:     while( my($id, $name) = each(%hostname)) {
13940: #	&logthis("-$id-$name-$hostname-");
13941: 	if ($hostname eq $name) {
13942: 	    push(@domains,&host_domain($id));
13943: 	}
13944:     }
13945:     return @domains;
13946: }
13947: 
13948: sub current_machine_ids {
13949:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13950: }
13951: 
13952: sub machine_ids {
13953:     my ($hostname) = @_;
13954:     $hostname ||= &hostname($perlvar{'lonHostID'});
13955:     my @ids;
13956:     my %name_to_host = &all_names();
13957:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13958: 	return @{ $name_to_host{$hostname} };
13959:     }
13960:     return;
13961: }
13962: 
13963: sub additional_machine_domains {
13964:     my @domains;
13965:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13966:     while( my $line = <$fh>) {
13967:         $line =~ s/\s//g;
13968:         push(@domains,$line);
13969:     }
13970:     return @domains;
13971: }
13972: 
13973: sub default_login_domain {
13974:     my $domain = $perlvar{'lonDefDomain'};
13975:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13976:     foreach my $posdom (&current_machine_domains(),
13977:                         &additional_machine_domains()) {
13978:         if (lc($posdom) eq lc($testdomain)) {
13979:             $domain=$posdom;
13980:             last;
13981:         }
13982:     }
13983:     return $domain;
13984: }
13985: 
13986: sub uses_sts {
13987:     my ($ignore_cache) = @_;
13988:     my $lonhost = $perlvar{'lonHostID'};
13989:     my $hostname = &hostname($lonhost);
13990:     my $sts_on;
13991:     if ($protocol{$lonhost} eq 'https') {
13992:         my $cachetime = 12*3600;
13993:         if (!$ignore_cache) {
13994:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13995:             if (defined($cached)) {
13996:                 return $sts_on;
13997:             }
13998:         }
13999:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14000:         my $request=new HTTP::Request('HEAD',$url);
14001:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14002:         if ($response->is_success) {
14003:             my $has_sts = $response->header('Strict-Transport-Security');
14004:             if ($has_sts eq '') {
14005:                 $sts_on = 0;
14006:             } else {
14007:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14008:                     my $maxage = $1;
14009:                     if ($maxage) {
14010:                         $sts_on = 1;
14011:                     } else {
14012:                         $sts_on = 0;
14013:                     }
14014:                 } else {
14015:                     $sts_on = 0;
14016:                 }
14017:             }
14018:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14019:         }
14020:     }
14021:     return;
14022: }
14023: 
14024: # ------------------------------------------------------------- Declutters URLs
14025: 
14026: sub declutter {
14027:     my $thisfn=shift;
14028:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14029:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14030:         $thisfn=~s{^/home/httpd/html}{};
14031:     }
14032:     $thisfn=~s/^\///;
14033:     $thisfn=~s|^adm/wrapper/||;
14034:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14035:     $thisfn=~s/^res\///;
14036:     $thisfn=~s/^priv\///;
14037:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14038:         $thisfn=~s/\?.+$//;
14039:     }
14040:     return $thisfn;
14041: }
14042: 
14043: # ------------------------------------------------------------- Clutter up URLs
14044: 
14045: sub clutter {
14046:     my $thisfn='/'.&declutter(shift);
14047:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14048: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14049:        $thisfn='/res'.$thisfn; 
14050:     }
14051:     if ($thisfn !~m|^/adm|) {
14052: 	if ($thisfn =~ m|^/ext/|) {
14053: 	    $thisfn='/adm/wrapper'.$thisfn;
14054: 	} else {
14055: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14056: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14057: 	    if ($embstyle eq 'ssi'
14058: 		|| ($embstyle eq 'hdn')
14059: 		|| ($embstyle eq 'rat')
14060: 		|| ($embstyle eq 'prv')
14061: 		|| ($embstyle eq 'ign')) {
14062: 		#do nothing with these
14063: 	    } elsif (($embstyle eq 'img') 
14064: 		|| ($embstyle eq 'emb')
14065: 		|| ($embstyle eq 'wrp')) {
14066: 		$thisfn='/adm/wrapper'.$thisfn;
14067: 	    } elsif ($embstyle eq 'unk'
14068: 		     && $thisfn!~/\.(sequence|page)$/) {
14069: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14070: 	    } else {
14071: #		&logthis("Got a blank emb style");
14072: 	    }
14073: 	}
14074:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14075:         $thisfn='/adm/wrapper'.$thisfn;
14076:     }
14077:     return $thisfn;
14078: }
14079: 
14080: sub clutter_with_no_wrapper {
14081:     my $uri = &clutter(shift);
14082:     if ($uri =~ m-^/adm/-) {
14083: 	$uri =~ s-^/adm/wrapper/-/-;
14084: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14085:     }
14086:     return $uri;
14087: }
14088: 
14089: sub freeze_escape {
14090:     my ($value)=@_;
14091:     if (ref($value)) {
14092: 	$value=&nfreeze($value);
14093: 	return '__FROZEN__'.&escape($value);
14094:     }
14095:     return &escape($value);
14096: }
14097: 
14098: 
14099: sub thaw_unescape {
14100:     my ($value)=@_;
14101:     if ($value =~ /^__FROZEN__/) {
14102: 	substr($value,0,10,undef);
14103: 	$value=&unescape($value);
14104: 	return &thaw($value);
14105:     }
14106:     return &unescape($value);
14107: }
14108: 
14109: sub correct_line_ends {
14110:     my ($result)=@_;
14111:     $$result =~s/\r\n/\n/mg;
14112:     $$result =~s/\r/\n/mg;
14113: }
14114: # ================================================================ Main Program
14115: 
14116: sub goodbye {
14117:    &logthis("Starting Shut down");
14118: #not converted to using infrastruture and probably shouldn't be
14119:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14120: #converted
14121: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14122:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14123: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14124: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14125: #1.1 only
14126: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14127: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14128: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14129: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14130:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14131:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14132:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14133:    &flushcourselogs();
14134:    &logthis("Shutting down");
14135: }
14136: 
14137: sub get_dns {
14138:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14139:     if (!$ignore_cache) {
14140: 	my ($content,$cached)=
14141: 	    &Apache::lonnet::is_cached_new('dns',$url);
14142: 	if ($cached) {
14143: 	    &$func($content,$hashref);
14144: 	    return;
14145: 	}
14146:     }
14147: 
14148:     my %alldns;
14149:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14150:         foreach my $dns (<$config>) {
14151: 	    next if ($dns !~ /^\^(\S*)/x);
14152:             my $line = $1;
14153:             my ($host,$protocol) = split(/:/,$line);
14154:             if ($protocol ne 'https') {
14155:                 $protocol = 'http';
14156:             }
14157: 	    $alldns{$host} = $protocol;
14158:         }
14159:         close($config);
14160:     }
14161:     while (%alldns) {
14162: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14163: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14164:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14165:         delete($alldns{$dns});
14166: 	next if ($response->is_error());
14167:         if ($url eq '/adm/dns/loncapaCRL') {
14168:             return &$func($response);
14169:         } else {
14170: 	    my @content = split("\n",$response->content);
14171: 	    unless ($nocache) {
14172: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14173: 	    }
14174: 	    &$func(\@content,$hashref);
14175:             return;
14176:         }
14177:     }
14178:     my $which = (split('/',$url,4))[3];
14179:     if ($which eq 'loncapaCRL') {
14180:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14181:         if (-e $diskfile) {
14182:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14183:         } else {
14184:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14185:         }
14186:     } else {
14187:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14188:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14189:             my @content = <$config>;
14190:             close($config);
14191:             &$func(\@content,$hashref);
14192:         }
14193:     }
14194:     return;
14195: }
14196: 
14197: # ------------------------------------------------------Get DNS checksums file
14198: sub parse_dns_checksums_tab {
14199:     my ($lines,$hashref) = @_;
14200:     my $lonhost = $perlvar{'lonHostID'};
14201:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14202:     my $loncaparev = &get_server_loncaparev($machine_dom);
14203:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14204:     my $webconfdir = '/etc/httpd/conf';
14205:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14206:         $webconfdir = '/etc/apache2';
14207:     } elsif ($distro =~ /^sles(\d+)$/) {
14208:         if ($1 >= 10) {
14209:             $webconfdir = '/etc/apache2';
14210:         }
14211:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14212:         if ($1 >= 10.0) {
14213:             $webconfdir = '/etc/apache2';
14214:         }
14215:     }
14216:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14217:     my (%chksum,%revnum);
14218:     if (ref($lines) eq 'ARRAY') {
14219:         chomp(@{$lines});
14220:         my $version = shift(@{$lines});
14221:         if ($version eq $release) {  
14222:             foreach my $line (@{$lines}) {
14223:                 my ($file,$version,$shasum) = split(/,/,$line);
14224:                 if ($file =~ m{^/etc/httpd/conf}) {
14225:                     if ($webconfdir eq '/etc/apache2') {
14226:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14227:                     }
14228:                 }
14229:                 $chksum{$file} = $shasum;
14230:                 $revnum{$file} = $version;
14231:             }
14232:             if (ref($hashref) eq 'HASH') {
14233:                 %{$hashref} = (
14234:                                 sums     => \%chksum,
14235:                                 versions => \%revnum,
14236:                               );
14237:             }
14238:         }
14239:     }
14240:     return;
14241: }
14242: 
14243: sub fetch_dns_checksums {
14244:     my %checksums;
14245:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14246:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14247:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14248:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14249:              \%checksums);
14250:     return \%checksums;
14251: }
14252: 
14253: sub fetch_crl_pemfile {
14254:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14255: }
14256: 
14257: sub save_crl_pem {
14258:     my ($response) = @_;
14259:     my ($msg,$hadchanges);
14260:     if (ref($response)) {
14261:         my $now = time;
14262:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14263:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14264:         if (open(my $fh,'>',"$tmpcrl")) {
14265:             print $fh $response->content;
14266:             close($fh);
14267:             if (-e $lonca) {
14268:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14269:                     my $check = <PIPE>;
14270:                     close(PIPE);
14271:                     chomp($check);
14272:                     if ($check eq 'verify OK') {
14273:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14274:                         my $backup;
14275:                         if (-e $dest) {
14276:                             if (&File::Copy::move($dest,"$dest.bak")) {
14277:                                 $backup = 'ok';
14278:                             }
14279:                         }
14280:                         if (&File::Copy::move($tmpcrl,$dest)) {
14281:                             $msg = 'ok';
14282:                             if ($backup) {
14283:                                 my (%oldnums,%newnums);
14284:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14285:                                     while (<PIPE>) {
14286:                                         $oldnums{(split(/:/))[1]} = 1;
14287:                                     }
14288:                                     close(PIPE);
14289:                                 }
14290:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14291:                                     while(<PIPE>) {
14292:                                         $newnums{(split(/:/))[1]} = 1;
14293:                                     }
14294:                                     close(PIPE);
14295:                                 }
14296:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14297:                                     unless (exists($oldnums{$key})) {
14298:                                         $hadchanges = 1;
14299:                                         last;
14300:                                     }
14301:                                 }
14302:                                 unless ($hadchanges) {
14303:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14304:                                         unless (exists($newnums{$key})) {
14305:                                             $hadchanges = 1;
14306:                                             last;
14307:                                         }
14308:                                     }
14309:                                 }
14310:                             }
14311:                         }
14312:                     } else {
14313:                         unlink($tmpcrl);
14314:                     }
14315:                 } else {
14316:                     unlink($tmpcrl);
14317:                 }
14318:             } else {
14319:                 unlink($tmpcrl);
14320:             }
14321:         }
14322:     }
14323:     return ($msg,$hadchanges);
14324: }
14325: 
14326: # ------------------------------------------------------------ Read domain file
14327: {
14328:     my $loaded;
14329:     my %domain;
14330: 
14331:     sub parse_domain_tab {
14332: 	my ($lines) = @_;
14333: 	foreach my $line (@$lines) {
14334: 	    next if ($line =~ /^(\#|\s*$ )/x);
14335: 
14336: 	    chomp($line);
14337: 	    my ($name,@elements) = split(/:/,$line,9);
14338: 	    my %this_domain;
14339: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14340: 			       'lang_def', 'city', 'longi', 'lati',
14341: 			       'primary') {
14342: 		$this_domain{$field} = shift(@elements);
14343: 	    }
14344: 	    $domain{$name} = \%this_domain;
14345: 	}
14346:     }
14347: 
14348:     sub reset_domain_info {
14349: 	undef($loaded);
14350: 	undef(%domain);
14351:     }
14352: 
14353:     sub load_domain_tab {
14354: 	my ($ignore_cache,$nocache) = @_;
14355: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14356: 	my $fh;
14357: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14358: 	    my @lines = <$fh>;
14359: 	    &parse_domain_tab(\@lines);
14360: 	}
14361: 	close($fh);
14362: 	$loaded = 1;
14363:     }
14364: 
14365:     sub domain {
14366: 	&load_domain_tab() if (!$loaded);
14367: 
14368: 	my ($name,$what) = @_;
14369: 	return if ( !exists($domain{$name}) );
14370: 
14371: 	if (!$what) {
14372: 	    return $domain{$name}{'description'};
14373: 	}
14374: 	return $domain{$name}{$what};
14375:     }
14376: 
14377:     sub domain_info {
14378:         &load_domain_tab() if (!$loaded);
14379:         return %domain;
14380:     }
14381: 
14382: }
14383: 
14384: 
14385: # ------------------------------------------------------------- Read hosts file
14386: {
14387:     my %hostname;
14388:     my %hostdom;
14389:     my %libserv;
14390:     my $loaded;
14391:     my %name_to_host;
14392:     my %internetdom;
14393:     my %LC_dns_serv;
14394: 
14395:     sub parse_hosts_tab {
14396: 	my ($file) = @_;
14397: 	foreach my $configline (@$file) {
14398: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14399:             chomp($configline);
14400: 	    if ($configline =~ /^\^/) {
14401:                 if ($configline =~ /^\^([\w.\-]+)/) {
14402:                     $LC_dns_serv{$1} = 1;
14403:                 }
14404:                 next;
14405:             }
14406: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14407: 	    $name=~s/\s//g;
14408: 	    if ($id && $domain && $role && $name) {
14409:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14410:                     my $curr = $hostname{$id};
14411:                     my $skip;
14412:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14413:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14414:                             $skip = 1;
14415:                         } else {
14416:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14417:                         }
14418:                     }
14419:                     unless ($skip) {
14420:                         push(@{$name_to_host{$name}},$id);
14421:                     }
14422:                 } else {
14423:                     push(@{$name_to_host{$name}},$id);
14424:                 }
14425: 		$hostname{$id}=$name;
14426: 		$hostdom{$id}=$domain;
14427: 		if ($role eq 'library') { $libserv{$id}=$name; }
14428:                 if (defined($protocol)) {
14429:                     if ($protocol eq 'https') {
14430:                         $protocol{$id} = $protocol;
14431:                     } else {
14432:                         $protocol{$id} = 'http'; 
14433:                     }
14434:                 } else {
14435:                     $protocol{$id} = 'http';
14436:                 }
14437:                 if (defined($intdom)) {
14438:                     $internetdom{$id} = $intdom;
14439:                 }
14440: 	    }
14441: 	}
14442:     }
14443:     
14444:     sub reset_hosts_info {
14445: 	&purge_remembered();
14446: 	&reset_domain_info();
14447: 	&reset_hosts_ip_info();
14448:         undef(%internetdom);
14449: 	undef(%name_to_host);
14450: 	undef(%hostname);
14451: 	undef(%hostdom);
14452: 	undef(%libserv);
14453: 	undef($loaded);
14454:     }
14455: 
14456:     sub load_hosts_tab {
14457: 	my ($ignore_cache,$nocache) = @_;
14458: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14459: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14460: 	my @config = <$config>;
14461: 	&parse_hosts_tab(\@config);
14462: 	close($config);
14463: 	$loaded=1;
14464:     }
14465: 
14466:     sub hostname {
14467: 	&load_hosts_tab() if (!$loaded);
14468: 
14469: 	my ($lonid) = @_;
14470: 	return $hostname{$lonid};
14471:     }
14472: 
14473:     sub all_hostnames {
14474: 	&load_hosts_tab() if (!$loaded);
14475: 
14476: 	return %hostname;
14477:     }
14478: 
14479:     sub all_names {
14480:         my ($ignore_cache,$nocache) = @_;
14481: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14482: 
14483: 	return %name_to_host;
14484:     }
14485: 
14486:     sub all_host_domain {
14487:         &load_hosts_tab() if (!$loaded);
14488:         return %hostdom;
14489:     }
14490: 
14491:     sub all_host_intdom {
14492:         &load_hosts_tab() if (!$loaded);
14493:         return %internetdom;
14494:     }
14495: 
14496:     sub is_library {
14497: 	&load_hosts_tab() if (!$loaded);
14498: 
14499: 	return exists($libserv{$_[0]});
14500:     }
14501: 
14502:     sub all_library {
14503: 	&load_hosts_tab() if (!$loaded);
14504: 
14505: 	return %libserv;
14506:     }
14507: 
14508:     sub unique_library {
14509: 	#2x reverse removes all hostnames that appear more than once
14510:         my %unique = reverse &all_library();
14511:         return reverse %unique;
14512:     }
14513: 
14514:     sub get_servers {
14515: 	&load_hosts_tab() if (!$loaded);
14516: 
14517: 	my ($domain,$type) = @_;
14518: 	my %possible_hosts = ($type eq 'library') ? %libserv
14519: 	                                          : %hostname;
14520: 	my %result;
14521: 	if (ref($domain) eq 'ARRAY') {
14522: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14523: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14524: 		    $result{$host} = $hostname;
14525: 		}
14526: 	    }
14527: 	} else {
14528: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14529: 		if ($hostdom{$host} eq $domain) {
14530: 		    $result{$host} = $hostname;
14531: 		}
14532: 	    }
14533: 	}
14534: 	return %result;
14535:     }
14536: 
14537:     sub get_unique_servers {
14538:         my %unique = reverse &get_servers(@_);
14539: 	return reverse %unique;
14540:     }
14541: 
14542:     sub host_domain {
14543: 	&load_hosts_tab() if (!$loaded);
14544: 
14545: 	my ($lonid) = @_;
14546: 	return $hostdom{$lonid};
14547:     }
14548: 
14549:     sub all_domains {
14550: 	&load_hosts_tab() if (!$loaded);
14551: 
14552: 	my %seen;
14553: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14554: 	return @uniq;
14555:     }
14556: 
14557:     sub internet_dom {
14558:         &load_hosts_tab() if (!$loaded);
14559: 
14560:         my ($lonid) = @_;
14561:         return $internetdom{$lonid};
14562:     }
14563: 
14564:     sub is_LC_dns {
14565:         &load_hosts_tab() if (!$loaded);
14566: 
14567:         my ($hostname) = @_;
14568:         return exists($LC_dns_serv{$hostname});
14569:     }
14570: 
14571: }
14572: 
14573: { 
14574:     my %iphost;
14575:     my %name_to_ip;
14576:     my %lonid_to_ip;
14577: 
14578:     sub get_hosts_from_ip {
14579: 	my ($ip) = @_;
14580: 	my %iphosts = &get_iphost();
14581: 	if (ref($iphosts{$ip})) {
14582: 	    return @{$iphosts{$ip}};
14583: 	}
14584: 	return;
14585:     }
14586:     
14587:     sub reset_hosts_ip_info {
14588: 	undef(%iphost);
14589: 	undef(%name_to_ip);
14590: 	undef(%lonid_to_ip);
14591:     }
14592: 
14593:     sub get_host_ip {
14594: 	my ($lonid) = @_;
14595: 	if (exists($lonid_to_ip{$lonid})) {
14596: 	    return $lonid_to_ip{$lonid};
14597: 	}
14598: 	my $name=&hostname($lonid);
14599:    	my $ip = gethostbyname($name);
14600: 	return if (!$ip || length($ip) ne 4);
14601: 	$ip=inet_ntoa($ip);
14602: 	$name_to_ip{$name}   = $ip;
14603: 	$lonid_to_ip{$lonid} = $ip;
14604: 	return $ip;
14605:     }
14606:     
14607:     sub get_iphost {
14608: 	my ($ignore_cache,$nocache) = @_;
14609: 
14610: 	if (!$ignore_cache) {
14611: 	    if (%iphost) {
14612: 		return %iphost;
14613: 	    }
14614: 	    my ($ip_info,$cached)=
14615: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14616: 	    if ($cached) {
14617: 		%iphost      = %{$ip_info->[0]};
14618: 		%name_to_ip  = %{$ip_info->[1]};
14619: 		%lonid_to_ip = %{$ip_info->[2]};
14620: 		return %iphost;
14621: 	    }
14622: 	}
14623: 
14624: 	# get yesterday's info for fallback
14625: 	my %old_name_to_ip;
14626: 	my ($ip_info,$cached)=
14627: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14628: 	if ($cached) {
14629: 	    %old_name_to_ip = %{$ip_info->[1]};
14630: 	}
14631: 
14632: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14633: 	foreach my $name (keys(%name_to_host)) {
14634: 	    my $ip;
14635: 	    if (!exists($name_to_ip{$name})) {
14636: 		$ip = gethostbyname($name);
14637: 		if (!$ip || length($ip) ne 4) {
14638: 		    if (defined($old_name_to_ip{$name})) {
14639: 			$ip = $old_name_to_ip{$name};
14640: 			&logthis("Can't find $name defaulting to old $ip");
14641: 		    } else {
14642: 			&logthis("Name $name no IP found");
14643: 			next;
14644: 		    }
14645: 		} else {
14646: 		    $ip=inet_ntoa($ip);
14647: 		}
14648: 		$name_to_ip{$name} = $ip;
14649: 	    } else {
14650: 		$ip = $name_to_ip{$name};
14651: 	    }
14652: 	    foreach my $id (@{ $name_to_host{$name} }) {
14653: 		$lonid_to_ip{$id} = $ip;
14654: 	    }
14655: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14656: 	}
14657:         unless ($nocache) {
14658: 	    &do_cache_new('iphost','iphost',
14659: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14660: 		          48*60*60);
14661:         }
14662: 
14663: 	return %iphost;
14664:     }
14665: 
14666:     #
14667:     #  Given a DNS returns the loncapa host name for that DNS 
14668:     # 
14669:     sub host_from_dns {
14670:         my ($dns) = @_;
14671:         my @hosts;
14672:         my $ip;
14673: 
14674:         if (exists($name_to_ip{$dns})) {
14675:             $ip = $name_to_ip{$dns};
14676:         }
14677:         if (!$ip) {
14678:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14679:             if (length($ip) == 4) { 
14680: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14681:             }
14682:         }
14683:         if ($ip) {
14684: 	    @hosts = get_hosts_from_ip($ip);
14685: 	    return $hosts[0];
14686:         }
14687:         return undef;
14688:     }
14689: 
14690:     sub get_internet_names {
14691:         my ($lonid) = @_;
14692:         return if ($lonid eq '');
14693:         my ($idnref,$cached)=
14694:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14695:         if ($cached) {
14696:             return $idnref;
14697:         }
14698:         my $ip = &get_host_ip($lonid);
14699:         my @hosts = &get_hosts_from_ip($ip);
14700:         my %iphost = &get_iphost();
14701:         my (@idns,%seen);
14702:         foreach my $id (@hosts) {
14703:             my $dom = &host_domain($id);
14704:             my $prim_id = &domain($dom,'primary');
14705:             my $prim_ip = &get_host_ip($prim_id);
14706:             next if ($seen{$prim_ip});
14707:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14708:                 foreach my $id (@{$iphost{$prim_ip}}) {
14709:                     my $intdom = &internet_dom($id);
14710:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14711:                         push(@idns,$intdom);
14712:                     }
14713:                 }
14714:             }
14715:             $seen{$prim_ip} = 1;
14716:         }
14717:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14718:     }
14719: 
14720: }
14721: 
14722: sub all_loncaparevs {
14723:     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);
14724: }
14725: 
14726: # ---------------------------------------------------------- Read loncaparev table
14727: {
14728:     sub load_loncaparevs { 
14729:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14730:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14731:                 while (my $configline=<$config>) {
14732:                     chomp($configline);
14733:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14734:                     $loncaparevs{$hostid}=$loncaparev;
14735:                 }
14736:                 close($config);
14737:             }
14738:         }
14739:     }
14740: }
14741: 
14742: # ---------------------------------------------------------- Read serverhostID table
14743: {
14744:     sub load_serverhomeIDs {
14745:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14746:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14747:                 while (my $configline=<$config>) {
14748:                     chomp($configline);
14749:                     my ($name,$id)=split(/:/,$configline);
14750:                     $serverhomeIDs{$name}=$id;
14751:                 }
14752:                 close($config);
14753:             }
14754:         }
14755:     }
14756: }
14757: 
14758: 
14759: BEGIN {
14760: 
14761: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14762:     unless ($readit) {
14763: {
14764:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14765:     %perlvar = (%perlvar,%{$configvars});
14766: }
14767: 
14768: 
14769: # ------------------------------------------------------ Read spare server file
14770: {
14771:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14772: 
14773:     while (my $configline=<$config>) {
14774:        chomp($configline);
14775:        if ($configline) {
14776: 	   my ($host,$type) = split(':',$configline,2);
14777: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14778: 	   push(@{ $spareid{$type} }, $host);
14779:        }
14780:     }
14781:     close($config);
14782: }
14783: # ------------------------------------------------------------ Read permissions
14784: {
14785:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14786: 
14787:     while (my $configline=<$config>) {
14788: 	chomp($configline);
14789: 	if ($configline) {
14790: 	    my ($role,$perm)=split(/ /,$configline);
14791: 	    if ($perm ne '') { $pr{$role}=$perm; }
14792: 	}
14793:     }
14794:     close($config);
14795: }
14796: 
14797: # -------------------------------------------- Read plain texts for permissions
14798: {
14799:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14800: 
14801:     while (my $configline=<$config>) {
14802: 	chomp($configline);
14803: 	if ($configline) {
14804: 	    my ($short,@plain)=split(/:/,$configline);
14805:             %{$prp{$short}} = ();
14806: 	    if (@plain > 0) {
14807:                 $prp{$short}{'std'} = $plain[0];
14808:                 for (my $i=1; $i<@plain; $i++) {
14809:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14810:                 }
14811:             }
14812: 	}
14813:     }
14814:     close($config);
14815: }
14816: 
14817: # ---------------------------------------------------------- Read package table
14818: {
14819:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14820: 
14821:     while (my $configline=<$config>) {
14822: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14823: 	chomp($configline);
14824: 	my ($short,$plain)=split(/:/,$configline);
14825: 	my ($pack,$name)=split(/\&/,$short);
14826: 	if ($plain ne '') {
14827: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14828: 	    $packagetab{$short}=$plain; 
14829: 	}
14830:     }
14831:     close($config);
14832: }
14833: 
14834: # ---------------------------------------------------------- Read loncaparev table
14835: 
14836: &load_loncaparevs();
14837: 
14838: # ---------------------------------------------------------- Read serverhostID table
14839: 
14840: &load_serverhomeIDs();
14841: 
14842: # ---------------------------------------------------------- Read releaseslist XML
14843: {
14844:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14845:     if (-e $file) {
14846:         my $parser = HTML::LCParser->new($file);
14847:         while (my $token = $parser->get_token()) {
14848:             if ($token->[0] eq 'S') {
14849:                 my $item = $token->[1];
14850:                 my $name = $token->[2]{'name'};
14851:                 my $value = $token->[2]{'value'};
14852:                 my $valuematch = $token->[2]{'valuematch'};
14853:                 my $namematch = $token->[2]{'namematch'};
14854:                 if ($item eq 'parameter') {
14855:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14856:                         my $release = $parser->get_text();
14857:                         $release =~ s/(^\s*|\s*$ )//gx;
14858:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14859:                     }
14860:                 } elsif ($item ne '' && $name ne '') {
14861:                     my $release = $parser->get_text();
14862:                     $release =~ s/(^\s*|\s*$ )//gx;
14863:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14864:                 }
14865:             }
14866:         }
14867:     }
14868: }
14869: 
14870: # ---------------------------------------------------------- Read managers table
14871: {
14872:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14873:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14874:             while (my $configline=<$config>) {
14875:                 chomp($configline);
14876:                 next if ($configline =~ /^\#/);
14877:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14878:                     $managerstab{$configline} = 1;
14879:                 }
14880:             }
14881:             close($config);
14882:         }
14883:     }
14884: }
14885: 
14886: # ------------- set up temporary directory
14887: {
14888:     $tmpdir = LONCAPA::tempdir();
14889: 
14890: }
14891: 
14892: # ------------- set default texengine (domain default overrides this)
14893: {
14894:     $deftex = LONCAPA::texengine();
14895: }
14896: 
14897: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14898: 				'compress_threshold'=> 20_000,
14899:  			        });
14900: 
14901: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14902: $dumpcount=0;
14903: $locknum=0;
14904: 
14905: &logtouch();
14906: &logthis('<font color="yellow">INFO: Read configuration</font>');
14907: $readit=1;
14908:     {
14909: 	use integer;
14910: 	my $test=(2**32)+1;
14911: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14912: 	&logthis(" Detected 64bit platform ($_64bit)");
14913:     }
14914: }
14915: }
14916: 
14917: 1;
14918: __END__
14919: 
14920: =pod
14921: 
14922: =head1 NAME
14923: 
14924: Apache::lonnet - Subroutines to ask questions about things in the network.
14925: 
14926: =head1 SYNOPSIS
14927: 
14928: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14929: 
14930:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14931: 
14932: Common parameters:
14933: 
14934: =over 4
14935: 
14936: =item *
14937: 
14938: $uname : an internal username (if $cname expecting a course Id specifically)
14939: 
14940: =item *
14941: 
14942: $udom : a domain (if $cdom expecting a course's domain specifically)
14943: 
14944: =item *
14945: 
14946: $symb : a resource instance identifier
14947: 
14948: =item *
14949: 
14950: $namespace : the name of a .db file that contains the data needed or
14951: being set.
14952: 
14953: =back
14954: 
14955: =head1 OVERVIEW
14956: 
14957: lonnet provides subroutines which interact with the
14958: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14959: about classes, users, and resources.
14960: 
14961: For many of these objects you can also use this to store data about
14962: them or modify them in various ways.
14963: 
14964: =head2 Symbs
14965: 
14966: To identify a specific instance of a resource, LON-CAPA uses symbols
14967: or "symbs"X<symb>. These identifiers are built from the URL of the
14968: map, the resource number of the resource in the map, and the URL of
14969: the resource itself. The latter is somewhat redundant, but might help
14970: if maps change.
14971: 
14972: An example is
14973: 
14974:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14975: 
14976: The respective map entry is
14977: 
14978:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14979:   title="Problem 2">
14980:  </resource>
14981: 
14982: Symbs are used by the random number generator, as well as to store and
14983: restore data specific to a certain instance of for example a problem.
14984: 
14985: =head2 Storing And Retrieving Data
14986: 
14987: X<store()>X<cstore()>X<restore()>Three of the most important functions
14988: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14989: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14990: is is the non-critical message twin of cstore. These functions are for
14991: handlers to store a perl hash to a user's permanent data space in an
14992: easy manner, and to retrieve it again on another call. It is expected
14993: that a handler would use this once at the beginning to retrieve data,
14994: and then again once at the end to send only the new data back.
14995: 
14996: The data is stored in the user's data directory on the user's
14997: homeserver under the ID of the course.
14998: 
14999: The hash that is returned by restore will have all of the previous
15000: value for all of the elements of the hash.
15001: 
15002: Example:
15003: 
15004:  #creating a hash
15005:  my %hash;
15006:  $hash{'foo'}='bar';
15007: 
15008:  #storing it
15009:  &Apache::lonnet::cstore(\%hash);
15010: 
15011:  #changing a value
15012:  $hash{'foo'}='notbar';
15013: 
15014:  #adding a new value
15015:  $hash{'bar'}='foo';
15016:  &Apache::lonnet::cstore(\%hash);
15017: 
15018:  #retrieving the hash
15019:  my %history=&Apache::lonnet::restore();
15020: 
15021:  #print the hash
15022:  foreach my $key (sort(keys(%history))) {
15023:    print("\%history{$key} = $history{$key}");
15024:  }
15025: 
15026: Will print out:
15027: 
15028:  %history{1:foo} = bar
15029:  %history{1:keys} = foo:timestamp
15030:  %history{1:timestamp} = 990455579
15031:  %history{2:bar} = foo
15032:  %history{2:foo} = notbar
15033:  %history{2:keys} = foo:bar:timestamp
15034:  %history{2:timestamp} = 990455580
15035:  %history{bar} = foo
15036:  %history{foo} = notbar
15037:  %history{timestamp} = 990455580
15038:  %history{version} = 2
15039: 
15040: Note that the special hash entries C<keys>, C<version> and
15041: C<timestamp> were added to the hash. C<version> will be equal to the
15042: total number of versions of the data that have been stored. The
15043: C<timestamp> attribute will be the UNIX time the hash was
15044: stored. C<keys> is available in every historical section to list which
15045: keys were added or changed at a specific historical revision of a
15046: hash.
15047: 
15048: B<Warning>: do not store the hash that restore returns directly. This
15049: will cause a mess since it will restore the historical keys as if the
15050: were new keys. I.E. 1:foo will become 1:1:foo etc.
15051: 
15052: Calling convention:
15053: 
15054:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15055:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15056: 
15057: For more detailed information, see lonnet specific documentation.
15058: 
15059: =head1 RETURN MESSAGES
15060: 
15061: =over 4
15062: 
15063: =item * B<con_lost>: unable to contact remote host
15064: 
15065: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15066: when the connection is brought back up
15067: 
15068: =item * B<con_failed>: unable to contact remote host and unable to save message
15069: for later delivery
15070: 
15071: =item * B<error:>: an error a occurred, a description of the error follows the :
15072: 
15073: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15074: that was requested
15075: 
15076: =back
15077: 
15078: =head1 PUBLIC SUBROUTINES
15079: 
15080: =head2 Session Environment Functions
15081: 
15082: =over 4
15083: 
15084: =item * 
15085: X<appenv()>
15086: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15087: the user envirnoment file, and will be restored for each access this
15088: user makes during this session, also modifies the %env for the current
15089: process. Optional rolesarrayref - if defined contains a reference to an array
15090: of roles which are exempt from the restriction on modifying user.role entries 
15091: in the user's environment.db and in %env.    
15092: 
15093: =item *
15094: X<delenv()>
15095: B<delenv($delthis,$regexp)>: removes all items from the session
15096: environment file that begin with $delthis. If the 
15097: optional second arg - $regexp - is true, $delthis is treated as a 
15098: regular expression, otherwise \Q$delthis\E is used. 
15099: The values are also deleted from the current processes %env.
15100: 
15101: =item * get_env_multiple($name) 
15102: 
15103: gets $name from the %env hash, it seemlessly handles the cases where multiple
15104: values may be defined and end up as an array ref.
15105: 
15106: returns an array of values
15107: 
15108: =back
15109: 
15110: =head2 User Information
15111: 
15112: =over 4
15113: 
15114: =item *
15115: X<queryauthenticate()>
15116: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15117: authentication scheme
15118: 
15119: =item *
15120: X<authenticate()>
15121: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15122: authenticate user from domain's lib servers (first use the current
15123: one). C<$upass> should be the users password.
15124: $checkdefauth is optional (value is 1 if a check should be made to
15125:    authenticate user using default authentication method, and allow
15126:    account creation if username does not have account in the domain).
15127: $clientcancheckhost is optional (value is 1 if checking whether the
15128:    server can host will occur on the client side in lonauth.pm).   
15129: 
15130: =item *
15131: X<homeserver()>
15132: B<homeserver($uname,$udom)>: find the server which has
15133: the user's directory and files (there must be only one), this caches
15134: the answer, and also caches if there is a borken connection.
15135: 
15136: =item *
15137: X<idget()>
15138: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15139: a list of student/employee IDs or clicker IDs
15140: (student/employee IDs are a unique resource in a domain, there must be 
15141: only 1 ID per username, and only 1 username per ID in a specific domain).
15142: clickerIDs are not necessarily unique, as students might share clickers.
15143: (returns hash: id=>name,id=>name)
15144: 
15145: =item *
15146: X<idrget()>
15147: B<idrget($udom,@unames)>: find the IDs behind a list of
15148: usernames (returns hash: name=>id,name=>id)
15149: 
15150: =item *
15151: X<idput()>
15152: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15153: names and associated student/employee IDs or clicker IDs.
15154: 
15155: =item *
15156: X<iddel()>
15157: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15158: student/employee ID or clicker ID username look-ups from domain.
15159: The homeserver ($uhome) and namespace ($namespace) are optional.
15160: If no $uhome is provided, it will be determined usig &homeserver()
15161: for each user.  If no $namespace is provided, the default is ids.
15162: 
15163: =item *
15164: X<updateclickers()>
15165: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15166: clicker ID-to-username look-ups in clickers.db on library server.
15167: Permitted actions are add or del (i.e., add or delete). The 
15168: clickers.db contains clickerID as keys (escaped), and each corresponding
15169: value is an escaped comma-separated list of usernames (for whom the
15170: library server is the homeserver), who registered that particular ID.
15171: If $critical is true, the update will be sent via &critical, otherwise
15172: &reply() will be used.
15173: 
15174: =item *
15175: X<rolesinit()>
15176: B<rolesinit($udom,$username)>: get user privileges.
15177: returns user role, first access and timer interval hashes
15178: 
15179: =item *
15180: X<privileged()>
15181: B<privileged($username,$domain)>: returns a true if user has a
15182: privileged and active role (i.e. su or dc), false otherwise.
15183: 
15184: =item *
15185: X<getsection()>
15186: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15187: course $cname, return section name/number or '' for "not in course"
15188: and '-1' for "no section"
15189: 
15190: =item *
15191: X<userenvironment()>
15192: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15193: passed in @what from the requested user's environment, returns a hash
15194: 
15195: =item * 
15196: X<userlog_query()>
15197: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15198: activity.log file. %filters defines filters applied when parsing the
15199: log file. These can be start or end timestamps, or the type of action
15200: - log to look for Login or Logout events, check for Checkin or
15201: Checkout, role for role selection. The response is in the form
15202: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15203: escaped strings of the action recorded in the activity.log file.
15204: 
15205: =back
15206: 
15207: =head2 User Roles
15208: 
15209: =over 4
15210: 
15211: =item *
15212: 
15213: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15214: returns codes for allowed actions.
15215: 
15216: The first argument is required, all others are optional.
15217: 
15218: $priv is the privilege being checked.
15219: $uri contains additional information about what is being checked for access (e.g.,
15220: URL, course ID etc.). 
15221: $symb is the unique resource instance identifier in a course; if needed,
15222: but not provided, it will be retrieved via a call to &symbread(). 
15223: $role is the role for which a priv is being checked (only used if priv is evb). 
15224: $clientip is the user's IP address (only used when checking for access to portfolio 
15225: files).
15226: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15227: prevents recursive calls to &allowed.
15228: 
15229:  F: full access
15230:  U,I,K: authentication modes (cxx only)
15231:  '': forbidden
15232:  1: user needs to choose course
15233:  2: browse allowed
15234:  A: passphrase authentication needed
15235:  B: access temporarily blocked because of a blocking event in a course.
15236:  D: access blocked because access is required via session initiated via deep-link 
15237: 
15238: =item *
15239: 
15240: constructaccess($url,$setpriv) : check for access to construction space URL
15241: 
15242: See if the owner domain and name in the URL match those in the
15243: expected environment.  If so, return three element list
15244: ($ownername,$ownerdomain,$ownerhome).
15245: 
15246: Otherwise return the null string.
15247: 
15248: If second argument 'setpriv' is true, it assigns the privileges,
15249: and returns the same three element list, unless the owner has
15250: blocked "ad hoc" Domain Coordinator access to the Author Space,
15251: in which case the null string is returned.
15252: 
15253: =item *
15254: 
15255: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15256: define a custom role rolename set privileges in format of lonTabs/roles.tab
15257: for system, domain, and course level. $uname and $udom are optional (current
15258: user's username and domain will be used when either of $uname or $udom are absent.
15259: 
15260: =item *
15261: 
15262: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15263: (rolesplain.tab); plain text explanation of a user role term.
15264: $type is Course (default) or Community.
15265: If $forcedefault evaluates to true, text returned will be default 
15266: text for $type. Otherwise, if this is a course, the text returned 
15267: will be a custom name for the role (if defined in the course's 
15268: environment).  If no custom name is defined the default is returned.
15269:    
15270: =item *
15271: 
15272: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15273: All arguments are optional. Returns a hash of a roles, either for
15274: co-author/assistant author roles for a user's Construction Space
15275: (default), or if $context is 'userroles', roles for the user himself,
15276: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15277: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15278: For each key, value is set to colon-separated start and end times for
15279: the role.  If no username and domain are specified, will default to
15280: current user/domain. Types, roles, and roledoms are references to arrays
15281: of role statuses (active, future or previous), roles 
15282: (e.g., cc,in, st etc.) and domains of the roles which can be used
15283: to restrict the list of roles reported. If no array ref is 
15284: provided for types, will default to return only active roles.
15285: 
15286: =item *
15287: 
15288: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15289: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15290: 
15291: Additional optional arguments are: $type (if role checking is to be restricted 
15292: to certain user status types -- previous (expired roles), active (currently
15293: available roles) or future (roles available in the future), and
15294: $hideprivileged -- if true will not report course roles for users who
15295: have active Domain Coordinator role in course's domain or in additional
15296: domains (specified in 'Domains to check for privileged users' in course
15297: environment -- set via:  Course Settings -> Classlists and staff listing).
15298: 
15299: =item *
15300: 
15301: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15302: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15303: $possdomains and $possroles are optional array refs -- to domains to check and
15304: roles to check.  If $possdomains is not specified, a dump will be done of the
15305: users' roles.db to check for a dc or su role in any domain. This can be
15306: time consuming if &privileged is called repeatedly (e.g., when displaying a
15307: classlist), so in such cases, supplying a $possdomains array is preferred, as
15308: this then allows &privileged_by_domain() to be used, which caches the identity
15309: of privileged users, eliminating the need for repeated calls to &dump().
15310: 
15311: =item *
15312: 
15313: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15314: where the outer hash keys are domains specified in the $possdomains array ref,
15315: next inner hash keys are privileged roles specified in the $roles array ref,
15316: and the innermost hash contains key = value pairs for username:domain = end:start
15317: for active or future "privileged" users with that role in that domain. To avoid
15318: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15319: innerhash are cached using priv_$role and $dom as the identifiers.
15320: 
15321: =back
15322: 
15323: =head2 User Modification
15324: 
15325: =over 4
15326: 
15327: =item *
15328: 
15329: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15330: user for the level given by URL.  Optional start and end dates (leave empty
15331: string or zero for "no date")
15332: 
15333: =item *
15334: 
15335: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15336: change a users, password, possible return values are: ok,
15337: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15338: refused
15339: 
15340: =item *
15341: 
15342: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15343: 
15344: =item *
15345: 
15346: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15347:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15348: 
15349: will update user information (firstname,middlename,lastname,generation,
15350: permanentemail), and if forceid is true, student/employee ID also.
15351: A user's institutional affiliation(s) can also be updated.
15352: User information fields will not be overwritten with empty entries 
15353: unless the field is included in the $candelete array reference.
15354: This array is included when a single user is modified via "Manage Users",
15355: or when Autoupdate.pl is run by cron in a domain.
15356: 
15357: =item *
15358: 
15359: modifystudent
15360: 
15361: modify a student's enrollment and identification information.
15362: The course id is resolved based on the current user's environment.  
15363: This means the invoking user must be a course coordinator or otherwise
15364: associated with a course.
15365: 
15366: This call is essentially a wrapper for lonnet::modifyuser and
15367: lonnet::modify_student_enrollment
15368: 
15369: Inputs: 
15370: 
15371: =over 4
15372: 
15373: =item B<$udom> Student's loncapa domain
15374: 
15375: =item B<$uname> Student's loncapa login name
15376: 
15377: =item B<$uid> Student/Employee ID
15378: 
15379: =item B<$umode> Student's authentication mode
15380: 
15381: =item B<$upass> Student's password
15382: 
15383: =item B<$first> Student's first name
15384: 
15385: =item B<$middle> Student's middle name
15386: 
15387: =item B<$last> Student's last name
15388: 
15389: =item B<$gene> Student's generation
15390: 
15391: =item B<$usec> Student's section in course
15392: 
15393: =item B<$end> Unix time of the roles expiration
15394: 
15395: =item B<$start> Unix time of the roles start date
15396: 
15397: =item B<$forceid> If defined, allow $uid to be changed
15398: 
15399: =item B<$desiredhome> server to use as home server for student
15400: 
15401: =item B<$email> Student's permanent e-mail address
15402: 
15403: =item B<$type> Type of enrollment (auto or manual)
15404: 
15405: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15406: 
15407: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15408: 
15409: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15410: 
15411: =item B<$context> role change context (shown in User Management Logs display in a course)
15412: 
15413: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15414: 
15415: =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.
15416: 
15417: =back
15418: 
15419: =item *
15420: 
15421: modify_student_enrollment
15422: 
15423: Change a student's enrollment status in a class.  The environment variable
15424: 'role.request.course' must be defined for this function to proceed.
15425: 
15426: Inputs:
15427: 
15428: =over 4
15429: 
15430: =item $udom, student's domain
15431: 
15432: =item $uname, student's name
15433: 
15434: =item $uid, student's user id
15435: 
15436: =item $first, student's first name
15437: 
15438: =item $middle
15439: 
15440: =item $last
15441: 
15442: =item $gene
15443: 
15444: =item $usec
15445: 
15446: =item $end
15447: 
15448: =item $start
15449: 
15450: =item $type
15451: 
15452: =item $locktype
15453: 
15454: =item $cid
15455: 
15456: =item $selfenroll
15457: 
15458: =item $context
15459: 
15460: =item $credits, number of credits student will earn from this class
15461: 
15462: =item $instsec, institutional course section code for student
15463: 
15464: =back
15465: 
15466: 
15467: =item *
15468: 
15469: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15470: custom role; give a custom role to a user for the level given by URL.  Specify
15471: name and domain of role author, and role name
15472: 
15473: =item *
15474: 
15475: revokerole($udom,$uname,$url,$role) : revoke a role for url
15476: 
15477: =item *
15478: 
15479: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15480: 
15481: =back
15482: 
15483: =head2 Course Infomation
15484: 
15485: =over 4
15486: 
15487: =item *
15488: 
15489: coursedescription($courseid,$options) : returns a hash of information about the
15490: specified course id, including all environment settings for the
15491: course, the description of the course will be in the hash under the
15492: key 'description'
15493: 
15494: $options is an optional parameter that if supplied is a hash reference that controls
15495: what how this function works.  It has the following key/values:
15496: 
15497: =over 4
15498: 
15499: =item freshen_cache
15500: 
15501: If defined, and the environment cache for the course is valid, it is 
15502: returned in the returned hash.
15503: 
15504: =item one_time
15505: 
15506: If defined, the last cache time is set to _now_
15507: 
15508: =item user
15509: 
15510: If defined, the supplied username is used instead of the current user.
15511: 
15512: 
15513: =back
15514: 
15515: =item *
15516: 
15517: resdata($name,$domain,$type,@which) : request for current parameter
15518: setting for a specific $type, where $type is either 'course' or 'user',
15519: @what should be a list of parameters to ask about. This routine caches
15520: answers for 10 minutes.
15521: 
15522: =item *
15523: 
15524: get_courseresdata($courseid, $domain) : dump the entire course resource
15525: data base, returning a hash that is keyed by the resource name and has
15526: values that are the resource value.  I believe that the timestamps and
15527: versions are also returned.
15528: 
15529: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15530: supplemental content area. This routine caches the number of files for 
15531: 10 minutes.
15532: 
15533: =back
15534: 
15535: =head2 Course Modification
15536: 
15537: =over 4
15538: 
15539: =item *
15540: 
15541: writecoursepref($courseid,%prefs) : write preferences (environment
15542: database) for a course
15543: 
15544: =item *
15545: 
15546: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15547: 
15548: =item *
15549: 
15550: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15551: 
15552: =item *
15553: 
15554: is_course($courseid), is_course($cdom, $cnum)
15555: 
15556: Accepts either a combined $courseid (in the form of domain_courseid) or the
15557: two component version $cdom, $cnum. It checks if the specified course exists.
15558: 
15559: Returns:
15560:     undef if the course doesn't exist, otherwise
15561:     in scalar context the combined courseid.
15562:     in list context the two components of the course identifier, domain and 
15563:     courseid.    
15564: 
15565: =back
15566: 
15567: =head2 Bubblesheet Configuration
15568: 
15569: =over 4
15570: 
15571: =item *
15572: 
15573: get_scantron_config($which)
15574: 
15575: $which - the name of the configuration to parse from the file.
15576: 
15577: Parses and returns the bubblesheet configuration line selected as a
15578: hash of configuration file fields.
15579: 
15580: 
15581: Returns:
15582:     If the named configuration is not in the file, an empty
15583:     hash is returned.
15584: 
15585:     a hash with the fields
15586:       name         - internal name for the this configuration setup
15587:       description  - text to display to operator that describes this config
15588:       CODElocation - if 0 or the string 'none'
15589:                           - no CODE exists for this config
15590:                      if -1 || the string 'letter'
15591:                           - a CODE exists for this config and is
15592:                             a string of letters
15593:                      Unsupported value (but planned for future support)
15594:                           if a positive integer
15595:                                - The CODE exists as the first n items from
15596:                                  the question section of the form
15597:                           if the string 'number'
15598:                                - The CODE exists for this config and is
15599:                                  a string of numbers
15600:       CODEstart   - (only matter if a CODE exists) column in the line where
15601:                      the CODE starts
15602:       CODElength  - length of the CODE
15603:       IDstart     - column where the student/employee ID starts
15604:       IDlength    - length of the student/employee ID info
15605:       Qstart      - column where the information from the bubbled
15606:                     'questions' start
15607:       Qlength     - number of columns comprising a single bubble line from
15608:                     the sheet. (usually either 1 or 10)
15609:       Qon         - either a single character representing the character used
15610:                     to signal a bubble was chosen in the positional setup, or
15611:                     the string 'letter' if the letter of the chosen bubble is
15612:                     in the final, or 'number' if a number representing the
15613:                     chosen bubble is in the file (1->A 0->J)
15614:       Qoff        - the character used to represent that a bubble was
15615:                     left blank
15616:       PaperID     - if the scanning process generates a unique number for each
15617:                     sheet scanned the column that this ID number starts in
15618:       PaperIDlength - number of columns that comprise the unique ID number
15619:                       for the sheet of paper
15620:       FirstName   - column that the first name starts in
15621:       FirstNameLength - number of columns that the first name spans
15622:       LastName    - column that the last name starts in
15623:       LastNameLength - number of columns that the last name spans
15624:       BubblesPerRow - number of bubbles available in each row used to
15625:                       bubble an answer. (If not specified, 10 assumed).
15626: 
15627: 
15628: =item *
15629: 
15630: get_scantronformat_file($cdom)
15631: 
15632: $cdom - the course's domain (optional); if not supplied, uses
15633: domain for current $env{'request.course.id'}.
15634: 
15635: Returns an array containing lines from the scantron format file for
15636: the domain of the course.
15637: 
15638: If a url for a custom.tab file is listed in domain's configuration.db,
15639: lines are from this file.
15640: 
15641: Otherwise, if a default.tab has been published in RES space by the
15642: domainconfig user, lines are from this file.
15643: 
15644: Otherwise, fall back to getting lines from the legacy file on the
15645: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15646: 
15647: =back
15648: 
15649: =head2 Resource Subroutines
15650: 
15651: =over 4
15652: 
15653: =item *
15654: 
15655: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15656: 
15657: =item *
15658: 
15659: repcopy($filename) : subscribes to the requested file, and attempts to
15660: replicate from the owning library server, Might return
15661: 'unavailable', 'not_found', 'forbidden', 'ok', or
15662: 'bad_request', also attempts to grab the metadata for the
15663: resource. Expects the local filesystem pathname
15664: (/home/httpd/html/res/....)
15665: 
15666: =back
15667: 
15668: =head2 Resource Information
15669: 
15670: =over 4
15671: 
15672: =item *
15673: 
15674: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15675: and returns the value of a variety of different possible values,
15676: $varname should be a request string, and the other parameters can be
15677: used to specify who and what one is asking about. Ordinarily, $cid 
15678: does not need to be specified, as it is retrived from 
15679: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15680: within lonuserstate::loadmap() when initializing a course, before
15681: $env{'request.course.id'} has been set, so it needs to be provided
15682: in that one case.
15683: 
15684: Possible values for $varname are environment.lastname (or other item
15685: from the envirnment hash), user.name (or someother aspect about the
15686: user), resource.0.maxtries (or some other part and parameter of a
15687: resource)
15688: 
15689: =item *
15690: 
15691: directcondval($number) : get current value of a condition; reads from a state
15692: string
15693: 
15694: =item *
15695: 
15696: condval($condidx) : value of condition index based on state
15697: 
15698: =item *
15699: 
15700: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15701: resource's metadata, $what should be either a specific key, or either
15702: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15703: packages that this resource currently uses, the last 3 arguments are 
15704: only used internally for recursive metadata.
15705: 
15706: the toolsymb is only used where the uri is for an external tool (for which
15707: the uri as well as the symb are guaranteed to be unique).
15708: 
15709: this function automatically caches all requests except any made recursively
15710: to retrieve a list of metadata keys for an imported library file ($liburi is 
15711: defined).
15712: 
15713: =item *
15714: 
15715: metadata_query($query,$custom,$customshow) : make a metadata query against the
15716: network of library servers; returns file handle of where SQL and regex results
15717: will be stored for query
15718: 
15719: =item *
15720: 
15721: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15722: return symbolic list entry (all arguments optional). 
15723: 
15724: Args: filename is the filename (including path) for the file for which a symb 
15725: is required; donotrecurse, if true will prevent calls to allowed() being made 
15726: to check access status if more than one resource was found in the bighash 
15727: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15728: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15729: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15730: cause possible symbs to be checked to determine if they are subject to content
15731: blocking, if so they will not be included as possible symbs; possibles is a
15732: ref to a hash, which, as a side effect, will be populated with all possible 
15733: symbs (content blocking not tested).
15734:  
15735: returns the data handle
15736: 
15737: =item *
15738: 
15739: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15740: and is a possible symb for the URL in $thisfn, and if is an encrypted
15741: resource that the user accessed using /enc/ returns a 1 on success, 0
15742: on failure, user must be in a course, as it assumes the existence of
15743: the course initial hash, and uses $env('request.course.id'}.  The third
15744: arg is an optional reference to a scalar.  If this arg is passed in the 
15745: call to symbverify, it will be set to 1 if the symb has been set to be 
15746: encrypted; otherwise it will be null.  
15747: 
15748: =item *
15749: 
15750: symbclean($symb) : removes versions numbers from a symb, returns the
15751: cleaned symb
15752: 
15753: =item *
15754: 
15755: is_on_map($uri) : checks if the $uri is somewhere on the current
15756: course map, user must be in a course for it to work.
15757: 
15758: =item *
15759: 
15760: numval($salt) : return random seed value (addend for rndseed)
15761: 
15762: =item *
15763: 
15764: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15765: a random seed, all arguments are optional, if they aren't sent it uses the
15766: environment to derive them. Note: if symb isn't sent and it can't get one
15767: from &symbread it will use the current time as its return value
15768: 
15769: =item *
15770: 
15771: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15772: unfakeable, receipt
15773: 
15774: =item *
15775: 
15776: receipt() : API to ireceipt working off of env values; given out to users
15777: 
15778: =item *
15779: 
15780: countacc($url) : count the number of accesses to a given URL
15781: 
15782: =item *
15783: 
15784: 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
15785: 
15786: =item *
15787: 
15788: 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)
15789: 
15790: =item *
15791: 
15792: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15793: 
15794: =item *
15795: 
15796: devalidate($symb) : devalidate temporary spreadsheet calculations,
15797: forcing spreadsheet to reevaluate the resource scores next time.
15798: 
15799: =item * 
15800: 
15801: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15802: when viewing in course context.
15803: 
15804:  input: six args -- filename (decluttered), course number, course domain,
15805:                     url, symb (if registered) and group (if this is a 
15806:                     group item -- e.g., bulletin board, group page etc.).
15807: 
15808:  output: array of five scalars --
15809:          $cfile -- url for file editing if editable on current server
15810:          $home -- homeserver of resource (i.e., for author if published,
15811:                                           or course if uploaded.).
15812:          $switchserver --  1 if server switch will be needed.
15813:          $forceedit -- 1 if icon/link should be to go to edit mode 
15814:          $forceview -- 1 if icon/link should be to go to view mode
15815: 
15816: =item *
15817: 
15818: is_course_upload($file,$cnum,$cdom)
15819: 
15820: Used in course context to determine if current file was uploaded to 
15821: the course (i.e., would be found in /userfiles/docs on the course's 
15822: homeserver.
15823: 
15824:   input: 3 args -- filename (decluttered), course number and course domain.
15825:   output: boolean -- 1 if file was uploaded.
15826: 
15827: =back
15828: 
15829: =head2 Storing/Retreiving Data
15830: 
15831: =over 4
15832: 
15833: =item *
15834: 
15835: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15836: permanently for this url; hashref needs to be given and should be a \%hashname;
15837: the remaining args aren't required and if they aren't passed or are '' they will
15838: be derived from the env (with the exception of $laststore, which is an 
15839: optional arg used when a user's submission is stored in grading).
15840: $laststore is $version=$timestamp, where $version is the most recent version
15841: number retrieved for the corresponding $symb in the $namespace db file, and
15842: $timestamp is the timestamp for that transaction (UNIX time).
15843: $laststore is currently only passed when cstore() is called by 
15844: structuretags::finalize_storage().
15845: 
15846: =item *
15847: 
15848: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15849: but uses critical subroutine
15850: 
15851: =item *
15852: 
15853: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15854: all args are optional
15855: 
15856: =item *
15857: 
15858: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15859: dumps the complete (or key matching regexp) namespace into a hash
15860: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15861: normally &store()ed into
15862: 
15863: $range should be either an integer '100' (give me the first 100
15864:                                            matching records)
15865:               or be  two integers sperated by a - with no spaces
15866:                  '30-50' (give me the 30th through the 50th matching
15867:                           records)
15868: 
15869: 
15870: =item *
15871: 
15872: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15873: replaces a &store() version of data with a replacement set of data
15874: for a particular resource in a namespace passed in the $storehash hash 
15875: reference. If $tolog is true, the transaction is logged in the courselog
15876: with an action=PUTSTORE.
15877: 
15878: =item *
15879: 
15880: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15881: works very similar to store/cstore, but all data is stored in a
15882: temporary location and can be reset using tmpreset, $storehash should
15883: be a hash reference, returns nothing on success
15884: 
15885: =item *
15886: 
15887: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15888: similar to restore, but all data is stored in a temporary location and
15889: can be reset using tmpreset. Returns a hash of values on success,
15890: error string otherwise.
15891: 
15892: =item *
15893: 
15894: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15895: deltes all keys for $symb form the temporary storage hash.
15896: 
15897: =item *
15898: 
15899: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15900: reference filled in from namesp ($udom and $uname are optional)
15901: 
15902: =item *
15903: 
15904: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15905: namesp ($udom and $uname are optional)
15906: 
15907: =item *
15908: 
15909: dump($namespace,$udom,$uname,$regexp,$range) : 
15910: dumps the complete (or key matching regexp) namespace into a hash
15911: ($udom, $uname, $regexp, $range are optional)
15912: 
15913: $range should be either an integer '100' (give me the first 100
15914:                                            matching records)
15915:               or be  two integers sperated by a - with no spaces
15916:                  '30-50' (give me the 30th through the 50th matching
15917:                           records)
15918: =item *
15919: 
15920: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15921: $store can be a scalar, an array reference, or if the amount to be 
15922: incremented is > 1, a hash reference.
15923: 
15924: ($udom and $uname are optional)
15925: 
15926: =item *
15927: 
15928: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15929: ($udom and $uname are optional)
15930: 
15931: =item *
15932: 
15933: cput($namespace,$storehash,$udom,$uname) : critical put
15934: ($udom and $uname are optional)
15935: 
15936: =item *
15937: 
15938: newput($namespace,$storehash,$udom,$uname) :
15939: 
15940: Attempts to store the items in the $storehash, but only if they don't
15941: currently exist, if this succeeds you can be certain that you have 
15942: successfully created a new key value pair in the $namespace db.
15943: 
15944: 
15945: Args:
15946:  $namespace: name of database to store values to
15947:  $storehash: hashref to store to the db
15948:  $udom: (optional) domain of user containing the db
15949:  $uname: (optional) name of user caontaining the db
15950: 
15951: Returns:
15952:  'ok' -> succeeded in storing all keys of $storehash
15953:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15954:                         least <key> already existed in the db (other
15955:                         requested keys may also already exist)
15956:  'error: <msg>' -> unable to tie the DB or other error occurred
15957:  'con_lost' -> unable to contact request server
15958:  'refused' -> action was not allowed by remote machine
15959: 
15960: 
15961: =item *
15962: 
15963: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15964: reference filled in from namesp (encrypts the return communication)
15965: ($udom and $uname are optional)
15966: 
15967: =item *
15968: 
15969: log($udom,$name,$home,$message) : write to permanent log for user; use
15970: critical subroutine
15971: 
15972: =item *
15973: 
15974: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15975: array reference filled in from namespace found in domain level on either
15976: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15977: 
15978: =item *
15979: 
15980: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15981: domain level either on specified domain server ($uhome) or primary domain 
15982: server ($udom and $uhome are optional)
15983: 
15984: =item * 
15985: 
15986: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15987: for: authentication, language, quotas, timezone, date locale, and portal URL in
15988: the target domain.
15989: 
15990: May also include additional key => value pairs for the following groups:
15991: 
15992: =over
15993: 
15994: =item
15995: disk quotas (MB allocated by default to portfolios and authoring spaces).
15996: 
15997: =over
15998: 
15999: =item defaultquota, authorquota
16000: 
16001: =back
16002: 
16003: =item
16004: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16005: portfolio for users).
16006: 
16007: =over
16008: 
16009: =item
16010: aboutme, blog, webdav, portfolio
16011: 
16012: =back
16013: 
16014: =item
16015: requestcourses: ability to request courses, and how requests are processed.
16016: 
16017: =over
16018: 
16019: =item
16020: official, unofficial, community, textbook, placement
16021: 
16022: =back
16023: 
16024: =item
16025: inststatus: types of institutional affiliation, and order in which they are displayed.
16026: 
16027: =over
16028: 
16029: =item
16030: inststatustypes, inststatusorder, inststatusguest
16031: 
16032: =back
16033: 
16034: =item
16035: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16036: for course's uploaded content.
16037: 
16038: =over
16039: 
16040: =item
16041: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16042: communityquota, textbookquota, placementquota
16043: 
16044: =back
16045: 
16046: =item
16047: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16048: on your servers.
16049: 
16050: =over
16051: 
16052: =item 
16053: remotesessions, hostedsessions
16054: 
16055: =back
16056: 
16057: =back
16058: 
16059: In cases where a domain coordinator has never used the "Set Domain Configuration"
16060: utility to create a configuration.db file on a domain's primary library server 
16061: only the following domain defaults: auth_def, auth_arg_def, lang_def
16062: -- corresponding values are authentication type (internal, krb4, krb5,
16063: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16064: will be available. Values are retrieved from cache (if current), unless the
16065: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16066: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16067: 
16068: Typical usage:
16069: 
16070: %domdefaults = &get_domain_defaults($target_domain);
16071: 
16072: =back
16073: 
16074: =head2 Network Status Functions
16075: 
16076: =over 4
16077: 
16078: =item *
16079: 
16080: dirlist() : return directory list based on URI (first arg).
16081: 
16082: Inputs: 1 required, 5 optional.
16083: 
16084: =over
16085: 
16086: =item 
16087: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16088: 
16089: =item
16090: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16091: 
16092: =item
16093: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16094: 
16095: =item
16096: $getpropath - boolean: 1 if prepend path using &propath(). 
16097: 
16098: =item
16099: $getuserdir - boolean: 1 if prepend path for "userfiles".
16100: 
16101: =item 
16102: $alternateRoot - path to prepend in place of path from $uri.
16103: 
16104: =back
16105: 
16106: Returns: Array of up to two items.
16107: 
16108: =over
16109: 
16110: a reference to an array of files/subdirectories
16111: 
16112: =over
16113: 
16114: Each element in the array of files/subdirectories is a & separated list of
16115: item name and the result of running stat on the item.  If dirlist was requested
16116: for a file instead of a directory, the item name will be ''. For a directory 
16117: listing, if the item is a metadata file, the element will end &N&M 
16118: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16119: default copyright set (1).  
16120: 
16121: =back
16122: 
16123: a scalar containing error condition (if encountered).
16124: 
16125: =over
16126: 
16127: =item 
16128: no_host (no homeserver identified for $username:$domain).
16129: 
16130: =item 
16131: no_such_host (server contacted for listing not identified as valid host).
16132: 
16133: =item 
16134: con_lost (connection to remote server failed).
16135: 
16136: =item 
16137: refused (invalid $username:$domain received on lond side).
16138: 
16139: =item 
16140: no_such_dir (directory at specified path on lond side does not exist). 
16141: 
16142: =item 
16143: empty (directory at specified path on lond side is empty).
16144: 
16145: =over
16146: 
16147: This is currently not encountered because the &ls3, &ls2, 
16148: &ls (_handler) routines on the lond side do not filter out
16149: . and .. from a directory listing. 
16150: 
16151: =back
16152: 
16153: =back
16154: 
16155: =back
16156: 
16157: =item *
16158: 
16159: spareserver() : find server with least workload from spare.tab
16160: 
16161: 
16162: =item *
16163: 
16164: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16165: if there is no corresponding loncapa host.
16166: 
16167: =back
16168: 
16169: 
16170: =head2 Apache Request
16171: 
16172: =over 4
16173: 
16174: =item *
16175: 
16176: ssi($url,%hash) : server side include, does a complete request cycle on url to
16177: localhost, posts hash
16178: 
16179: =back
16180: 
16181: =head2 Data to String to Data
16182: 
16183: =over 4
16184: 
16185: =item *
16186: 
16187: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16188: and '&' separators, supports elements that are arrayrefs and hashrefs
16189: 
16190: =item *
16191: 
16192: hashref2str($hashref) : convert a hashref into a string complete with
16193: escaping and '=' and '&' separators, supports elements that are
16194: arrayrefs and hashrefs
16195: 
16196: =item *
16197: 
16198: arrayref2str($arrayref) : convert an arrayref into a string complete
16199: with escaping and '&' separators, supports elements that are arrayrefs
16200: and hashrefs
16201: 
16202: =item *
16203: 
16204: str2hash($string) : convert string to hash using unescaping and
16205: splitting on '=' and '&', supports elements that are arrayrefs and
16206: hashrefs
16207: 
16208: =item *
16209: 
16210: str2array($string) : convert string to hash using unescaping and
16211: splitting on '&', supports elements that are arrayrefs and hashrefs
16212: 
16213: =back
16214: 
16215: =head2 Logging Routines
16216: 
16217: 
16218: These routines allow one to make log messages in the lonnet.log and
16219: lonnet.perm logfiles.
16220: 
16221: =over 4
16222: 
16223: =item *
16224: 
16225: logtouch() : make sure the logfile, lonnet.log, exists
16226: 
16227: =item *
16228: 
16229: logthis() : append message to the normal lonnet.log file, it gets
16230: preiodically rolled over and deleted.
16231: 
16232: =item *
16233: 
16234: logperm() : append a permanent message to lonnet.perm.log, this log
16235: file never gets deleted by any automated portion of the system, only
16236: messages of critical importance should go in here.
16237: 
16238: 
16239: =back
16240: 
16241: =head2 General File Helper Routines
16242: 
16243: =over 4
16244: 
16245: =item *
16246: 
16247: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16248: (a) files in /uploaded
16249:   (i) If a local copy of the file exists - 
16250:       compares modification date of local copy with last-modified date for 
16251:       definitive version stored on home server for course. If local copy is 
16252:       stale, requests a new version from the home server and stores it. 
16253:       If the original has been removed from the home server, then local copy 
16254:       is unlinked.
16255:   (ii) If local copy does not exist -
16256:       requests the file from the home server and stores it. 
16257:   
16258:   If $caller is 'uploadrep':  
16259:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16260:     for request for files originally uploaded via DOCS. 
16261:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16262:   
16263:   Otherwise:
16264:      This indicates a call from the content generation phase of the request.
16265:      -  returns the entire contents of the file or -1.
16266:      
16267: (b) files in /res
16268:    - returns the entire contents of a file or -1; 
16269:    it properly subscribes to and replicates the file if neccessary.
16270: 
16271: 
16272: =item *
16273: 
16274: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16275:                   reference
16276: 
16277: returns either a stat() list of data about the file or an empty list
16278: if the file doesn't exist or couldn't find out about it (connection
16279: problems or user unknown)
16280: 
16281: =item *
16282: 
16283: filelocation($dir,$file) : returns file system location of a file
16284: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16285: directory that relative $file lookups are to looked in ($dir of /a/dir
16286: and a file of ../bob will become /a/bob)
16287: 
16288: =item *
16289: 
16290: hreflocation($dir,$file) : returns file system location or a URL; same as
16291: filelocation except for hrefs
16292: 
16293: =item *
16294: 
16295: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16296: also removes beginning /home/httpd/html unless /priv/ follows it.
16297: 
16298: =back
16299: 
16300: =head2 Usererfile file routines (/uploaded*)
16301: 
16302: =over 4
16303: 
16304: =item *
16305: 
16306: userfileupload(): main rotine for putting a file in a user or course's
16307:                   filespace, arguments are,
16308: 
16309:  formname - required - this is the name of the element in $env where the
16310:            filename, and the contents of the file to create/modifed exist
16311:            the filename is in $env{'form.'.$formname.'.filename'} and the
16312:            contents of the file is located in $env{'form.'.$formname}
16313:  context - if coursedoc, store the file in the course of the active role
16314:              of the current user; 
16315:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16316:            if 'canceloverwrite': delete file in tmp/overwrites directory
16317:  subdir - required - subdirectory to put the file in under ../userfiles/
16318:          if undefined, it will be placed in "unknown"
16319: 
16320:  (This routine calls clean_filename() to remove any dangerous
16321:  characters from the filename, and then calls finuserfileupload() to
16322:  complete the transaction)
16323: 
16324:  returns either the url of the uploaded file (/uploaded/....) if successful
16325:  and /adm/notfound.html if unsuccessful
16326: 
16327: =item *
16328: 
16329: clean_filename(): routine for cleaing a filename up for storage in
16330:                  userfile space, argument is:
16331: 
16332:  filename - proposed filename
16333: 
16334: returns: the new clean filename
16335: 
16336: =item *
16337: 
16338: finishuserfileupload(): routine that creates and sends the file to
16339: userspace, probably shouldn't be called directly
16340: 
16341:   docuname: username or courseid of destination for the file
16342:   docudom: domain of user/course of destination for the file
16343:   formname: same as for userfileupload()
16344:   fname: filename (including subdirectories) for the file
16345:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16346:           if hashref, and context is scantron, will convert csv format to standard format
16347:   allfiles: reference to hash used to store objects found by parser
16348:   codebase: reference to hash used for codebases of java objects found by parser
16349:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16350:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16351:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16352:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16353:   context: if 'overwrite', will move the uploaded file from its temporary location to
16354:             userfiles to facilitate overwriting a previously uploaded file with same name.
16355:   mimetype: reference to scalar to accommodate mime type determined
16356:             from File::MMagic if $parser = parse.
16357: 
16358:  returns either the url of the uploaded file (/uploaded/....) if successful
16359:  and /adm/notfound.html if unsuccessful (or an error message if context 
16360:  was 'overwrite').
16361:  
16362: 
16363: =item *
16364: 
16365: renameuserfile(): renames an existing userfile to a new name
16366: 
16367:   Args:
16368:    docuname: username or courseid of destination for the file
16369:    docudom: domain of user/course of destination for the file
16370:    old: current file name (including any subdirs under userfiles)
16371:    new: desired file name (including any subdirs under userfiles)
16372: 
16373: =item *
16374: 
16375: mkdiruserfile(): creates a directory is a userfiles dir
16376: 
16377:   Args:
16378:    docuname: username or courseid of destination for the file
16379:    docudom: domain of user/course of destination for the file
16380:    dir: dir to create (including any subdirs under userfiles)
16381: 
16382: =item *
16383: 
16384: removeuserfile(): removes a file that exists in userfiles
16385: 
16386:   Args:
16387:    docuname: username or courseid of destination for the file
16388:    docudom: domain of user/course of destination for the file
16389:    fname: filname to delete (including any subdirs under userfiles)
16390: 
16391: =item *
16392: 
16393: removeuploadedurl(): convience function for removeuserfile()
16394: 
16395:   Args:
16396:    url:  a full /uploaded/... url to delete
16397: 
16398: =item * 
16399: 
16400: get_portfile_permissions():
16401:   Args:
16402:     domain: domain of user or course contain the portfolio files
16403:     user: name of user or num of course contain the portfolio files
16404:   Returns:
16405:     hashref of a dump of the proper file_permissions.db
16406:    
16407: 
16408: =item * 
16409: 
16410: get_access_controls():
16411: 
16412: Args:
16413:   current_permissions: the hash ref returned from get_portfile_permissions()
16414:   group: (optional) the group you want the files associated with
16415:   file: (optional) the file you want access info on
16416: 
16417: Returns:
16418:     a hash (keys are file names) of hashes containing
16419:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16420:         values are XML containing access control settings (see below) 
16421: 
16422: Internal notes:
16423: 
16424:  access controls are stored in file_permissions.db as key=value pairs.
16425:     key -> path to file/file_name\0uniqueID:scope_end_start
16426:         where scope -> public,guest,course,group,domains or users.
16427:               end -> UNIX time for end of access (0 -> no end date)
16428:               start -> UNIX time for start of access
16429: 
16430:     value -> XML description of access control
16431:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16432:             <start></start>
16433:             <end></end>
16434: 
16435:             <password></password>  for scope type = guest
16436: 
16437:             <domain></domain>     for scope type = course or group
16438:             <number></number>
16439:             <roles id="">
16440:              <role></role>
16441:              <access></access>
16442:              <section></section>
16443:              <group></group>
16444:             </roles>
16445: 
16446:             <dom></dom>         for scope type = domains
16447: 
16448:             <users>             for scope type = users
16449:              <user>
16450:               <uname></uname>
16451:               <udom></udom>
16452:              </user>
16453:             </users>
16454:            </scope> 
16455:               
16456:  Access data is also aggregated for each file in an additional key=value pair:
16457:  key -> path to file/file_name\0accesscontrol 
16458:  value -> reference to hash
16459:           hash contains key = value pairs
16460:           where key = uniqueID:scope_end_start
16461:                 value = UNIX time record was last updated
16462: 
16463:           Used to improve speed of look-ups of access controls for each file.  
16464:  
16465:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16466: 
16467: =item *
16468: 
16469: modify_access_controls():
16470: 
16471: Modifies access controls for a portfolio file
16472: Args
16473: 1. file name
16474: 2. reference to hash of required changes,
16475: 3. domain
16476: 4. username
16477:   where domain,username are the domain of the portfolio owner 
16478:   (either a user or a course) 
16479: 
16480: Returns:
16481: 1. result of additions or updates ('ok' or 'error', with error message). 
16482: 2. result of deletions ('ok' or 'error', with error message).
16483: 3. reference to hash of any new or updated access controls.
16484: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16485:    key = integer (inbound ID)
16486:    value = uniqueID
16487: 
16488: =item *
16489: 
16490: get_timebased_id():
16491: 
16492: Attempts to get a unique timestamp-based suffix for use with items added to a 
16493: course via the Course Editor (e.g., folders, composite pages, 
16494: group bulletin boards).
16495: 
16496: Args: (first three required; six others optional)
16497: 
16498: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16499:    docssequence, or name of group
16500: 
16501: 2. keyid (alphanumeric): name of temporary locking key in hash,
16502:    e.g., num, boardids
16503: 
16504: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16505:    file will be named nohist_namespace.db
16506: 
16507: 4. cdom: domain of course; default is current course domain from %env
16508: 
16509: 5. cnum: course number; default is current course number from %env
16510: 
16511: 6. idtype: set to concat if an additional digit is to be appended to the 
16512:    unix timestamp to form the suffix, if the plain timestamp is already
16513:    in use.  Default is to not do this, but simply increment the unix 
16514:    timestamp by 1 until a unique key is obtained.
16515: 
16516: 7. who: holder of locking key; defaults to user:domain for user.
16517: 
16518: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16519:    retrying); default is 3.
16520: 
16521: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16522: 
16523: Returns:
16524: 
16525: 1. suffix obtained (numeric)
16526: 
16527: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16528: 
16529: 3. error: contains (localized) error message if an error occurred.
16530: 
16531: 
16532: =back
16533: 
16534: =head2 HTTP Helper Routines
16535: 
16536: =over 4
16537: 
16538: =item *
16539: 
16540: escape() : unpack non-word characters into CGI-compatible hex codes
16541: 
16542: =item *
16543: 
16544: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16545: 
16546: =back
16547: 
16548: =head1 PRIVATE SUBROUTINES
16549: 
16550: =head2 Underlying communication routines (Shouldn't call)
16551: 
16552: =over 4
16553: 
16554: =item *
16555: 
16556: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16557: 
16558: =item *
16559: 
16560: reply() : uses subreply to send a message to remote machine, logs all failures
16561: 
16562: =item *
16563: 
16564: critical() : passes a critical message to another server; if cannot
16565: get through then place message in connection buffer directory and
16566: returns con_delayed, if incapable of saving message, returns
16567: con_failed
16568: 
16569: =item *
16570: 
16571: reconlonc() : tries to reconnect lonc client processes.
16572: 
16573: =back
16574: 
16575: =head2 Resource Access Logging
16576: 
16577: =over 4
16578: 
16579: =item *
16580: 
16581: flushcourselogs() : flush (save) buffer logs and access logs
16582: 
16583: =item *
16584: 
16585: courselog($what) : save message for course in hash
16586: 
16587: =item *
16588: 
16589: courseacclog($what) : save message for course using &courselog().  Perform
16590: special processing for specific resource types (problems, exams, quizzes, etc).
16591: 
16592: =item *
16593: 
16594: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16595: as a PerlChildExitHandler
16596: 
16597: =back
16598: 
16599: =head2 Other
16600: 
16601: =over 4
16602: 
16603: =item *
16604: 
16605: symblist($mapname,%newhash) : update symbolic storage links
16606: 
16607: =back
16608: 
16609: =cut
16610: 

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