File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1412: download - view: text, annotated - select for diffs
Tue Jul 23 01:30:44 2019 UTC (4 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Course categories defined in a domain are cached for 1 hour.
- Devalidate cats cache for domain if categories changed by DC.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1412 2019/07/23 01:30:44 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: sub delusersession {
 1086:     my ($lonid,$udom,$uname) = @_;
 1087:     my $uprimary_id = &domain($udom,'primary');
 1088:     my $uintdom = &internet_dom($uprimary_id);
 1089:     my $intdom = &internet_dom($lonid);
 1090:     my $serverhomedom = &host_domain($lonid);
 1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1092:         return &reply(join(':','delusersession',
 1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1094:     }
 1095:     return;
 1096: }
 1097: 
 1098: # check if user's browser sent load balancer cookie and server still has session
 1099: # and is not overloaded.
 1100: sub check_for_balancer_cookie {
 1101:     my ($r,$update_mtime) = @_;
 1102:     my ($otherserver,$cookie);
 1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1104:     if (exists($cookies{'balanceID'})) {
 1105:         my $balid = $cookies{'balanceID'};
 1106:         $cookie=&LONCAPA::clean_handle($balid->value);
 1107:         my $balancedir=$r->dir_config('lonBalanceDir');
 1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1110:                 my ($possudom,$possuname) = ($1,$2);
 1111:                 my $has_session = 0;
 1112:                 if ((&domain($possudom) ne '') &&
 1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1114:                     my $try_server;
 1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1116:                     if ($opened) {
 1117:                         flock($idf,LOCK_SH);
 1118:                         while (my $line = <$idf>) {
 1119:                             chomp($line);
 1120:                             if (&hostname($line) ne '') {
 1121:                                 $try_server = $line;
 1122:                                 last;
 1123:                             }
 1124:                         }
 1125:                         close($idf);
 1126:                         if (($try_server) &&
 1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1128:                             my $lowest_load = 30000;
 1129:                             ($otherserver,$lowest_load) =
 1130:                                 &compare_server_load($try_server,undef,$lowest_load);
 1131:                             if ($otherserver ne '' && $lowest_load < 100) {
 1132:                                 $has_session = 1;
 1133:                             } else {
 1134:                                 undef($otherserver);
 1135:                             }
 1136:                         }
 1137:                     }
 1138:                 }
 1139:                 if ($has_session) {
 1140:                     if ($update_mtime) {
 1141:                         my $atime = my $mtime = time;
 1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1143:                     }
 1144:                 } else {
 1145:                     unlink("$balancedir/$cookie.id");
 1146:                 }
 1147:             }
 1148:         }
 1149:     }
 1150:     return ($otherserver,$cookie);
 1151: }
 1152: 
 1153: sub delbalcookie {
 1154:     my ($cookie,$balancer) =@_;
 1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1156:         my ($udom,$uname) = ($1,$2);
 1157:         my $uprimary_id = &domain($udom,'primary');
 1158:         my $uintdom = &internet_dom($uprimary_id);
 1159:         my $intdom = &internet_dom($balancer);
 1160:         my $serverhomedom = &host_domain($balancer);
 1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1162:             return &reply("delbalcookie:$cookie",$balancer);
 1163:         }
 1164:     }
 1165: }
 1166: 
 1167: # -------------------------------- ask if server already has a session for user
 1168: sub has_user_session {
 1169:     my ($lonid,$udom,$uname) = @_;
 1170:     my $result = &reply(join(':','userhassession',
 1171: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1172:     return 1 if ($result eq 'ok');
 1173: 
 1174:     return 0;
 1175: }
 1176: 
 1177: # --------- determine least loaded server in a user's domain which allows login
 1178: 
 1179: sub choose_server {
 1180:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1181:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1182:     my %servers = &get_servers($udom);
 1183:     my $lowest_load = 30000;
 1184:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1185:     if ($skiploadbal) {
 1186:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1187:         unless (defined($cached)) {
 1188:             my $cachetime = 60*60*24;
 1189:             my %domconfig =
 1190:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1191:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1192:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1193:                                            $cachetime);
 1194:             }
 1195:         }
 1196:     }
 1197:     foreach my $lonhost (keys(%servers)) {
 1198:         if ($skiploadbal) {
 1199:             if (ref($balancers) eq 'HASH') {
 1200:                 next if (exists($balancers->{$lonhost}));
 1201:             }
 1202:         }
 1203:         my $loginvia;
 1204:         if ($checkloginvia) {
 1205:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1206:             if ($loginvia) {
 1207:                 my ($server,$path) = split(/:/,$loginvia);
 1208:                 ($login_host, $lowest_load) =
 1209:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1210:                 if ($login_host eq $server) {
 1211:                     $portal_path = $path;
 1212:                     $isredirect = 1;
 1213:                 }
 1214:             } else {
 1215:                 ($login_host, $lowest_load) =
 1216:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1217:                 if ($login_host eq $lonhost) {
 1218:                     $portal_path = '';
 1219:                     $isredirect = ''; 
 1220:                 }
 1221:             }
 1222:         } else {
 1223:             ($login_host, $lowest_load) =
 1224:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1225:         }
 1226:     }
 1227:     if ($login_host ne '') {
 1228:         $hostname = &hostname($login_host);
 1229:     }
 1230:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1231: }
 1232: 
 1233: # --------------------------------------------- Try to change a user's password
 1234: 
 1235: sub changepass {
 1236:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1237:     $currentpass = &escape($currentpass);
 1238:     $newpass     = &escape($newpass);
 1239:     my $lonhost = $perlvar{'lonHostID'};
 1240:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1241: 		       $server);
 1242:     if (! $answer) {
 1243: 	&logthis("No reply on password change request to $server ".
 1244: 		 "by $uname in domain $udom.");
 1245:     } elsif ($answer =~ "^ok") {
 1246:         &logthis("$uname in $udom successfully changed their password ".
 1247: 		 "on $server.");
 1248:     } elsif ($answer =~ "^pwchange_failure") {
 1249: 	&logthis("$uname in $udom was unable to change their password ".
 1250: 		 "on $server.  The action was blocked by either lcpasswd ".
 1251: 		 "or pwchange");
 1252:     } elsif ($answer =~ "^non_authorized") {
 1253:         &logthis("$uname in $udom did not get their password correct when ".
 1254: 		 "attempting to change it on $server.");
 1255:     } elsif ($answer =~ "^auth_mode_error") {
 1256:         &logthis("$uname in $udom attempted to change their password despite ".
 1257: 		 "not being locally or internally authenticated on $server.");
 1258:     } elsif ($answer =~ "^unknown_user") {
 1259:         &logthis("$uname in $udom attempted to change their password ".
 1260: 		 "on $server but were unable to because $server is not ".
 1261: 		 "their home server.");
 1262:     } elsif ($answer =~ "^refused") {
 1263: 	&logthis("$server refused to change $uname in $udom password because ".
 1264: 		 "it was sent an unencrypted request to change the password.");
 1265:     } elsif ($answer =~ "invalid_client") {
 1266:         &logthis("$server refused to change $uname in $udom password because ".
 1267:                  "it was a reset by e-mail originating from an invalid server.");
 1268:     } elsif ($answer =~ "^prioruse") {
 1269:        &logthis("$server refused to change $uname in $udom password because ".
 1270:                 "the password had been used before");
 1271:     }
 1272:     return $answer;
 1273: }
 1274: 
 1275: # ----------------------- Try to determine user's current authentication scheme
 1276: 
 1277: sub queryauthenticate {
 1278:     my ($uname,$udom)=@_;
 1279:     my $uhome=&homeserver($uname,$udom);
 1280:     if (!$uhome) {
 1281: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1282: 	return 'no_host';
 1283:     }
 1284:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1285:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1286: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1287:     }
 1288:     return $answer;
 1289: }
 1290: 
 1291: # --------- Try to authenticate user from domain's lib servers (first this one)
 1292: 
 1293: sub authenticate {
 1294:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1295:     $upass=&escape($upass);
 1296:     $uname= &LONCAPA::clean_username($uname);
 1297:     my $uhome=&homeserver($uname,$udom,1);
 1298:     my $newhome;
 1299:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1300: # Maybe the machine was offline and only re-appeared again recently?
 1301:         &reconlonc();
 1302: # One more
 1303: 	$uhome=&homeserver($uname,$udom,1);
 1304:         if (($uhome eq 'no_host') && $checkdefauth) {
 1305:             if (defined(&domain($udom,'primary'))) {
 1306:                 $newhome=&domain($udom,'primary');
 1307:             }
 1308:             if ($newhome ne '') {
 1309:                 $uhome = $newhome;
 1310:             }
 1311:         }
 1312: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1313: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1314: 	    return 'no_host';
 1315:         }
 1316:     }
 1317:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1318:     if ($answer eq 'authorized') {
 1319:         if ($newhome) {
 1320:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1321:             return 'no_account_on_host'; 
 1322:         } else {
 1323:             &logthis("User $uname at $udom authorized by $uhome");
 1324:             return $uhome;
 1325:         }
 1326:     }
 1327:     if ($answer eq 'non_authorized') {
 1328: 	&logthis("User $uname at $udom rejected by $uhome");
 1329: 	return 'no_host'; 
 1330:     }
 1331:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1332:     return 'no_host';
 1333: }
 1334: 
 1335: sub can_host_session {
 1336:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1337:     my $canhost = 1;
 1338:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1339:     if (ref($remotesessions) eq 'HASH') {
 1340:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1341:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1342:                 $canhost = 0;
 1343:             } else {
 1344:                 $canhost = 1;
 1345:             }
 1346:         }
 1347:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1348:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1349:                 $canhost = 1;
 1350:             } else {
 1351:                 $canhost = 0;
 1352:             }
 1353:         }
 1354:         if ($canhost) {
 1355:             if ($remotesessions->{'version'} ne '') {
 1356:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1357:                 if ($reqmajor ne '' && $reqminor ne '') {
 1358:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1359:                         my $major = $1;
 1360:                         my $minor = $2;
 1361:                         if (($major < $reqmajor ) ||
 1362:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1363:                             $canhost = 0;
 1364:                         }
 1365:                     } else {
 1366:                         $canhost = 0;
 1367:                     }
 1368:                 }
 1369:             }
 1370:         }
 1371:     }
 1372:     if ($canhost) {
 1373:         if (ref($hostedsessions) eq 'HASH') {
 1374:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1375:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1376:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1377:                 if (($uint_dom ne '') && 
 1378:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1379:                     $canhost = 0;
 1380:                 } else {
 1381:                     $canhost = 1;
 1382:                 }
 1383:             }
 1384:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1385:                 if (($uint_dom ne '') && 
 1386:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1387:                     $canhost = 1;
 1388:                 } else {
 1389:                     $canhost = 0;
 1390:                 }
 1391:             }
 1392:         }
 1393:     }
 1394:     return $canhost;
 1395: }
 1396: 
 1397: sub spare_can_host {
 1398:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1399:     my $canhost=1;
 1400:     my $try_server_hostname = &hostname($try_server);
 1401:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1402:     my $serverhomedom = &host_domain($serverhomeID);
 1403:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1404:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1405:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1406:             $canhost = 0;
 1407:         }
 1408:     }
 1409:     if (($canhost) && ($uint_dom)) {
 1410:         my @intdoms;
 1411:         my $internet_names = &get_internet_names($try_server);
 1412:         if (ref($internet_names) eq 'ARRAY') {
 1413:             @intdoms = @{$internet_names};
 1414:         }
 1415:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1416:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1417:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1418:                                          $remotesessions,
 1419:                                          $defdomdefaults{'hostedsessions'});
 1420:         }
 1421:     }
 1422:     return $canhost;
 1423: }
 1424: 
 1425: sub this_host_spares {
 1426:     my ($dom) = @_;
 1427:     my ($dom_in_use,$lonhost_in_use,$result);
 1428:     my @hosts = &current_machine_ids();
 1429:     foreach my $lonhost (@hosts) {
 1430:         if (&host_domain($lonhost) eq $dom) {
 1431:             $dom_in_use = $dom;
 1432:             $lonhost_in_use = $lonhost;
 1433:             last;
 1434:         }
 1435:     }
 1436:     if ($dom_in_use ne '') {
 1437:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1438:     }
 1439:     if (ref($result) ne 'HASH') {
 1440:         $lonhost_in_use = $perlvar{'lonHostID'};
 1441:         $dom_in_use = &host_domain($lonhost_in_use);
 1442:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1443:         if (ref($result) ne 'HASH') {
 1444:             $result = \%spareid;
 1445:         }
 1446:     }
 1447:     return $result;
 1448: }
 1449: 
 1450: sub spares_for_offload  {
 1451:     my ($dom_in_use,$lonhost_in_use) = @_;
 1452:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1453:     if (defined($cached)) {
 1454:         return $result;
 1455:     } else {
 1456:         my $cachetime = 60*60*24;
 1457:         my %domconfig =
 1458:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1459:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1460:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1461:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1462:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1463:                 }
 1464:             }
 1465:         }
 1466:     }
 1467:     return;
 1468: }
 1469: 
 1470: sub get_lonbalancer_config {
 1471:     my ($servers) = @_;
 1472:     my ($currbalancer,$currtargets);
 1473:     if (ref($servers) eq 'HASH') {
 1474:         foreach my $server (keys(%{$servers})) {
 1475:             my %what = (
 1476:                          spareid => 1,
 1477:                          perlvar => 1,
 1478:                        );
 1479:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1480:             if ($result eq 'ok') {
 1481:                 if (ref($returnhash) eq 'HASH') {
 1482:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1483:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1484:                             $currbalancer = $server;
 1485:                             $currtargets = {};
 1486:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1487:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1488:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1489:                                 }
 1490:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1491:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1492:                                 }
 1493:                             }
 1494:                             last;
 1495:                         }
 1496:                     }
 1497:                 }
 1498:             }
 1499:         }
 1500:     }
 1501:     return ($currbalancer,$currtargets);
 1502: }
 1503: 
 1504: sub check_loadbalancing {
 1505:     my ($uname,$udom,$caller) = @_;
 1506:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1507:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1508:     my $lonhost = $perlvar{'lonHostID'};
 1509:     my @hosts = &current_machine_ids();
 1510:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1511:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1512:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1513:     my $serverhomedom = &host_domain($lonhost);
 1514:     my $domneedscache;
 1515:     my $cachetime = 60*60*24;
 1516: 
 1517:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1518:         $dom_in_use = $udom;
 1519:         $homeintdom = 1;
 1520:     } else {
 1521:         $dom_in_use = $serverhomedom;
 1522:     }
 1523:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1524:     unless (defined($cached)) {
 1525:         my %domconfig =
 1526:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1527:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1528:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1529:         } else {
 1530:             $domneedscache = $dom_in_use;
 1531:         }
 1532:     }
 1533:     if (ref($result) eq 'HASH') {
 1534:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1535:             &check_balancer_result($result,@hosts);
 1536:         if ($is_balancer) {
 1537:             if (ref($currrules) eq 'HASH') {
 1538:                 if ($homeintdom) {
 1539:                     if ($uname ne '') {
 1540:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1541:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1542:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1543:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1544:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1545:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1546:                             }
 1547:                         }
 1548:                         if ($rule_in_effect eq '') {
 1549:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1550:                             if ($userenv{'inststatus'} ne '') {
 1551:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1552:                                 my ($othertitle,$usertypes,$types) =
 1553:                                     &Apache::loncommon::sorted_inst_types($udom);
 1554:                                 if (ref($types) eq 'ARRAY') {
 1555:                                     foreach my $type (@{$types}) {
 1556:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1557:                                             if (exists($currrules->{$type})) {
 1558:                                                 $rule_in_effect = $currrules->{$type};
 1559:                                             }
 1560:                                         }
 1561:                                     }
 1562:                                 }
 1563:                             } else {
 1564:                                 if (exists($currrules->{'default'})) {
 1565:                                     $rule_in_effect = $currrules->{'default'};
 1566:                                 }
 1567:                             }
 1568:                         }
 1569:                     } else {
 1570:                         if (exists($currrules->{'default'})) {
 1571:                             $rule_in_effect = $currrules->{'default'};
 1572:                         }
 1573:                     }
 1574:                 } else {
 1575:                     if ($currrules->{'_LC_external'} ne '') {
 1576:                         $rule_in_effect = $currrules->{'_LC_external'};
 1577:                     }
 1578:                 }
 1579:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1580:                                                        $uname,$udom);
 1581:             }
 1582:         }
 1583:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1584:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1585:         unless (defined($cached)) {
 1586:             my %domconfig =
 1587:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1588:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1589:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1590:             } else {
 1591:                 $domneedscache = $serverhomedom;
 1592:             }
 1593:         }
 1594:         if (ref($result) eq 'HASH') {
 1595:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1596:                 &check_balancer_result($result,@hosts);
 1597:             if ($is_balancer) {
 1598:                 if (ref($currrules) eq 'HASH') {
 1599:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1600:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1601:                     }
 1602:                 }
 1603:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1604:                                                        $uname,$udom);
 1605:             }
 1606:         } else {
 1607:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1608:                 $is_balancer = 1;
 1609:                 $offloadto = &this_host_spares($dom_in_use);
 1610:             }
 1611:             unless (defined($cached)) {
 1612:                 $domneedscache = $serverhomedom;
 1613:             }
 1614:         }
 1615:     } else {
 1616:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1617:             $is_balancer = 1;
 1618:             $offloadto = &this_host_spares($dom_in_use);
 1619:         }
 1620:         unless (defined($cached)) {
 1621:             $domneedscache = $serverhomedom;
 1622:         }
 1623:     }
 1624:     if ($domneedscache) {
 1625:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1626:     }
 1627:     if ($is_balancer) {
 1628:         my $lowest_load = 30000;
 1629:         if (ref($offloadto) eq 'HASH') {
 1630:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1631:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1632:                     ($otherserver,$lowest_load) =
 1633:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1634:                 }
 1635:             }
 1636:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1637: 
 1638:             if (!$found_server) {
 1639:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1640:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1641:                         ($otherserver,$lowest_load) =
 1642:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1643:                     }
 1644:                 }
 1645:             }
 1646:         } elsif (ref($offloadto) eq 'ARRAY') {
 1647:             if (@{$offloadto} == 1) {
 1648:                 $otherserver = $offloadto->[0];
 1649:             } elsif (@{$offloadto} > 1) {
 1650:                 foreach my $try_server (@{$offloadto}) {
 1651:                     ($otherserver,$lowest_load) =
 1652:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1653:                 }
 1654:             }
 1655:         }
 1656:         unless ($caller eq 'login') {
 1657:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1658:                 $is_balancer = 0;
 1659:                 if ($uname ne '' && $udom ne '') {
 1660:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1661:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1662:                                  'user.loadbalcheck.time' => time});
 1663:                     }
 1664:                 }
 1665:             }
 1666:         }
 1667:         unless ($homeintdom) {
 1668:             undef($setcookie);
 1669:         }
 1670:     }
 1671:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1672: }
 1673: 
 1674: sub check_balancer_result {
 1675:     my ($result,@hosts) = @_;
 1676:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1677:     if (ref($result) eq 'HASH') {
 1678:         if ($result->{'lonhost'} ne '') {
 1679:             my $currbalancer = $result->{'lonhost'};
 1680:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1681:                 $is_balancer = 1;
 1682:                 $currtargets = $result->{'targets'};
 1683:                 $currrules = $result->{'rules'};
 1684:             }
 1685:             $dom_balancers = $currbalancer;
 1686:         } else {
 1687:             if (keys(%{$result})) {
 1688:                 foreach my $key (keys(%{$result})) {
 1689:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1690:                         (ref($result->{$key}) eq 'HASH')) {
 1691:                         $is_balancer = 1;
 1692:                         $currrules = $result->{$key}{'rules'};
 1693:                         $currtargets = $result->{$key}{'targets'};
 1694:                         $setcookie = $result->{$key}{'cookie'};
 1695:                         last;
 1696:                     }
 1697:                 }
 1698:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1699:             }
 1700:         }
 1701:     }
 1702:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1703: }
 1704: 
 1705: sub get_loadbalancer_targets {
 1706:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1707:     my $offloadto;
 1708:     if ($rule_in_effect eq 'none') {
 1709:         return [$perlvar{'lonHostID'}];
 1710:     } elsif ($rule_in_effect eq '') {
 1711:         $offloadto = $currtargets;
 1712:     } else {
 1713:         if ($rule_in_effect eq 'homeserver') {
 1714:             my $homeserver = &homeserver($uname,$udom);
 1715:             if ($homeserver ne 'no_host') {
 1716:                 $offloadto = [$homeserver];
 1717:             }
 1718:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1719:             my %domconfig =
 1720:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1721:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1722:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1723:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1724:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1725:                     }
 1726:                 }
 1727:             } else {
 1728:                 my %servers = &internet_dom_servers($udom);
 1729:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1730:                 if (&hostname($remotebalancer) ne '') {
 1731:                     $offloadto = [$remotebalancer];
 1732:                 }
 1733:             }
 1734:         } elsif (&hostname($rule_in_effect) ne '') {
 1735:             $offloadto = [$rule_in_effect];
 1736:         }
 1737:     }
 1738:     return $offloadto;
 1739: }
 1740: 
 1741: sub internet_dom_servers {
 1742:     my ($dom) = @_;
 1743:     my (%uniqservers,%servers);
 1744:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1745:     my @machinedoms = &machine_domains($primaryserver);
 1746:     foreach my $mdom (@machinedoms) {
 1747:         my %currservers = %servers;
 1748:         my %server = &get_servers($mdom);
 1749:         %servers = (%currservers,%server);
 1750:     }
 1751:     my %by_hostname;
 1752:     foreach my $id (keys(%servers)) {
 1753:         push(@{$by_hostname{$servers{$id}}},$id);
 1754:     }
 1755:     foreach my $hostname (sort(keys(%by_hostname))) {
 1756:         if (@{$by_hostname{$hostname}} > 1) {
 1757:             my $match = 0;
 1758:             foreach my $id (@{$by_hostname{$hostname}}) {
 1759:                 if (&host_domain($id) eq $dom) {
 1760:                     $uniqservers{$id} = $hostname;
 1761:                     $match = 1;
 1762:                 }
 1763:             }
 1764:             unless ($match) {
 1765:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1766:             }
 1767:         } else {
 1768:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1769:         }
 1770:     }
 1771:     return %uniqservers;
 1772: }
 1773: 
 1774: sub trusted_domains {
 1775:     my ($cmdtype,$calldom) = @_;
 1776:     my ($trusted,$untrusted);
 1777:     if (&domain($calldom) eq '') {
 1778:         return ($trusted,$untrusted);
 1779:     }
 1780:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1781:         return ($trusted,$untrusted);
 1782:     }
 1783:     my $callprimary = &domain($calldom,'primary');
 1784:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1785:     if ($intcalldom eq '') {
 1786:         return ($trusted,$untrusted);
 1787:     }
 1788: 
 1789:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1790:     unless (defined($cached)) {
 1791:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1792:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1793:         $trustconfig = $domconfig{'trust'};
 1794:     }
 1795:     if (ref($trustconfig)) {
 1796:         my (%possexc,%possinc,@allexc,@allinc); 
 1797:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1798:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1799:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1800:             }
 1801:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1802:                 $possinc{$intcalldom} = 1;
 1803:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1804:             }
 1805:         }
 1806:         if (keys(%possexc)) {
 1807:             if (keys(%possinc)) {
 1808:                 foreach my $key (sort(keys(%possexc))) {
 1809:                     next if ($key eq $intcalldom);
 1810:                     unless ($possinc{$key}) {
 1811:                         push(@allexc,$key);
 1812:                     }
 1813:                 }
 1814:             } else {
 1815:                 @allexc = sort(keys(%possexc));
 1816:             }
 1817:         }
 1818:         if (keys(%possinc)) {
 1819:             $possinc{$intcalldom} = 1;
 1820:             @allinc = sort(keys(%possinc));
 1821:         }
 1822:         if ((@allexc > 0) || (@allinc > 0)) {
 1823:             my %doms_by_intdom;
 1824:             my %allintdoms = &all_host_intdom();
 1825:             my %alldoms = &all_host_domain();
 1826:             foreach my $key (%allintdoms) {
 1827:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1828:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1829:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1830:                     }
 1831:                 } else {
 1832:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1833:                 }
 1834:             }
 1835:             foreach my $exc (@allexc) {
 1836:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1837:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1838:                 }
 1839:             }
 1840:             foreach my $inc (@allinc) {
 1841:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1842:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1843:                 }
 1844:             }
 1845:         }
 1846:     }
 1847:     return ($trusted,$untrusted);
 1848: }
 1849: 
 1850: sub will_trust {
 1851:     my ($cmdtype,$domain,$possdom) = @_;
 1852:     return 1 if ($domain eq $possdom);
 1853:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1854:     my $willtrust; 
 1855:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1856:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1857:             $willtrust = 1;
 1858:         }
 1859:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1860:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1861:             $willtrust = 1;
 1862:         }
 1863:     } else {
 1864:         $willtrust = 1;
 1865:     }
 1866:     return $willtrust;
 1867: }
 1868: 
 1869: # ---------------------- Find the homebase for a user from domain's lib servers
 1870: 
 1871: my %homecache;
 1872: sub homeserver {
 1873:     my ($uname,$udom,$ignoreBadCache)=@_;
 1874:     my $index="$uname:$udom";
 1875: 
 1876:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1877: 
 1878:     my %servers = &get_servers($udom,'library');
 1879:     foreach my $tryserver (keys(%servers)) {
 1880:         next if ($ignoreBadCache ne 'true' && 
 1881: 		 exists($badServerCache{$tryserver}));
 1882: 
 1883: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1884: 	if ($answer eq 'found') {
 1885: 	    delete($badServerCache{$tryserver}); 
 1886: 	    return $homecache{$index}=$tryserver;
 1887: 	} elsif ($answer eq 'no_host') {
 1888: 	    $badServerCache{$tryserver}=1;
 1889: 	}
 1890:     }    
 1891:     return 'no_host';
 1892: }
 1893: 
 1894: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1895: 
 1896: sub idget {
 1897:     my ($udom,$idsref,$namespace)=@_;
 1898:     my %returnhash=();
 1899:     my @ids=(); 
 1900:     if (ref($idsref) eq 'ARRAY') {
 1901:         @ids = @{$idsref};
 1902:     } else {
 1903:         return %returnhash; 
 1904:     }
 1905:     if ($namespace eq '') {
 1906:         $namespace = 'ids';
 1907:     }
 1908:     
 1909:     my %servers = &get_servers($udom,'library');
 1910:     foreach my $tryserver (keys(%servers)) {
 1911: 	my $idlist=join('&', map { &escape($_); } @ids);
 1912: 	if ($namespace eq 'ids') {
 1913: 	    $idlist=~tr/A-Z/a-z/;
 1914: 	}
 1915: 	my $reply;
 1916: 	if ($namespace eq 'ids') {
 1917: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1918: 	} else {
 1919: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1920: 	}
 1921: 	my @answer=();
 1922: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1923: 	    @answer=split(/\&/,$reply);
 1924: 	}                    ;
 1925: 	my $i;
 1926: 	for ($i=0;$i<=$#ids;$i++) {
 1927: 	    if ($answer[$i]) {
 1928: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1929: 	    }
 1930: 	}
 1931:     }
 1932:     return %returnhash;
 1933: }
 1934: 
 1935: # ------------------------------------- Find the IDs behind a list of usernames
 1936: 
 1937: sub idrget {
 1938:     my ($udom,@unames)=@_;
 1939:     my %returnhash=();
 1940:     foreach my $uname (@unames) {
 1941:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1942:     }
 1943:     return %returnhash;
 1944: }
 1945: 
 1946: # Store away a list of names and associated student/employee IDs or clicker IDs
 1947: 
 1948: sub idput {
 1949:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1950:     my %servers=();
 1951:     my %ids=();
 1952:     my %byid = ();
 1953:     if (ref($idsref) eq 'HASH') {
 1954:         %ids=%{$idsref};
 1955:     }
 1956:     if ($namespace eq '') {
 1957:         $namespace = 'ids'; 
 1958:     }
 1959:     foreach my $uname (keys(%ids)) {
 1960: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1961:         if ($uhom eq '') {
 1962:             $uhom=&homeserver($uname,$udom);
 1963:         }
 1964:         if ($uhom ne 'no_host') {
 1965:             my $esc_unam=&escape($uname);
 1966:             if ($namespace eq 'ids') {
 1967:                 my $id=&escape($ids{$uname});
 1968:                 $id=~tr/A-Z/a-z/;
 1969:                 my $esc_unam=&escape($uname);
 1970:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1971:             } else {
 1972:                 my @currids = split(/,/,$ids{$uname});
 1973:                 foreach my $id (@currids) {
 1974:                     $byid{$uhom}{$id} .= $uname.',';
 1975:                 }
 1976:             }
 1977:         }
 1978:     }
 1979:     if ($namespace eq 'clickers') {
 1980:         foreach my $server (keys(%byid)) {
 1981:             if (ref($byid{$server}) eq 'HASH') {
 1982:                 foreach my $id (keys(%{$byid{$server}})) {
 1983:                     $byid{$server} =~ s/,$//;
 1984:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1985:                 }
 1986:             }
 1987:         }
 1988:     }
 1989:     foreach my $server (keys(%servers)) {
 1990:         $servers{$server} =~ s/\&$//;
 1991:         if ($namespace eq 'ids') {     
 1992:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1993:         } else {
 1994:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1995:         }
 1996:     }
 1997: }
 1998: 
 1999: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2000: 
 2001: sub iddel {
 2002:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2003:     my %result=();
 2004:     my %ids=();
 2005:     my %byid = ();
 2006:     if (ref($idshashref) eq 'HASH') {
 2007:         %ids=%{$idshashref};
 2008:     } else {
 2009:         return %result;
 2010:     }
 2011:     if ($namespace eq '') {
 2012:         $namespace = 'ids';
 2013:     }
 2014:     my %servers=();
 2015:     while (my ($id,$unamestr) = each(%ids)) {
 2016:         if ($namespace eq 'ids') {
 2017:             my $uhom = $uhome;
 2018:             if ($uhom eq '') { 
 2019:                 $uhom=&homeserver($unamestr,$udom);
 2020:             }
 2021:             if ($uhom ne 'no_host') {
 2022:                 $servers{$uhom}.='&'.&escape($id);
 2023:             }
 2024:          } else {
 2025:             my @curritems = split(/,/,$ids{$id});
 2026:             foreach my $uname (@curritems) {
 2027:                 my $uhom = $uhome;
 2028:                 if ($uhom eq '') {
 2029:                     $uhom=&homeserver($uname,$udom);
 2030:                 }
 2031:                 if ($uhom ne 'no_host') { 
 2032:                     $byid{$uhom}{$id} .= $uname.',';
 2033:                 }
 2034:             }
 2035:         }
 2036:     }
 2037:     if ($namespace eq 'clickers') {
 2038:         foreach my $server (keys(%byid)) {
 2039:             if (ref($byid{$server}) eq 'HASH') {
 2040:                 foreach my $id (keys(%{$byid{$server}})) {
 2041:                     $byid{$server}{$id} =~ s/,$//;
 2042:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2043:                 }
 2044:             }
 2045:         }
 2046:     }
 2047:     foreach my $server (keys(%servers)) {
 2048:         $servers{$server} =~ s/\&$//;
 2049:         if ($namespace eq 'ids') {
 2050:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2051:         } elsif ($namespace eq 'clickers') {
 2052:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2053:         }
 2054:     }
 2055:     return %result;
 2056: }
 2057: 
 2058: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2059: 
 2060: sub updateclickers {
 2061:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2062:     my %clickers;
 2063:     if (ref($idshashref) eq 'HASH') {
 2064:         %clickers=%{$idshashref};
 2065:     } else {
 2066:         return;
 2067:     }
 2068:     my $items='';
 2069:     foreach my $item (keys(%clickers)) {
 2070:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2071:     }
 2072:     $items=~s/\&$//;
 2073:     my $request = "updateclickers:$udom:$action:$items";
 2074:     if ($critical) {
 2075:         return &critical($request,$uhome);
 2076:     } else {
 2077:         return &reply($request,$uhome);
 2078:     }
 2079: }
 2080: 
 2081: # ------------------------------dump from db file owned by domainconfig user
 2082: sub dump_dom {
 2083:     my ($namespace, $udom, $regexp) = @_;
 2084: 
 2085:     $udom ||= $env{'user.domain'};
 2086: 
 2087:     return () unless $udom;
 2088: 
 2089:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2090: }
 2091: 
 2092: # ------------------------------------------ get items from domain db files   
 2093: 
 2094: sub get_dom {
 2095:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2096:     return if ($udom eq 'public');
 2097:     my $items='';
 2098:     foreach my $item (@$storearr) {
 2099:         $items.=&escape($item).'&';
 2100:     }
 2101:     $items=~s/\&$//;
 2102:     if (!$udom) {
 2103:         $udom=$env{'user.domain'};
 2104:         return if ($udom eq 'public');
 2105:         if (defined(&domain($udom,'primary'))) {
 2106:             $uhome=&domain($udom,'primary');
 2107:         } else {
 2108:             undef($uhome);
 2109:         }
 2110:     } else {
 2111:         if (!$uhome) {
 2112:             if (defined(&domain($udom,'primary'))) {
 2113:                 $uhome=&domain($udom,'primary');
 2114:             }
 2115:         }
 2116:     }
 2117:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2118:         my $rep;
 2119:         if ($namespace =~ /^enc/) {
 2120:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2121:         } else {
 2122:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2123:         }
 2124:         my %returnhash;
 2125:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2126:             return %returnhash;
 2127:         }
 2128:         my @pairs=split(/\&/,$rep);
 2129:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2130:             return @pairs;
 2131:         }
 2132:         my $i=0;
 2133:         foreach my $item (@$storearr) {
 2134:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2135:             $i++;
 2136:         }
 2137:         return %returnhash;
 2138:     } else {
 2139:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2140:     }
 2141: }
 2142: 
 2143: # -------------------------------------------- put items in domain db files 
 2144: 
 2145: sub put_dom {
 2146:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2147:     if (!$udom) {
 2148:         $udom=$env{'user.domain'};
 2149:         if (defined(&domain($udom,'primary'))) {
 2150:             $uhome=&domain($udom,'primary');
 2151:         } else {
 2152:             undef($uhome);
 2153:         }
 2154:     } else {
 2155:         if (!$uhome) {
 2156:             if (defined(&domain($udom,'primary'))) {
 2157:                 $uhome=&domain($udom,'primary');
 2158:             }
 2159:         }
 2160:     } 
 2161:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2162:         my $items='';
 2163:         foreach my $item (keys(%$storehash)) {
 2164:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2165:         }
 2166:         $items=~s/\&$//;
 2167:         if ($namespace =~ /^enc/) {
 2168:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2169:         } else {
 2170:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2171:         }
 2172:     } else {
 2173:         &logthis("put_dom failed - no homeserver and/or domain");
 2174:     }
 2175: }
 2176: 
 2177: # --------------------- newput for items in db file owned by domainconfig user
 2178: sub newput_dom {
 2179:     my ($namespace,$storehash,$udom) = @_;
 2180:     my $result;
 2181:     if (!$udom) {
 2182:         $udom=$env{'user.domain'};
 2183:     }
 2184:     if ($udom) {
 2185:         my $uname = &get_domainconfiguser($udom);
 2186:         $result = &newput($namespace,$storehash,$udom,$uname);
 2187:     }
 2188:     return $result;
 2189: }
 2190: 
 2191: # --------------------- delete for items in db file owned by domainconfig user
 2192: sub del_dom {
 2193:     my ($namespace,$storearr,$udom)=@_;
 2194:     if (ref($storearr) eq 'ARRAY') {
 2195:         if (!$udom) {
 2196:             $udom=$env{'user.domain'};
 2197:         }
 2198:         if ($udom) {
 2199:             my $uname = &get_domainconfiguser($udom); 
 2200:             return &del($namespace,$storearr,$udom,$uname);
 2201:         }
 2202:     }
 2203: }
 2204: 
 2205: # ----------------------------------construct domainconfig user for a domain 
 2206: sub get_domainconfiguser {
 2207:     my ($udom) = @_;
 2208:     return $udom.'-domainconfig';
 2209: }
 2210: 
 2211: sub retrieve_inst_usertypes {
 2212:     my ($udom) = @_;
 2213:     my (%returnhash,@order);
 2214:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2215:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2216:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2217:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2218:     } else {
 2219:         if (defined(&domain($udom,'primary'))) {
 2220:             my $uhome=&domain($udom,'primary');
 2221:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2222:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2223:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2224:                 return (\%returnhash,\@order);
 2225:             }
 2226:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2227:             my @pairs=split(/\&/,$hashitems);
 2228:             foreach my $item (@pairs) {
 2229:                 my ($key,$value)=split(/=/,$item,2);
 2230:                 $key = &unescape($key);
 2231:                 next if ($key =~ /^error: 2 /);
 2232:                 $returnhash{$key}=&thaw_unescape($value);
 2233:             }
 2234:             my @esc_order = split(/\&/,$orderitems);
 2235:             foreach my $item (@esc_order) {
 2236:                 push(@order,&unescape($item));
 2237:             }
 2238:         } else {
 2239:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2240:         }
 2241:         return (\%returnhash,\@order);
 2242:     }
 2243: }
 2244: 
 2245: sub is_domainimage {
 2246:     my ($url) = @_;
 2247:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2248:         if (&domain($1) ne '') {
 2249:             return '1';
 2250:         }
 2251:     }
 2252:     return;
 2253: }
 2254: 
 2255: sub inst_directory_query {
 2256:     my ($srch) = @_;
 2257:     my $udom = $srch->{'srchdomain'};
 2258:     my %results;
 2259:     my $homeserver = &domain($udom,'primary');
 2260:     my $outcome;
 2261:     if ($homeserver ne '') {
 2262:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2263:             if ($srch->{'srchby'} eq 'email') {
 2264:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2265:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2266:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2267:                     (($major == 2) && ($minor < 12))) {
 2268:                     return;
 2269:                 }
 2270:             }
 2271:         }
 2272: 	my $queryid=&reply("querysend:instdirsearch:".
 2273: 			   &escape($srch->{'srchby'}).':'.
 2274: 			   &escape($srch->{'srchterm'}).':'.
 2275: 			   &escape($srch->{'srchtype'}),$homeserver);
 2276: 	my $host=&hostname($homeserver);
 2277: 	if ($queryid !~/^\Q$host\E\_/) {
 2278: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2279: 	    return;
 2280: 	}
 2281: 	my $response = &get_query_reply($queryid);
 2282: 	my $maxtries = 5;
 2283: 	my $tries = 1;
 2284: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2285: 	    $response = &get_query_reply($queryid);
 2286: 	    $tries ++;
 2287: 	}
 2288: 
 2289:         if (!&error($response) && $response ne 'refused') {
 2290:             if ($response eq 'unavailable') {
 2291:                 $outcome = $response;
 2292:             } else {
 2293:                 $outcome = 'ok';
 2294:                 my @matches = split(/\n/,$response);
 2295:                 foreach my $match (@matches) {
 2296:                     my ($key,$value) = split(/=/,$match);
 2297:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2298:                 }
 2299:             }
 2300:         }
 2301:     }
 2302:     return ($outcome,%results);
 2303: }
 2304: 
 2305: sub usersearch {
 2306:     my ($srch) = @_;
 2307:     my $dom = $srch->{'srchdomain'};
 2308:     my %results;
 2309:     my %libserv = &all_library();
 2310:     my $query = 'usersearch';
 2311:     foreach my $tryserver (keys(%libserv)) {
 2312:         if (&host_domain($tryserver) eq $dom) {
 2313:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2314:                 if ($srch->{'srchby'} eq 'email') {
 2315:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2316:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2317:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2318:                              (($major == 2) && ($minor < 12)));
 2319:                 }
 2320:             }
 2321:             my $host=&hostname($tryserver);
 2322:             my $queryid=
 2323:                 &reply("querysend:".&escape($query).':'.
 2324:                        &escape($srch->{'srchby'}).':'.
 2325:                        &escape($srch->{'srchtype'}).':'.
 2326:                        &escape($srch->{'srchterm'}),$tryserver);
 2327:             if ($queryid !~/^\Q$host\E\_/) {
 2328:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2329:                 next;
 2330:             }
 2331:             my $reply = &get_query_reply($queryid);
 2332:             my $maxtries = 1;
 2333:             my $tries = 1;
 2334:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2335:                 $reply = &get_query_reply($queryid);
 2336:                 $tries ++;
 2337:             }
 2338:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2339:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2340:             } else {
 2341:                 my @matches;
 2342:                 if ($reply =~ /\n/) {
 2343:                     @matches = split(/\n/,$reply);
 2344:                 } else {
 2345:                     @matches = split(/\&/,$reply);
 2346:                 }
 2347:                 foreach my $match (@matches) {
 2348:                     my ($uname,$udom,%userhash);
 2349:                     foreach my $entry (split(/:/,$match)) {
 2350:                         my ($key,$value) =
 2351:                             map {&unescape($_);} split(/=/,$entry);
 2352:                         $userhash{$key} = $value;
 2353:                         if ($key eq 'username') {
 2354:                             $uname = $value;
 2355:                         } elsif ($key eq 'domain') {
 2356:                             $udom = $value;
 2357:                         }
 2358:                     }
 2359:                     $results{$uname.':'.$udom} = \%userhash;
 2360:                 }
 2361:             }
 2362:         }
 2363:     }
 2364:     return %results;
 2365: }
 2366: 
 2367: sub get_instuser {
 2368:     my ($udom,$uname,$id) = @_;
 2369:     my $homeserver = &domain($udom,'primary');
 2370:     my ($outcome,%results);
 2371:     if ($homeserver ne '') {
 2372:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2373:                            &escape($id).':'.&escape($udom),$homeserver);
 2374:         my $host=&hostname($homeserver);
 2375:         if ($queryid !~/^\Q$host\E\_/) {
 2376:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2377:             return;
 2378:         }
 2379:         my $response = &get_query_reply($queryid);
 2380:         my $maxtries = 5;
 2381:         my $tries = 1;
 2382:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2383:             $response = &get_query_reply($queryid);
 2384:             $tries ++;
 2385:         }
 2386:         if (!&error($response) && $response ne 'refused') {
 2387:             if ($response eq 'unavailable') {
 2388:                 $outcome = $response;
 2389:             } else {
 2390:                 $outcome = 'ok';
 2391:                 my @matches = split(/\n/,$response);
 2392:                 foreach my $match (@matches) {
 2393:                     my ($key,$value) = split(/=/,$match);
 2394:                     $results{&unescape($key)} = &thaw_unescape($value);
 2395:                 }
 2396:             }
 2397:         }
 2398:     }
 2399:     my %userinfo;
 2400:     if (ref($results{$uname}) eq 'HASH') {
 2401:         %userinfo = %{$results{$uname}};
 2402:     } 
 2403:     return ($outcome,%userinfo);
 2404: }
 2405: 
 2406: sub get_multiple_instusers {
 2407:     my ($udom,$users,$caller) = @_;
 2408:     my ($outcome,$results);
 2409:     if (ref($users) eq 'HASH') {
 2410:         my $count = keys(%{$users}); 
 2411:         my $requested = &freeze_escape($users);
 2412:         my $homeserver = &domain($udom,'primary');
 2413:         if ($homeserver ne '') {
 2414:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2415:             my $host=&hostname($homeserver);
 2416:             if ($queryid !~/^\Q$host\E\_/) {
 2417:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2418:                          ' for host: '.$homeserver.'in domain '.$udom);
 2419:                 return ($outcome,$results);
 2420:             }
 2421:             my $response = &get_query_reply($queryid);
 2422:             my $maxtries = 5;
 2423:             if ($count > 100) {
 2424:                 $maxtries = 1+int($count/20);
 2425:             }
 2426:             my $tries = 1;
 2427:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2428:                 $response = &get_query_reply($queryid);
 2429:                 $tries ++;
 2430:             }
 2431:             if ($response eq '') {
 2432:                 $results = {};
 2433:                 foreach my $key (keys(%{$users})) {
 2434:                     my ($uname,$id);
 2435:                     if ($caller eq 'id') {
 2436:                         $id = $key;
 2437:                     } else {
 2438:                         $uname = $key;
 2439:                     }
 2440:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2441:                     $outcome = $resp;
 2442:                     if ($resp eq 'ok') {
 2443:                         %{$results} = (%{$results}, %info);
 2444:                     } else {
 2445:                         last;
 2446:                     }
 2447:                 }
 2448:             } elsif(!&error($response) && ($response ne 'refused')) {
 2449:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2450:                     $outcome = $response;
 2451:                 } else {
 2452:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2453:                     if ($outcome eq 'ok') {
 2454:                         $results = &thaw_unescape($userdata); 
 2455:                     }
 2456:                 }
 2457:             }
 2458:         }
 2459:     }
 2460:     return ($outcome,$results);
 2461: }
 2462: 
 2463: sub inst_rulecheck {
 2464:     my ($udom,$uname,$id,$item,$rules) = @_;
 2465:     my %returnhash;
 2466:     if ($udom ne '') {
 2467:         if (ref($rules) eq 'ARRAY') {
 2468:             @{$rules} = map {&escape($_);} (@{$rules});
 2469:             my $rulestr = join(':',@{$rules});
 2470:             my $homeserver=&domain($udom,'primary');
 2471:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2472:                 my $response;
 2473:                 if ($item eq 'username') {                
 2474:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2475:                                               ':'.&escape($uname).':'.$rulestr,
 2476:                                               $homeserver));
 2477:                 } elsif ($item eq 'id') {
 2478:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2479:                                               ':'.&escape($id).':'.$rulestr,
 2480:                                               $homeserver));
 2481:                 } elsif ($item eq 'selfcreate') {
 2482:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2483:                                                &escape($udom).':'.&escape($uname).
 2484:                                               ':'.$rulestr,$homeserver));
 2485:                 }
 2486:                 if ($response ne 'refused') {
 2487:                     my @pairs=split(/\&/,$response);
 2488:                     foreach my $item (@pairs) {
 2489:                         my ($key,$value)=split(/=/,$item,2);
 2490:                         $key = &unescape($key);
 2491:                         next if ($key =~ /^error: 2 /);
 2492:                         $returnhash{$key}=&thaw_unescape($value);
 2493:                     }
 2494:                 }
 2495:             }
 2496:         }
 2497:     }
 2498:     return %returnhash;
 2499: }
 2500: 
 2501: sub inst_userrules {
 2502:     my ($udom,$check) = @_;
 2503:     my (%ruleshash,@ruleorder);
 2504:     if ($udom ne '') {
 2505:         my $homeserver=&domain($udom,'primary');
 2506:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2507:             my $response;
 2508:             if ($check eq 'id') {
 2509:                 $response=&reply('instidrules:'.&escape($udom),
 2510:                                  $homeserver);
 2511:             } elsif ($check eq 'email') {
 2512:                 $response=&reply('instemailrules:'.&escape($udom),
 2513:                                  $homeserver);
 2514:             } else {
 2515:                 $response=&reply('instuserrules:'.&escape($udom),
 2516:                                  $homeserver);
 2517:             }
 2518:             if (($response ne 'refused') && ($response ne 'error') && 
 2519:                 ($response ne 'unknown_cmd') && 
 2520:                 ($response ne 'no_such_host')) {
 2521:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2522:                 my @pairs=split(/\&/,$hashitems);
 2523:                 foreach my $item (@pairs) {
 2524:                     my ($key,$value)=split(/=/,$item,2);
 2525:                     $key = &unescape($key);
 2526:                     next if ($key =~ /^error: 2 /);
 2527:                     $ruleshash{$key}=&thaw_unescape($value);
 2528:                 }
 2529:                 my @esc_order = split(/\&/,$orderitems);
 2530:                 foreach my $item (@esc_order) {
 2531:                     push(@ruleorder,&unescape($item));
 2532:                 }
 2533:             }
 2534:         }
 2535:     }
 2536:     return (\%ruleshash,\@ruleorder);
 2537: }
 2538: 
 2539: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2540: 
 2541: sub get_domain_defaults {
 2542:     my ($domain,$ignore_cache) = @_;
 2543:     return if (($domain eq '') || ($domain eq 'public'));
 2544:     my $cachetime = 60*60*24;
 2545:     unless ($ignore_cache) {
 2546:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2547:         if (defined($cached)) {
 2548:             if (ref($result) eq 'HASH') {
 2549:                 return %{$result};
 2550:             }
 2551:         }
 2552:     }
 2553:     my %domdefaults;
 2554:     my %domconfig =
 2555:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2556:                                   'requestcourses','inststatus',
 2557:                                   'coursedefaults','usersessions',
 2558:                                   'requestauthor','selfenrollment',
 2559:                                   'coursecategories','ssl','autoenroll',
 2560:                                   'trust','helpsettings'],$domain);
 2561:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2562:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2563:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2564:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2565:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2566:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2567:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2568:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2569:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2570:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2571:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2572:     } else {
 2573:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2574:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2575:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2576:     }
 2577:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2578:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2579:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2580:         } else {
 2581:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2582:         }
 2583:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2584:         foreach my $item (@usertools) {
 2585:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2586:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2587:             }
 2588:         }
 2589:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2590:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2591:         }
 2592:     }
 2593:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2594:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2595:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2596:         }
 2597:     }
 2598:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2599:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2600:     }
 2601:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2602:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2603:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2604:         }
 2605:     }
 2606:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2607:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2608:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2609:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2610:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2611:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2612:         }
 2613:         foreach my $type (@coursetypes) {
 2614:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2615:                 unless ($type eq 'community') {
 2616:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2617:                 }
 2618:             }
 2619:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2620:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2621:             }
 2622:             if ($domdefaults{'postsubmit'} eq 'on') {
 2623:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2624:                     $domdefaults{$type.'postsubtimeout'} = 
 2625:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2626:                 }
 2627:             }
 2628:         }
 2629:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2630:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2631:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2632:                 if (@clonecodes) {
 2633:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2634:                 }
 2635:             }
 2636:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2637:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2638:         }
 2639:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2640:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2641:         } 
 2642:     }
 2643:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2644:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2645:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2646:         }
 2647:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2648:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2649:         }
 2650:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2651:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2652:         }
 2653:     }
 2654:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2655:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2656:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2657:                             'approval','limit');
 2658:             foreach my $type (@coursetypes) {
 2659:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2660:                     my @mgrdc = ();
 2661:                     foreach my $item (@settings) {
 2662:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2663:                             push(@mgrdc,$item);
 2664:                         }
 2665:                     }
 2666:                     if (@mgrdc) {
 2667:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2668:                     }
 2669:                 }
 2670:             }
 2671:         }
 2672:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2673:             foreach my $type (@coursetypes) {
 2674:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2675:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2676:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2677:                     }
 2678:                 }
 2679:             }
 2680:         }
 2681:     }
 2682:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2683:         $domdefaults{'catauth'} = 'std';
 2684:         $domdefaults{'catunauth'} = 'std';
 2685:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2686:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2687:         }
 2688:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2689:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2690:         }
 2691:     }
 2692:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2693:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2694:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2695:         }
 2696:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2697:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2698:         }
 2699:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2700:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2701:         }
 2702:     }
 2703:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2704:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2705:         foreach my $prefix (@prefixes) {
 2706:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2707:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2708:             }
 2709:         }
 2710:     }
 2711:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2712:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2713:     }
 2714:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2715:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2716:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2717:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2718:         }
 2719:     }
 2720:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2721:     return %domdefaults;
 2722: }
 2723: 
 2724: sub get_dom_cats {
 2725:     my ($dom) = @_;
 2726:     return unless (&domain($dom));
 2727:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2728:     unless (defined($cached)) {
 2729:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2730:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2731:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2732:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2733:             } else {
 2734:                 $cats = {};
 2735:             }
 2736:         } else {
 2737:             $cats = {};
 2738:         }
 2739:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2740:     }
 2741:     return $cats; 
 2742: }
 2743: 
 2744: sub course_portal_url {
 2745:     my ($cnum,$cdom) = @_;
 2746:     my $chome = &homeserver($cnum,$cdom);
 2747:     my $hostname = &hostname($chome);
 2748:     my $protocol = $protocol{$chome};
 2749:     $protocol = 'http' if ($protocol ne 'https');
 2750:     my %domdefaults = &get_domain_defaults($cdom);
 2751:     my $firsturl;
 2752:     if ($domdefaults{'portal_def'}) {
 2753:         $firsturl = $domdefaults{'portal_def'};
 2754:     } else {
 2755:         $firsturl = $protocol.'://'.$hostname;
 2756:     }
 2757:     return $firsturl;
 2758: }
 2759: 
 2760: # --------------------------------------------- Get domain config for passwords
 2761: 
 2762: sub get_passwdconf {
 2763:     my ($dom) = @_;
 2764:     my (%passwdconf,$gotconf,$lookup);
 2765:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2766:     if (defined($cached)) {
 2767:         if (ref($result) eq 'HASH') {
 2768:             %passwdconf = %{$result};
 2769:             $gotconf = 1;
 2770:         }
 2771:     }
 2772:     unless ($gotconf) {
 2773:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2774:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2775:             %passwdconf = %{$domconfig{'passwords'}};
 2776:         }
 2777:         my $cachetime = 24*60*60;
 2778:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2779:     }
 2780:     return %passwdconf;
 2781: }
 2782: 
 2783: # --------------------------------------------------- Assign a key to a student
 2784: 
 2785: sub assign_access_key {
 2786: #
 2787: # a valid key looks like uname:udom#comments
 2788: # comments are being appended
 2789: #
 2790:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2791:     $kdom=
 2792:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2793:     $knum=
 2794:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2795:     $cdom=
 2796:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2797:     $cnum=
 2798:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2799:     $udom=$env{'user.name'} unless (defined($udom));
 2800:     $uname=$env{'user.domain'} unless (defined($uname));
 2801:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2802:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2803:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2804:                                                   # assigned to this person
 2805:                                                   # - this should not happen,
 2806:                                                   # unless something went wrong
 2807:                                                   # the first time around
 2808: # ready to assign
 2809:         $logentry=$1.'; '.$logentry;
 2810:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2811:                                                  $kdom,$knum) eq 'ok') {
 2812: # key now belongs to user
 2813: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2814:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2815:                 &appenv({'environment.'.$envkey => $ckey});
 2816:                 return 'ok';
 2817:             } else {
 2818:                 return 
 2819:   'error: Count not permanently assign key, will need to be re-entered later.';
 2820: 	    }
 2821:         } else {
 2822:             return 'error: Could not assign key, try again later.';
 2823:         }
 2824:     } elsif (!$existing{$ckey}) {
 2825: # the key does not exist
 2826: 	return 'error: The key does not exist';
 2827:     } else {
 2828: # the key is somebody else's
 2829: 	return 'error: The key is already in use';
 2830:     }
 2831: }
 2832: 
 2833: # ------------------------------------------ put an additional comment on a key
 2834: 
 2835: sub comment_access_key {
 2836: #
 2837: # a valid key looks like uname:udom#comments
 2838: # comments are being appended
 2839: #
 2840:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2841:     $cdom=
 2842:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2843:     $cnum=
 2844:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2845:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2846:     if ($existing{$ckey}) {
 2847:         $existing{$ckey}.='; '.$logentry;
 2848: # ready to assign
 2849:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2850:                                                  $cdom,$cnum) eq 'ok') {
 2851: 	    return 'ok';
 2852:         } else {
 2853: 	    return 'error: Count not store comment.';
 2854:         }
 2855:     } else {
 2856: # the key does not exist
 2857: 	return 'error: The key does not exist';
 2858:     }
 2859: }
 2860: 
 2861: # ------------------------------------------------------ Generate a set of keys
 2862: 
 2863: sub generate_access_keys {
 2864:     my ($number,$cdom,$cnum,$logentry)=@_;
 2865:     $cdom=
 2866:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2867:     $cnum=
 2868:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2869:     unless (&allowed('mky',$cdom)) { return 0; }
 2870:     unless (($cdom) && ($cnum)) { return 0; }
 2871:     if ($number>10000) { return 0; }
 2872:     sleep(2); # make sure don't get same seed twice
 2873:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2874:     my $total=0;
 2875:     for (my $i=1;$i<=$number;$i++) {
 2876:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2877:                   sprintf("%lx",int(100000*rand)).'-'.
 2878:                   sprintf("%lx",int(100000*rand));
 2879:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2880:        $newkey=~s/0/h/g; # and also 0 and O
 2881:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2882:        if ($existing{$newkey}) {
 2883:            $i--;
 2884:        } else {
 2885: 	  if (&put('accesskeys',
 2886:               { $newkey => '# generated '.localtime().
 2887:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2888:                            '; '.$logentry },
 2889: 		   $cdom,$cnum) eq 'ok') {
 2890:               $total++;
 2891: 	  }
 2892:        }
 2893:     }
 2894:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2895:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2896:     return $total;
 2897: }
 2898: 
 2899: # ------------------------------------------------------- Validate an accesskey
 2900: 
 2901: sub validate_access_key {
 2902:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2903:     $cdom=
 2904:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2905:     $cnum=
 2906:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2907:     $udom=$env{'user.domain'} unless (defined($udom));
 2908:     $uname=$env{'user.name'} unless (defined($uname));
 2909:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2910:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2911: }
 2912: 
 2913: # ------------------------------------- Find the section of student in a course
 2914: sub devalidate_getsection_cache {
 2915:     my ($udom,$unam,$courseid)=@_;
 2916:     my $hashid="$udom:$unam:$courseid";
 2917:     &devalidate_cache_new('getsection',$hashid);
 2918: }
 2919: 
 2920: sub courseid_to_courseurl {
 2921:     my ($courseid) = @_;
 2922:     #already url style courseid
 2923:     return $courseid if ($courseid =~ m{^/});
 2924: 
 2925:     if (exists($env{'course.'.$courseid.'.num'})) {
 2926: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2927: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2928: 	return "/$cdom/$cnum";
 2929:     }
 2930: 
 2931:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2932:     if (exists($courseinfo{'num'})) {
 2933: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2934:     }
 2935: 
 2936:     return undef;
 2937: }
 2938: 
 2939: sub getsection {
 2940:     my ($udom,$unam,$courseid)=@_;
 2941:     my $cachetime=1800;
 2942: 
 2943:     my $hashid="$udom:$unam:$courseid";
 2944:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2945:     if (defined($cached)) { return $result; }
 2946: 
 2947:     my %Pending; 
 2948:     my %Expired;
 2949:     #
 2950:     # Each role can either have not started yet (pending), be active, 
 2951:     #    or have expired.
 2952:     #
 2953:     # If there is an active role, we are done.
 2954:     #
 2955:     # If there is more than one role which has not started yet, 
 2956:     #     choose the one which will start sooner
 2957:     # If there is one role which has not started yet, return it.
 2958:     #
 2959:     # If there is more than one expired role, choose the one which ended last.
 2960:     # If there is a role which has expired, return it.
 2961:     #
 2962:     $courseid = &courseid_to_courseurl($courseid);
 2963:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2964:     foreach my $key (keys(%roleshash)) {
 2965:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2966:         my $section=$1;
 2967:         if ($key eq $courseid.'_st') { $section=''; }
 2968:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2969:         my $now=time;
 2970:         if (defined($end) && $end && ($now > $end)) {
 2971:             $Expired{$end}=$section;
 2972:             next;
 2973:         }
 2974:         if (defined($start) && $start && ($now < $start)) {
 2975:             $Pending{$start}=$section;
 2976:             next;
 2977:         }
 2978:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2979:     }
 2980:     #
 2981:     # Presumedly there will be few matching roles from the above
 2982:     # loop and the sorting time will be negligible.
 2983:     if (scalar(keys(%Pending))) {
 2984:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2985:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2986:     } 
 2987:     if (scalar(keys(%Expired))) {
 2988:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2989:         my $time = pop(@sorted);
 2990:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2991:     }
 2992:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2993: }
 2994: 
 2995: sub save_cache {
 2996:     &purge_remembered();
 2997:     #&Apache::loncommon::validate_page();
 2998:     undef(%env);
 2999:     undef($env_loaded);
 3000: }
 3001: 
 3002: my $to_remember=-1;
 3003: my %remembered;
 3004: my %accessed;
 3005: my $kicks=0;
 3006: my $hits=0;
 3007: sub make_key {
 3008:     my ($name,$id) = @_;
 3009:     if (length($id) > 65 
 3010: 	&& length(&escape($id)) > 200) {
 3011: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3012:     }
 3013:     return &escape($name.':'.$id);
 3014: }
 3015: 
 3016: sub devalidate_cache_new {
 3017:     my ($name,$id,$debug) = @_;
 3018:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3019:     my $remembered_id=$name.':'.$id;
 3020:     $id=&make_key($name,$id);
 3021:     $memcache->delete($id);
 3022:     delete($remembered{$remembered_id});
 3023:     delete($accessed{$remembered_id});
 3024: }
 3025: 
 3026: sub is_cached_new {
 3027:     my ($name,$id,$debug) = @_;
 3028:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3029:     if (exists($remembered{$remembered_id})) {
 3030: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3031: 	$accessed{$remembered_id}=[&gettimeofday()];
 3032: 	$hits++;
 3033: 	return ($remembered{$remembered_id},1);
 3034:     }
 3035:     $id=&make_key($name,$id);
 3036:     my $value = $memcache->get($id);
 3037:     if (!(defined($value))) {
 3038: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3039: 	return (undef,undef);
 3040:     }
 3041:     if ($value eq '__undef__') {
 3042: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3043: 	$value=undef;
 3044:     }
 3045:     &make_room($remembered_id,$value,$debug);
 3046:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3047:     return ($value,1);
 3048: }
 3049: 
 3050: sub do_cache_new {
 3051:     my ($name,$id,$value,$time,$debug) = @_;
 3052:     my $remembered_id=$name.':'.$id;
 3053:     $id=&make_key($name,$id);
 3054:     my $setvalue=$value;
 3055:     if (!defined($setvalue)) {
 3056: 	$setvalue='__undef__';
 3057:     }
 3058:     if (!defined($time) ) {
 3059: 	$time=600;
 3060:     }
 3061:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3062:     my $result = $memcache->set($id,$setvalue,$time);
 3063:     if (! $result) {
 3064: 	&logthis("caching of id -> $id  failed");
 3065: 	$memcache->disconnect_all();
 3066:     }
 3067:     # need to make a copy of $value
 3068:     &make_room($remembered_id,$value,$debug);
 3069:     return $value;
 3070: }
 3071: 
 3072: sub make_room {
 3073:     my ($remembered_id,$value,$debug)=@_;
 3074: 
 3075:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3076:                                     : $value;
 3077:     if ($to_remember<0) { return; }
 3078:     $accessed{$remembered_id}=[&gettimeofday()];
 3079:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3080:     my $to_kick;
 3081:     my $max_time=0;
 3082:     foreach my $other (keys(%accessed)) {
 3083: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3084: 	    $to_kick=$other;
 3085: 	    $max_time=&tv_interval($accessed{$other});
 3086: 	}
 3087:     }
 3088:     delete($remembered{$to_kick});
 3089:     delete($accessed{$to_kick});
 3090:     $kicks++;
 3091:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3092:     return;
 3093: }
 3094: 
 3095: sub purge_remembered {
 3096:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3097:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3098:     undef(%remembered);
 3099:     undef(%accessed);
 3100: }
 3101: # ------------------------------------- Read an entry from a user's environment
 3102: 
 3103: sub userenvironment {
 3104:     my ($udom,$unam,@what)=@_;
 3105:     my $items;
 3106:     foreach my $item (@what) {
 3107:         $items.=&escape($item).'&';
 3108:     }
 3109:     $items=~s/\&$//;
 3110:     my %returnhash=();
 3111:     my $uhome = &homeserver($unam,$udom);
 3112:     unless ($uhome eq 'no_host') {
 3113:         my @answer=split(/\&/, 
 3114:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3115:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3116:             return %returnhash;
 3117:         }
 3118:         my $i;
 3119:         for ($i=0;$i<=$#what;$i++) {
 3120: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3121:         }
 3122:     }
 3123:     return %returnhash;
 3124: }
 3125: 
 3126: # ---------------------------------------------------------- Get a studentphoto
 3127: sub studentphoto {
 3128:     my ($udom,$unam,$ext) = @_;
 3129:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3130:     if (defined($env{'request.course.id'})) {
 3131:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3132:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3133:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3134:             } else {
 3135:                 my ($result,$perm_reqd)=
 3136: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3137:                 if ($result eq 'ok') {
 3138:                     if (!($perm_reqd eq 'yes')) {
 3139:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3140:                     }
 3141:                 }
 3142:             }
 3143:         }
 3144:     } else {
 3145:         my ($result,$perm_reqd) = 
 3146: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3147:         if ($result eq 'ok') {
 3148:             if (!($perm_reqd eq 'yes')) {
 3149:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3150:             }
 3151:         }
 3152:     }
 3153:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3154: }
 3155: 
 3156: sub retrievestudentphoto {
 3157:     my ($udom,$unam,$ext,$type) = @_;
 3158:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3159:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3160:     if ($ret eq 'ok') {
 3161:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3162:         if ($type eq 'thumbnail') {
 3163:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3164:         }
 3165:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3166:         return $tokenurl;
 3167:     } else {
 3168:         if ($type eq 'thumbnail') {
 3169:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3170:         } else { 
 3171:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3172:         }
 3173:     }
 3174: }
 3175: 
 3176: # -------------------------------------------------------------------- New chat
 3177: 
 3178: sub chatsend {
 3179:     my ($newentry,$anon,$group)=@_;
 3180:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3181:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3182:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3183:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3184: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3185: 		   &escape($newentry)).':'.$group,$chome);
 3186: }
 3187: 
 3188: # ------------------------------------------ Find current version of a resource
 3189: 
 3190: sub getversion {
 3191:     my $fname=&clutter(shift);
 3192:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3193:     return &currentversion(&filelocation('',$fname));
 3194: }
 3195: 
 3196: sub currentversion {
 3197:     my $fname=shift;
 3198:     my $author=$fname;
 3199:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3200:     my ($udom,$uname)=split(/\//,$author);
 3201:     my $home=&homeserver($uname,$udom);
 3202:     if ($home eq 'no_host') { 
 3203:         return -1; 
 3204:     }
 3205:     my $answer=&reply("currentversion:$fname",$home);
 3206:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3207: 	return -1;
 3208:     }
 3209:     return $answer;
 3210: }
 3211: 
 3212: #
 3213: # Return special version number of resource if set by override, empty otherwise
 3214: #
 3215: sub usedversion {
 3216:     my $fname=shift;
 3217:     unless ($fname) { $fname=$env{'request.uri'}; }
 3218:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3219:     if ($urlversion) { return $urlversion; }
 3220:     return '';
 3221: }
 3222: 
 3223: # ----------------------------- Subscribe to a resource, return URL if possible
 3224: 
 3225: sub subscribe {
 3226:     my $fname=shift;
 3227:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3228:     $fname=~s/[\n\r]//g;
 3229:     my $author=$fname;
 3230:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3231:     my ($udom,$uname)=split(/\//,$author);
 3232:     my $home=homeserver($uname,$udom);
 3233:     if ($home eq 'no_host') {
 3234:         return 'not_found';
 3235:     }
 3236:     my $answer=reply("sub:$fname",$home);
 3237:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3238: 	$answer.=' by '.$home;
 3239:     }
 3240:     return $answer;
 3241: }
 3242:     
 3243: # -------------------------------------------------------------- Replicate file
 3244: 
 3245: sub repcopy {
 3246:     my $filename=shift;
 3247:     $filename=~s/\/+/\//g;
 3248:     my $londocroot = $perlvar{'lonDocRoot'};
 3249:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3250:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3251:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3252: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3253: 	return &repcopy_userfile($filename);
 3254:     }
 3255:     $filename=~s/[\n\r]//g;
 3256:     my $transname="$filename.in.transfer";
 3257: # FIXME: this should flock
 3258:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3259:     my $remoteurl=subscribe($filename);
 3260:     if ($remoteurl =~ /^con_lost by/) {
 3261: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3262:            return 'unavailable';
 3263:     } elsif ($remoteurl eq 'not_found') {
 3264: 	   #&logthis("Subscribe returned not_found: $filename");
 3265: 	   return 'not_found';
 3266:     } elsif ($remoteurl =~ /^rejected by/) {
 3267: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3268:            return 'forbidden';
 3269:     } elsif ($remoteurl eq 'directory') {
 3270:            return 'ok';
 3271:     } else {
 3272:         my $author=$filename;
 3273:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3274:         my ($udom,$uname)=split(/\//,$author);
 3275:         my $home=homeserver($uname,$udom);
 3276:         unless ($home eq $perlvar{'lonHostID'}) {
 3277:            my @parts=split(/\//,$filename);
 3278:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3279:            if ($path ne "$londocroot/res") {
 3280:                &logthis("Malconfiguration for replication: $filename");
 3281: 	       return 'bad_request';
 3282:            }
 3283:            my $count;
 3284:            for ($count=5;$count<$#parts;$count++) {
 3285:                $path.="/$parts[$count]";
 3286:                if ((-e $path)!=1) {
 3287: 		   mkdir($path,0777);
 3288:                }
 3289:            }
 3290:            my $request=new HTTP::Request('GET',"$remoteurl");
 3291:            my $response;
 3292:            if ($remoteurl =~ m{/raw/}) {
 3293:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3294:            } else {
 3295:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3296:            }
 3297:            if ($response->is_error()) {
 3298: 	       unlink($transname);
 3299:                my $message=$response->status_line;
 3300:                &logthis("<font color=\"blue\">WARNING:"
 3301:                        ." LWP get: $message: $filename</font>");
 3302:                return 'unavailable';
 3303:            } else {
 3304: 	       if ($remoteurl!~/\.meta$/) {
 3305:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3306:                   my $mresponse;
 3307:                   if ($remoteurl =~ m{/raw/}) {
 3308:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3309:                   } else {
 3310:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3311:                   }
 3312:                   if ($mresponse->is_error()) {
 3313: 		      unlink($filename.'.meta');
 3314:                       &logthis(
 3315:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3316:                   }
 3317: 	       }
 3318:                rename($transname,$filename);
 3319:                return 'ok';
 3320:            }
 3321:        }
 3322:     }
 3323: }
 3324: 
 3325: # ------------------------------------------------ Get server side include body
 3326: sub ssi_body {
 3327:     my ($filelink,%form)=@_;
 3328:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3329:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3330:     }
 3331:     my $output='';
 3332:     my $response;
 3333:     if ($filelink=~/^https?\:/) {
 3334:        ($output,$response)=&externalssi($filelink);
 3335:     } else {
 3336:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3337:        $filelink .= 'inhibitmenu=yes';
 3338:        ($output,$response)=&ssi($filelink,%form);
 3339:     }
 3340:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3341:     $output=~s/^.*?\<body[^\>]*\>//si;
 3342:     $output=~s/\<\/body\s*\>.*?$//si;
 3343:     if (wantarray) {
 3344:         return ($output, $response);
 3345:     } else {
 3346:         return $output;
 3347:     }
 3348: }
 3349: 
 3350: # --------------------------------------------------------- Server Side Include
 3351: 
 3352: sub absolute_url {
 3353:     my ($host_name) = @_;
 3354:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3355:     if ($host_name eq '') {
 3356: 	$host_name = $ENV{'SERVER_NAME'};
 3357:     }
 3358:     return $protocol.$host_name;
 3359: }
 3360: 
 3361: #
 3362: #   Server side include.
 3363: # Parameters:
 3364: #  fn     Possibly encrypted resource name/id.
 3365: #  form   Hash that describes how the rendering should be done
 3366: #         and other things.
 3367: # Returns:
 3368: #   Scalar context: The content of the response.
 3369: #   Array context:  2 element list of the content and the full response object.
 3370: #     
 3371: sub ssi {
 3372: 
 3373:     my ($fn,%form)=@_;
 3374:     my $request;
 3375: 
 3376:     $form{'no_update_last_known'}=1;
 3377:     &Apache::lonenc::check_encrypt(\$fn);
 3378:     if (%form) {
 3379:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3380:       $request->content(join('&',map { 
 3381:             my $name = escape($_);
 3382:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3383:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3384:             : &escape($form{$_}) );    
 3385:         } keys(%form)));
 3386:     } else {
 3387:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3388:     }
 3389: 
 3390:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3391:     my $lonhost = $perlvar{'lonHostID'};
 3392:     my $islocal;
 3393:     if (($env{'request.course.id'}) &&
 3394:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3395:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3396:         ($form{'grade_symb'} ne '') &&
 3397:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3398:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3399:         $islocal = 1;
 3400:     }
 3401:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3402:                                                 '','','',$islocal);
 3403: 
 3404:     if (wantarray) {
 3405: 	return ($response->content, $response);
 3406:     } else {
 3407: 	return $response->content;
 3408:     }
 3409: }
 3410: 
 3411: sub externalssi {
 3412:     my ($url)=@_;
 3413:     my $request=new HTTP::Request('GET',$url);
 3414:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3415:     if (wantarray) {
 3416:         return ($response->content, $response);
 3417:     } else {
 3418:         return $response->content;
 3419:     }
 3420: }
 3421: 
 3422: 
 3423: # If the local copy of a replicated resource is outdated, trigger a  
 3424: # connection from the homeserver to flush the delayed queue. If no update 
 3425: # happens, remove local copies of outdated resource (and corresponding
 3426: # metadata file).
 3427: 
 3428: sub remove_stale_resfile {
 3429:     my ($url) = @_;
 3430:     my $removed;
 3431:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3432:         my $audom = $1;
 3433:         my $auname = $2;
 3434:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3435:             my $homeserver = &homeserver($auname,$audom);
 3436:             unless (($homeserver eq 'no_host') ||
 3437:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3438:                 my $fname = &filelocation('',$url);
 3439:                 if (-e $fname) {
 3440:                     my $hostname = &hostname($homeserver);
 3441:                     if ($hostname) {
 3442:                         my $protocol = $protocol{$homeserver};
 3443:                         $protocol = 'http' if ($protocol ne 'https');
 3444:                         my $uri = &declutter($url);
 3445:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3446:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3447:                         if ($response->is_success()) {
 3448:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3449:                             my $locmodtime = (stat($fname))[9];
 3450:                             if ($locmodtime < $remmodtime) {
 3451:                                 my $stale;
 3452:                                 my $answer = &reply('pong',$homeserver);
 3453:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3454:                                     sleep(0.2);
 3455:                                     $locmodtime = (stat($fname))[9];
 3456:                                     if ($locmodtime < $remmodtime) {
 3457:                                         my $posstransfer = $fname.'.in.transfer';
 3458:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3459:                                             $removed = 1;
 3460:                                         } else {
 3461:                                             $stale = 1;
 3462:                                         }
 3463:                                     } else {
 3464:                                         $removed = 1;
 3465:                                     }
 3466:                                 } else {
 3467:                                     $stale = 1;
 3468:                                 }
 3469:                                 if ($stale) {
 3470:                                     unlink($fname);
 3471:                                     if ($uri!~/\.meta$/) {
 3472:                                         unlink($fname.'.meta');
 3473:                                     }
 3474:                                     &reply("unsub:$fname",$homeserver);
 3475:                                     $removed = 1;
 3476:                                 }
 3477:                             }
 3478:                         }
 3479:                     }
 3480:                 }
 3481:             }
 3482:         }
 3483:     }
 3484:     return $removed;
 3485: }
 3486: 
 3487: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3488: 
 3489: sub allowuploaded {
 3490:     my ($srcurl,$url)=@_;
 3491:     $url=&clutter(&declutter($url));
 3492:     my $dir=$url;
 3493:     $dir=~s/\/[^\/]+$//;
 3494:     my %httpref=();
 3495:     my $httpurl=&hreflocation('',$url);
 3496:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3497:     &Apache::lonnet::appenv(\%httpref);
 3498: }
 3499: 
 3500: #
 3501: # Determine if the current user should be able to edit a particular resource,
 3502: # when viewing in course context.
 3503: # (a) When viewing resource used to determine if "Edit" item is included in 
 3504: #     Functions.
 3505: # (b) When displaying folder contents in course editor, used to determine if
 3506: #     "Edit" link will be displayed alongside resource.
 3507: #
 3508: #  input: six args -- filename (decluttered), course number, course domain,
 3509: #                   url, symb (if registered) and group (if this is a group
 3510: #                   item -- e.g., bulletin board, group page etc.).
 3511: #  output: array of five scalars -- 
 3512: #          $cfile -- url for file editing if editable on current server
 3513: #          $home -- homeserver of resource (i.e., for author if published,
 3514: #                                           or course if uploaded.).
 3515: #          $switchserver --  1 if server switch will be needed.
 3516: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3517: #          $forceview -- 1 if icon/link should be to go to view mode
 3518: #
 3519: 
 3520: sub can_edit_resource {
 3521:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3522:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3523: #
 3524: # For aboutme pages user can only edit his/her own.
 3525: #
 3526:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3527:         my ($sdom,$sname) = ($1,$2);
 3528:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3529:             $home = $env{'user.home'};
 3530:             $cfile = $resurl;
 3531:             if ($env{'form.forceedit'}) {
 3532:                 $forceview = 1;
 3533:             } else {
 3534:                 $forceedit = 1;
 3535:             }
 3536:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3537:         } else {
 3538:             return;
 3539:         }
 3540:     }
 3541: 
 3542:     if ($env{'request.course.id'}) {
 3543:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3544:         if ($group ne '') {
 3545: # if this is a group homepage or group bulletin board, check group privs
 3546:             my $allowed = 0;
 3547:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3548:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3549:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3550:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3551:                     $allowed = 1;
 3552:                 }
 3553:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3554:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3555:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3556:                     $allowed = 1;
 3557:                 }
 3558:             }
 3559:             if ($allowed) {
 3560:                 $home=&homeserver($cnum,$cdom);
 3561:                 if ($env{'form.forceedit'}) {
 3562:                     $forceview = 1;
 3563:                 } else {
 3564:                     $forceedit = 1;
 3565:                 }
 3566:                 $cfile = $resurl;
 3567:             } else {
 3568:                 return;
 3569:             }
 3570:         } else {
 3571:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3572:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3573:                     return;
 3574:                 }
 3575:             } elsif (!$crsedit) {
 3576: #
 3577: # No edit allowed where CC has switched to student role.
 3578: #
 3579:                 return;
 3580:             }
 3581:         }
 3582:     }
 3583: 
 3584:     if ($file ne '') {
 3585:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3586:             if (&is_course_upload($file,$cnum,$cdom)) {
 3587:                 $uploaded = 1;
 3588:                 $incourse = 1;
 3589:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3590:                     $cfile = &hreflocation('',$file);
 3591:                     if ($env{'form.forceedit'}) {
 3592:                         $forceview = 1;
 3593:                     } else {
 3594:                         $forceedit = 1;
 3595:                     }
 3596:                 }
 3597:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3598:                 $incourse = 1;
 3599:                 if ($env{'form.forceedit'}) {
 3600:                     $forceview = 1;
 3601:                 } else {
 3602:                     $forceedit = 1;
 3603:                 }
 3604:                 $cfile = $resurl;
 3605:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3606:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3607:                     $incourse = 1;
 3608:                     if ($env{'form.forceedit'}) {
 3609:                         $forceview = 1;
 3610:                     } else {
 3611:                         $forceedit = 1;
 3612:                     }
 3613:                     $cfile = $resurl;
 3614:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3615:                     $incourse = 1;
 3616:                     $cfile = $resurl.'/smpedit';
 3617:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3618:                     $incourse = 1;
 3619:                     if ($env{'form.forceedit'}) {
 3620:                         $forceview = 1;
 3621:                     } else {
 3622:                         $forceedit = 1;
 3623:                     }
 3624:                     $cfile = $resurl;
 3625:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3626:                     $incourse = 1;
 3627:                     if ($env{'form.forceedit'}) {
 3628:                         $forceview = 1;
 3629:                     } else {
 3630:                         $forceedit = 1;
 3631:                     }
 3632:                     $cfile = $resurl;
 3633:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3634:                     $incourse = 1;
 3635:                     if ($env{'form.forceedit'}) {
 3636:                         $forceview = 1;
 3637:                     } else {
 3638:                         $forceedit = 1;
 3639:                     }
 3640:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3641:                 }
 3642:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3643:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3644:                 if (&is_on_map($template)) { 
 3645:                     $incourse = 1;
 3646:                     $forceview = 1;
 3647:                     $cfile = $template;
 3648:                 }
 3649:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3650:                     $incourse = 1;
 3651:                     if ($env{'form.forceedit'}) {
 3652:                         $forceview = 1;
 3653:                     } else {
 3654:                         $forceedit = 1;
 3655:                     }
 3656:                     $cfile = $resurl;
 3657:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3658:                 $incourse = 1;
 3659:                 if ($env{'form.forceedit'}) {
 3660:                     $forceview = 1;
 3661:                 } else {
 3662:                     $forceedit = 1;
 3663:                 }
 3664:                 $cfile = $resurl;
 3665:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3666:                 $incourse = 1;
 3667:                 $forceview = 1;
 3668:                 if ($symb) {
 3669:                     my ($map,$id,$res)=&decode_symb($symb);
 3670:                     $env{'request.symb'} = $symb;
 3671:                     $cfile = &clutter($res);
 3672:                 } else {
 3673:                     $cfile = $env{'form.suppurl'};
 3674:                     my $escfile = &unescape($cfile);
 3675:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3676:                         $cfile = '/adm/wrapper'.$escfile;
 3677:                     } else {
 3678:                         $escfile =~ s{^http://}{};
 3679:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3680:                     }
 3681:                 }
 3682:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3683:                 if ($env{'form.forceedit'}) {
 3684:                     $forceview = 1;
 3685:                 } else {
 3686:                     $forceedit = 1;
 3687:                 }
 3688:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3689:             }
 3690:         }
 3691:         if ($uploaded || $incourse) {
 3692:             $home=&homeserver($cnum,$cdom);
 3693:         } elsif ($file !~ m{/$}) {
 3694:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3695:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3696:             # Check that the user has permission to edit this resource
 3697:             my $setpriv = 1;
 3698:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3699:             if (defined($cfudom)) {
 3700:                 $home=&homeserver($cfuname,$cfudom);
 3701:                 $cfile=$file;
 3702:             }
 3703:         }
 3704:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3705:             (($home ne '') && ($home ne 'no_host'))) {
 3706:             my @ids=&current_machine_ids();
 3707:             unless (grep(/^\Q$home\E$/,@ids)) {
 3708:                 $switchserver=1;
 3709:             }
 3710:         }
 3711:     }
 3712:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3713: }
 3714: 
 3715: sub is_course_upload {
 3716:     my ($file,$cnum,$cdom) = @_;
 3717:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3718:     $uploadpath =~ s{^\/}{};
 3719:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3720:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3721:         return 1;
 3722:     }
 3723:     return;
 3724: }
 3725: 
 3726: sub in_course {
 3727:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3728:     if ($hideprivileged) {
 3729:         my $skipuser;
 3730:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3731:         my @possdoms = ($cdom);  
 3732:         if ($coursehash{'checkforpriv'}) { 
 3733:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3734:         }
 3735:         if (&privileged($uname,$udom,\@possdoms)) {
 3736:             $skipuser = 1;
 3737:             if ($coursehash{'nothideprivileged'}) {
 3738:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3739:                     my $user;
 3740:                     if ($item =~ /:/) {
 3741:                         $user = $item;
 3742:                     } else {
 3743:                         $user = join(':',split(/[\@]/,$item));
 3744:                     }
 3745:                     if ($user eq $uname.':'.$udom) {
 3746:                         undef($skipuser);
 3747:                         last;
 3748:                     }
 3749:                 }
 3750:             }
 3751:             if ($skipuser) {
 3752:                 return 0;
 3753:             }
 3754:         }
 3755:     }
 3756:     $type ||= 'any';
 3757:     if (!defined($cdom) || !defined($cnum)) {
 3758:         my $cid  = $env{'request.course.id'};
 3759:         $cdom = $env{'course.'.$cid.'.domain'};
 3760:         $cnum = $env{'course.'.$cid.'.num'};
 3761:     }
 3762:     my $typesref;
 3763:     if (($type eq 'any') || ($type eq 'all')) {
 3764:         $typesref = ['active','previous','future'];
 3765:     } elsif ($type eq 'previous' || $type eq 'future') {
 3766:         $typesref = [$type];
 3767:     }
 3768:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3769:                               $typesref,undef,[$cdom]);
 3770:     my ($tmp) = keys(%roles);
 3771:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3772:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3773:     if (@course_roles > 0) {
 3774:         return 1;
 3775:     }
 3776:     return 0;
 3777: }
 3778: 
 3779: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3780: # input: action, courseID, current domain, intended
 3781: #        path to file, source of file, instruction to parse file for objects,
 3782: #        ref to hash for embedded objects,
 3783: #        ref to hash for codebase of java objects.
 3784: #        reference to scalar to accommodate mime type determined
 3785: #          from File::MMagic if $parser = parse.
 3786: #
 3787: # output: url to file (if action was uploaddoc), 
 3788: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3789: #
 3790: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3791: # course.
 3792: #
 3793: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3794: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3795: #          course's home server.
 3796: #
 3797: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3798: #          be copied from $source (current location) to 
 3799: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3800: #         and will then be copied to
 3801: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3802: #         course's home server.
 3803: #
 3804: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3805: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3806: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3807: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3808: #         in course's home server.
 3809: #
 3810: 
 3811: sub process_coursefile {
 3812:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3813:         $mimetype)=@_;
 3814:     my $fetchresult;
 3815:     my $home=&homeserver($docuname,$docudom);
 3816:     if ($action eq 'propagate') {
 3817:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3818: 			     $home);
 3819:     } else {
 3820:         my $fpath = '';
 3821:         my $fname = $file;
 3822:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3823:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3824:         my $filepath = &build_filepath($fpath);
 3825:         if ($action eq 'copy') {
 3826:             if ($source eq '') {
 3827:                 $fetchresult = 'no source file';
 3828:                 return $fetchresult;
 3829:             } else {
 3830:                 my $destination = $filepath.'/'.$fname;
 3831:                 rename($source,$destination);
 3832:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3833:                                  $home);
 3834:             }
 3835:         } elsif ($action eq 'uploaddoc') {
 3836:             open(my $fh,'>',$filepath.'/'.$fname);
 3837:             print $fh $env{'form.'.$source};
 3838:             close($fh);
 3839:             if ($parser eq 'parse') {
 3840:                 my $mm = new File::MMagic;
 3841:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3842:                 if ($type eq 'text/html') {
 3843:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3844:                     unless ($parse_result eq 'ok') {
 3845:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3846:                     }
 3847:                 }
 3848:                 if (ref($mimetype)) {
 3849:                     $$mimetype = $type;
 3850:                 } 
 3851:             }
 3852:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3853:                                  $home);
 3854:             if ($fetchresult eq 'ok') {
 3855:                 return '/uploaded/'.$fpath.'/'.$fname;
 3856:             } else {
 3857:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3858:                         ' to host '.$home.': '.$fetchresult);
 3859:                 return '/adm/notfound.html';
 3860:             }
 3861:         }
 3862:     }
 3863:     unless ( $fetchresult eq 'ok') {
 3864:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3865:              ' to host '.$home.': '.$fetchresult);
 3866:     }
 3867:     return $fetchresult;
 3868: }
 3869: 
 3870: sub build_filepath {
 3871:     my ($fpath) = @_;
 3872:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3873:     unless ($fpath eq '') {
 3874:         my @parts=split('/',$fpath);
 3875:         foreach my $part (@parts) {
 3876:             $filepath.= '/'.$part;
 3877:             if ((-e $filepath)!=1) {
 3878:                 mkdir($filepath,0777);
 3879:             }
 3880:         }
 3881:     }
 3882:     return $filepath;
 3883: }
 3884: 
 3885: sub store_edited_file {
 3886:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3887:     my $file = $primary_url;
 3888:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3889:     my $fpath = '';
 3890:     my $fname = $file;
 3891:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3892:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3893:     my $filepath = &build_filepath($fpath);
 3894:     open(my $fh,'>',$filepath.'/'.$fname);
 3895:     print $fh $content;
 3896:     close($fh);
 3897:     my $home=&homeserver($docuname,$docudom);
 3898:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3899: 			  $home);
 3900:     if ($$fetchresult eq 'ok') {
 3901:         return '/uploaded/'.$fpath.'/'.$fname;
 3902:     } else {
 3903:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3904: 		 ' to host '.$home.': '.$$fetchresult);
 3905:         return '/adm/notfound.html';
 3906:     }
 3907: }
 3908: 
 3909: sub clean_filename {
 3910:     my ($fname,$args)=@_;
 3911: # Replace Windows backslashes by forward slashes
 3912:     $fname=~s/\\/\//g;
 3913:     if (!$args->{'keep_path'}) {
 3914:         # Get rid of everything but the actual filename
 3915: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3916:     }
 3917: # Replace spaces by underscores
 3918:     $fname=~s/\s+/\_/g;
 3919: # Transliterate non-ascii text to ascii
 3920:     my $lang = &Apache::lonlocal::current_language();
 3921:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3922: # Replace all other weird characters by nothing
 3923:     $fname=~s{[^/\w\.\-]}{}g;
 3924: # Replace all .\d. sequences with _\d. so they no longer look like version
 3925: # numbers
 3926:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3927:     return $fname;
 3928: }
 3929: 
 3930: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3931: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3932: # image with the same aspect ratio as the original, but with dimensions which do 
 3933: # not exceed $resizewidth and $resizeheight.
 3934:  
 3935: sub resizeImage {
 3936:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3937:     my $ima = Image::Magick->new;
 3938:     my $resized;
 3939:     if (-e $img_path) {
 3940:         $ima->Read($img_path);
 3941:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3942:             my $width = $ima->Get('width');
 3943:             my $height = $ima->Get('height');
 3944:             if ($width > $resizewidth) {
 3945: 	        my $factor = $width/$resizewidth;
 3946:                 my $newheight = $height/$factor;
 3947:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3948:                 $resized = 1;
 3949:             }
 3950:         }
 3951:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3952:             my $width = $ima->Get('width');
 3953:             my $height = $ima->Get('height');
 3954:             if ($height > $resizeheight) {
 3955:                 my $factor = $height/$resizeheight;
 3956:                 my $newwidth = $width/$factor;
 3957:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3958:                 $resized = 1;
 3959:             }
 3960:         }
 3961:         if ($resized) {
 3962:             $ima->Write($img_path);
 3963:         }
 3964:     }
 3965:     return;
 3966: }
 3967: 
 3968: # --------------- Take an uploaded file and put it into the userfiles directory
 3969: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3970: #                    the desired filename is in $env{"form.$formname.filename"}
 3971: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3972: #                                    canceloverwrite, scantron or ''.
 3973: #                   if 'coursedoc': upload to the current course
 3974: #                   if 'existingfile': write file to tmp/overwrites directory 
 3975: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3976: #                   $context is passed as argument to &finishuserfileupload
 3977: #        $subdir - directory in userfile to store the file into
 3978: #        $parser - instruction to parse file for objects ($parser = parse) or
 3979: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3980: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3981: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3982: #        $allfiles - reference to hash for embedded objects
 3983: #        $codebase - reference to hash for codebase of java objects
 3984: #        $desuname - username for permanent storage of uploaded file
 3985: #        $dsetudom - domain for permanaent storage of uploaded file
 3986: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3987: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3988: #        $resizewidth - width (pixels) to which to resize uploaded image
 3989: #        $resizeheight - height (pixels) to which to resize uploaded image
 3990: #        $mimetype - reference to scalar to accommodate mime type determined
 3991: #                    from File::MMagic.
 3992: # 
 3993: # output: url of file in userspace, or error: <message> 
 3994: #             or /adm/notfound.html if failure to upload occurse
 3995: 
 3996: sub userfileupload {
 3997:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3998:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3999:     if (!defined($subdir)) { $subdir='unknown'; }
 4000:     my $fname=$env{'form.'.$formname.'.filename'};
 4001:     $fname=&clean_filename($fname);
 4002:     # See if there is anything left
 4003:     unless ($fname) { return 'error: no uploaded file'; }
 4004:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4005:     if ($fname =~ /^\./) {
 4006:         my ($s,$usec) = &gettimeofday();
 4007:         while (length($usec) < 6) {
 4008:             $usec = '0'.$usec;
 4009:         }
 4010:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4011:     }
 4012:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4013:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4014:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4015:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4016:         my $now = time;
 4017:         my $filepath;
 4018:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4019:              $filepath = 'tmp/helprequests/'.$now;
 4020:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4021:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4022:                          '_'.$env{'user.domain'}.'/pending';
 4023:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4024:             my ($docuname,$docudom);
 4025:             if ($destudom =~ /^$match_domain$/) {
 4026:                 $docudom = $destudom;
 4027:             } else {
 4028:                 $docudom = $env{'user.domain'};
 4029:             }
 4030:             if ($destuname =~ /^$match_username$/) {
 4031:                 $docuname = $destuname;
 4032:             } else {
 4033:                 $docuname = $env{'user.name'};
 4034:             }
 4035:             if (exists($env{'form.group'})) {
 4036:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4037:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4038:             }
 4039:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4040:             if ($context eq 'canceloverwrite') {
 4041:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4042:                 if (-e  $tempfile) {
 4043:                     my @info = stat($tempfile);
 4044:                     if ($info[9] eq $env{'form.timestamp'}) {
 4045:                         unlink($tempfile);
 4046:                     }
 4047:                 }
 4048:                 return;
 4049:             }
 4050:         }
 4051:         # Create the directory if not present
 4052:         my @parts=split(/\//,$filepath);
 4053:         my $fullpath = $perlvar{'lonDaemons'};
 4054:         for (my $i=0;$i<@parts;$i++) {
 4055:             $fullpath .= '/'.$parts[$i];
 4056:             if ((-e $fullpath)!=1) {
 4057:                 mkdir($fullpath,0777);
 4058:             }
 4059:         }
 4060:         open(my $fh,'>',$fullpath.'/'.$fname);
 4061:         print $fh $env{'form.'.$formname};
 4062:         close($fh);
 4063:         if ($context eq 'existingfile') {
 4064:             my @info = stat($fullpath.'/'.$fname);
 4065:             return ($fullpath.'/'.$fname,$info[9]);
 4066:         } else {
 4067:             return $fullpath.'/'.$fname;
 4068:         }
 4069:     }
 4070:     if ($subdir eq 'scantron') {
 4071:         $fname = 'scantron_orig_'.$fname;
 4072:     } else {
 4073:         $fname="$subdir/$fname";
 4074:     }
 4075:     if ($context eq 'coursedoc') {
 4076: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4077: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4078:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4079:             return &finishuserfileupload($docuname,$docudom,
 4080: 					 $formname,$fname,$parser,$allfiles,
 4081: 					 $codebase,$thumbwidth,$thumbheight,
 4082:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4083:         } else {
 4084:             if ($env{'form.folder'}) {
 4085:                 $fname=$env{'form.folder'}.'/'.$fname;
 4086:             }
 4087:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4088: 				       $fname,$formname,$parser,
 4089: 				       $allfiles,$codebase,$mimetype);
 4090:         }
 4091:     } elsif (defined($destuname)) {
 4092:         my $docuname=$destuname;
 4093:         my $docudom=$destudom;
 4094: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4095: 				     $parser,$allfiles,$codebase,
 4096:                                      $thumbwidth,$thumbheight,
 4097:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4098:     } else {
 4099:         my $docuname=$env{'user.name'};
 4100:         my $docudom=$env{'user.domain'};
 4101:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4102:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4103:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4104:         }
 4105: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4106: 				     $parser,$allfiles,$codebase,
 4107:                                      $thumbwidth,$thumbheight,
 4108:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4109:     }
 4110: }
 4111: 
 4112: sub finishuserfileupload {
 4113:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4114:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4115:     my $path=$docudom.'/'.$docuname.'/';
 4116:     my $filepath=$perlvar{'lonDocRoot'};
 4117:   
 4118:     my ($fnamepath,$file,$fetchthumb);
 4119:     $file=$fname;
 4120:     if ($fname=~m|/|) {
 4121:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4122: 	$path.=$fnamepath.'/';
 4123:     }
 4124:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4125:     my $count;
 4126:     for ($count=4;$count<=$#parts;$count++) {
 4127:         $filepath.="/$parts[$count]";
 4128:         if ((-e $filepath)!=1) {
 4129: 	    mkdir($filepath,0777);
 4130:         }
 4131:     }
 4132: 
 4133: # Save the file
 4134:     {
 4135: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4136: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4137: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4138: 	    return '/adm/notfound.html';
 4139: 	}
 4140:         if ($context eq 'overwrite') {
 4141:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4142:             my $target = $filepath.'/'.$file;
 4143:             if (-e $source) {
 4144:                 my @info = stat($source);
 4145:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4146:                     unless (&File::Copy::move($source,$target)) {
 4147:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4148:                         return "Moving from $source failed";
 4149:                     }
 4150:                 } else {
 4151:                     return "Temporary file: $source had unexpected date/time for last modification";
 4152:                 }
 4153:             } else {
 4154:                 return "Temporary file: $source missing";
 4155:             }
 4156:         } elsif (!print FH ($env{'form.'.$formname})) {
 4157: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4158: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4159: 	    return '/adm/notfound.html';
 4160: 	}
 4161: 	close(FH);
 4162:         if ($resizewidth && $resizeheight) {
 4163:             my $mm = new File::MMagic;
 4164:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4165:             if ($mime_type =~ m{^image/}) {
 4166: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4167:             }  
 4168: 	}
 4169:     }
 4170:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4171:         if (ref($mimetype)) {
 4172:             if ($$mimetype eq '') {
 4173:                 my $mm = new File::MMagic;
 4174:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4175:                 $$mimetype = $type;
 4176:             }
 4177:         }
 4178:     }
 4179:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4180:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4181:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4182:                                                        $allfiles,$codebase);
 4183:             unless ($parse_result eq 'ok') {
 4184:                 &logthis('Failed to parse '.$filepath.$file.
 4185: 	   	         ' for embedded media: '.$parse_result); 
 4186:             }
 4187:         }
 4188:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4189:         my $format = $env{'form.scantron_format'};
 4190:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4191:     }
 4192:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4193:         my $input = $filepath.'/'.$file;
 4194:         my $output = $filepath.'/'.'tn-'.$file;
 4195:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4196:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4197:         system({$args[0]} @args);
 4198:         if (-e $filepath.'/'.'tn-'.$file) {
 4199:             $fetchthumb  = 1; 
 4200:         }
 4201:     }
 4202:  
 4203: # Notify homeserver to grep it
 4204: #
 4205:     my $docuhome=&homeserver($docuname,$docudom);	
 4206:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4207:     if ($fetchresult eq 'ok') {
 4208:         if ($fetchthumb) {
 4209:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4210:             if ($thumbresult ne 'ok') {
 4211:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4212:                          $docuhome.': '.$thumbresult);
 4213:             }
 4214:         }
 4215: #
 4216: # Return the URL to it
 4217:         return '/uploaded/'.$path.$file;
 4218:     } else {
 4219:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4220: 		 ': '.$fetchresult);
 4221:         return '/adm/notfound.html';
 4222:     }
 4223: }
 4224: 
 4225: sub extract_embedded_items {
 4226:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4227:     my @state = ();
 4228:     my (%lastids,%related,%shockwave,%flashvars);
 4229:     my %javafiles = (
 4230:                       codebase => '',
 4231:                       code => '',
 4232:                       archive => ''
 4233:                     );
 4234:     my %mediafiles = (
 4235:                       src => '',
 4236:                       movie => '',
 4237:                      );
 4238:     my $p;
 4239:     if ($content) {
 4240:         $p = HTML::LCParser->new($content);
 4241:     } else {
 4242:         $p = HTML::LCParser->new($fullpath);
 4243:     }
 4244:     while (my $t=$p->get_token()) {
 4245: 	if ($t->[0] eq 'S') {
 4246: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4247: 	    push(@state, $tagname);
 4248:             if (lc($tagname) eq 'allow') {
 4249:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4250:             }
 4251: 	    if (lc($tagname) eq 'img') {
 4252: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4253: 	    }
 4254: 	    if (lc($tagname) eq 'a') {
 4255:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4256:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4257:                 }
 4258: 	    }
 4259:             if (lc($tagname) eq 'script') {
 4260:                 my $src;
 4261:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4262:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4263:                 } else {
 4264:                     if ($attr->{'src'} ne '') {
 4265:                         $src = $attr->{'src'};
 4266:                         &add_filetype($allfiles,$src,'src');
 4267:                     }
 4268:                 }
 4269:                 my $text = $p->get_trimmed_text();
 4270:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4271:                     my @swfargs = split(/,/,$1);
 4272:                     foreach my $item (@swfargs) {
 4273:                         $item =~ s/["']//g;
 4274:                         $item =~ s/^\s+//;
 4275:                         $item =~ s/\s+$//;
 4276:                     }
 4277:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4278:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4279:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4280:                         } else {
 4281:                             $related{$swfargs[0]} = [$swfargs[2]];
 4282:                         }
 4283:                     }
 4284:                 }
 4285:             }
 4286:             if (lc($tagname) eq 'link') {
 4287:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4288:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4289:                 }
 4290:             }
 4291: 	    if (lc($tagname) eq 'object' ||
 4292: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4293: 		foreach my $item (keys(%javafiles)) {
 4294: 		    $javafiles{$item} = '';
 4295: 		}
 4296:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4297:                     $lastids{lc($tagname)} = $attr->{'id'};
 4298:                 }
 4299: 	    }
 4300: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4301: 		my $name = lc($attr->{'name'});
 4302: 		foreach my $item (keys(%javafiles)) {
 4303: 		    if ($name eq $item) {
 4304: 			$javafiles{$item} = $attr->{'value'};
 4305: 			last;
 4306: 		    }
 4307: 		}
 4308:                 my $pathfrom;
 4309: 		foreach my $item (keys(%mediafiles)) {
 4310: 		    if ($name eq $item) {
 4311:                         $pathfrom = $attr->{'value'};
 4312:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4313: 			&add_filetype($allfiles,$pathfrom,$name);
 4314: 			last;
 4315: 		    }
 4316: 		}
 4317:                 if ($name eq 'flashvars') {
 4318:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4319:                 }
 4320:                 if ($pathfrom ne '') {
 4321:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4322:                                          $pathfrom);
 4323:                 }
 4324: 	    }
 4325: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4326: 		foreach my $item (keys(%javafiles)) {
 4327: 		    if ($attr->{$item}) {
 4328: 			$javafiles{$item} = $attr->{$item};
 4329: 			last;
 4330: 		    }
 4331: 		}
 4332: 		foreach my $item (keys(%mediafiles)) {
 4333: 		    if ($attr->{$item}) {
 4334: 			&add_filetype($allfiles,$attr->{$item},$item);
 4335: 			last;
 4336: 		    }
 4337: 		}
 4338:                 if (lc($tagname) eq 'embed') {
 4339:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4340:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4341:                                              $attr->{'src'});
 4342:                     }
 4343:                 }
 4344: 	    }
 4345:             if (lc($tagname) eq 'iframe') {
 4346:                 my $src = $attr->{'src'} ;
 4347:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4348:                     &add_filetype($allfiles,$src,'src');
 4349:                 } elsif ($src =~ m{^/}) {
 4350:                     if ($env{'request.course.id'}) {
 4351:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4352:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4353:                         my $url = &hreflocation('',$fullpath);
 4354:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4355:                             my $relpath = $1;
 4356:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4357:                                 &add_filetype($allfiles,$1,'src');
 4358:                             }
 4359:                         }
 4360:                     }
 4361:                 }
 4362:             }
 4363:             if ($t->[4] =~ m{/>$}) {
 4364:                 pop(@state);
 4365:             }
 4366: 	} elsif ($t->[0] eq 'E') {
 4367: 	    my ($tagname) = ($t->[1]);
 4368: 	    if ($javafiles{'codebase'} ne '') {
 4369: 		$javafiles{'codebase'} .= '/';
 4370: 	    }  
 4371: 	    if (lc($tagname) eq 'applet' ||
 4372: 		lc($tagname) eq 'object' ||
 4373: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4374: 		) {
 4375: 		foreach my $item (keys(%javafiles)) {
 4376: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4377: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4378: 			&add_filetype($allfiles,$file,$item);
 4379: 		    }
 4380: 		}
 4381: 	    } 
 4382: 	    pop @state;
 4383: 	}
 4384:     }
 4385:     foreach my $id (sort(keys(%flashvars))) {
 4386:         if ($shockwave{$id} ne '') {
 4387:             my @pairs = split(/\&/,$flashvars{$id});
 4388:             foreach my $pair (@pairs) {
 4389:                 my ($key,$value) = split(/\=/,$pair);
 4390:                 if ($key eq 'thumb') {
 4391:                     &add_filetype($allfiles,$value,$key);
 4392:                 } elsif ($key eq 'content') {
 4393:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4394:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4395:                     if ($ext ne '') {
 4396:                         &add_filetype($allfiles,$path.$value,$ext);
 4397:                     }
 4398:                 }
 4399:             }
 4400:         }
 4401:     }
 4402:     return 'ok';
 4403: }
 4404: 
 4405: sub add_filetype {
 4406:     my ($allfiles,$file,$type)=@_;
 4407:     if (exists($allfiles->{$file})) {
 4408: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4409: 	    push(@{$allfiles->{$file}}, &escape($type));
 4410: 	}
 4411:     } else {
 4412: 	@{$allfiles->{$file}} = (&escape($type));
 4413:     }
 4414: }
 4415: 
 4416: sub embedded_dependency {
 4417:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4418:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4419:         if (($identifier ne '') &&
 4420:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4421:             ($pathfrom ne '')) {
 4422:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4423:             foreach my $dep (@{$related->{$identifier}}) {
 4424:                 &add_filetype($allfiles,$path.$dep,'object');
 4425:             }
 4426:         }
 4427:     }
 4428:     return;
 4429: }
 4430: 
 4431: sub bubblesheet_converter {
 4432:     my ($cdom,$fullpath,$config,$format) = @_;
 4433:     if ((&domain($cdom) ne '') &&
 4434:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4435:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4436:         my (%csvcols,%csvoptions);
 4437:         if (ref($config->{'fields'}) eq 'HASH') {  
 4438:             %csvcols = %{$config->{'fields'}};
 4439:         }
 4440:         if (ref($config->{'options'}) eq 'HASH') {
 4441:             %csvoptions = %{$config->{'options'}};
 4442:         }
 4443:         my %csvbynum = reverse(%csvcols);
 4444:         my %scantronconf = &get_scantron_config($format,$cdom);
 4445:         if (keys(%scantronconf)) {
 4446:             my %bynum = (
 4447:                           $scantronconf{CODEstart} => 'CODEstart',
 4448:                           $scantronconf{IDstart}   => 'IDstart',
 4449:                           $scantronconf{PaperID}   => 'PaperID',
 4450:                           $scantronconf{FirstName} => 'FirstName',
 4451:                           $scantronconf{LastName}  => 'LastName',
 4452:                           $scantronconf{Qstart}    => 'Qstart',
 4453:                         );
 4454:             my @ordered;
 4455:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4456:                 push(@ordered,$bynum{$item});
 4457:             }
 4458:             my %mapstart = (
 4459:                               CODEstart => 'CODE',
 4460:                               IDstart   => 'ID',
 4461:                               PaperID   => 'PaperID',
 4462:                               FirstName => 'FirstName',
 4463:                               LastName  => 'LastName',
 4464:                               Qstart    => 'FirstQuestion',
 4465:                            );
 4466:             my %maplength = (
 4467:                               CODEstart => 'CODElength',
 4468:                               IDstart   => 'IDlength',
 4469:                               PaperID   => 'PaperIDlength',
 4470:                               FirstName => 'FirstNamelength',
 4471:                               LastName  => 'LastNamelength',
 4472:             );
 4473:             if (open(my $fh,'<',$fullpath)) {
 4474:                 my $output;
 4475:                 my %lettdig = &letter_to_digits();
 4476:                 my %diglett = reverse(%lettdig);
 4477:                 my $numletts = scalar(keys(%lettdig));
 4478:                 my $num = 0;
 4479:                 while (my $line=<$fh>) {
 4480:                     $num ++;
 4481:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4482:                     $line =~ s{[\r\n]+$}{};
 4483:                     my %found;
 4484:                     my @values = split(/,/,$line);
 4485:                     my ($qstart,$record);
 4486:                     for (my $i=0; $i<@values; $i++) {
 4487:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4488:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4489:                             if ($values[$i] eq '') {
 4490:                                 $values[$i] = $scantronconf{'Qoff'};
 4491:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4492:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4493:                                     $values[$i] = $lettdig{uc($values[$i])};
 4494:                                 }
 4495:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4496:                                 if ($values[$i] =~ /^[0-9]$/) {
 4497:                                     $values[$i] = $diglett{$values[$i]};
 4498:                                 }
 4499:                             } else {
 4500:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4501:                                     my $digit;
 4502:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4503:                                         $digit = $lettdig{uc($values[$i])}-1;
 4504:                                         if ($values[$i] eq 'J') {
 4505:                                             $digit += $numletts;
 4506:                                         }
 4507:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4508:                                         $digit = $values[$i]-1;
 4509:                                         if ($values[$i] eq '0') {
 4510:                                             $digit += $numletts;
 4511:                                         }
 4512:                                     }
 4513:                                     my $qval='';
 4514:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4515:                                         if ($j == $digit) {
 4516:                                             $qval .= $scantronconf{'Qon'};
 4517:                                         } else {
 4518:                                             $qval .= $scantronconf{'Qoff'};
 4519:                                         }
 4520:                                     }
 4521:                                     $values[$i] = $qval;
 4522:                                 }
 4523:                             }
 4524:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4525:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4526:                             }
 4527:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4528:                             if ($numblank > 0) {
 4529:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4530:                             }
 4531:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4532:                                 $qstart = $i;
 4533:                                 $found{$csvbynum{$i}} = $values[$i];
 4534:                             } else {
 4535:                                 $found{'FirstQuestion'} .= $values[$i];
 4536:                             }
 4537:                         } elsif (exists($csvbynum{$i})) {
 4538:                             if ($csvoptions{'rem'}) {
 4539:                                 $values[$i] =~ s/^\s+//;
 4540:                             }
 4541:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4542:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4543:                                     $values[$i] = '0'.$values[$i];
 4544:                                 }
 4545:                             }
 4546:                             $found{$csvbynum{$i}} = $values[$i];
 4547:                         }
 4548:                     }
 4549:                     foreach my $item (@ordered) {
 4550:                         my $currlength = 1+length($record);
 4551:                         my $numspaces = $scantronconf{$item} - $currlength;
 4552:                         if ($numspaces > 0) {
 4553:                             $record .= (' ' x $numspaces);
 4554:                         }
 4555:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4556:                             unless ($item eq 'Qstart') {
 4557:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4558:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4559:                                 }
 4560:                             }
 4561:                             $record .= $found{$mapstart{$item}};
 4562:                         }
 4563:                     }
 4564:                     $output .= "$record\n";
 4565:                 }
 4566:                 close($fh);
 4567:                 if ($output) {
 4568:                     if (open(my $fh,'>',$fullpath)) {
 4569:                         print $fh $output;
 4570:                         close($fh);
 4571:                     }
 4572:                 }
 4573:             }
 4574:         }
 4575:         return;
 4576:     }
 4577: }
 4578: 
 4579: sub letter_to_digits {
 4580:     my %lettdig = (
 4581:                     A => 1,
 4582:                     B => 2,
 4583:                     C => 3,
 4584:                     D => 4,
 4585:                     E => 5,
 4586:                     F => 6,
 4587:                     G => 7,
 4588:                     H => 8,
 4589:                     I => 9,
 4590:                     J => 0,
 4591:                   );
 4592:     return %lettdig;
 4593: }
 4594: 
 4595: sub get_scantron_config {
 4596:     my ($which,$cdom) = @_;
 4597:     my @lines = &get_scantronformat_file($cdom);
 4598:     my %config;
 4599:     #FIXME probably should move to XML it has already gotten a bit much now
 4600:     foreach my $line (@lines) {
 4601:         my ($name,$descrip)=split(/:/,$line);
 4602:         if ($name ne $which ) { next; }
 4603:         chomp($line);
 4604:         my @config=split(/:/,$line);
 4605:         $config{'name'}=$config[0];
 4606:         $config{'description'}=$config[1];
 4607:         $config{'CODElocation'}=$config[2];
 4608:         $config{'CODEstart'}=$config[3];
 4609:         $config{'CODElength'}=$config[4];
 4610:         $config{'IDstart'}=$config[5];
 4611:         $config{'IDlength'}=$config[6];
 4612:         $config{'Qstart'}=$config[7];
 4613:         $config{'Qlength'}=$config[8];
 4614:         $config{'Qoff'}=$config[9];
 4615:         $config{'Qon'}=$config[10];
 4616:         $config{'PaperID'}=$config[11];
 4617:         $config{'PaperIDlength'}=$config[12];
 4618:         $config{'FirstName'}=$config[13];
 4619:         $config{'FirstNamelength'}=$config[14];
 4620:         $config{'LastName'}=$config[15];
 4621:         $config{'LastNamelength'}=$config[16];
 4622:         $config{'BubblesPerRow'}=$config[17];
 4623:         last;
 4624:     }
 4625:     return %config;
 4626: }
 4627: 
 4628: sub get_scantronformat_file {
 4629:     my ($cdom) = @_;
 4630:     if ($cdom eq '') {
 4631:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4632:     }
 4633:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4634:     my $gottab = 0;
 4635:     my @lines;
 4636:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4637:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4638:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4639:             if ($formatfile ne '-1') {
 4640:                 @lines = split("\n",$formatfile,-1);
 4641:                 $gottab = 1;
 4642:             }
 4643:         }
 4644:     }
 4645:     if (!$gottab) {
 4646:         my $confname = $cdom.'-domainconfig';
 4647:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4648:         my $formatfile = &getfile($default);
 4649:         if ($formatfile ne '-1') {
 4650:             @lines = split("\n",$formatfile,-1);
 4651:             $gottab = 1;
 4652:         }
 4653:     }
 4654:     if (!$gottab) {
 4655:         my @domains = &current_machine_domains();
 4656:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4657:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4658:                 @lines = <$fh>;
 4659:                 close($fh);
 4660:             }
 4661:         } else {
 4662:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4663:                 @lines = <$fh>;
 4664:                 close($fh);
 4665:             }
 4666:         }
 4667:     }
 4668:     return @lines;
 4669: }
 4670: 
 4671: sub removeuploadedurl {
 4672:     my ($url)=@_;	
 4673:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4674:     return &removeuserfile($uname,$udom,$fname);
 4675: }
 4676: 
 4677: sub removeuserfile {
 4678:     my ($docuname,$docudom,$fname)=@_;
 4679:     my $home=&homeserver($docuname,$docudom);    
 4680:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4681:     if ($result eq 'ok') {	
 4682:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4683:             my $metafile = $fname.'.meta';
 4684:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4685: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4686:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4687:             my $sqlresult = 
 4688:                 &update_portfolio_table($docuname,$docudom,$file,
 4689:                                         'portfolio_metadata',$group,
 4690:                                         'delete');
 4691:         }
 4692:     }
 4693:     return $result;
 4694: }
 4695: 
 4696: sub mkdiruserfile {
 4697:     my ($docuname,$docudom,$dir)=@_;
 4698:     my $home=&homeserver($docuname,$docudom);
 4699:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4700: }
 4701: 
 4702: sub renameuserfile {
 4703:     my ($docuname,$docudom,$old,$new)=@_;
 4704:     my $home=&homeserver($docuname,$docudom);
 4705:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4706:                         &escape("$old").':'.&escape("$new"),$home);
 4707:     if ($result eq 'ok') {
 4708:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4709:             my $oldmeta = $old.'.meta';
 4710:             my $newmeta = $new.'.meta';
 4711:             my $metaresult = 
 4712:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4713: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4714:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4715:             my $sqlresult = 
 4716:                 &update_portfolio_table($docuname,$docudom,$file,
 4717:                                         'portfolio_metadata',$group,
 4718:                                         'delete');
 4719:         }
 4720:     }
 4721:     return $result;
 4722: }
 4723: 
 4724: # ------------------------------------------------------------------------- Log
 4725: 
 4726: sub log {
 4727:     my ($dom,$nam,$hom,$what)=@_;
 4728:     return critical("log:$dom:$nam:$what",$hom);
 4729: }
 4730: 
 4731: # ------------------------------------------------------------------ Course Log
 4732: #
 4733: # This routine flushes several buffers of non-mission-critical nature
 4734: #
 4735: 
 4736: sub flushcourselogs {
 4737:     &logthis('Flushing log buffers');
 4738: #
 4739: # course logs
 4740: # This is a log of all transactions in a course, which can be used
 4741: # for data mining purposes
 4742: #
 4743: # It also collects the courseid database, which lists last transaction
 4744: # times and course titles for all courseids
 4745: #
 4746:     my %courseidbuffer=();
 4747:     foreach my $crsid (keys(%courselogs)) {
 4748:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4749: 		          &escape($courselogs{$crsid}),
 4750: 		          $coursehombuf{$crsid}) eq 'ok') {
 4751: 	    delete $courselogs{$crsid};
 4752:         } else {
 4753:             &logthis('Failed to flush log buffer for '.$crsid);
 4754:             if (length($courselogs{$crsid})>40000) {
 4755:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4756:                         " exceeded maximum size, deleting.</font>");
 4757:                delete $courselogs{$crsid};
 4758:             }
 4759:         }
 4760:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4761:             'description' => $coursedescrbuf{$crsid},
 4762:             'inst_code'    => $courseinstcodebuf{$crsid},
 4763:             'type'        => $coursetypebuf{$crsid},
 4764:             'owner'       => $courseownerbuf{$crsid},
 4765:         };
 4766:     }
 4767: #
 4768: # Write course id database (reverse lookup) to homeserver of courses 
 4769: # Is used in pickcourse
 4770: #
 4771:     foreach my $crs_home (keys(%courseidbuffer)) {
 4772:         my $response = &courseidput(&host_domain($crs_home),
 4773:                                     $courseidbuffer{$crs_home},
 4774:                                     $crs_home,'timeonly');
 4775:     }
 4776: #
 4777: # File accesses
 4778: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4779: #
 4780:     foreach my $entry (keys(%accesshash)) {
 4781:         if ($entry =~ /___count$/) {
 4782:             my ($dom,$name);
 4783:             ($dom,$name,undef)=
 4784: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4785:             if (! defined($dom) || $dom eq '' || 
 4786:                 ! defined($name) || $name eq '') {
 4787:                 my $cid = $env{'request.course.id'};
 4788:                 $dom  = $env{'request.'.$cid.'.domain'};
 4789:                 $name = $env{'request.'.$cid.'.num'};
 4790:             }
 4791:             my $value = $accesshash{$entry};
 4792:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4793:             my %temphash=($url => $value);
 4794:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4795:             if ($result eq 'ok') {
 4796:                 delete $accesshash{$entry};
 4797:             }
 4798:         } else {
 4799:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4800:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4801:             my %temphash=($entry => $accesshash{$entry});
 4802:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4803:                 delete $accesshash{$entry};
 4804:             }
 4805:         }
 4806:     }
 4807: #
 4808: # Roles
 4809: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4810: #
 4811:     foreach my $entry (keys(%userrolehash)) {
 4812:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4813: 	    split(/\:/,$entry);
 4814:         if (&Apache::lonnet::put('nohist_userroles',
 4815:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4816:                 $rudom,$runame) eq 'ok') {
 4817: 	    delete $userrolehash{$entry};
 4818:         }
 4819:     }
 4820: #
 4821: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4822: #
 4823:     my %domrolebuffer = ();
 4824:     foreach my $entry (keys(%domainrolehash)) {
 4825:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4826:         if ($domrolebuffer{$rudom}) {
 4827:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4828:                       '='.&escape($domainrolehash{$entry});
 4829:         } else {
 4830:             $domrolebuffer{$rudom}.=&escape($entry).
 4831:                       '='.&escape($domainrolehash{$entry});
 4832:         }
 4833:         delete $domainrolehash{$entry};
 4834:     }
 4835:     foreach my $dom (keys(%domrolebuffer)) {
 4836: 	my %servers;
 4837: 	if (defined(&domain($dom,'primary'))) {
 4838: 	    my $primary=&domain($dom,'primary');
 4839: 	    my $hostname=&hostname($primary);
 4840: 	    $servers{$primary} = $hostname;
 4841: 	} else { 
 4842: 	    %servers = &get_servers($dom,'library');
 4843: 	}
 4844: 	foreach my $tryserver (keys(%servers)) {
 4845: 	    if (&reply('domroleput:'.$dom.':'.
 4846: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4847: 		last;
 4848: 	    } else {  
 4849: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4850: 	    }
 4851:         }
 4852:     }
 4853:     $dumpcount++;
 4854: }
 4855: 
 4856: sub courselog {
 4857:     my $what=shift;
 4858:     $what=time.':'.$what;
 4859:     unless ($env{'request.course.id'}) { return ''; }
 4860:     $coursedombuf{$env{'request.course.id'}}=
 4861:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4862:     $coursenumbuf{$env{'request.course.id'}}=
 4863:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4864:     $coursehombuf{$env{'request.course.id'}}=
 4865:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4866:     $coursedescrbuf{$env{'request.course.id'}}=
 4867:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4868:     $courseinstcodebuf{$env{'request.course.id'}}=
 4869:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4870:     $courseownerbuf{$env{'request.course.id'}}=
 4871:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4872:     $coursetypebuf{$env{'request.course.id'}}=
 4873:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4874:     if (defined $courselogs{$env{'request.course.id'}}) {
 4875: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4876:     } else {
 4877: 	$courselogs{$env{'request.course.id'}}.=$what;
 4878:     }
 4879:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4880: 	&flushcourselogs();
 4881:     }
 4882: }
 4883: 
 4884: sub courseacclog {
 4885:     my $fnsymb=shift;
 4886:     unless ($env{'request.course.id'}) { return ''; }
 4887:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4888:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4889:         $what.=':POST';
 4890:         # FIXME: Probably ought to escape things....
 4891: 	foreach my $key (keys(%env)) {
 4892:             if ($key=~/^form\.(.*)/) {
 4893:                 my $formitem = $1;
 4894:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4895:                     $what.=':'.$formitem.'='.$env{$key};
 4896:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4897:                     $what.=':'.$formitem.'='.$env{$key};
 4898:                 }
 4899:             }
 4900:         }
 4901:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4902:         # FIXME: We should not be depending on a form parameter that someone
 4903:         # editing lonsearchcat.pm might change in the future.
 4904:         if ($env{'form.phase'} eq 'course_search') {
 4905:             $what.= ':POST';
 4906:             # FIXME: Probably ought to escape things....
 4907:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4908:                                  'crsdiscuss') {
 4909:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4910:             }
 4911:         }
 4912:     }
 4913:     &courselog($what);
 4914: }
 4915: 
 4916: sub countacc {
 4917:     my $url=&declutter(shift);
 4918:     return if (! defined($url) || $url eq '');
 4919:     unless ($env{'request.course.id'}) { return ''; }
 4920: #
 4921: # Mark that this url was used in this course
 4922: #
 4923:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4924: #
 4925: # Increase the access count for this resource in this child process
 4926: #
 4927:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4928:     $accesshash{$key}++;
 4929: }
 4930: 
 4931: sub linklog {
 4932:     my ($from,$to)=@_;
 4933:     $from=&declutter($from);
 4934:     $to=&declutter($to);
 4935:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4936:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4937: }
 4938: 
 4939: sub statslog {
 4940:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4941:     if ($users<2) { return; }
 4942:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4943:             'course'       => $env{'request.course.id'},
 4944:             'sections'     => '"all"',
 4945:             'num_students' => $users,
 4946:             'part'         => $part,
 4947:             'symb'         => $symb,
 4948:             'mean_tries'   => $av_attempts,
 4949:             'deg_of_diff'  => $degdiff});
 4950:     foreach my $key (keys(%dynstore)) {
 4951:         $accesshash{$key}=$dynstore{$key};
 4952:     }
 4953: }
 4954:   
 4955: sub userrolelog {
 4956:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4957:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4958:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4959:        $userrolehash
 4960:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4961:                     =$tend.':'.$tstart;
 4962:     }
 4963:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4964:        $userrolehash
 4965:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4966:                     =$tend.':'.$tstart;
 4967:     }
 4968:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4969:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4970:        $domainrolehash
 4971:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4972:                     = $tend.':'.$tstart;
 4973:     }
 4974: }
 4975: 
 4976: sub courserolelog {
 4977:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4978:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4979:         my $cdom = $1;
 4980:         my $cnum = $2;
 4981:         my $sec = $3;
 4982:         my $namespace = 'rolelog';
 4983:         my %storehash = (
 4984:                            role    => $trole,
 4985:                            start   => $tstart,
 4986:                            end     => $tend,
 4987:                            selfenroll => $selfenroll,
 4988:                            context    => $context,
 4989:                         );
 4990:         if ($trole eq 'gr') {
 4991:             $namespace = 'groupslog';
 4992:             $storehash{'group'} = $sec;
 4993:         } else {
 4994:             $storehash{'section'} = $sec;
 4995:         }
 4996:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4997:                    $domain,$cnum,$cdom);
 4998:         if (($trole ne 'st') || ($sec ne '')) {
 4999:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5000:         }
 5001:     }
 5002:     return;
 5003: }
 5004: 
 5005: sub domainrolelog {
 5006:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5007:     if ($area =~ m{^/($match_domain)/$}) {
 5008:         my $cdom = $1;
 5009:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5010:         my $namespace = 'rolelog';
 5011:         my %storehash = (
 5012:                            role    => $trole,
 5013:                            start   => $tstart,
 5014:                            end     => $tend,
 5015:                            context => $context,
 5016:                         );
 5017:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5018:                    $domain,$domconfiguser,$cdom);
 5019:     }
 5020:     return;
 5021: 
 5022: }
 5023: 
 5024: sub coauthorrolelog {
 5025:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5026:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5027:         my $audom = $1;
 5028:         my $auname = $2;
 5029:         my $namespace = 'rolelog';
 5030:         my %storehash = (
 5031:                            role    => $trole,
 5032:                            start   => $tstart,
 5033:                            end     => $tend,
 5034:                            context => $context,
 5035:                         );
 5036:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5037:                    $domain,$auname,$audom);
 5038:     }
 5039:     return;
 5040: }
 5041: 
 5042: sub get_course_adv_roles {
 5043:     my ($cid,$codes) = @_;
 5044:     $cid=$env{'request.course.id'} unless (defined($cid));
 5045:     my %coursehash=&coursedescription($cid);
 5046:     my $crstype = &Apache::loncommon::course_type($cid);
 5047:     my %nothide=();
 5048:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5049:         if ($user !~ /:/) {
 5050: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5051:         } else {
 5052:             $nothide{$user}=1;
 5053:         }
 5054:     }
 5055:     my @possdoms = ($coursehash{'domain'});
 5056:     if ($coursehash{'checkforpriv'}) {
 5057:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5058:     }
 5059:     my %returnhash=();
 5060:     my %dumphash=
 5061:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5062:     my $now=time;
 5063:     my %privileged;
 5064:     foreach my $entry (keys(%dumphash)) {
 5065: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5066:         if (($tstart) && ($tstart<0)) { next; }
 5067:         if (($tend) && ($tend<$now)) { next; }
 5068:         if (($tstart) && ($now<$tstart)) { next; }
 5069:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5070: 	if ($username eq '' || $domain eq '') { next; }
 5071:         if ((&privileged($username,$domain,\@possdoms)) &&
 5072:             (!$nothide{$username.':'.$domain})) { next; }
 5073: 	if ($role eq 'cr') { next; }
 5074:         if ($codes) {
 5075:             if ($section) { $role .= ':'.$section; }
 5076:             if ($returnhash{$role}) {
 5077:                 $returnhash{$role}.=','.$username.':'.$domain;
 5078:             } else {
 5079:                 $returnhash{$role}=$username.':'.$domain;
 5080:             }
 5081:         } else {
 5082:             my $key=&plaintext($role,$crstype);
 5083:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5084:             if ($returnhash{$key}) {
 5085: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5086:             } else {
 5087:                 $returnhash{$key}=$username.':'.$domain;
 5088:             }
 5089:         }
 5090:     }
 5091:     return %returnhash;
 5092: }
 5093: 
 5094: sub get_my_roles {
 5095:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5096:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5097:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5098:     my (%dumphash,%nothide);
 5099:     if ($context eq 'userroles') {
 5100:         %dumphash = &dump('roles',$udom,$uname);
 5101:     } else {
 5102:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5103:         if ($hidepriv) {
 5104:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5105:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5106:                 if ($user !~ /:/) {
 5107:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5108:                 } else {
 5109:                     $nothide{$user} = 1;
 5110:                 }
 5111:             }
 5112:         }
 5113:     }
 5114:     my %returnhash=();
 5115:     my $now=time;
 5116:     my %privileged;
 5117:     foreach my $entry (keys(%dumphash)) {
 5118:         my ($role,$tend,$tstart);
 5119:         if ($context eq 'userroles') {
 5120:             next if ($entry =~ /^rolesdef/);
 5121: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5122:         } else {
 5123:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5124:         }
 5125:         if (($tstart) && ($tstart<0)) { next; }
 5126:         my $status = 'active';
 5127:         if (($tend) && ($tend<=$now)) {
 5128:             $status = 'previous';
 5129:         } 
 5130:         if (($tstart) && ($now<$tstart)) {
 5131:             $status = 'future';
 5132:         }
 5133:         if (ref($types) eq 'ARRAY') {
 5134:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5135:                 next;
 5136:             } 
 5137:         } else {
 5138:             if ($status ne 'active') {
 5139:                 next;
 5140:             }
 5141:         }
 5142:         my ($rolecode,$username,$domain,$section,$area);
 5143:         if ($context eq 'userroles') {
 5144:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5145:             (undef,$domain,$username,$section) = split(/\//,$area);
 5146:         } else {
 5147:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5148:         }
 5149:         if (ref($roledoms) eq 'ARRAY') {
 5150:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5151:                 next;
 5152:             }
 5153:         }
 5154:         if (ref($roles) eq 'ARRAY') {
 5155:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5156:                 if ($role =~ /^cr\//) {
 5157:                     if (!grep(/^cr$/,@{$roles})) {
 5158:                         next;
 5159:                     }
 5160:                 } elsif ($role =~ /^gr\//) {
 5161:                     if (!grep(/^gr$/,@{$roles})) {
 5162:                         next;
 5163:                     }
 5164:                 } else {
 5165:                     next;
 5166:                 }
 5167:             }
 5168:         }
 5169:         if ($hidepriv) {
 5170:             my @privroles = ('dc','su');
 5171:             if ($context eq 'userroles') {
 5172:                 next if (grep(/^\Q$role\E$/,@privroles));
 5173:             } else {
 5174:                 my $possdoms = [$domain];
 5175:                 if (ref($roledoms) eq 'ARRAY') {
 5176:                    push(@{$possdoms},@{$roledoms}); 
 5177:                 }
 5178:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5179:                     if (!$nothide{$username.':'.$domain}) {
 5180:                         next;
 5181:                     }
 5182:                 }
 5183:             }
 5184:         }
 5185:         if ($withsec) {
 5186:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5187:                 $tstart.':'.$tend;
 5188:         } else {
 5189:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5190:         }
 5191:     }
 5192:     return %returnhash;
 5193: }
 5194: 
 5195: sub get_all_adhocroles {
 5196:     my ($dom) = @_;
 5197:     my @roles_by_num = ();
 5198:     my %domdefaults = &get_domain_defaults($dom);
 5199:     my (%description,%access_in_dom,%access_info);
 5200:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5201:         my $count = 0;
 5202:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5203:         my %ordered;
 5204:         foreach my $role (sort(keys(%domcurrent))) {
 5205:             my ($order,$desc,$access_in_dom);
 5206:             if (ref($domcurrent{$role}) eq 'HASH') {
 5207:                 $order = $domcurrent{$role}{'order'};
 5208:                 $desc = $domcurrent{$role}{'desc'};
 5209:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5210:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5211:             }
 5212:             if ($order eq '') {
 5213:                 $order = $count;
 5214:             }
 5215:             $ordered{$order} = $role;
 5216:             if ($desc ne '') {
 5217:                 $description{$role} = $desc;
 5218:             } else {
 5219:                 $description{$role}= $role;
 5220:             }
 5221:             $count++;
 5222:         }
 5223:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5224:             push(@roles_by_num,$ordered{$item});
 5225:         }
 5226:     }
 5227:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5228: }
 5229: 
 5230: sub get_my_adhocroles {
 5231:     my ($cid,$checkreg) = @_;
 5232:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5233:     if ($env{'request.course.id'} eq $cid) {
 5234:         $cdom = $env{'course.'.$cid.'.domain'};
 5235:         $cnum = $env{'course.'.$cid.'.num'};
 5236:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5237:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5238:         $cdom = $1;
 5239:         $cnum = $2;
 5240:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5241:                                      $cdom,$cnum);
 5242:     }
 5243:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5244:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5245:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5246:         if ($rosterhash{$user} ne '') {
 5247:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5248:             return ([],{}) if ($type eq 'auto');
 5249:         }
 5250:     }
 5251:     if (($cdom ne '') && ($cnum ne ''))  {
 5252:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5253:             my $then=$env{'user.login.time'};
 5254:             my $update=$env{'user.update.time'};
 5255:             if (!$update) {
 5256:                 $update = $then;
 5257:             }
 5258:             my @liveroles;
 5259:             foreach my $role ('dh','da') {
 5260:                 if ($env{"user.role.$role./$cdom/"}) {
 5261:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5262:                     my $limit = $update;
 5263:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5264:                         $limit = $then;
 5265:                     }
 5266:                     my $activerole = 1;
 5267:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5268:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5269:                     if ($activerole) {
 5270:                         push(@liveroles,$role);
 5271:                     }
 5272:                 }
 5273:             }
 5274:             if (@liveroles) {
 5275:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5276:                     my ($accessref,$accessinfo,%access_in_dom);
 5277:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5278:                     if (ref($roles_by_num) eq 'ARRAY') {
 5279:                         if (@{$roles_by_num}) {
 5280:                             my %settings;
 5281:                             if ($env{'request.course.id'} eq $cid) {
 5282:                                 foreach my $envkey (keys(%env)) {
 5283:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5284:                                         $settings{$1} = $env{$envkey};
 5285:                                     }
 5286:                                 }
 5287:                             } else {
 5288:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5289:                             }
 5290:                             my %setincrs;
 5291:                             if ($settings{'internal.adhocaccess'}) {
 5292:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5293:                             }
 5294:                             my @statuses;
 5295:                             if ($env{'environment.inststatus'}) {
 5296:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5297:                             }
 5298:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5299:                             if (ref($accessref) eq 'HASH') {
 5300:                                 %access_in_dom = %{$accessref};
 5301:                             }
 5302:                             foreach my $role (@{$roles_by_num}) {
 5303:                                 my ($curraccess,@okstatus,@personnel);
 5304:                                 if ($setincrs{$role}) {
 5305:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5306:                                     if ($curraccess eq 'status') {
 5307:                                         @okstatus = split(/\&/,$rest);
 5308:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5309:                                         @personnel = split(/\&/,$rest);
 5310:                                     }
 5311:                                 } else {
 5312:                                     $curraccess = $access_in_dom{$role};
 5313:                                     if (ref($accessinfo) eq 'HASH') {
 5314:                                         if ($curraccess eq 'status') {
 5315:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5316:                                                 @okstatus = @{$accessinfo->{$role}};
 5317:                                             }
 5318:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5319:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5320:                                                 @personnel = @{$accessinfo->{$role}};
 5321:                                             }
 5322:                                         }
 5323:                                     }
 5324:                                 }
 5325:                                 if ($curraccess eq 'none') {
 5326:                                     next;
 5327:                                 } elsif ($curraccess eq 'all') {
 5328:                                     push(@possroles,$role);
 5329:                                 } elsif ($curraccess eq 'dh') {
 5330:                                     if (grep(/^dh$/,@liveroles)) {
 5331:                                         push(@possroles,$role);
 5332:                                     } else {
 5333:                                         next;
 5334:                                     }
 5335:                                 } elsif ($curraccess eq 'da') {
 5336:                                     if (grep(/^da$/,@liveroles)) {
 5337:                                         push(@possroles,$role);
 5338:                                     } else {
 5339:                                         next;
 5340:                                     }
 5341:                                 } elsif ($curraccess eq 'status') {
 5342:                                     if (@okstatus) {
 5343:                                         if (!@statuses) {
 5344:                                             if (grep(/^default$/,@okstatus)) {
 5345:                                                 push(@possroles,$role);
 5346:                                             }
 5347:                                         } else {
 5348:                                             foreach my $status (@okstatus) {
 5349:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5350:                                                     push(@possroles,$role);
 5351:                                                     last;
 5352:                                                 }
 5353:                                             }
 5354:                                         }
 5355:                                     }
 5356:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5357:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5358:                                         if ($curraccess eq 'exc') {
 5359:                                             push(@possroles,$role);
 5360:                                         }
 5361:                                     } elsif ($curraccess eq 'inc') {
 5362:                                         push(@possroles,$role);
 5363:                                     }
 5364:                                 }
 5365:                             }
 5366:                         }
 5367:                     }
 5368:                 }
 5369:             }
 5370:         }
 5371:     }
 5372:     unless (ref($description) eq 'HASH') {
 5373:         if (ref($roles_by_num) eq 'ARRAY') {
 5374:             my %desc;
 5375:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5376:             $description = \%desc;
 5377:         } else {
 5378:             $description = {};
 5379:         }
 5380:     }
 5381:     return (\@possroles,$description);
 5382: }
 5383: 
 5384: # ----------------------------------------------------- Frontpage Announcements
 5385: #
 5386: #
 5387: 
 5388: sub postannounce {
 5389:     my ($server,$text)=@_;
 5390:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5391:     unless ($text=~/\w/) { $text=''; }
 5392:     return &reply('setannounce:'.&escape($text),$server);
 5393: }
 5394: 
 5395: sub getannounce {
 5396: 
 5397:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5398: 	my $announcement='';
 5399: 	while (my $line = <$fh>) { $announcement .= $line; }
 5400: 	close($fh);
 5401: 	if ($announcement=~/\w/) { 
 5402: 	    return 
 5403:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5404:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5405: 	} else {
 5406: 	    return '';
 5407: 	}
 5408:     } else {
 5409: 	return '';
 5410:     }
 5411: }
 5412: 
 5413: # ---------------------------------------------------------- Course ID routines
 5414: # Deal with domain's nohist_courseid.db files
 5415: #
 5416: 
 5417: sub courseidput {
 5418:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5419:     return unless (ref($storehash) eq 'HASH');
 5420:     my $outcome;
 5421:     if ($caller eq 'timeonly') {
 5422:         my $cids = '';
 5423:         foreach my $item (keys(%$storehash)) {
 5424:             $cids.=&escape($item).'&';
 5425:         }
 5426:         $cids=~s/\&$//;
 5427:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5428:                           $coursehome);       
 5429:     } else {
 5430:         my $items = '';
 5431:         foreach my $item (keys(%$storehash)) {
 5432:             $items.= &escape($item).'='.
 5433:                      &freeze_escape($$storehash{$item}).'&';
 5434:         }
 5435:         $items=~s/\&$//;
 5436:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5437:                           $coursehome);
 5438:     }
 5439:     if ($outcome eq 'unknown_cmd') {
 5440:         my $what;
 5441:         foreach my $cid (keys(%$storehash)) {
 5442:             $what .= &escape($cid).'=';
 5443:             foreach my $item ('description','inst_code','owner','type') {
 5444:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5445:             }
 5446:             $what =~ s/\:$/&/;
 5447:         }
 5448:         $what =~ s/\&$//;  
 5449:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5450:     } else {
 5451:         return $outcome;
 5452:     }
 5453: }
 5454: 
 5455: sub courseiddump {
 5456:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5457:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5458:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5459:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5460:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5461:     my $as_hash = 1;
 5462:     my %returnhash;
 5463:     if (!$domfilter) { $domfilter=''; }
 5464:     my %libserv = &all_library();
 5465:     foreach my $tryserver (keys(%libserv)) {
 5466:         if ( (  $hostidflag == 1 
 5467: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5468: 	     || (!defined($hostidflag)) ) {
 5469: 
 5470: 	    if (($domfilter eq '') ||
 5471: 		(&host_domain($tryserver) eq $domfilter)) {
 5472:                 my $rep;
 5473:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5474:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5475:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5476:                                 &escape($descfilter), &escape($instcodefilter), 
 5477:                                 &escape($ownerfilter), &escape($coursefilter),
 5478:                                 &escape($typefilter), &escape($regexp_ok), 
 5479:                                 $as_hash, &escape($selfenrollonly), 
 5480:                                 &escape($catfilter), $showhidden, $caller, 
 5481:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5482:                                 &escape($createdbefore), &escape($createdafter), 
 5483:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5484:                                 $reqcrsdom,&escape($reqinstcode))));
 5485:                 } else {
 5486:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5487:                              $sincefilter.':'.&escape($descfilter).':'.
 5488:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5489:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5490:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5491:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5492:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5493:                              &escape($cc_clone).':'.$cloneonly.':'.
 5494:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5495:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5496:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5497:                 }
 5498:                      
 5499:                 my @pairs=split(/\&/,$rep);
 5500:                 foreach my $item (@pairs) {
 5501:                     my ($key,$value)=split(/\=/,$item,2);
 5502:                     $key = &unescape($key);
 5503:                     next if ($key =~ /^error: 2 /);
 5504:                     my $result = &thaw_unescape($value);
 5505:                     if (ref($result) eq 'HASH') {
 5506:                         $returnhash{$key}=$result;
 5507:                     } else {
 5508:                         my @responses = split(/:/,$value);
 5509:                         my @items = ('description','inst_code','owner','type');
 5510:                         for (my $i=0; $i<@responses; $i++) {
 5511:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5512:                         }
 5513:                     }
 5514:                 }
 5515:             }
 5516:         }
 5517:     }
 5518:     return %returnhash;
 5519: }
 5520: 
 5521: sub courselastaccess {
 5522:     my ($cdom,$cnum,$hostidref) = @_;
 5523:     my %returnhash;
 5524:     if ($cdom && $cnum) {
 5525:         my $chome = &homeserver($cnum,$cdom);
 5526:         if ($chome ne 'no_host') {
 5527:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5528:             &extract_lastaccess(\%returnhash,$rep);
 5529:         }
 5530:     } else {
 5531:         if (!$cdom) { $cdom=''; }
 5532:         my %libserv = &all_library();
 5533:         foreach my $tryserver (keys(%libserv)) {
 5534:             if (ref($hostidref) eq 'ARRAY') {
 5535:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5536:             } 
 5537:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5538:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5539:                 &extract_lastaccess(\%returnhash,$rep);
 5540:             }
 5541:         }
 5542:     }
 5543:     return %returnhash;
 5544: }
 5545: 
 5546: sub extract_lastaccess {
 5547:     my ($returnhash,$rep) = @_;
 5548:     if (ref($returnhash) eq 'HASH') {
 5549:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5550:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5551:                  $rep eq '') {
 5552:             my @pairs=split(/\&/,$rep);
 5553:             foreach my $item (@pairs) {
 5554:                 my ($key,$value)=split(/\=/,$item,2);
 5555:                 $key = &unescape($key);
 5556:                 next if ($key =~ /^error: 2 /);
 5557:                 $returnhash->{$key} = &thaw_unescape($value);
 5558:             }
 5559:         }
 5560:     }
 5561:     return;
 5562: }
 5563: 
 5564: # ---------------------------------------------------------- DC e-mail
 5565: 
 5566: sub dcmailput {
 5567:     my ($domain,$msgid,$message,$server)=@_;
 5568:     my $status = &Apache::lonnet::critical(
 5569:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5570:        &escape($message),$server);
 5571:     return $status;
 5572: }
 5573: 
 5574: sub dcmaildump {
 5575:     my ($dom,$startdate,$enddate,$senders) = @_;
 5576:     my %returnhash=();
 5577: 
 5578:     if (defined(&domain($dom,'primary'))) {
 5579:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5580:                                                          &escape($enddate).':';
 5581: 	my @esc_senders=map { &escape($_)} @$senders;
 5582: 	$cmd.=&escape(join('&',@esc_senders));
 5583: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5584:             my ($key,$value) = split(/\=/,$line,2);
 5585:             if (($key) && ($value)) {
 5586:                 $returnhash{&unescape($key)} = &unescape($value);
 5587:             }
 5588:         }
 5589:     }
 5590:     return %returnhash;
 5591: }
 5592: # ---------------------------------------------------------- Domain roles
 5593: 
 5594: sub get_domain_roles {
 5595:     my ($dom,$roles,$startdate,$enddate)=@_;
 5596:     if ((!defined($startdate)) || ($startdate eq '')) {
 5597:         $startdate = '.';
 5598:     }
 5599:     if ((!defined($enddate)) || ($enddate eq '')) {
 5600:         $enddate = '.';
 5601:     }
 5602:     my $rolelist;
 5603:     if (ref($roles) eq 'ARRAY') {
 5604:         $rolelist = join('&',@{$roles});
 5605:     }
 5606:     my %personnel = ();
 5607: 
 5608:     my %servers = &get_servers($dom,'library');
 5609:     foreach my $tryserver (keys(%servers)) {
 5610: 	%{$personnel{$tryserver}}=();
 5611: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5612: 					    &escape($startdate).':'.
 5613: 					    &escape($enddate).':'.
 5614: 					    &escape($rolelist), $tryserver))) {
 5615: 	    my ($key,$value) = split(/\=/,$line,2);
 5616: 	    if (($key) && ($value)) {
 5617: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5618: 	    }
 5619: 	}
 5620:     }
 5621:     return %personnel;
 5622: }
 5623: 
 5624: sub get_active_domroles {
 5625:     my ($dom,$roles) = @_;
 5626:     return () unless (ref($roles) eq 'ARRAY');
 5627:     my $now = time;
 5628:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5629:     my %domroles;
 5630:     foreach my $server (keys(%dompersonnel)) {
 5631:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5632:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5633:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5634:         }
 5635:     }
 5636:     return %domroles;
 5637: }
 5638: 
 5639: # ----------------------------------------------------------- Interval timing 
 5640: 
 5641: {
 5642: # Caches needed for speedup of navmaps
 5643: # We don't want to cache this for very long at all (5 seconds at most)
 5644: # 
 5645: # The user for whom we cache
 5646: my $cachedkey='';
 5647: # The cached times for this user
 5648: my %cachedtimes=();
 5649: # When this was last done
 5650: my $cachedtime='';
 5651: 
 5652: sub load_all_first_access {
 5653:     my ($uname,$udom,$ignorecache)=@_;
 5654:     if (($cachedkey eq $uname.':'.$udom) &&
 5655:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5656:         (!$ignorecache)) {
 5657:         return;
 5658:     }
 5659:     $cachedtime=time;
 5660:     $cachedkey=$uname.':'.$udom;
 5661:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5662: }
 5663: 
 5664: sub get_first_access {
 5665:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5666:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5667:     if ($argsymb) { $symb=$argsymb; }
 5668:     my ($map,$id,$res)=&decode_symb($symb);
 5669:     if ($argmap) { $map = $argmap; }
 5670:     if ($type eq 'course') {
 5671: 	$res='course';
 5672:     } elsif ($type eq 'map') {
 5673: 	$res=&symbread($map);
 5674:     } else {
 5675: 	$res=$symb;
 5676:     }
 5677:     &load_all_first_access($uname,$udom,$ignorecache);
 5678:     return $cachedtimes{"$courseid\0$res"};
 5679: }
 5680: 
 5681: sub set_first_access {
 5682:     my ($type,$interval)=@_;
 5683:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5684:     my ($map,$id,$res)=&decode_symb($symb);
 5685:     if ($type eq 'course') {
 5686: 	$res='course';
 5687:     } elsif ($type eq 'map') {
 5688: 	$res=&symbread($map);
 5689:     } else {
 5690: 	$res=$symb;
 5691:     }
 5692:     $cachedkey='';
 5693:     my $firstaccess=&get_first_access($type,$symb,$map);
 5694:     if ($firstaccess) {
 5695:         &logthis("First access time already set ($firstaccess) when attempting ".
 5696:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5697:                  "in $courseid");
 5698:         return 'already_set';
 5699:     } else {
 5700:         my $start = time;
 5701: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5702:                           $udom,$uname);
 5703:         if ($putres eq 'ok') {
 5704:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5705:                  $udom,$uname); 
 5706:             &appenv(
 5707:                      {
 5708:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5709:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5710:                      }
 5711:                   );
 5712:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5713:                 $cachedtimes{"$courseid\0$res"} = $start;
 5714:             }
 5715:         } elsif ($putres ne 'refused') {
 5716:             &logthis("Result: $putres when attempting to set first access time ".
 5717:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5718:         }
 5719:         return $putres;
 5720:     }
 5721:     return 'already_set';
 5722: }
 5723: }
 5724: 
 5725: # --------------------------------------------- Set Expire Date for Spreadsheet
 5726: 
 5727: sub expirespread {
 5728:     my ($uname,$udom,$stype,$usymb)=@_;
 5729:     my $cid=$env{'request.course.id'}; 
 5730:     if ($cid) {
 5731:        my $now=time;
 5732:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5733:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5734:                             $env{'course.'.$cid.'.num'}.
 5735: 	        	    ':nohist_expirationdates:'.
 5736:                             &escape($key).'='.$now,
 5737:                             $env{'course.'.$cid.'.home'})
 5738:     }
 5739:     return 'ok';
 5740: }
 5741: 
 5742: # ----------------------------------------------------- Devalidate Spreadsheets
 5743: 
 5744: sub devalidate {
 5745:     my ($symb,$uname,$udom)=@_;
 5746:     my $cid=$env{'request.course.id'}; 
 5747:     if ($cid) {
 5748:         # delete the stored spreadsheets for
 5749:         # - the student level sheet of this user in course's homespace
 5750:         # - the assessment level sheet for this resource 
 5751:         #   for this user in user's homespace
 5752: 	# - current conditional state info
 5753: 	my $key=$uname.':'.$udom.':';
 5754:         my $status=
 5755: 	    &del('nohist_calculatedsheets',
 5756: 		 [$key.'studentcalc:'],
 5757: 		 $env{'course.'.$cid.'.domain'},
 5758: 		 $env{'course.'.$cid.'.num'})
 5759: 		.' '.
 5760: 	    &del('nohist_calculatedsheets_'.$cid,
 5761: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5762:         unless ($status eq 'ok ok') {
 5763:            &logthis('Could not devalidate spreadsheet '.
 5764:                     $uname.' at '.$udom.' for '.
 5765: 		    $symb.': '.$status);
 5766:         }
 5767: 	&delenv('user.state.'.$cid);
 5768:     }
 5769: }
 5770: 
 5771: sub get_scalar {
 5772:     my ($string,$end) = @_;
 5773:     my $value;
 5774:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5775: 	$value = $1;
 5776:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5777: 	$value = $1;
 5778:     }
 5779:     return &unescape($value);
 5780: }
 5781: 
 5782: sub array2str {
 5783:   my (@array) = @_;
 5784:   my $result=&arrayref2str(\@array);
 5785:   $result=~s/^__ARRAY_REF__//;
 5786:   $result=~s/__END_ARRAY_REF__$//;
 5787:   return $result;
 5788: }
 5789: 
 5790: sub arrayref2str {
 5791:   my ($arrayref) = @_;
 5792:   my $result='__ARRAY_REF__';
 5793:   foreach my $elem (@$arrayref) {
 5794:     if(ref($elem) eq 'ARRAY') {
 5795:       $result.=&arrayref2str($elem).'&';
 5796:     } elsif(ref($elem) eq 'HASH') {
 5797:       $result.=&hashref2str($elem).'&';
 5798:     } elsif(ref($elem)) {
 5799:       #print("Got a ref of ".(ref($elem))." skipping.");
 5800:     } else {
 5801:       $result.=&escape($elem).'&';
 5802:     }
 5803:   }
 5804:   $result=~s/\&$//;
 5805:   $result .= '__END_ARRAY_REF__';
 5806:   return $result;
 5807: }
 5808: 
 5809: sub hash2str {
 5810:   my (%hash) = @_;
 5811:   my $result=&hashref2str(\%hash);
 5812:   $result=~s/^__HASH_REF__//;
 5813:   $result=~s/__END_HASH_REF__$//;
 5814:   return $result;
 5815: }
 5816: 
 5817: sub hashref2str {
 5818:   my ($hashref)=@_;
 5819:   my $result='__HASH_REF__';
 5820:   foreach my $key (sort(keys(%$hashref))) {
 5821:     if (ref($key) eq 'ARRAY') {
 5822:       $result.=&arrayref2str($key).'=';
 5823:     } elsif (ref($key) eq 'HASH') {
 5824:       $result.=&hashref2str($key).'=';
 5825:     } elsif (ref($key)) {
 5826:       $result.='=';
 5827:       #print("Got a ref of ".(ref($key))." skipping.");
 5828:     } else {
 5829: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5830:     }
 5831: 
 5832:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5833:       $result.=&arrayref2str($hashref->{$key}).'&';
 5834:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5835:       $result.=&hashref2str($hashref->{$key}).'&';
 5836:     } elsif(ref($hashref->{$key})) {
 5837:        $result.='&';
 5838:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5839:     } else {
 5840:       $result.=&escape($hashref->{$key}).'&';
 5841:     }
 5842:   }
 5843:   $result=~s/\&$//;
 5844:   $result .= '__END_HASH_REF__';
 5845:   return $result;
 5846: }
 5847: 
 5848: sub str2hash {
 5849:     my ($string)=@_;
 5850:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5851:     return %$hash;
 5852: }
 5853: 
 5854: sub str2hashref {
 5855:   my ($string) = @_;
 5856: 
 5857:   my %hash;
 5858: 
 5859:   if($string !~ /^__HASH_REF__/) {
 5860:       if (! ($string eq '' || !defined($string))) {
 5861: 	  $hash{'error'}='Not hash reference';
 5862:       }
 5863:       return (\%hash, $string);
 5864:   }
 5865: 
 5866:   $string =~ s/^__HASH_REF__//;
 5867: 
 5868:   while($string !~ /^__END_HASH_REF__/) {
 5869:       #key
 5870:       my $key='';
 5871:       if($string =~ /^__HASH_REF__/) {
 5872:           ($key, $string)=&str2hashref($string);
 5873:           if(defined($key->{'error'})) {
 5874:               $hash{'error'}='Bad data';
 5875:               return (\%hash, $string);
 5876:           }
 5877:       } elsif($string =~ /^__ARRAY_REF__/) {
 5878:           ($key, $string)=&str2arrayref($string);
 5879:           if($key->[0] eq 'Array reference error') {
 5880:               $hash{'error'}='Bad data';
 5881:               return (\%hash, $string);
 5882:           }
 5883:       } else {
 5884:           $string =~ s/^(.*?)=//;
 5885: 	  $key=&unescape($1);
 5886:       }
 5887:       $string =~ s/^=//;
 5888: 
 5889:       #value
 5890:       my $value='';
 5891:       if($string =~ /^__HASH_REF__/) {
 5892:           ($value, $string)=&str2hashref($string);
 5893:           if(defined($value->{'error'})) {
 5894:               $hash{'error'}='Bad data';
 5895:               return (\%hash, $string);
 5896:           }
 5897:       } elsif($string =~ /^__ARRAY_REF__/) {
 5898:           ($value, $string)=&str2arrayref($string);
 5899:           if($value->[0] eq 'Array reference error') {
 5900:               $hash{'error'}='Bad data';
 5901:               return (\%hash, $string);
 5902:           }
 5903:       } else {
 5904: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5905:       }
 5906:       $string =~ s/^&//;
 5907: 
 5908:       $hash{$key}=$value;
 5909:   }
 5910: 
 5911:   $string =~ s/^__END_HASH_REF__//;
 5912: 
 5913:   return (\%hash, $string);
 5914: }
 5915: 
 5916: sub str2array {
 5917:     my ($string)=@_;
 5918:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5919:     return @$array;
 5920: }
 5921: 
 5922: sub str2arrayref {
 5923:   my ($string) = @_;
 5924:   my @array;
 5925: 
 5926:   if($string !~ /^__ARRAY_REF__/) {
 5927:       if (! ($string eq '' || !defined($string))) {
 5928: 	  $array[0]='Array reference error';
 5929:       }
 5930:       return (\@array, $string);
 5931:   }
 5932: 
 5933:   $string =~ s/^__ARRAY_REF__//;
 5934: 
 5935:   while($string !~ /^__END_ARRAY_REF__/) {
 5936:       my $value='';
 5937:       if($string =~ /^__HASH_REF__/) {
 5938:           ($value, $string)=&str2hashref($string);
 5939:           if(defined($value->{'error'})) {
 5940:               $array[0] ='Array reference error';
 5941:               return (\@array, $string);
 5942:           }
 5943:       } elsif($string =~ /^__ARRAY_REF__/) {
 5944:           ($value, $string)=&str2arrayref($string);
 5945:           if($value->[0] eq 'Array reference error') {
 5946:               $array[0] ='Array reference error';
 5947:               return (\@array, $string);
 5948:           }
 5949:       } else {
 5950: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5951:       }
 5952:       $string =~ s/^&//;
 5953: 
 5954:       push(@array, $value);
 5955:   }
 5956: 
 5957:   $string =~ s/^__END_ARRAY_REF__//;
 5958: 
 5959:   return (\@array, $string);
 5960: }
 5961: 
 5962: # -------------------------------------------------------------------Temp Store
 5963: 
 5964: sub tmpreset {
 5965:   my ($symb,$namespace,$domain,$stuname) = @_;
 5966:   if (!$symb) {
 5967:     $symb=&symbread();
 5968:     if (!$symb) { $symb= $env{'request.url'}; }
 5969:   }
 5970:   $symb=escape($symb);
 5971: 
 5972:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5973:   $namespace=~s/\//\_/g;
 5974:   $namespace=~s/\W//g;
 5975: 
 5976:   if (!$domain) { $domain=$env{'user.domain'}; }
 5977:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5978:   if ($domain eq 'public' && $stuname eq 'public') {
 5979:       $stuname=$ENV{'REMOTE_ADDR'};
 5980:   }
 5981:   my $path=LONCAPA::tempdir();
 5982:   my %hash;
 5983:   if (tie(%hash,'GDBM_File',
 5984: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5985: 	  &GDBM_WRCREAT(),0640)) {
 5986:     foreach my $key (keys(%hash)) {
 5987:       if ($key=~ /:$symb/) {
 5988: 	delete($hash{$key});
 5989:       }
 5990:     }
 5991:   }
 5992: }
 5993: 
 5994: sub tmpstore {
 5995:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5996: 
 5997:   if (!$symb) {
 5998:     $symb=&symbread();
 5999:     if (!$symb) { $symb= $env{'request.url'}; }
 6000:   }
 6001:   $symb=escape($symb);
 6002: 
 6003:   if (!$namespace) {
 6004:     # I don't think we would ever want to store this for a course.
 6005:     # it seems this will only be used if we don't have a course.
 6006:     #$namespace=$env{'request.course.id'};
 6007:     #if (!$namespace) {
 6008:       $namespace=$env{'request.state'};
 6009:     #}
 6010:   }
 6011:   $namespace=~s/\//\_/g;
 6012:   $namespace=~s/\W//g;
 6013:   if (!$domain) { $domain=$env{'user.domain'}; }
 6014:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6015:   if ($domain eq 'public' && $stuname eq 'public') {
 6016:       $stuname=$ENV{'REMOTE_ADDR'};
 6017:   }
 6018:   my $now=time;
 6019:   my %hash;
 6020:   my $path=LONCAPA::tempdir();
 6021:   if (tie(%hash,'GDBM_File',
 6022: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6023: 	  &GDBM_WRCREAT(),0640)) {
 6024:     $hash{"version:$symb"}++;
 6025:     my $version=$hash{"version:$symb"};
 6026:     my $allkeys=''; 
 6027:     foreach my $key (keys(%$storehash)) {
 6028:       $allkeys.=$key.':';
 6029:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6030:     }
 6031:     $hash{"$version:$symb:timestamp"}=$now;
 6032:     $allkeys.='timestamp';
 6033:     $hash{"$version:keys:$symb"}=$allkeys;
 6034:     if (untie(%hash)) {
 6035:       return 'ok';
 6036:     } else {
 6037:       return "error:$!";
 6038:     }
 6039:   } else {
 6040:     return "error:$!";
 6041:   }
 6042: }
 6043: 
 6044: # -----------------------------------------------------------------Temp Restore
 6045: 
 6046: sub tmprestore {
 6047:   my ($symb,$namespace,$domain,$stuname) = @_;
 6048: 
 6049:   if (!$symb) {
 6050:     $symb=&symbread();
 6051:     if (!$symb) { $symb= $env{'request.url'}; }
 6052:   }
 6053:   $symb=escape($symb);
 6054: 
 6055:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6056: 
 6057:   if (!$domain) { $domain=$env{'user.domain'}; }
 6058:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6059:   if ($domain eq 'public' && $stuname eq 'public') {
 6060:       $stuname=$ENV{'REMOTE_ADDR'};
 6061:   }
 6062:   my %returnhash;
 6063:   $namespace=~s/\//\_/g;
 6064:   $namespace=~s/\W//g;
 6065:   my %hash;
 6066:   my $path=LONCAPA::tempdir();
 6067:   if (tie(%hash,'GDBM_File',
 6068: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6069: 	  &GDBM_READER(),0640)) {
 6070:     my $version=$hash{"version:$symb"};
 6071:     $returnhash{'version'}=$version;
 6072:     my $scope;
 6073:     for ($scope=1;$scope<=$version;$scope++) {
 6074:       my $vkeys=$hash{"$scope:keys:$symb"};
 6075:       my @keys=split(/:/,$vkeys);
 6076:       my $key;
 6077:       $returnhash{"$scope:keys"}=$vkeys;
 6078:       foreach $key (@keys) {
 6079: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6080: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6081:       }
 6082:     }
 6083:     if (!(untie(%hash))) {
 6084:       return "error:$!";
 6085:     }
 6086:   } else {
 6087:     return "error:$!";
 6088:   }
 6089:   return %returnhash;
 6090: }
 6091: 
 6092: # ----------------------------------------------------------------------- Store
 6093: 
 6094: sub store {
 6095:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6096:     my $home='';
 6097: 
 6098:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6099: 
 6100:     $symb=&symbclean($symb);
 6101:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6102: 
 6103:     if (!$domain) { $domain=$env{'user.domain'}; }
 6104:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6105: 
 6106:     &devalidate($symb,$stuname,$domain);
 6107: 
 6108:     $symb=escape($symb);
 6109:     if (!$namespace) { 
 6110:        unless ($namespace=$env{'request.course.id'}) { 
 6111:           return ''; 
 6112:        } 
 6113:     }
 6114:     if (!$home) { $home=$env{'user.home'}; }
 6115: 
 6116:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6117:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6118: 
 6119:     my $namevalue='';
 6120:     foreach my $key (keys(%$storehash)) {
 6121:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6122:     }
 6123:     $namevalue=~s/\&$//;
 6124:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6125:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6126: }
 6127: 
 6128: # -------------------------------------------------------------- Critical Store
 6129: 
 6130: sub cstore {
 6131:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6132:     my $home='';
 6133: 
 6134:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6135: 
 6136:     $symb=&symbclean($symb);
 6137:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6138: 
 6139:     if (!$domain) { $domain=$env{'user.domain'}; }
 6140:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6141: 
 6142:     &devalidate($symb,$stuname,$domain);
 6143: 
 6144:     $symb=escape($symb);
 6145:     if (!$namespace) { 
 6146:        unless ($namespace=$env{'request.course.id'}) { 
 6147:           return ''; 
 6148:        } 
 6149:     }
 6150:     if (!$home) { $home=$env{'user.home'}; }
 6151: 
 6152:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6153:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6154: 
 6155:     my $namevalue='';
 6156:     foreach my $key (keys(%$storehash)) {
 6157:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6158:     }
 6159:     $namevalue=~s/\&$//;
 6160:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6161:     return critical
 6162:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6163: }
 6164: 
 6165: # --------------------------------------------------------------------- Restore
 6166: 
 6167: sub restore {
 6168:     my ($symb,$namespace,$domain,$stuname) = @_;
 6169:     my $home='';
 6170: 
 6171:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6172: 
 6173:     if (!$symb) {
 6174:         return if ($namespace eq 'courserequests');
 6175:         unless ($symb=escape(&symbread())) { return ''; }
 6176:     } else {
 6177:         unless ($namespace eq 'courserequests') {
 6178:             $symb=&escape(&symbclean($symb));
 6179:         }
 6180:     }
 6181:     if (!$namespace) { 
 6182:        unless ($namespace=$env{'request.course.id'}) { 
 6183:           return ''; 
 6184:        } 
 6185:     }
 6186:     if (!$domain) { $domain=$env{'user.domain'}; }
 6187:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6188:     if (!$home) { $home=$env{'user.home'}; }
 6189:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6190: 
 6191:     my %returnhash=();
 6192:     foreach my $line (split(/\&/,$answer)) {
 6193: 	my ($name,$value)=split(/\=/,$line);
 6194:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6195:     }
 6196:     my $version;
 6197:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6198:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6199:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6200:        }
 6201:     }
 6202:     return %returnhash;
 6203: }
 6204: 
 6205: # ---------------------------------------------------------- Course Description
 6206: #
 6207: #  
 6208: 
 6209: sub coursedescription {
 6210:     my ($courseid,$args)=@_;
 6211:     $courseid=~s/^\///;
 6212:     $courseid=~s/\_/\//g;
 6213:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6214:     my $chome=&homeserver($cnum,$cdomain);
 6215:     my $normalid=$cdomain.'_'.$cnum;
 6216:     # need to always cache even if we get errors otherwise we keep 
 6217:     # trying and trying and trying to get the course description.
 6218:     my %envhash=();
 6219:     my %returnhash=();
 6220:     
 6221:     my $expiretime=600;
 6222:     if ($env{'request.course.id'} eq $normalid) {
 6223: 	$expiretime=120;
 6224:     }
 6225: 
 6226:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6227:     if (!$args->{'freshen_cache'}
 6228: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6229: 	foreach my $key (keys(%env)) {
 6230: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6231: 	    my ($setting) = $1;
 6232: 	    $returnhash{$setting} = $env{$key};
 6233: 	}
 6234: 	return %returnhash;
 6235:     }
 6236: 
 6237:     # get the data again
 6238: 
 6239:     if (!$args->{'one_time'}) {
 6240: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6241:     }
 6242: 
 6243:     if ($chome ne 'no_host') {
 6244:        %returnhash=&dump('environment',$cdomain,$cnum);
 6245:        if (!exists($returnhash{'con_lost'})) {
 6246: 	   my $username = $env{'user.name'}; # Defult username
 6247: 	   if(defined $args->{'user'}) {
 6248: 	       $username = $args->{'user'};
 6249: 	   }
 6250:            $returnhash{'home'}= $chome;
 6251: 	   $returnhash{'domain'} = $cdomain;
 6252: 	   $returnhash{'num'} = $cnum;
 6253:            if (!defined($returnhash{'type'})) {
 6254:                $returnhash{'type'} = 'Course';
 6255:            }
 6256:            while (my ($name,$value) = each %returnhash) {
 6257:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6258:            }
 6259:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6260:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6261: 	       $username.'_'.$cdomain.'_'.$cnum;
 6262:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6263:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6264:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6265:        }
 6266:     }
 6267:     if (!$args->{'one_time'}) {
 6268: 	&appenv(\%envhash);
 6269:     }
 6270:     return %returnhash;
 6271: }
 6272: 
 6273: sub update_released_required {
 6274:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6275:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6276:         $cid = $env{'request.course.id'};
 6277:         $cdom = $env{'course.'.$cid.'.domain'};
 6278:         $cnum = $env{'course.'.$cid.'.num'};
 6279:         $chome = $env{'course.'.$cid.'.home'};
 6280:     }
 6281:     if ($needsrelease) {
 6282:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6283:         my $needsupdate;
 6284:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6285:             $needsupdate = 1;
 6286:         } else {
 6287:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6288:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6289:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6290:                 $needsupdate = 1;
 6291:             }
 6292:         }
 6293:         if ($needsupdate) {
 6294:             my %needshash = (
 6295:                              'internal.releaserequired' => $needsrelease,
 6296:                             );
 6297:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6298:             if ($putresult eq 'ok') {
 6299:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6300:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6301:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6302:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6303:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6304:                 }
 6305:             }
 6306:         }
 6307:     }
 6308:     return;
 6309: }
 6310: 
 6311: # -------------------------------------------------See if a user is privileged
 6312: 
 6313: sub privileged {
 6314:     my ($username,$domain,$possdomains,$possroles)=@_;
 6315:     my $now = time;
 6316:     my $roles;
 6317:     if (ref($possroles) eq 'ARRAY') {
 6318:         $roles = $possroles; 
 6319:     } else {
 6320:         $roles = ['dc','su'];
 6321:     }
 6322:     if (ref($possdomains) eq 'ARRAY') {
 6323:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6324:         foreach my $dom (@{$possdomains}) {
 6325:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6326:                 (ref($privileged{$dom}) eq 'HASH')) {
 6327:                 foreach my $role (@{$roles}) {
 6328:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6329:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6330:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6331:                             return 1 unless (($end && $end < $now) ||
 6332:                                              ($start && $start > $now));
 6333:                         }
 6334:                     }
 6335:                 }
 6336:             }
 6337:         }
 6338:     } else {
 6339:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6340:         my $now = time;
 6341: 
 6342:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6343:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6344:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6345:                 return 1 unless ($tend && $tend < $now) 
 6346:                         or ($tstart && $tstart > $now);
 6347:             }
 6348:         }
 6349:     }
 6350:     return 0;
 6351: }
 6352: 
 6353: sub privileged_by_domain {
 6354:     my ($domains,$roles) = @_;
 6355:     my %privileged = ();
 6356:     my $cachetime = 60*60*24;
 6357:     my $now = time;
 6358:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6359:         return %privileged;
 6360:     }
 6361:     foreach my $dom (@{$domains}) {
 6362:         next if (ref($privileged{$dom}) eq 'HASH');
 6363:         my $needroles;
 6364:         foreach my $role (@{$roles}) {
 6365:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6366:             if (defined($cached)) {
 6367:                 if (ref($result) eq 'HASH') {
 6368:                     $privileged{$dom}{$role} = $result;
 6369:                 }
 6370:             } else {
 6371:                 $needroles = 1;
 6372:             }
 6373:         }
 6374:         if ($needroles) {
 6375:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6376:             $privileged{$dom} = {};
 6377:             foreach my $server (keys(%dompersonnel)) {
 6378:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6379:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6380:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6381:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6382:                         next if ($end && $end < $now);
 6383:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6384:                             $dompersonnel{$server}{$item};
 6385:                     }
 6386:                 }
 6387:             }
 6388:             if (ref($privileged{$dom}) eq 'HASH') {
 6389:                 foreach my $role (@{$roles}) {
 6390:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6391:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6392:                     } else {
 6393:                         my %hash = ();
 6394:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6395:                     }
 6396:                 }
 6397:             }
 6398:         }
 6399:     }
 6400:     return %privileged;
 6401: }
 6402: 
 6403: # -------------------------------------------------------- Get user privileges
 6404: 
 6405: sub rolesinit {
 6406:     my ($domain, $username) = @_;
 6407:     my %userroles = ('user.login.time' => time);
 6408:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6409: 
 6410:     # firstaccess and timerinterval are related to timed maps/resources. 
 6411:     # also, blocking can be triggered by an activating timer
 6412:     # it's saved in the user's %env.
 6413:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6414:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6415:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6416:         %timerintchk, %timerintenv);
 6417: 
 6418:     foreach my $key (keys(%firstaccess)) {
 6419:         my ($cid, $rest) = split(/\0/, $key);
 6420:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6421:     }
 6422: 
 6423:     foreach my $key (keys(%timerinterval)) {
 6424:         my ($cid,$rest) = split(/\0/,$key);
 6425:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6426:     }
 6427: 
 6428:     my %allroles=();
 6429:     my %allgroups=();
 6430: 
 6431:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6432:         my $role = $rolesdump{$area};
 6433:         $area =~ s/\_\w\w$//;
 6434: 
 6435:         my ($trole, $tend, $tstart, $group_privs);
 6436: 
 6437:         if ($role =~ /^cr/) {
 6438:         # Custom role, defined by a user 
 6439:         # e.g., user.role.cr/msu/smith/mynewrole
 6440:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6441:                 $trole = $1;
 6442:                 ($tend, $tstart) = split('_', $2);
 6443:             } else {
 6444:                 $trole = $role;
 6445:             }
 6446:         } elsif ($role =~ m|^gr/|) {
 6447:         # Role of member in a group, defined within a course/community
 6448:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6449:             ($trole, $tend, $tstart) = split(/_/, $role);
 6450:             next if $tstart eq '-1';
 6451:             ($trole, $group_privs) = split(/\//, $trole);
 6452:             $group_privs = &unescape($group_privs);
 6453:         } else {
 6454:         # Just a normal role, defined in roles.tab
 6455:             ($trole, $tend, $tstart) = split(/_/,$role);
 6456:         }
 6457: 
 6458:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6459:                  $username);
 6460:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6461: 
 6462:         # role expired or not available yet?
 6463:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6464:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6465: 
 6466:         next if $area eq '' or $trole eq '';
 6467: 
 6468:         my $spec = "$trole.$area";
 6469:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6470: 
 6471:         if ($trole =~ /^cr\//) {
 6472:         # Custom role, defined by a user
 6473:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6474:         } elsif ($trole eq 'gr') {
 6475:         # Role of a member in a group, defined within a course/community
 6476:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6477:             next;
 6478:         } else {
 6479:         # Normal role, defined in roles.tab
 6480:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6481:         }
 6482: 
 6483:         my $cid = $tdomain.'_'.$trest;
 6484:         unless ($firstaccchk{$cid}) {
 6485:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6486:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6487:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6488:                         $coursetimerstarts{$cid}{$item}; 
 6489:                 }
 6490:             }
 6491:             $firstaccchk{$cid} = 1;
 6492:         }
 6493:         unless ($timerintchk{$cid}) {
 6494:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6495:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6496:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6497:                        $coursetimerintervals{$cid}{$item};
 6498:                 }
 6499:             }
 6500:             $timerintchk{$cid} = 1;
 6501:         }
 6502:     }
 6503: 
 6504:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6505:                                                           \%allroles, \%allgroups);
 6506:     $env{'user.adv'} = $userroles{'user.adv'};
 6507:     $env{'user.rar'} = $userroles{'user.rar'};
 6508: 
 6509:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6510: }
 6511: 
 6512: sub set_arearole {
 6513:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6514:     unless ($nolog) {
 6515: # log the associated role with the area
 6516:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6517:     }
 6518:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6519: }
 6520: 
 6521: sub custom_roleprivs {
 6522:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6523:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6524:     my $homsvr = &homeserver($rauthor,$rdomain);
 6525:     if (&hostname($homsvr) ne '') {
 6526:         my ($rdummy,$roledef)=
 6527:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6528:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6529:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6530:             if (defined($syspriv)) {
 6531:                 if ($trest =~ /^$match_community$/) {
 6532:                     $syspriv =~ s/bre\&S//; 
 6533:                 }
 6534:                 $$allroles{'cm./'}.=':'.$syspriv;
 6535:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6536:             }
 6537:             if ($tdomain ne '') {
 6538:                 if (defined($dompriv)) {
 6539:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6540:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6541:                 }
 6542:                 if (($trest ne '') && (defined($coursepriv))) {
 6543:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6544:                         my $rolename = $1;
 6545:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6546:                     }
 6547:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6548:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6549:                 }
 6550:             }
 6551:         }
 6552:     }
 6553: }
 6554: 
 6555: sub course_adhocrole_privs {
 6556:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6557:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6558:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6559:         my (%currprivs,%storeprivs);
 6560:         foreach my $item (split(/:/,$coursepriv)) {
 6561:             my ($priv,$restrict) = split(/\&/,$item);
 6562:             $currprivs{$priv} = $restrict;
 6563:         }
 6564:         my (%possadd,%possremove,%full);
 6565:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6566:             my ($priv,$restrict)=split(/\&/,$item);
 6567:             $full{$priv} = $restrict;
 6568:         }
 6569:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6570:              next if ($item eq '');
 6571:              my ($rule,$rest) = split(/=/,$item);
 6572:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6573:              foreach my $priv (split(/:/,$rest)) {
 6574:                  if ($priv ne '') {
 6575:                      if ($rule eq 'off') {
 6576:                          $possremove{$priv} = 1;
 6577:                      } else {
 6578:                          $possadd{$priv} = 1;
 6579:                      }
 6580:                  }
 6581:              }
 6582:          }
 6583:          foreach my $priv (sort(keys(%full))) {
 6584:              if (exists($currprivs{$priv})) {
 6585:                  unless (exists($possremove{$priv})) {
 6586:                      $storeprivs{$priv} = $currprivs{$priv};
 6587:                  }
 6588:              } elsif (exists($possadd{$priv})) {
 6589:                  $storeprivs{$priv} = $full{$priv};
 6590:              }
 6591:          }
 6592:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6593:      }
 6594:      return $coursepriv;
 6595: }
 6596: 
 6597: sub group_roleprivs {
 6598:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6599:     my $access = 1;
 6600:     my $now = time;
 6601:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6602:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6603:     if ($access) {
 6604:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6605:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6606:     }
 6607: }
 6608: 
 6609: sub standard_roleprivs {
 6610:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6611:     if (defined($pr{$trole.':s'})) {
 6612:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6613:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6614:     }
 6615:     if ($tdomain ne '') {
 6616:         if (defined($pr{$trole.':d'})) {
 6617:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6618:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6619:         }
 6620:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6621:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6622:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6623:         }
 6624:     }
 6625: }
 6626: 
 6627: sub set_userprivs {
 6628:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6629:     my $author=0;
 6630:     my $adv=0;
 6631:     my $rar=0;
 6632:     my %grouproles = ();
 6633:     if (keys(%{$allgroups}) > 0) {
 6634:         my @groupkeys; 
 6635:         foreach my $role (keys(%{$allroles})) {
 6636:             push(@groupkeys,$role);
 6637:         }
 6638:         if (ref($groups_roles) eq 'HASH') {
 6639:             foreach my $key (keys(%{$groups_roles})) {
 6640:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6641:                     push(@groupkeys,$key);
 6642:                 }
 6643:             }
 6644:         }
 6645:         if (@groupkeys > 0) {
 6646:             foreach my $role (@groupkeys) {
 6647:                 my ($trole,$area,$sec,$extendedarea);
 6648:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6649:                     $trole = $1;
 6650:                     $area = $2;
 6651:                     $sec = $3;
 6652:                     $extendedarea = $area.$sec;
 6653:                     if (exists($$allgroups{$area})) {
 6654:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6655:                             my $spec = $trole.'.'.$extendedarea;
 6656:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6657:                                                 $$allgroups{$area}{$group};
 6658:                         }
 6659:                     }
 6660:                 }
 6661:             }
 6662:         }
 6663:     }
 6664:     foreach my $group (keys(%grouproles)) {
 6665:         $$allroles{$group} = $grouproles{$group};
 6666:     }
 6667:     foreach my $role (keys(%{$allroles})) {
 6668:         my %thesepriv;
 6669:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6670:         foreach my $item (split(/:/,$$allroles{$role})) {
 6671:             if ($item ne '') {
 6672:                 my ($privilege,$restrictions)=split(/&/,$item);
 6673:                 if ($restrictions eq '') {
 6674:                     $thesepriv{$privilege}='F';
 6675:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6676:                     $thesepriv{$privilege}.=$restrictions;
 6677:                 }
 6678:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6679:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6680:             }
 6681:         }
 6682:         my $thesestr='';
 6683:         foreach my $priv (sort(keys(%thesepriv))) {
 6684: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6685: 	}
 6686:         $userroles->{'user.priv.'.$role} = $thesestr;
 6687:     }
 6688:     return ($author,$adv,$rar);
 6689: }
 6690: 
 6691: sub role_status {
 6692:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6693:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6694:         my ($one,$two) = split(m{\./},$rolekey,2);
 6695:         (undef,undef,$$role) = split(/\./,$one,3);
 6696:         unless (!defined($$role) || $$role eq '') {
 6697:             $$where = '/'.$two;
 6698:             $$trolecode=$$role.'.'.$$where;
 6699:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6700:             $$tstatus='is';
 6701:             if ($$tstart && $$tstart>$update) {
 6702:                 $$tstatus='future';
 6703:                 if ($$tstart<$now) {
 6704:                     if ($$tstart && $$tstart>$refresh) {
 6705:                         if (($$where ne '') && ($$role ne '')) {
 6706:                             my (%allroles,%allgroups,$group_privs,
 6707:                                 %groups_roles,@rolecodes);
 6708:                             my %userroles = (
 6709:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6710:                             );
 6711:                             @rolecodes = ('cm'); 
 6712:                             my $spec=$$role.'.'.$$where;
 6713:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6714:                             if ($$role =~ /^cr\//) {
 6715:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6716:                                 push(@rolecodes,'cr');
 6717:                             } elsif ($$role eq 'gr') {
 6718:                                 push(@rolecodes,$$role);
 6719:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6720:                                                     $env{'user.name'});
 6721:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6722:                                 (undef,my $group_privs) = split(/\//,$trole);
 6723:                                 $group_privs = &unescape($group_privs);
 6724:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6725:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6726:                                 &get_groups_roles($tdomain,$trest,
 6727:                                                   \%course_roles,\@rolecodes,
 6728:                                                   \%groups_roles);
 6729:                             } else {
 6730:                                 push(@rolecodes,$$role);
 6731:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6732:                             }
 6733:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6734:                                                                    \%groups_roles);
 6735:                             &appenv(\%userroles,\@rolecodes);
 6736:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6737:                         }
 6738:                     }
 6739:                     $$tstatus = 'is';
 6740:                 }
 6741:             }
 6742:             if ($$tend) {
 6743:                 if ($$tend<$update) {
 6744:                     $$tstatus='expired';
 6745:                 } elsif ($$tend<$now) {
 6746:                     $$tstatus='will_not';
 6747:                 }
 6748:             }
 6749:         }
 6750:     }
 6751: }
 6752: 
 6753: sub get_groups_roles {
 6754:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6755:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6756:                   (ref($rolecodes) eq 'ARRAY') && 
 6757:                   (ref($groups_roles) eq 'HASH')); 
 6758:     if (keys(%{$cdom_courseroles}) > 0) {
 6759:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6760:         if ($cdom ne '' && $cnum ne '') {
 6761:             foreach my $key (keys(%{$cdom_courseroles})) {
 6762:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6763:                     my $crsrole = $1;
 6764:                     my $crssec = $2;
 6765:                     if ($crsrole =~ /^cr/) {
 6766:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6767:                             push(@{$rolecodes},'cr');
 6768:                         }
 6769:                     } else {
 6770:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6771:                             push(@{$rolecodes},$crsrole);
 6772:                         }
 6773:                     }
 6774:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6775:                     if ($crssec ne '') {
 6776:                         $rolekey .= "/$crssec";
 6777:                     }
 6778:                     $rolekey .= './';
 6779:                     $groups_roles->{$rolekey} = $rolecodes;
 6780:                 }
 6781:             }
 6782:         }
 6783:     }
 6784:     return;
 6785: }
 6786: 
 6787: sub delete_env_groupprivs {
 6788:     my ($where,$courseroles,$possroles) = @_;
 6789:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6790:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6791:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6792:         %{$courseroles->{$udom}} =
 6793:             &get_my_roles('','','userroles',['active'],
 6794:                           $possroles,[$udom],1);
 6795:     }
 6796:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6797:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6798:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6799:             my $area = '/'.$cdom.'/'.$cnum;
 6800:             my $privkey = "user.priv.$crsrole.$area";
 6801:             if ($crssec ne '') {
 6802:                 $privkey .= '/'.$crssec;
 6803:             }
 6804:             $privkey .= ".$area/$group";
 6805:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6806:         }
 6807:     }
 6808:     return;
 6809: }
 6810: 
 6811: sub check_adhoc_privs {
 6812:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6813:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6814:     if ($sec) {
 6815:         $cckey .= '/'.$sec;
 6816:     } 
 6817:     my $setprivs;
 6818:     if ($env{$cckey}) {
 6819:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6820:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6821:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6822:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6823:             $setprivs = 1;
 6824:         }
 6825:     } else {
 6826:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6827:         $setprivs = 1;
 6828:     }
 6829:     return $setprivs;
 6830: }
 6831: 
 6832: sub set_adhoc_privileges {
 6833: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6834:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6835:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6836:     if ($sec ne '') {
 6837:         $area .= '/'.$sec;
 6838:     }
 6839:     my $spec = $role.'.'.$area;
 6840:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6841:                                   $env{'user.name'},1);
 6842:     my %rolehash = ();
 6843:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6844:         my $rolename = $1;
 6845:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6846:         my %domdef = &get_domain_defaults($dcdom);
 6847:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6848:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6849:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6850:             }
 6851:         }
 6852:     } else {
 6853:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6854:     }
 6855:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6856:     &appenv(\%userroles,[$role,'cm']);
 6857:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6858:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6859:             ($caller eq 'tiny')) {
 6860:         &appenv( {'request.role'        => $spec,
 6861:                   'request.role.domain' => $dcdom,
 6862:                   'request.course.sec'  => $sec,
 6863:                  }
 6864:                );
 6865:         my $tadv=0;
 6866:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6867:         &appenv({'request.role.adv'    => $tadv});
 6868:     }
 6869: }
 6870: 
 6871: # --------------------------------------------------------------- get interface
 6872: 
 6873: sub get {
 6874:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6875:    my $items='';
 6876:    foreach my $item (@$storearr) {
 6877:        $items.=&escape($item).'&';
 6878:    }
 6879:    $items=~s/\&$//;
 6880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6881:    if (!$uname) { $uname=$env{'user.name'}; }
 6882:    my $uhome=&homeserver($uname,$udomain);
 6883: 
 6884:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6885:    my @pairs=split(/\&/,$rep);
 6886:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6887:      return @pairs;
 6888:    }
 6889:    my %returnhash=();
 6890:    my $i=0;
 6891:    foreach my $item (@$storearr) {
 6892:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6893:       $i++;
 6894:    }
 6895:    return %returnhash;
 6896: }
 6897: 
 6898: # --------------------------------------------------------------- del interface
 6899: 
 6900: sub del {
 6901:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6902:    my $items='';
 6903:    foreach my $item (@$storearr) {
 6904:        $items.=&escape($item).'&';
 6905:    }
 6906: 
 6907:    $items=~s/\&$//;
 6908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6909:    if (!$uname) { $uname=$env{'user.name'}; }
 6910:    my $uhome=&homeserver($uname,$udomain);
 6911:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6912: }
 6913: 
 6914: # -------------------------------------------------------------- dump interface
 6915: 
 6916: sub unserialize {
 6917:     my ($rep, $escapedkeys) = @_;
 6918: 
 6919:     return {} if $rep =~ /^error/;
 6920: 
 6921:     my %returnhash=();
 6922: 	foreach my $item (split(/\&/,$rep)) {
 6923: 	    my ($key, $value) = split(/=/, $item, 2);
 6924: 	    $key = unescape($key) unless $escapedkeys;
 6925: 	    next if $key =~ /^error: 2 /;
 6926: 	    $returnhash{$key} = &thaw_unescape($value);
 6927: 	}
 6928:     #return %returnhash;
 6929:     return \%returnhash;
 6930: }        
 6931: 
 6932: # see Lond::dump_with_regexp
 6933: # if $escapedkeys hash keys won't get unescaped.
 6934: sub dump {
 6935:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6936:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6937:     if (!$uname) { $uname=$env{'user.name'}; }
 6938:     my $uhome=&homeserver($uname,$udomain);
 6939: 
 6940:     if ($regexp) {
 6941:         $regexp=&escape($regexp);
 6942:     } else {
 6943:         $regexp='.';
 6944:     }
 6945:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6946:         # user is hosted on this machine
 6947:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6948:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6949:         return %{unserialize($reply, $escapedkeys)};
 6950:     }
 6951:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6952:     my @pairs=split(/\&/,$rep);
 6953:     my %returnhash=();
 6954:     if (!($rep =~ /^error/ )) {
 6955: 	foreach my $item (@pairs) {
 6956: 	    my ($key,$value)=split(/=/,$item,2);
 6957:         $key = unescape($key) unless $escapedkeys;
 6958:         #$key = &unescape($key);
 6959: 	    next if ($key =~ /^error: 2 /);
 6960: 	    $returnhash{$key}=&thaw_unescape($value);
 6961: 	}
 6962:     }
 6963:     return %returnhash;
 6964: }
 6965: 
 6966: 
 6967: # --------------------------------------------------------- dumpstore interface
 6968: 
 6969: sub dumpstore {
 6970:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6971:    # same as dump but keys must be escaped. They may contain colon separated
 6972:    # lists of values that may themself contain colons (e.g. symbs).
 6973:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6974: }
 6975: 
 6976: # -------------------------------------------------------------- keys interface
 6977: 
 6978: sub getkeys {
 6979:    my ($namespace,$udomain,$uname)=@_;
 6980:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6981:    if (!$uname) { $uname=$env{'user.name'}; }
 6982:    my $uhome=&homeserver($uname,$udomain);
 6983:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6984:    my @keyarray=();
 6985:    foreach my $key (split(/\&/,$rep)) {
 6986:       next if ($key =~ /^error: 2 /);
 6987:       push(@keyarray,&unescape($key));
 6988:    }
 6989:    return @keyarray;
 6990: }
 6991: 
 6992: # --------------------------------------------------------------- currentdump
 6993: sub currentdump {
 6994:    my ($courseid,$sdom,$sname)=@_;
 6995:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6996:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6997:    $sname    = $env{'user.name'}         if (! defined($sname));
 6998:    my $uhome = &homeserver($sname,$sdom);
 6999:    my $rep;
 7000: 
 7001:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7002:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7003:                    $courseid)));
 7004:    } else {
 7005:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7006:    }
 7007: 
 7008:    return if ($rep =~ /^(error:|no_such_host)/);
 7009:    #
 7010:    my %returnhash=();
 7011:    #
 7012:    if ($rep eq 'unknown_cmd') {
 7013:        # an old lond will not know currentdump
 7014:        # Do a dump and make it look like a currentdump
 7015:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7016:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7017:        my %hash = @tmp;
 7018:        @tmp=();
 7019:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7020:    } else {
 7021:        my @pairs=split(/\&/,$rep);
 7022:        foreach my $pair (@pairs) {
 7023:            my ($key,$value)=split(/=/,$pair,2);
 7024:            my ($symb,$param) = split(/:/,$key);
 7025:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7026:                                                         &thaw_unescape($value);
 7027:        }
 7028:    }
 7029:    return %returnhash;
 7030: }
 7031: 
 7032: sub convert_dump_to_currentdump{
 7033:     my %hash = %{shift()};
 7034:     my %returnhash;
 7035:     # Code ripped from lond, essentially.  The only difference
 7036:     # here is the unescaping done by lonnet::dump().  Conceivably
 7037:     # we might run in to problems with parameter names =~ /^v\./
 7038:     while (my ($key,$value) = each(%hash)) {
 7039:         my ($v,$symb,$param) = split(/:/,$key);
 7040: 	$symb  = &unescape($symb);
 7041: 	$param = &unescape($param);
 7042:         next if ($v eq 'version' || $symb eq 'keys');
 7043:         next if (exists($returnhash{$symb}) &&
 7044:                  exists($returnhash{$symb}->{$param}) &&
 7045:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7046:         $returnhash{$symb}->{$param}=$value;
 7047:         $returnhash{$symb}->{'v.'.$param}=$v;
 7048:     }
 7049:     #
 7050:     # Remove all of the keys in the hashes which keep track of
 7051:     # the version of the parameter.
 7052:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7053:         # use a foreach because we are going to delete from the hash.
 7054:         foreach my $key (keys(%$param_hash)) {
 7055:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7056:         }
 7057:     }
 7058:     return \%returnhash;
 7059: }
 7060: 
 7061: # ------------------------------------------------------ critical inc interface
 7062: 
 7063: sub cinc {
 7064:     return &inc(@_,'critical');
 7065: }
 7066: 
 7067: # --------------------------------------------------------------- inc interface
 7068: 
 7069: sub inc {
 7070:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7071:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7072:     if (!$uname) { $uname=$env{'user.name'}; }
 7073:     my $uhome=&homeserver($uname,$udomain);
 7074:     my $items='';
 7075:     if (! ref($store)) {
 7076:         # got a single value, so use that instead
 7077:         $items = &escape($store).'=&';
 7078:     } elsif (ref($store) eq 'SCALAR') {
 7079:         $items = &escape($$store).'=&';        
 7080:     } elsif (ref($store) eq 'ARRAY') {
 7081:         $items = join('=&',map {&escape($_);} @{$store});
 7082:     } elsif (ref($store) eq 'HASH') {
 7083:         while (my($key,$value) = each(%{$store})) {
 7084:             $items.= &escape($key).'='.&escape($value).'&';
 7085:         }
 7086:     }
 7087:     $items=~s/\&$//;
 7088:     if ($critical) {
 7089: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7090:     } else {
 7091: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7092:     }
 7093: }
 7094: 
 7095: # --------------------------------------------------------------- put interface
 7096: 
 7097: sub put {
 7098:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7099:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7100:    if (!$uname) { $uname=$env{'user.name'}; }
 7101:    my $uhome=&homeserver($uname,$udomain);
 7102:    my $items='';
 7103:    foreach my $item (keys(%$storehash)) {
 7104:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7105:    }
 7106:    $items=~s/\&$//;
 7107:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7108: }
 7109: 
 7110: # ------------------------------------------------------------ newput interface
 7111: 
 7112: sub newput {
 7113:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7114:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7115:    if (!$uname) { $uname=$env{'user.name'}; }
 7116:    my $uhome=&homeserver($uname,$udomain);
 7117:    my $items='';
 7118:    foreach my $key (keys(%$storehash)) {
 7119:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7120:    }
 7121:    $items=~s/\&$//;
 7122:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7123: }
 7124: 
 7125: # ---------------------------------------------------------  putstore interface
 7126: 
 7127: sub putstore {
 7128:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7130:    if (!$uname) { $uname=$env{'user.name'}; }
 7131:    my $uhome=&homeserver($uname,$udomain);
 7132:    my $items='';
 7133:    foreach my $key (keys(%$storehash)) {
 7134:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7135:    }
 7136:    $items=~s/\&$//;
 7137:    my $esc_symb=&escape($symb);
 7138:    my $esc_v=&escape($version);
 7139:    my $reply =
 7140:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7141: 	      $uhome);
 7142:    if (($tolog) && ($reply eq 'ok')) {
 7143:        my $namevalue='';
 7144:        foreach my $key (keys(%{$storehash})) {
 7145:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7146:        }
 7147:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7148:                      '&host='.&escape($perlvar{'lonHostID'}).
 7149:                      '&version='.$esc_v.
 7150:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7151:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7152:    }
 7153:    if ($reply eq 'unknown_cmd') {
 7154:        # gfall back to way things use to be done
 7155:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7156: 			    $uname);
 7157:    }
 7158:    return $reply;
 7159: }
 7160: 
 7161: sub old_putstore {
 7162:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7163:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7164:     if (!$uname) { $uname=$env{'user.name'}; }
 7165:     my $uhome=&homeserver($uname,$udomain);
 7166:     my %newstorehash;
 7167:     foreach my $item (keys(%$storehash)) {
 7168: 	my $key = $version.':'.&escape($symb).':'.$item;
 7169: 	$newstorehash{$key} = $storehash->{$item};
 7170:     }
 7171:     my $items='';
 7172:     my %allitems = ();
 7173:     foreach my $item (keys(%newstorehash)) {
 7174: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7175: 	    my $key = $1.':keys:'.$2;
 7176: 	    $allitems{$key} .= $3.':';
 7177: 	}
 7178: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7179:     }
 7180:     foreach my $item (keys(%allitems)) {
 7181: 	$allitems{$item} =~ s/\:$//;
 7182: 	$items.= $item.'='.$allitems{$item}.'&';
 7183:     }
 7184:     $items=~s/\&$//;
 7185:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7186: }
 7187: 
 7188: # ------------------------------------------------------ critical put interface
 7189: 
 7190: sub cput {
 7191:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7192:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7193:    if (!$uname) { $uname=$env{'user.name'}; }
 7194:    my $uhome=&homeserver($uname,$udomain);
 7195:    my $items='';
 7196:    foreach my $item (keys(%$storehash)) {
 7197:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7198:    }
 7199:    $items=~s/\&$//;
 7200:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7201: }
 7202: 
 7203: # -------------------------------------------------------------- eget interface
 7204: 
 7205: sub eget {
 7206:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7207:    my $items='';
 7208:    foreach my $item (@$storearr) {
 7209:        $items.=&escape($item).'&';
 7210:    }
 7211:    $items=~s/\&$//;
 7212:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7213:    if (!$uname) { $uname=$env{'user.name'}; }
 7214:    my $uhome=&homeserver($uname,$udomain);
 7215:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7216:    my @pairs=split(/\&/,$rep);
 7217:    my %returnhash=();
 7218:    my $i=0;
 7219:    foreach my $item (@$storearr) {
 7220:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7221:       $i++;
 7222:    }
 7223:    return %returnhash;
 7224: }
 7225: 
 7226: # ------------------------------------------------------------ tmpput interface
 7227: sub tmpput {
 7228:     my ($storehash,$server,$context)=@_;
 7229:     my $items='';
 7230:     foreach my $item (keys(%$storehash)) {
 7231: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7232:     }
 7233:     $items=~s/\&$//;
 7234:     if (defined($context)) {
 7235:         $items .= ':'.&escape($context);
 7236:     }
 7237:     return &reply("tmpput:$items",$server);
 7238: }
 7239: 
 7240: # ------------------------------------------------------------ tmpget interface
 7241: sub tmpget {
 7242:     my ($token,$server)=@_;
 7243:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7244:     my $rep=&reply("tmpget:$token",$server);
 7245:     my %returnhash;
 7246:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7247:         return %returnhash;
 7248:     }
 7249:     foreach my $item (split(/\&/,$rep)) {
 7250: 	my ($key,$value)=split(/=/,$item);
 7251: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7252:     }
 7253:     return %returnhash;
 7254: }
 7255: 
 7256: # ------------------------------------------------------------ tmpdel interface
 7257: sub tmpdel {
 7258:     my ($token,$server)=@_;
 7259:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7260:     return &reply("tmpdel:$token",$server);
 7261: }
 7262: 
 7263: # ------------------------------------------------------------ get_timebased_id 
 7264: 
 7265: sub get_timebased_id {
 7266:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7267:         $maxtries) = @_;
 7268:     my ($newid,$error,$dellock);
 7269:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7270:         return ('','ok','invalid call to get suffix');
 7271:     }
 7272: 
 7273: # set defaults for any optional args for which values were not supplied
 7274:     if ($who eq '') {
 7275:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7276:     }
 7277:     if (!$locktries) {
 7278:         $locktries = 3;
 7279:     }
 7280:     if (!$maxtries) {
 7281:         $maxtries = 10;
 7282:     }
 7283:     
 7284:     if (($cdom eq '') || ($cnum eq '')) {
 7285:         if ($env{'request.course.id'}) {
 7286:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7287:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7288:         }
 7289:         if (($cdom eq '') || ($cnum eq '')) {
 7290:             return ('','ok','call to get suffix not in course context');
 7291:         }
 7292:     }
 7293: 
 7294: # construct locking item
 7295:     my $lockhash = {
 7296:                       $prefix."\0".'locked_'.$keyid => $who,
 7297:                    };
 7298:     my $tries = 0;
 7299: 
 7300: # attempt to get lock on nohist_$namespace file
 7301:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7302:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7303:         $tries ++;
 7304:         sleep 1;
 7305:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7306:     }
 7307: 
 7308: # attempt to get unique identifier, based on current timestamp
 7309:     if ($gotlock eq 'ok') {
 7310:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7311:         my $id = time;
 7312:         $newid = $id;
 7313:         if ($idtype eq 'addcode') {
 7314:             $newid .= &sixnum_code();
 7315:         }
 7316:         my $idtries = 0;
 7317:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7318:             if ($idtype eq 'concat') {
 7319:                 $newid = $id.$idtries;
 7320:             } elsif ($idtype eq 'addcode') {
 7321:                 $newid = $newid.&sixnum_code();
 7322:             } else {
 7323:                 $newid ++;
 7324:             }
 7325:             $idtries ++;
 7326:         }
 7327:         if (!exists($inuse{$prefix."\0".$newid})) {
 7328:             my %new_item =  (
 7329:                               $prefix."\0".$newid => $who,
 7330:                             );
 7331:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7332:                                                  $cdom,$cnum);
 7333:             if ($putresult ne 'ok') {
 7334:                 undef($newid);
 7335:                 $error = 'error saving new item: '.$putresult;
 7336:             }
 7337:         } else {
 7338:              undef($newid);
 7339:              $error = ('error: no unique suffix available for the new item ');
 7340:         }
 7341: #  remove lock
 7342:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7343:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7344:     } else {
 7345:         $error = "error: could not obtain lockfile\n";
 7346:         $dellock = 'ok';
 7347:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7348:             $dellock = 'nolock';
 7349:         }
 7350:     }
 7351:     return ($newid,$dellock,$error);
 7352: }
 7353: 
 7354: sub sixnum_code {
 7355:     my $code;
 7356:     for (0..6) {
 7357:         $code .= int( rand(9) );
 7358:     }
 7359:     return $code;
 7360: }
 7361: 
 7362: # -------------------------------------------------- portfolio access checking
 7363: 
 7364: sub portfolio_access {
 7365:     my ($requrl,$clientip) = @_;
 7366:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7367:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7368:     if ($result) {
 7369:         my %setters;
 7370:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7371:             my ($startblock,$endblock) =
 7372:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7373:             if ($startblock && $endblock) {
 7374:                 return 'B';
 7375:             }
 7376:         } else {
 7377:             my ($startblock,$endblock) =
 7378:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7379:             if ($startblock && $endblock) {
 7380:                 return 'B';
 7381:             }
 7382:         }
 7383:     }
 7384:     if ($result eq 'ok') {
 7385:        return 'F';
 7386:     } elsif ($result =~ /^[^:]+:guest_/) {
 7387:        return 'A';
 7388:     }
 7389:     return '';
 7390: }
 7391: 
 7392: sub get_portfolio_access {
 7393:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7394: 
 7395:     if (!ref($access_hash)) {
 7396: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7397: 	my %access_controls = &get_access_controls($current_perms,$group,
 7398: 						   $file_name);
 7399: 	$access_hash = $access_controls{$file_name};
 7400:     }
 7401: 
 7402:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7403:     my $now = time;
 7404:     if (ref($access_hash) eq 'HASH') {
 7405:         foreach my $key (keys(%{$access_hash})) {
 7406:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7407:             if ($start > $now) {
 7408:                 next;
 7409:             }
 7410:             if ($end && $end<$now) {
 7411:                 next;
 7412:             }
 7413:             if ($scope eq 'public') {
 7414:                 $public = $key;
 7415:                 last;
 7416:             } elsif ($scope eq 'guest') {
 7417:                 $guest = $key;
 7418:             } elsif ($scope eq 'domains') {
 7419:                 push(@domains,$key);
 7420:             } elsif ($scope eq 'users') {
 7421:                 push(@users,$key);
 7422:             } elsif ($scope eq 'course') {
 7423:                 push(@courses,$key);
 7424:             } elsif ($scope eq 'group') {
 7425:                 push(@groups,$key);
 7426:             } elsif ($scope eq 'ip') {
 7427:                 push(@ips,$key);
 7428:             }
 7429:         }
 7430:         if ($public) {
 7431:             return 'ok';
 7432:         } elsif (@ips > 0) {
 7433:             my $allowed;
 7434:             foreach my $ipkey (@ips) {
 7435:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7436:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7437:                         $allowed = 1;
 7438:                         last; 
 7439:                     }
 7440:                 }
 7441:             }
 7442:             if ($allowed) {
 7443:                 return 'ok';
 7444:             }
 7445:         }
 7446:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7447:             if ($guest) {
 7448:                 return $guest;
 7449:             }
 7450:         } else {
 7451:             if (@domains > 0) {
 7452:                 foreach my $domkey (@domains) {
 7453:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7454:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7455:                             return 'ok';
 7456:                         }
 7457:                     }
 7458:                 }
 7459:             }
 7460:             if (@users > 0) {
 7461:                 foreach my $userkey (@users) {
 7462:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7463:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7464:                             if (ref($item) eq 'HASH') {
 7465:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7466:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7467:                                     return 'ok';
 7468:                                 }
 7469:                             }
 7470:                         }
 7471:                     } 
 7472:                 }
 7473:             }
 7474:             my %roleshash;
 7475:             my @courses_and_groups = @courses;
 7476:             push(@courses_and_groups,@groups); 
 7477:             if (@courses_and_groups > 0) {
 7478:                 my (%allgroups,%allroles); 
 7479:                 my ($start,$end,$role,$sec,$group);
 7480:                 foreach my $envkey (%env) {
 7481:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7482:                         my $cid = $2.'_'.$3; 
 7483:                         if ($1 eq 'gr') {
 7484:                             $group = $4;
 7485:                             $allgroups{$cid}{$group} = $env{$envkey};
 7486:                         } else {
 7487:                             if ($4 eq '') {
 7488:                                 $sec = 'none';
 7489:                             } else {
 7490:                                 $sec = $4;
 7491:                             }
 7492:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7493:                         }
 7494:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7495:                         my $cid = $2.'_'.$3;
 7496:                         if ($4 eq '') {
 7497:                             $sec = 'none';
 7498:                         } else {
 7499:                             $sec = $4;
 7500:                         }
 7501:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7502:                     }
 7503:                 }
 7504:                 if (keys(%allroles) == 0) {
 7505:                     return;
 7506:                 }
 7507:                 foreach my $key (@courses_and_groups) {
 7508:                     my %content = %{$$access_hash{$key}};
 7509:                     my $cnum = $content{'number'};
 7510:                     my $cdom = $content{'domain'};
 7511:                     my $cid = $cdom.'_'.$cnum;
 7512:                     if (!exists($allroles{$cid})) {
 7513:                         next;
 7514:                     }    
 7515:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7516:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7517:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7518:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7519:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7520:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7521:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7522:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7523:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7524:                                         if (grep/^all$/,@sections) {
 7525:                                             return 'ok';
 7526:                                         } else {
 7527:                                             if (grep/^$sec$/,@sections) {
 7528:                                                 return 'ok';
 7529:                                             }
 7530:                                         }
 7531:                                     }
 7532:                                 }
 7533:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7534:                                     if (grep/^none$/,@groups) {
 7535:                                         return 'ok';
 7536:                                     }
 7537:                                 } else {
 7538:                                     if (grep/^all$/,@groups) {
 7539:                                         return 'ok';
 7540:                                     } 
 7541:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7542:                                         if (grep/^$group$/,@groups) {
 7543:                                             return 'ok';
 7544:                                         }
 7545:                                     }
 7546:                                 } 
 7547:                             }
 7548:                         }
 7549:                     }
 7550:                 }
 7551:             }
 7552:             if ($guest) {
 7553:                 return $guest;
 7554:             }
 7555:         }
 7556:     }
 7557:     return;
 7558: }
 7559: 
 7560: sub course_group_datechecker {
 7561:     my ($dates,$now,$status) = @_;
 7562:     my ($start,$end) = split(/\./,$dates);
 7563:     if (!$start && !$end) {
 7564:         return 'ok';
 7565:     }
 7566:     if (grep/^active$/,@{$status}) {
 7567:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7568:             return 'ok';
 7569:         }
 7570:     }
 7571:     if (grep/^previous$/,@{$status}) {
 7572:         if ($end > $now ) {
 7573:             return 'ok';
 7574:         }
 7575:     }
 7576:     if (grep/^future$/,@{$status}) {
 7577:         if ($start > $now) {
 7578:             return 'ok';
 7579:         }
 7580:     }
 7581:     return; 
 7582: }
 7583: 
 7584: sub parse_portfolio_url {
 7585:     my ($url) = @_;
 7586: 
 7587:     my ($type,$udom,$unum,$group,$file_name);
 7588:     
 7589:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7590: 	$type = 1;
 7591:         $udom = $1;
 7592:         $unum = $2;
 7593:         $file_name = $3;
 7594:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7595: 	$type = 2;
 7596:         $udom = $1;
 7597:         $unum = $2;
 7598:         $group = $3;
 7599:         $file_name = $3.'/'.$4;
 7600:     }
 7601:     if (wantarray) {
 7602: 	return ($type,$udom,$unum,$file_name,$group);
 7603:     }
 7604:     return $type;
 7605: }
 7606: 
 7607: sub is_portfolio_url {
 7608:     my ($url) = @_;
 7609:     return scalar(&parse_portfolio_url($url));
 7610: }
 7611: 
 7612: sub is_portfolio_file {
 7613:     my ($file) = @_;
 7614:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7615:         return 1;
 7616:     }
 7617:     return;
 7618: }
 7619: 
 7620: sub usertools_access {
 7621:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7622:     my ($access,%tools);
 7623:     if ($context eq '') {
 7624:         $context = 'tools';
 7625:     }
 7626:     if ($context eq 'requestcourses') {
 7627:         %tools = (
 7628:                       official   => 1,
 7629:                       unofficial => 1,
 7630:                       community  => 1,
 7631:                       textbook   => 1,
 7632:                       placement  => 1,
 7633:                       lti        => 1,
 7634:                  );
 7635:     } elsif ($context eq 'requestauthor') {
 7636:         %tools = (
 7637:                       requestauthor => 1,
 7638:                  );
 7639:     } else {
 7640:         %tools = (
 7641:                       aboutme   => 1,
 7642:                       blog      => 1,
 7643:                       webdav    => 1,
 7644:                       portfolio => 1,
 7645:                  );
 7646:     }
 7647:     return if (!defined($tools{$tool}));
 7648: 
 7649:     if (($udom eq '') || ($uname eq '')) {
 7650:         $udom = $env{'user.domain'};
 7651:         $uname = $env{'user.name'};
 7652:     }
 7653: 
 7654:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7655:         if ($action ne 'reload') {
 7656:             if ($context eq 'requestcourses') {
 7657:                 return $env{'environment.canrequest.'.$tool};
 7658:             } elsif ($context eq 'requestauthor') {
 7659:                 return $env{'environment.canrequest.author'};
 7660:             } else {
 7661:                 return $env{'environment.availabletools.'.$tool};
 7662:             }
 7663:         }
 7664:     }
 7665: 
 7666:     my ($toolstatus,$inststatus,$envkey);
 7667:     if ($context eq 'requestauthor') {
 7668:         $envkey = $context; 
 7669:     } else {
 7670:         $envkey = $context.'.'.$tool;
 7671:     }
 7672: 
 7673:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7674:          ($action ne 'reload')) {
 7675:         $toolstatus = $env{'environment.'.$envkey};
 7676:         $inststatus = $env{'environment.inststatus'};
 7677:     } else {
 7678:         if (ref($userenvref) eq 'HASH') {
 7679:             $toolstatus = $userenvref->{$envkey};
 7680:             $inststatus = $userenvref->{'inststatus'};
 7681:         } else {
 7682:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7683:             $toolstatus = $userenv{$envkey};
 7684:             $inststatus = $userenv{'inststatus'};
 7685:         }
 7686:     }
 7687: 
 7688:     if ($toolstatus ne '') {
 7689:         if ($toolstatus) {
 7690:             $access = 1;
 7691:         } else {
 7692:             $access = 0;
 7693:         }
 7694:         return $access;
 7695:     }
 7696: 
 7697:     my ($is_adv,%domdef);
 7698:     if (ref($is_advref) eq 'HASH') {
 7699:         $is_adv = $is_advref->{'is_adv'};
 7700:     } else {
 7701:         $is_adv = &is_advanced_user($udom,$uname);
 7702:     }
 7703:     if (ref($domdefref) eq 'HASH') {
 7704:         %domdef = %{$domdefref};
 7705:     } else {
 7706:         %domdef = &get_domain_defaults($udom);
 7707:     }
 7708:     if (ref($domdef{$tool}) eq 'HASH') {
 7709:         if ($is_adv) {
 7710:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7711:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7712:                     $access = 1;
 7713:                 } else {
 7714:                     $access = 0;
 7715:                 }
 7716:                 return $access;
 7717:             }
 7718:         }
 7719:         if ($inststatus ne '') {
 7720:             my ($hasaccess,$hasnoaccess);
 7721:             foreach my $affiliation (split(/:/,$inststatus)) {
 7722:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7723:                     if ($domdef{$tool}{$affiliation}) {
 7724:                         $hasaccess = 1;
 7725:                     } else {
 7726:                         $hasnoaccess = 1;
 7727:                     }
 7728:                 }
 7729:             }
 7730:             if ($hasaccess || $hasnoaccess) {
 7731:                 if ($hasaccess) {
 7732:                     $access = 1;
 7733:                 } elsif ($hasnoaccess) {
 7734:                     $access = 0; 
 7735:                 }
 7736:                 return $access;
 7737:             }
 7738:         } else {
 7739:             if ($domdef{$tool}{'default'} ne '') {
 7740:                 if ($domdef{$tool}{'default'}) {
 7741:                     $access = 1;
 7742:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7743:                     $access = 0;
 7744:                 }
 7745:                 return $access;
 7746:             }
 7747:         }
 7748:     } else {
 7749:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7750:             $access = 1;
 7751:         } else {
 7752:             $access = 0;
 7753:         }
 7754:         return $access;
 7755:     }
 7756: }
 7757: 
 7758: sub is_course_owner {
 7759:     my ($cdom,$cnum,$udom,$uname) = @_;
 7760:     if (($udom eq '') || ($uname eq '')) {
 7761:         $udom = $env{'user.domain'};
 7762:         $uname = $env{'user.name'};
 7763:     }
 7764:     unless (($udom eq '') || ($uname eq '')) {
 7765:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7766:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7767:                 return 1;
 7768:             } else {
 7769:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7770:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7771:                     return 1;
 7772:                 }
 7773:             }
 7774:         }
 7775:     }
 7776:     return;
 7777: }
 7778: 
 7779: sub is_advanced_user {
 7780:     my ($udom,$uname) = @_;
 7781:     if ($udom ne '' && $uname ne '') {
 7782:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7783:             if (wantarray) {
 7784:                 return ($env{'user.adv'},$env{'user.author'});
 7785:             } else {
 7786:                 return $env{'user.adv'};
 7787:             }
 7788:         }
 7789:     }
 7790:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7791:     my %allroles;
 7792:     my ($is_adv,$is_author);
 7793:     foreach my $role (keys(%roleshash)) {
 7794:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7795:         my $area = '/'.$tdomain.'/'.$trest;
 7796:         if ($sec ne '') {
 7797:             $area .= '/'.$sec;
 7798:         }
 7799:         if (($area ne '') && ($trole ne '')) {
 7800:             my $spec=$trole.'.'.$area;
 7801:             if ($trole =~ /^cr\//) {
 7802:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7803:             } elsif ($trole ne 'gr') {
 7804:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7805:             }
 7806:             if ($trole eq 'au') {
 7807:                 $is_author = 1;
 7808:             }
 7809:         }
 7810:     }
 7811:     foreach my $role (keys(%allroles)) {
 7812:         last if ($is_adv);
 7813:         foreach my $item (split(/:/,$allroles{$role})) {
 7814:             if ($item ne '') {
 7815:                 my ($privilege,$restrictions)=split(/&/,$item);
 7816:                 if ($privilege eq 'adv') {
 7817:                     $is_adv = 1;
 7818:                     last;
 7819:                 }
 7820:             }
 7821:         }
 7822:     }
 7823:     if (wantarray) {
 7824:         return ($is_adv,$is_author);
 7825:     }
 7826:     return $is_adv;
 7827: }
 7828: 
 7829: sub check_can_request {
 7830:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7831:     my $canreq = 0;
 7832:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7833:         $uname = $env{'user.name'};
 7834:         $udom = $env{'user.domain'};
 7835:     }
 7836:     my ($types,$typename) = &Apache::loncommon::course_types();
 7837:     my @options = ('approval','validate','autolimit');
 7838:     my $optregex = join('|',@options);
 7839:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7840:         foreach my $type (@{$types}) {
 7841:             if (&usertools_access($uname,$udom,$type,undef,
 7842:                                   'requestcourses')) {
 7843:                 $canreq ++;
 7844:                 if (ref($request_domains) eq 'HASH') {
 7845:                     push(@{$request_domains->{$type}},$udom);
 7846:                 }
 7847:                 if ($dom eq $udom) {
 7848:                     $can_request->{$type} = 1;
 7849:                 }
 7850:             }
 7851:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7852:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7853:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7854:                 if (@curr > 0) {
 7855:                     foreach my $item (@curr) {
 7856:                         if (ref($request_domains) eq 'HASH') {
 7857:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7858:                             if ($otherdom ne '') {
 7859:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7860:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7861:                                         push(@{$request_domains->{$type}},$otherdom);
 7862:                                     }
 7863:                                 } else {
 7864:                                     push(@{$request_domains->{$type}},$otherdom);
 7865:                                 }
 7866:                             }
 7867:                         }
 7868:                     }
 7869:                     unless ($dom eq $env{'user.domain'}) {
 7870:                         $canreq ++;
 7871:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7872:                             $can_request->{$type} = 1;
 7873:                         }
 7874:                     }
 7875:                 }
 7876:             }
 7877:         }
 7878:     }
 7879:     return $canreq;
 7880: }
 7881: 
 7882: # ---------------------------------------------- Custom access rule evaluation
 7883: 
 7884: sub customaccess {
 7885:     my ($priv,$uri)=@_;
 7886:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7887:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7888:     $udom = &LONCAPA::clean_domain($udom);
 7889:     $ucrs = &LONCAPA::clean_username($ucrs);
 7890:     my $access=0;
 7891:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7892: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7893: 	if ($type eq 'user') {
 7894: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7895: 		my ($tdom,$tuname)=split(m{/},$scope);
 7896: 		if ($tdom) {
 7897: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7898: 		}
 7899: 		if ($tuname) {
 7900: 		    if ($tuname ne $env{'user.name'}) { next; }
 7901: 		}
 7902: 		$access=($effect eq 'allow');
 7903: 		last;
 7904: 	    }
 7905: 	} else {
 7906: 	    if ($role) {
 7907: 		if ($role ne $urole) { next; }
 7908: 	    }
 7909: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7910: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7911: 		if ($tdom) {
 7912: 		    if ($tdom ne $udom) { next; }
 7913: 		}
 7914: 		if ($tcrs) {
 7915: 		    if ($tcrs ne $ucrs) { next; }
 7916: 		}
 7917: 		if ($tsec) {
 7918: 		    if ($tsec ne $usec) { next; }
 7919: 		}
 7920: 		$access=($effect eq 'allow');
 7921: 		last;
 7922: 	    }
 7923: 	    if ($realm eq '' && $role eq '') {
 7924: 		$access=($effect eq 'allow');
 7925: 	    }
 7926: 	}
 7927:     }
 7928:     return $access;
 7929: }
 7930: 
 7931: # ------------------------------------------------- Check for a user privilege
 7932: 
 7933: sub allowed {
 7934:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7935:     my $ver_orguri=$uri;
 7936:     $uri=&deversion($uri);
 7937:     my $orguri=$uri;
 7938:     $uri=&declutter($uri);
 7939: 
 7940:     if ($priv eq 'evb') {
 7941: # Evade communication block restrictions for specified role in a course
 7942:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7943:             return $1;
 7944:         } else {
 7945:             return;
 7946:         }
 7947:     }
 7948: 
 7949:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7950: # Free bre access to adm and meta resources
 7951:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7952: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7953: 	&& ($priv eq 'bre')) {
 7954: 	return 'F';
 7955:     }
 7956: 
 7957: # Free bre access to user's own portfolio contents
 7958:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7959:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7960: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7961:         my %setters;
 7962:         my ($startblock,$endblock) = 
 7963:             &Apache::loncommon::blockcheck(\%setters,'port');
 7964:         if ($startblock && $endblock) {
 7965:             return 'B';
 7966:         } else {
 7967:             return 'F';
 7968:         }
 7969:     }
 7970: 
 7971: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7972:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7973:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7974:         if (exists($env{'request.course.id'})) {
 7975:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7976:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7977:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7978:                 my $courseprivid=$env{'request.course.id'};
 7979:                 $courseprivid=~s/\_/\//;
 7980:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7981:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7982:                     return $1; 
 7983:                 } else {
 7984:                     if ($env{'request.course.sec'}) {
 7985:                         $courseprivid.='/'.$env{'request.course.sec'};
 7986:                     }
 7987:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7988:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7989:                         return $2;
 7990:                     }
 7991:                 }
 7992:             }
 7993:         }
 7994:     }
 7995: 
 7996: # Free bre to public access
 7997: 
 7998:     if ($priv eq 'bre') {
 7999:         my $copyright;
 8000:         unless ($uri =~ /ext\.tool/) {
 8001:             $copyright=&metadata($uri,'copyright');
 8002:         }
 8003: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8004:            return 'F'; 
 8005:         }
 8006:         if ($copyright eq 'priv') {
 8007:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8008: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8009: 		return '';
 8010:             }
 8011:         }
 8012:         if ($copyright eq 'domain') {
 8013:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8014: 	    unless (($env{'user.domain'} eq $1) ||
 8015:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8016: 		return '';
 8017:             }
 8018:         }
 8019:         if ($env{'request.role'}=~ /li\.\//) {
 8020:             # Library role, so allow browsing of resources in this domain.
 8021:             return 'F';
 8022:         }
 8023:         if ($copyright eq 'custom') {
 8024: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8025:         }
 8026:     }
 8027:     # Domain coordinator is trying to create a course
 8028:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8029:         # uri is the requested domain in this case.
 8030:         # comparison to 'request.role.domain' shows if the user has selected
 8031:         # a role of dc for the domain in question.
 8032:         return 'F' if ($uri eq $env{'request.role.domain'});
 8033:     }
 8034: 
 8035:     my $thisallowed='';
 8036:     my $statecond=0;
 8037:     my $courseprivid='';
 8038: 
 8039:     my $ownaccess;
 8040:     # Community Coordinator or Assistant Co-author browsing resource space.
 8041:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8042:         if ($uri eq '') {
 8043:             $ownaccess = 1;
 8044:         } else {
 8045:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8046:                 my $udom = $env{'user.domain'};
 8047:                 my $uname = $env{'user.name'};
 8048:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8049:                     $ownaccess = 1;
 8050:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8051:                     unless ($uri =~ m{\.\./}) {
 8052:                         $ownaccess = 1;
 8053:                     }
 8054:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8055:                     my $now = time;
 8056:                     if ($uri =~ m{^([^/]+)/?$}) {
 8057:                         my $adom = $1;
 8058:                         foreach my $key (keys(%env)) {
 8059:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8060:                                 my ($start,$end) = split('.',$env{$key});
 8061:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8062:                                     $ownaccess = 1;
 8063:                                     last;
 8064:                                 }
 8065:                             }
 8066:                         }
 8067:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8068:                         my $adom = $1;
 8069:                         my $aname = $2;
 8070:                         foreach my $role ('ca','aa') { 
 8071:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8072:                                 my ($start,$end) =
 8073:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8074:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8075:                                     $ownaccess = 1;
 8076:                                     last;
 8077:                                 }
 8078:                             }
 8079:                         }
 8080:                     }
 8081:                 }
 8082:             }
 8083:         }
 8084:     }
 8085: 
 8086: # Course
 8087: 
 8088:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8089:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8090:             $thisallowed.=$1;
 8091:         }
 8092:     }
 8093: 
 8094: # Domain
 8095: 
 8096:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8097:        =~/\Q$priv\E\&([^\:]*)/) {
 8098:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8099:             $thisallowed.=$1;
 8100:         }
 8101:     }
 8102: 
 8103: # User who is not author or co-author might still be able to edit
 8104: # resource of an author in the domain (e.g., if Domain Coordinator).
 8105:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8106:         (&allowed('mdc',$env{'request.course.id'}))) {
 8107:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8108:             $thisallowed.=$1;
 8109:         }
 8110:     }
 8111: 
 8112: # Course: uri itself is a course
 8113:     my $courseuri=$uri;
 8114:     $courseuri=~s/\_(\d)/\/$1/;
 8115:     $courseuri=~s/^([^\/])/\/$1/;
 8116: 
 8117:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8118:        =~/\Q$priv\E\&([^\:]*)/) {
 8119:         if ($priv eq 'mip') {
 8120:             my $rem = $1;
 8121:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8122:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8123:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8124:                 if ($cdom ne '') {
 8125:                     my %passwdconf = &get_passwdconf($cdom);
 8126:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8127:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8128:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8129:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8130:                                 unless (@inststatuses) {
 8131:                                     @inststatuses = ('default');
 8132:                                 }
 8133:                                 foreach my $status (@inststatuses) {
 8134:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8135:                                         $thisallowed.=$rem;
 8136:                                     }
 8137:                                 }
 8138:                             }
 8139:                         }
 8140:                     }
 8141:                 }
 8142:             }
 8143:         } else {
 8144:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8145:                 $thisallowed.=$1;
 8146:             }
 8147:         }
 8148:     }
 8149: 
 8150: # URI is an uploaded document for this course, default permissions don't matter
 8151: # not allowing 'edit' access (editupload) to uploaded course docs
 8152:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8153: 	$thisallowed='';
 8154:         my ($match)=&is_on_map($uri);
 8155:         if ($match) {
 8156:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8157:                   =~/\Q$priv\E\&([^\:]*)/) {
 8158:                 my $value = $1;
 8159:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8160:                 if ($deeplinkblock) {
 8161:                     $thisallowed='D';
 8162:                 } elsif ($noblockcheck) {
 8163:                     $thisallowed.=$value;
 8164:                 } else {
 8165:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8166:                     if (@blockers > 0) {
 8167:                         $thisallowed = 'B';
 8168:                     } else {
 8169:                         $thisallowed.=$value;
 8170:                     }
 8171:                 }
 8172:             }
 8173:         } else {
 8174:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8175:             if ($refuri) {
 8176:                 if ($refuri =~ m|^/adm/|) {
 8177:                     $thisallowed='F';
 8178:                 } else {
 8179:                     $refuri=&declutter($refuri);
 8180:                     my ($match) = &is_on_map($refuri);
 8181:                     if ($match) {
 8182:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8183:                         if ($deeplinkblock) {
 8184:                             $thisallowed='D';
 8185:                         } elsif ($noblockcheck) {
 8186:                             $thisallowed='F';
 8187:                         } else {
 8188:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8189:                             if (@blockers > 0) {
 8190:                                 $thisallowed = 'B';
 8191:                             } else {
 8192:                                 $thisallowed='F';
 8193:                             }
 8194:                         }
 8195:                     }
 8196:                 }
 8197:             }
 8198:         }
 8199:     }
 8200: 
 8201:     if ($priv eq 'bre'
 8202: 	&& $thisallowed ne 'F' 
 8203: 	&& $thisallowed ne '2'
 8204: 	&& &is_portfolio_url($uri)) {
 8205: 	$thisallowed = &portfolio_access($uri,$clientip);
 8206:     }
 8207: 
 8208: # Full access at system, domain or course-wide level? Exit.
 8209:     if ($thisallowed=~/F/) {
 8210: 	return 'F';
 8211:     }
 8212: 
 8213: # If this is generating or modifying users, exit with special codes
 8214: 
 8215:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8216: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8217: 	    my ($audom,$auname)=split('/',$uri);
 8218: # no author name given, so this just checks on the general right to make a co-author in this domain
 8219: 	    unless ($auname) { return $thisallowed; }
 8220: # an author name is given, so we are about to actually make a co-author for a certain account
 8221: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8222: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8223: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8224: 	}
 8225: 	return $thisallowed;
 8226:     }
 8227: #
 8228: # Gathered so far: system, domain and course wide privileges
 8229: #
 8230: # Course: See if uri or referer is an individual resource that is part of 
 8231: # the course
 8232: 
 8233:     if ($env{'request.course.id'}) {
 8234: 
 8235: # If this is modifying password (internal auth) domains must match for user and user's role.
 8236: 
 8237:         if ($priv eq 'mip') {
 8238:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8239:                 return $thisallowed;
 8240:             } else {
 8241:                 return '';
 8242:             }
 8243:         }
 8244: 
 8245:        $courseprivid=$env{'request.course.id'};
 8246:        if ($env{'request.course.sec'}) {
 8247:           $courseprivid.='/'.$env{'request.course.sec'};
 8248:        }
 8249:        $courseprivid=~s/\_/\//;
 8250:        my $checkreferer=1;
 8251:        my ($match,$cond)=&is_on_map($uri);
 8252:        if ($match) {
 8253:            $statecond=$cond;
 8254:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8255:                =~/\Q$priv\E\&([^\:]*)/) {
 8256:                my $value = $1;
 8257:                if ($priv eq 'bre') {
 8258:                    if ($noblockcheck) {
 8259:                        $thisallowed.=$value;
 8260:                    } else {
 8261:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8262:                        if (@blockers > 0) {
 8263:                            $thisallowed = 'B';
 8264:                        } else {
 8265:                            $thisallowed.=$value;
 8266:                        }
 8267:                    }
 8268:                } else {
 8269:                    $thisallowed.=$value;
 8270:                }
 8271:                $checkreferer=0;
 8272:            }
 8273:        }
 8274:        
 8275:        if ($checkreferer) {
 8276: 	  my $refuri=$env{'httpref.'.$orguri};
 8277:             unless ($refuri) {
 8278:                 foreach my $key (keys(%env)) {
 8279: 		    if ($key=~/^httpref\..*\*/) {
 8280: 			my $pattern=$key;
 8281:                         $pattern=~s/^httpref\.\/res\///;
 8282:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8283:                         $pattern=~s/\//\\\//g;
 8284:                         if ($orguri=~/$pattern/) {
 8285: 			    $refuri=$env{$key};
 8286:                         }
 8287:                     }
 8288:                 }
 8289:             }
 8290: 
 8291:          if ($refuri) { 
 8292: 	  $refuri=&declutter($refuri);
 8293:           my ($match,$cond)=&is_on_map($refuri);
 8294:             if ($match) {
 8295:               my $refstatecond=$cond;
 8296:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8297:                   =~/\Q$priv\E\&([^\:]*)/) {
 8298:                   my $value = $1;
 8299:                   if ($priv eq 'bre') {
 8300:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8301:                       if ($deeplinkblock) {
 8302:                           $thisallowed = 'D';
 8303:                       } elsif ($noblockcheck) {
 8304:                           $thisallowed.=$value;
 8305:                       } else {
 8306:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8307:                           if (@blockers > 0) {
 8308:                               $thisallowed = 'B';
 8309:                           } else {
 8310:                               $thisallowed.=$value;
 8311:                           }
 8312:                       }
 8313:                   } else {
 8314:                       $thisallowed.=$value;
 8315:                   }
 8316:                   $uri=$refuri;
 8317:                   $statecond=$refstatecond;
 8318:               }
 8319:           }
 8320:         }
 8321:        }
 8322:    }
 8323: 
 8324: #
 8325: # Gathered now: all privileges that could apply, and condition number
 8326: # 
 8327: #
 8328: # Full or no access?
 8329: #
 8330: 
 8331:     if ($thisallowed=~/F/) {
 8332: 	return 'F';
 8333:     }
 8334: 
 8335:     unless ($thisallowed) {
 8336:         return '';
 8337:     }
 8338: 
 8339: # Restrictions exist, deal with them
 8340: #
 8341: #   C:according to course preferences
 8342: #   R:according to resource settings
 8343: #   L:unless locked
 8344: #   X:according to user session state
 8345: #
 8346: 
 8347: # Possibly locked functionality, check all courses
 8348: # Locks might take effect only after 10 minutes cache expiration for other
 8349: # courses, and 2 minutes for current course
 8350: 
 8351:     my $envkey;
 8352:     if ($thisallowed=~/L/) {
 8353:         foreach $envkey (keys(%env)) {
 8354:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8355:                my $courseid=$2;
 8356:                my $roleid=$1.'.'.$2;
 8357:                $courseid=~s/^\///;
 8358:                my $expiretime=600;
 8359:                if ($env{'request.role'} eq $roleid) {
 8360: 		  $expiretime=120;
 8361:                }
 8362: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8363:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8364:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8365: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8366:                }
 8367:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8368:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8369: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8370:                        &log($env{'user.domain'},$env{'user.name'},
 8371:                             $env{'user.home'},
 8372:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8373:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8374:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8375: 		       return '';
 8376:                    }
 8377:                }
 8378:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8379:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8380: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8381:                        &log($env{'user.domain'},$env{'user.name'},
 8382:                             $env{'user.home'},
 8383:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8384:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8385:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8386: 		       return '';
 8387:                    }
 8388:                }
 8389: 	   }
 8390:        }
 8391:     }
 8392:    
 8393: #
 8394: # Rest of the restrictions depend on selected course
 8395: #
 8396: 
 8397:     unless ($env{'request.course.id'}) {
 8398: 	if ($thisallowed eq 'A') {
 8399: 	    return 'A';
 8400:         } elsif ($thisallowed eq 'B') {
 8401:             return 'B';
 8402: 	} else {
 8403: 	    return '1';
 8404: 	}
 8405:     }
 8406: 
 8407: #
 8408: # Now user is definitely in a course
 8409: #
 8410: 
 8411: 
 8412: # Course preferences
 8413: 
 8414:    if ($thisallowed=~/C/) {
 8415:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8416:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8417:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8418: 	   =~/\Q$rolecode\E/) {
 8419: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8420: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8421: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8422: 			$env{'request.course.id'});
 8423: 	   }
 8424:            return '';
 8425:        }
 8426: 
 8427:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8428: 	   =~/\Q$unamedom\E/) {
 8429: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8430: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8431: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8432: 			$env{'request.course.id'});
 8433: 	   }
 8434:            return '';
 8435:        }
 8436:    }
 8437: 
 8438: # Resource preferences
 8439: 
 8440:    if ($thisallowed=~/R/) {
 8441:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8442:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8443: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8444: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8445: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8446: 	   }
 8447: 	   return '';
 8448:        }
 8449:    }
 8450: 
 8451: # Restricted by state or randomout?
 8452: 
 8453:    if ($thisallowed=~/X/) {
 8454:       if ($env{'acc.randomout'}) {
 8455: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8456:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8457:             return ''; 
 8458:          }
 8459:       }
 8460:       if (&condval($statecond)) {
 8461: 	 return '2';
 8462:       } else {
 8463:          return '';
 8464:       }
 8465:    }
 8466: 
 8467:     if ($thisallowed eq 'A') {
 8468: 	return 'A';
 8469:     } elsif ($thisallowed eq 'B') {
 8470:         return 'B';
 8471:     } elsif ($thisallowed eq 'D') {
 8472:         return 'D';
 8473:     }
 8474:    return 'F';
 8475: }
 8476: 
 8477: # ------------------------------------------- Check construction space access
 8478: 
 8479: sub constructaccess {
 8480:     my ($url,$setpriv)=@_;
 8481: 
 8482: # We do not allow editing of previous versions of files
 8483:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8484: 
 8485: # Get username and domain from URL
 8486:     my ($ownername,$ownerdomain,$ownerhome);
 8487: 
 8488:     ($ownerdomain,$ownername) =
 8489:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8490: 
 8491: # The URL does not really point to any authorspace, forget it
 8492:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8493: 
 8494: # Now we need to see if the user has access to the authorspace of
 8495: # $ownername at $ownerdomain
 8496: 
 8497:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8498: # Real author for this?
 8499:        $ownerhome = $env{'user.home'};
 8500:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8501:           return ($ownername,$ownerdomain,$ownerhome);
 8502:        }
 8503:     } else {
 8504: # Co-author for this?
 8505:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8506:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8507:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8508:             return ($ownername,$ownerdomain,$ownerhome);
 8509:         }
 8510:         if ($env{'request.course.id'}) {
 8511:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8512:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8513:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8514:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8515:                     return ($ownername,$ownerdomain,$ownerhome);
 8516:                 }
 8517:             }
 8518:         }
 8519:     }
 8520: 
 8521: # We don't have any access right now. If we are not possibly going to do anything about this,
 8522: # we might as well leave
 8523:    unless ($setpriv) { return ''; }
 8524: 
 8525: # Backdoor access?
 8526:     my $allowed=&allowed('eco',$ownerdomain);
 8527: # Nope
 8528:     unless ($allowed) { return ''; }
 8529: # Looks like we may have access, but could be locked by the owner of the construction space
 8530:     if ($allowed eq 'U') {
 8531:         my %blocked=&get('environment',['domcoord.author'],
 8532:                          $ownerdomain,$ownername);
 8533: # Is blocked by owner
 8534:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8535:     }
 8536:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8537: # Grant temporary access
 8538:         my $then=$env{'user.login.time'};
 8539:         my $update=$env{'user.update.time'};
 8540:         if (!$update) { $update = $then; }
 8541:         my $refresh=$env{'user.refresh.time'};
 8542:         if (!$refresh) { $refresh = $update; }
 8543:         my $now = time;
 8544:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8545:                            $now,'ca','constructaccess');
 8546:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8547:         return($ownername,$ownerdomain,$ownerhome);
 8548:     }
 8549: # No business here
 8550:     return '';
 8551: }
 8552: 
 8553: # ----------------------------------------------------------- Content Blocking
 8554: 
 8555: {
 8556: # Caches for faster Course Contents display where content blocking
 8557: # is in operation (i.e., interval param set) for timed quiz.
 8558: #
 8559: # User for whom data are being temporarily cached.
 8560: my $cacheduser='';
 8561: # Cached blockers for this user (a hash of blocking items). 
 8562: my %cachedblockers=();
 8563: # When the data were last cached.
 8564: my $cachedlast='';
 8565: 
 8566: sub load_all_blockers {
 8567:     my ($uname,$udom,$blocks)=@_;
 8568:     if (($uname ne '') && ($udom ne '')) { 
 8569:         if (($cacheduser eq $uname.':'.$udom) &&
 8570:             (abs($cachedlast-time)<5)) {
 8571:             return;
 8572:         }
 8573:     }
 8574:     $cachedlast=time;
 8575:     $cacheduser=$uname.':'.$udom;
 8576:     %cachedblockers = &get_commblock_resources($blocks);
 8577: }
 8578: 
 8579: sub get_comm_blocks {
 8580:     my ($cdom,$cnum) = @_;
 8581:     if ($cdom eq '' || $cnum eq '') {
 8582:         return unless ($env{'request.course.id'});
 8583:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8584:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8585:     }
 8586:     my %commblocks;
 8587:     my $hashid=$cdom.'_'.$cnum;
 8588:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8589:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8590:         %commblocks = %{$blocksref};
 8591:     } else {
 8592:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8593:         my $cachetime = 600;
 8594:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8595:     }
 8596:     return %commblocks;
 8597: }
 8598: 
 8599: sub get_commblock_resources {
 8600:     my ($blocks) = @_;
 8601:     my %blockers = ();
 8602:     return %blockers unless ($env{'request.course.id'});
 8603:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8604:     my %commblocks;
 8605:     if (ref($blocks) eq 'HASH') {
 8606:         %commblocks = %{$blocks};
 8607:     } else {
 8608:         %commblocks = &get_comm_blocks();
 8609:     }
 8610:     return %blockers unless (keys(%commblocks) > 0); 
 8611:     my $navmap = Apache::lonnavmaps::navmap->new();
 8612:     return %blockers unless (ref($navmap));
 8613:     my $now = time;
 8614:     foreach my $block (keys(%commblocks)) {
 8615:         if ($block =~ /^(\d+)____(\d+)$/) {
 8616:             my ($start,$end) = ($1,$2);
 8617:             if ($start <= $now && $end >= $now) {
 8618:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8619:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8620:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8621:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8622:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8623:                             }
 8624:                         }
 8625:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8626:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8627:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8628:                             }
 8629:                         }
 8630:                     }
 8631:                 }
 8632:             }
 8633:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8634:             my $item = $1;
 8635:             my @to_test;
 8636:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8637:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8638:                     my @interval;
 8639:                     my $type = 'map';
 8640:                     if ($item eq 'course') {
 8641:                         $type = 'course';
 8642:                         @interval=&EXT("resource.0.interval");
 8643:                     } else {
 8644:                         if ($item =~ /___\d+___/) {
 8645:                             $type = 'resource';
 8646:                             @interval=&EXT("resource.0.interval",$item);
 8647:                             if (ref($navmap)) {                        
 8648:                                 my $res = $navmap->getBySymb($item); 
 8649:                                 push(@to_test,$res);
 8650:                             }
 8651:                         } else {
 8652:                             my $mapsymb = &symbread($item,1);
 8653:                             if ($mapsymb) {
 8654:                                 if (ref($navmap)) {
 8655:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8656:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8657:                                     foreach my $res (@to_test) {
 8658:                                         my $symb = $res->symb();
 8659:                                         next if ($symb eq $mapsymb);
 8660:                                         if ($symb ne '') {
 8661:                                             @interval=&EXT("resource.0.interval",$symb);
 8662:                                             if ($interval[1] eq 'map') {
 8663:                                                 last;
 8664:                                             }
 8665:                                         }
 8666:                                     }
 8667:                                 }
 8668:                             }
 8669:                         }
 8670:                     }
 8671:                     if ($interval[0] =~ /^(\d+)/) {
 8672:                         my $timelimit = $1; 
 8673:                         my $first_access;
 8674:                         if ($type eq 'resource') {
 8675:                             $first_access=&get_first_access($interval[1],$item);
 8676:                         } elsif ($type eq 'map') {
 8677:                             $first_access=&get_first_access($interval[1],undef,$item);
 8678:                         } else {
 8679:                             $first_access=&get_first_access($interval[1]);
 8680:                         }
 8681:                         if ($first_access) {
 8682:                             my $timesup = $first_access+$timelimit;
 8683:                             if ($timesup > $now) {
 8684:                                 my $activeblock;
 8685:                                 foreach my $res (@to_test) {
 8686:                                     if ($res->answerable()) {
 8687:                                         $activeblock = 1;
 8688:                                         last;
 8689:                                     }
 8690:                                 }
 8691:                                 if ($activeblock) {
 8692:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8693:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8694:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8695:                                          }
 8696:                                     }
 8697:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8698:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8699:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8700:                                         }
 8701:                                     }
 8702:                                 }
 8703:                             }
 8704:                         }
 8705:                     }
 8706:                 }
 8707:             }
 8708:         }
 8709:     }
 8710:     return %blockers;
 8711: }
 8712: 
 8713: sub has_comm_blocking {
 8714:     my ($priv,$symb,$uri,$blocks) = @_;
 8715:     my @blockers;
 8716:     return unless ($env{'request.course.id'});
 8717:     return unless ($priv eq 'bre');
 8718:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8719:     return if ($env{'request.state'} eq 'construct');
 8720:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8721:     return unless (keys(%cachedblockers) > 0);
 8722:     my (%possibles,@symbs);
 8723:     if (!$symb) {
 8724:         $symb = &symbread($uri,1,1,1,\%possibles);
 8725:     }
 8726:     if ($symb) {
 8727:         @symbs = ($symb);
 8728:     } elsif (keys(%possibles)) { 
 8729:         @symbs = keys(%possibles);
 8730:     }
 8731:     my $noblock;
 8732:     foreach my $symb (@symbs) {
 8733:         last if ($noblock);
 8734:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8735:         foreach my $block (keys(%cachedblockers)) {
 8736:             if ($block =~ /^firstaccess____(.+)$/) {
 8737:                 my $item = $1;
 8738:                 if (($item eq $map) || ($item eq $symb)) {
 8739:                     $noblock = 1;
 8740:                     last;
 8741:                 }
 8742:             }
 8743:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8744:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8745:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8746:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8747:                             push(@blockers,$block);
 8748:                         }
 8749:                     }
 8750:                 }
 8751:             }
 8752:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8753:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8754:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8755:                         push(@blockers,$block);
 8756:                     }
 8757:                 }
 8758:             }
 8759:         }
 8760:     }
 8761:     return if ($noblock);
 8762:     return @blockers;
 8763: }
 8764: }
 8765: 
 8766: sub deeplink_check {
 8767:     my ($priv,$symb,$uri) = @_;
 8768:     return unless ($env{'request.course.id'});
 8769:     return unless ($priv eq 'bre');
 8770:     return if ($env{'request.state'} eq 'construct');
 8771:     return if ($env{'request.role.adv'});
 8772:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8773:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8774:     my (%possibles,@symbs);
 8775:     if (!$symb) {
 8776:         $symb = &symbread($uri,1,1,1,\%possibles);
 8777:     }
 8778:     if ($symb) {
 8779:         @symbs = ($symb);
 8780:     } elsif (keys(%possibles)) {
 8781:         @symbs = keys(%possibles);
 8782:     }
 8783: 
 8784:     my ($login,$switchrole,$allow);
 8785:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8786:         my $key = $1;
 8787:         my $tinyurl;
 8788:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8789:         if (defined($cached)) {
 8790:              $tinyurl = $result;
 8791:         } else {
 8792:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8793:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8794:              if ($currtiny{$key} ne '') {
 8795:                  $tinyurl = $currtiny{$key};
 8796:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8797:              }
 8798:         }
 8799:         if ($tinyurl ne '') {
 8800:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8801:             if ($cnumreq eq $cnum) {
 8802:                 $login = $posslogin;
 8803:             } else {
 8804:                 $switchrole = 1;
 8805:             }
 8806:         }
 8807:     }
 8808:     foreach my $symb (@symbs) {
 8809:         last if ($allow);
 8810:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8811:         if ($deeplink eq '') {
 8812:             $allow = 1;
 8813:         } else {
 8814:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8815:             if ($access eq 'any') {
 8816:                 $allow = 1;
 8817:             } elsif ($login) {
 8818:                 if ($access eq 'only') {
 8819:                     if ($scope eq 'res') {
 8820:                         if ($symb eq $login) {
 8821:                             $allow = 1;
 8822:                         }
 8823:                     } elsif ($scope eq 'map') {
 8824: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8825:                     } elsif ($scope eq 'rec') {
 8826: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8827:                     }
 8828:                 } else {
 8829:                     my ($acctype,$item) = split(/:/,$access);
 8830:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8831:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8832:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8833:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8834:                                 $allow = 1;
 8835:                             }
 8836:                         }
 8837:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8838:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8839:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8840:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8841:                                 $allow = 1;
 8842:                             }
 8843:                         }
 8844:                     }
 8845:                 }
 8846:             }
 8847:         }
 8848:     }
 8849:     return if ($allow);
 8850:     return 1;
 8851: }
 8852: 
 8853: # -------------------------------- Deversion and split uri into path an filename   
 8854: 
 8855: #
 8856: #   Removes the version from a URI and
 8857: #   splits it in to its filename and path to the filename.
 8858: #   Seems like File::Basename could have done this more clearly.
 8859: #   Parameters:
 8860: #      $uri   - input URI
 8861: #   Returns:
 8862: #     Two element list consisting of 
 8863: #     $pathname  - the URI up to and excluding the trailing /
 8864: #     $filename  - The part of the URI following the last /
 8865: #  NOTE:
 8866: #    Another realization of this is simply:
 8867: #    use File::Basename;
 8868: #    ...
 8869: #    $uri = shift;
 8870: #    $filename = basename($uri);
 8871: #    $path     = dirname($uri);
 8872: #    return ($filename, $path);
 8873: #
 8874: #     The implementation below is probably faster however.
 8875: #
 8876: sub split_uri_for_cond {
 8877:     my $uri=&deversion(&declutter(shift));
 8878:     my @uriparts=split(/\//,$uri);
 8879:     my $filename=pop(@uriparts);
 8880:     my $pathname=join('/',@uriparts);
 8881:     return ($pathname,$filename);
 8882: }
 8883: # --------------------------------------------------- Is a resource on the map?
 8884: 
 8885: sub is_on_map {
 8886:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8887:     #Trying to find the conditional for the file
 8888:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8889: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8890:     if ($match) {
 8891: 	return (1,$1);
 8892:     } else {
 8893: 	return (0,0);
 8894:     }
 8895: }
 8896: 
 8897: # --------------------------------------------------------- Get symb from alias
 8898: 
 8899: sub get_symb_from_alias {
 8900:     my $symb=shift;
 8901:     my ($map,$resid,$url)=&decode_symb($symb);
 8902: # Already is a symb
 8903:     if ($url) { return $symb; }
 8904: # Must be an alias
 8905:     my $aliassymb='';
 8906:     my %bighash;
 8907:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8908:                             &GDBM_READER(),0640)) {
 8909:         my $rid=$bighash{'mapalias_'.$symb};
 8910: 	if ($rid) {
 8911: 	    my ($mapid,$resid)=split(/\./,$rid);
 8912: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8913: 				    $resid,$bighash{'src_'.$rid});
 8914: 	}
 8915:         untie %bighash;
 8916:     }
 8917:     return $aliassymb;
 8918: }
 8919: 
 8920: # ----------------------------------------------------------------- Define Role
 8921: 
 8922: sub definerole {
 8923:   if (allowed('mcr','/')) {
 8924:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8925:     foreach my $role (split(':',$sysrole)) {
 8926: 	my ($crole,$cqual)=split(/\&/,$role);
 8927:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8928:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8929: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8930:                return "refused:s:$crole&$cqual"; 
 8931:             }
 8932:         }
 8933:     }
 8934:     foreach my $role (split(':',$domrole)) {
 8935: 	my ($crole,$cqual)=split(/\&/,$role);
 8936:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8937:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8938: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8939:                return "refused:d:$crole&$cqual"; 
 8940:             }
 8941:         }
 8942:     }
 8943:     foreach my $role (split(':',$courole)) {
 8944: 	my ($crole,$cqual)=split(/\&/,$role);
 8945:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8946:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8947: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8948:                return "refused:c:$crole&$cqual"; 
 8949:             }
 8950:         }
 8951:     }
 8952:     my $uhome;
 8953:     if (($uname ne '') && ($udom ne '')) {
 8954:         $uhome = &homeserver($uname,$udom);
 8955:         return $uhome if ($uhome eq 'no_host');
 8956:     } else {
 8957:         $uname = $env{'user.name'};
 8958:         $udom = $env{'user.domain'};
 8959:         $uhome = $env{'user.home'};
 8960:     }
 8961:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8962:                 "$udom:$uname:rolesdef_$rolename=".
 8963:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8964:     return reply($command,$uhome);
 8965:   } else {
 8966:     return 'refused';
 8967:   }
 8968: }
 8969: 
 8970: # ---------------- Make a metadata query against the network of library servers
 8971: 
 8972: sub metadata_query {
 8973:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8974:     my %rhash;
 8975:     my %libserv = &all_library();
 8976:     my @server_list = (defined($server_array) ? @$server_array
 8977:                                               : keys(%libserv) );
 8978:     for my $server (@server_list) {
 8979:         my $domains = ''; 
 8980:         if (ref($domains_hash) eq 'HASH') {
 8981:             $domains = $domains_hash->{$server}; 
 8982:         }
 8983: 	unless ($custom or $customshow) {
 8984: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8985: 	    $rhash{$server}=$reply;
 8986: 	}
 8987: 	else {
 8988: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8989: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8990: 			     $server);
 8991: 	    $rhash{$server}=$reply;
 8992: 	}
 8993:     }
 8994:     return \%rhash;
 8995: }
 8996: 
 8997: # ----------------------------------------- Send log queries and wait for reply
 8998: 
 8999: sub log_query {
 9000:     my ($uname,$udom,$query,%filters)=@_;
 9001:     my $uhome=&homeserver($uname,$udom);
 9002:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9003:     my $uhost=&hostname($uhome);
 9004:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9005:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9006:                        $uhome);
 9007:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9008:     return get_query_reply($queryid);
 9009: }
 9010: 
 9011: # -------------------------- Update MySQL table for portfolio file
 9012: 
 9013: sub update_portfolio_table {
 9014:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9015:     if ($group ne '') {
 9016:         $file_name =~s /^\Q$group\E//;
 9017:     }
 9018:     my $homeserver = &homeserver($uname,$udom);
 9019:     my $queryid=
 9020:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9021:                ':'.&escape($file_name).':'.$action,$homeserver);
 9022:     my $reply = &get_query_reply($queryid);
 9023:     return $reply;
 9024: }
 9025: 
 9026: # -------------------------- Update MySQL allusers table
 9027: 
 9028: sub update_allusers_table {
 9029:     my ($uname,$udom,$names) = @_;
 9030:     my $homeserver = &homeserver($uname,$udom);
 9031:     my $queryid=
 9032:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9033:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9034:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9035:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9036:                'generation='.&escape($names->{'generation'}).'%%'.
 9037:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9038:                'id='.&escape($names->{'id'}),$homeserver);
 9039:     return;
 9040: }
 9041: 
 9042: # ------- Request retrieval of institutional classlists for course(s)
 9043: 
 9044: sub fetch_enrollment_query {
 9045:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9046:     my ($homeserver,$sleep,$loopmax);
 9047:     my $maxtries = 1;
 9048:     if ($context eq 'automated') {
 9049:         $homeserver = $perlvar{'lonHostID'};
 9050:         $sleep = 2;
 9051:         $loopmax = 100;
 9052:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9053:     } else {
 9054:         $homeserver = &homeserver($cnum,$dom);
 9055:     }
 9056:     my $host=&hostname($homeserver);
 9057:     my $cmd = '';
 9058:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9059:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9060:     }
 9061:     $cmd =~ s/%%$//;
 9062:     $cmd = &escape($cmd);
 9063:     my $query = 'fetchenrollment';
 9064:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9065:     unless ($queryid=~/^\Q$host\E\_/) { 
 9066:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9067:         return 'error: '.$queryid;
 9068:     }
 9069:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9070:     my $tries = 1;
 9071:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9072:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9073:         $tries ++;
 9074:     }
 9075:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9076:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9077:     } else {
 9078:         my @responses = split(/:/,$reply);
 9079:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9080:             foreach my $line (@responses) {
 9081:                 my ($key,$value) = split(/=/,$line,2);
 9082:                 $$replyref{$key} = $value;
 9083:             }
 9084:         } else {
 9085:             my $pathname = LONCAPA::tempdir();
 9086:             foreach my $line (@responses) {
 9087:                 my ($key,$value) = split(/=/,$line);
 9088:                 $$replyref{$key} = $value;
 9089:                 if ($value > 0) {
 9090:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9091:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9092:                         my $destname = $pathname.'/'.$filename;
 9093:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9094:                         if ($xml_classlist =~ /^error/) {
 9095:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9096:                         } else {
 9097:                             if ( open(FILE,">",$destname) ) {
 9098:                                 print FILE &unescape($xml_classlist);
 9099:                                 close(FILE);
 9100:                             } else {
 9101:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9102:                             }
 9103:                         }
 9104:                     }
 9105:                 }
 9106:             }
 9107:         }
 9108:         return 'ok';
 9109:     }
 9110:     return 'error';
 9111: }
 9112: 
 9113: sub get_query_reply {
 9114:     my ($queryid,$sleep,$loopmax) = @_;;
 9115:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9116:         $sleep = 0.2;
 9117:     }
 9118:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9119:         $loopmax = 100;
 9120:     }
 9121:     my $replyfile=LONCAPA::tempdir().$queryid;
 9122:     my $reply='';
 9123:     for (1..$loopmax) {
 9124: 	sleep($sleep);
 9125:         if (-e $replyfile.'.end') {
 9126: 	    if (open(my $fh,"<",$replyfile)) {
 9127: 		$reply = join('',<$fh>);
 9128: 		close($fh);
 9129: 	   } else { return 'error: reply_file_error'; }
 9130:            return &unescape($reply);
 9131: 	}
 9132:     }
 9133:     return 'timeout:'.$queryid;
 9134: }
 9135: 
 9136: sub courselog_query {
 9137: #
 9138: # possible filters:
 9139: # url: url or symb
 9140: # username
 9141: # domain
 9142: # action: view, submit, grade
 9143: # start: timestamp
 9144: # end: timestamp
 9145: #
 9146:     my (%filters)=@_;
 9147:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9148:     if ($filters{'url'}) {
 9149: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9150:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9151:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9152:     }
 9153:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9154:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9155:     return &log_query($cname,$cdom,'courselog',%filters);
 9156: }
 9157: 
 9158: sub userlog_query {
 9159: #
 9160: # possible filters:
 9161: # action: log check role
 9162: # start: timestamp
 9163: # end: timestamp
 9164: #
 9165:     my ($uname,$udom,%filters)=@_;
 9166:     return &log_query($uname,$udom,'userlog',%filters);
 9167: }
 9168: 
 9169: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9170: 
 9171: sub auto_run {
 9172:     my ($cnum,$cdom) = @_;
 9173:     my $response = 0;
 9174:     my $settings;
 9175:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9176:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9177:         $settings = $domconfig{'autoenroll'};
 9178:         if ($settings->{'run'} eq '1') {
 9179:             $response = 1;
 9180:         }
 9181:     } else {
 9182:         my $homeserver;
 9183:         if (&is_course($cdom,$cnum)) {
 9184:             $homeserver = &homeserver($cnum,$cdom);
 9185:         } else {
 9186:             $homeserver = &domain($cdom,'primary');
 9187:         }
 9188:         if ($homeserver ne 'no_host') {
 9189:             $response = &reply('autorun:'.$cdom,$homeserver);
 9190:         }
 9191:     }
 9192:     return $response;
 9193: }
 9194: 
 9195: sub auto_get_sections {
 9196:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9197:     my $homeserver;
 9198:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9199:         $homeserver = &homeserver($cnum,$cdom);
 9200:     }
 9201:     if (!defined($homeserver)) { 
 9202:         if ($cdom =~ /^$match_domain$/) {
 9203:             $homeserver = &domain($cdom,'primary');
 9204:         }
 9205:     }
 9206:     my @secs;
 9207:     if (defined($homeserver)) {
 9208:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9209:         unless ($response eq 'refused') {
 9210:             @secs = split(/:/,$response);
 9211:         }
 9212:     }
 9213:     return @secs;
 9214: }
 9215: 
 9216: sub auto_new_course {
 9217:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9218:     my $homeserver = &homeserver($cnum,$cdom);
 9219:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9220:     return $response;
 9221: }
 9222: 
 9223: sub auto_validate_courseID {
 9224:     my ($cnum,$cdom,$inst_course_id) = @_;
 9225:     my $homeserver = &homeserver($cnum,$cdom);
 9226:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9227:     return $response;
 9228: }
 9229: 
 9230: sub auto_validate_instcode {
 9231:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9232:     my ($homeserver,$response);
 9233:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9234:         $homeserver = &homeserver($cnum,$cdom);
 9235:     }
 9236:     if (!defined($homeserver)) {
 9237:         if ($cdom =~ /^$match_domain$/) {
 9238:             $homeserver = &domain($cdom,'primary');
 9239:         }
 9240:     }
 9241:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9242:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9243:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9244:     return ($outcome,$description,$defaultcredits);
 9245: }
 9246: 
 9247: sub auto_create_password {
 9248:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9249:     my ($homeserver,$response);
 9250:     my $create_passwd = 0;
 9251:     my $authchk = '';
 9252:     if ($udom =~ /^$match_domain$/) {
 9253:         $homeserver = &domain($udom,'primary');
 9254:     }
 9255:     if ($homeserver eq '') {
 9256:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9257:             $homeserver = &homeserver($cnum,$cdom);
 9258:         }
 9259:     }
 9260:     if ($homeserver eq '') {
 9261:         $authchk = 'nodomain';
 9262:     } else {
 9263:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9264:         if ($response eq 'refused') {
 9265:             $authchk = 'refused';
 9266:         } else {
 9267:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9268:         }
 9269:     }
 9270:     return ($authparam,$create_passwd,$authchk);
 9271: }
 9272: 
 9273: sub auto_photo_permission {
 9274:     my ($cnum,$cdom,$students) = @_;
 9275:     my $homeserver = &homeserver($cnum,$cdom);
 9276:     my ($outcome,$perm_reqd,$conditions) = 
 9277: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9278:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9279: 	return (undef,undef);
 9280:     }
 9281:     return ($outcome,$perm_reqd,$conditions);
 9282: }
 9283: 
 9284: sub auto_checkphotos {
 9285:     my ($uname,$udom,$pid) = @_;
 9286:     my $homeserver = &homeserver($uname,$udom);
 9287:     my ($result,$resulttype);
 9288:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9289: 				   &escape($uname).':'.&escape($pid),
 9290: 				   $homeserver));
 9291:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9292: 	return (undef,undef);
 9293:     }
 9294:     if ($outcome) {
 9295:         ($result,$resulttype) = split(/:/,$outcome);
 9296:     } 
 9297:     return ($result,$resulttype);
 9298: }
 9299: 
 9300: sub auto_photochoice {
 9301:     my ($cnum,$cdom) = @_;
 9302:     my $homeserver = &homeserver($cnum,$cdom);
 9303:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9304: 						       &escape($cdom),
 9305: 						       $homeserver)));
 9306:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9307: 	return (undef,undef);
 9308:     }
 9309:     return ($update,$comment);
 9310: }
 9311: 
 9312: sub auto_photoupdate {
 9313:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9314:     my $homeserver = &homeserver($cnum,$dom);
 9315:     my $host=&hostname($homeserver);
 9316:     my $cmd = '';
 9317:     my $maxtries = 1;
 9318:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9319:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9320:     }
 9321:     $cmd =~ s/%%$//;
 9322:     $cmd = &escape($cmd);
 9323:     my $query = 'institutionalphotos';
 9324:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9325:     unless ($queryid=~/^\Q$host\E\_/) {
 9326:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9327:         return 'error: '.$queryid;
 9328:     }
 9329:     my $reply = &get_query_reply($queryid);
 9330:     my $tries = 1;
 9331:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9332:         $reply = &get_query_reply($queryid);
 9333:         $tries ++;
 9334:     }
 9335:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9336:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9337:     } else {
 9338:         my @responses = split(/:/,$reply);
 9339:         my $outcome = shift(@responses); 
 9340:         foreach my $item (@responses) {
 9341:             my ($key,$value) = split(/=/,$item);
 9342:             $$photo{$key} = $value;
 9343:         }
 9344:         return $outcome;
 9345:     }
 9346:     return 'error';
 9347: }
 9348: 
 9349: sub auto_instcode_format {
 9350:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9351: 	$cat_order) = @_;
 9352:     my $courses = '';
 9353:     my @homeservers;
 9354:     if ($caller eq 'global') {
 9355: 	my %servers = &get_servers($codedom,'library');
 9356: 	foreach my $tryserver (keys(%servers)) {
 9357: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9358: 		push(@homeservers,$tryserver);
 9359: 	    }
 9360:         }
 9361:     } elsif ($caller eq 'requests') {
 9362:         if ($codedom =~ /^$match_domain$/) {
 9363:             my $chome = &domain($codedom,'primary');
 9364:             unless ($chome eq 'no_host') {
 9365:                 push(@homeservers,$chome);
 9366:             }
 9367:         }
 9368:     } else {
 9369:         push(@homeservers,&homeserver($caller,$codedom));
 9370:     }
 9371:     foreach my $code (keys(%{$instcodes})) {
 9372:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9373:     }
 9374:     chop($courses);
 9375:     my $ok_response = 0;
 9376:     my $response;
 9377:     while (@homeservers > 0 && $ok_response == 0) {
 9378:         my $server = shift(@homeservers); 
 9379:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9380:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9381:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9382: 		split(/:/,$response);
 9383:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9384:             push(@{$codetitles},&str2array($codetitles_str));
 9385:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9386:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9387:             $ok_response = 1;
 9388:         }
 9389:     }
 9390:     if ($ok_response) {
 9391:         return 'ok';
 9392:     } else {
 9393:         return $response;
 9394:     }
 9395: }
 9396: 
 9397: sub auto_instcode_defaults {
 9398:     my ($domain,$returnhash,$code_order) = @_;
 9399:     my @homeservers;
 9400: 
 9401:     my %servers = &get_servers($domain,'library');
 9402:     foreach my $tryserver (keys(%servers)) {
 9403: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9404: 	    push(@homeservers,$tryserver);
 9405: 	}
 9406:     }
 9407: 
 9408:     my $response;
 9409:     foreach my $server (@homeservers) {
 9410:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9411:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9412: 	
 9413: 	foreach my $pair (split(/\&/,$response)) {
 9414: 	    my ($name,$value)=split(/\=/,$pair);
 9415: 	    if ($name eq 'code_order') {
 9416: 		@{$code_order} = split(/\&/,&unescape($value));
 9417: 	    } else {
 9418: 		$returnhash->{&unescape($name)}=&unescape($value);
 9419: 	    }
 9420: 	}
 9421: 	return 'ok';
 9422:     }
 9423: 
 9424:     return $response;
 9425: }
 9426: 
 9427: sub auto_possible_instcodes {
 9428:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9429:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9430:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9431:         return;
 9432:     }
 9433:     my (@homeservers,$uhome);
 9434:     if (defined(&domain($domain,'primary'))) {
 9435:         $uhome=&domain($domain,'primary');
 9436:         push(@homeservers,&domain($domain,'primary'));
 9437:     } else {
 9438:         my %servers = &get_servers($domain,'library');
 9439:         foreach my $tryserver (keys(%servers)) {
 9440:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9441:                 push(@homeservers,$tryserver);
 9442:             }
 9443:         }
 9444:     }
 9445:     my $response;
 9446:     foreach my $server (@homeservers) {
 9447:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9448:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9449:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9450:             split(':',$response);
 9451:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9452:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9453:         foreach my $item (split('&',$cat_title)) {   
 9454:             my ($name,$value)=split('=',$item);
 9455:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9456:         }
 9457:         foreach my $item (split('&',$cat_order)) {
 9458:             my ($name,$value)=split('=',$item);
 9459:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9460:         }
 9461:         return 'ok';
 9462:     }
 9463:     return $response;
 9464: }
 9465: 
 9466: sub auto_courserequest_checks {
 9467:     my ($dom) = @_;
 9468:     my ($homeserver,%validations);
 9469:     if ($dom =~ /^$match_domain$/) {
 9470:         $homeserver = &domain($dom,'primary');
 9471:     }
 9472:     unless ($homeserver eq 'no_host') {
 9473:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9474:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9475:             my @items = split(/&/,$response);
 9476:             foreach my $item (@items) {
 9477:                 my ($key,$value) = split('=',$item);
 9478:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9479:             }
 9480:         }
 9481:     }
 9482:     return %validations; 
 9483: }
 9484: 
 9485: sub auto_courserequest_validation {
 9486:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9487:     my ($homeserver,$response);
 9488:     if ($dom =~ /^$match_domain$/) {
 9489:         $homeserver = &domain($dom,'primary');
 9490:     }
 9491:     unless ($homeserver eq 'no_host') {
 9492:         my $customdata;
 9493:         if (ref($custominfo) eq 'HASH') {
 9494:             $customdata = &freeze_escape($custominfo);
 9495:         }
 9496:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9497:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9498:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9499:                                     $customdata,$homeserver));
 9500:     }
 9501:     return $response;
 9502: }
 9503: 
 9504: sub auto_validate_class_sec {
 9505:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9506:     my $homeserver = &homeserver($cnum,$cdom);
 9507:     my $ownerlist;
 9508:     if (ref($owners) eq 'ARRAY') {
 9509:         $ownerlist = join(',',@{$owners});
 9510:     } else {
 9511:         $ownerlist = $owners;
 9512:     }
 9513:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9514:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9515:     return $response;
 9516: }
 9517: 
 9518: sub auto_validate_instclasses {
 9519:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9520:     my ($homeserver,%validations);
 9521:     $homeserver = &homeserver($cnum,$cdom);
 9522:     unless ($homeserver eq 'no_host') {
 9523:         my $ownerlist;
 9524:         if (ref($owners) eq 'ARRAY') {
 9525:             $ownerlist = join(',',@{$owners});
 9526:         } else {
 9527:             $ownerlist = $owners;
 9528:         }
 9529:         if (ref($classesref) eq 'HASH') {
 9530:             my $classes = &freeze_escape($classesref);
 9531:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9532:                                 ':'.$cdom.':'.$classes,$homeserver);
 9533:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9534:                 my @items = split(/&/,$response);
 9535:                 foreach my $item (@items) {
 9536:                     my ($key,$value) = split('=',$item);
 9537:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9538:                 }
 9539:             }
 9540:         }
 9541:     }
 9542:     return %validations;
 9543: }
 9544: 
 9545: sub auto_crsreq_update {
 9546:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9547:         $code,$accessstart,$accessend,$inbound) = @_;
 9548:     my ($homeserver,%crsreqresponse);
 9549:     if ($cdom =~ /^$match_domain$/) {
 9550:         $homeserver = &domain($cdom,'primary');
 9551:     }
 9552:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9553:         my $info;
 9554:         if (ref($inbound) eq 'HASH') {
 9555:             $info = &freeze_escape($inbound);
 9556:         }
 9557:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9558:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9559:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9560:                             &escape($title).':'.&escape($code).':'.
 9561:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9562:                             $homeserver);
 9563:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9564:             my @items = split(/&/,$response);
 9565:             foreach my $item (@items) {
 9566:                 my ($key,$value) = split('=',$item);
 9567:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9568:             }
 9569:         }
 9570:     }
 9571:     return \%crsreqresponse;
 9572: }
 9573: 
 9574: sub auto_export_grades {
 9575:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9576:     my ($homeserver,%exportresponse);
 9577:     if ($cdom =~ /^$match_domain$/) {
 9578:         $homeserver = &domain($cdom,'primary');
 9579:     }
 9580:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9581:         my $info;
 9582:         if (ref($inforef) eq 'HASH') {
 9583:             $info = &freeze_escape($inforef);
 9584:         }
 9585:         if (ref($gradesref) eq 'HASH') {
 9586:             my $grades = &freeze_escape($gradesref);
 9587:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9588:                                 $info.':'.$grades,$homeserver);
 9589:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9590:                 my @items = split(/&/,$response);
 9591:                 foreach my $item (@items) {
 9592:                     my ($key,$value) = split('=',$item);
 9593:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9594:                 }
 9595:             }
 9596:         }
 9597:     }
 9598:     return \%exportresponse;
 9599: }
 9600: 
 9601: sub check_instcode_cloning {
 9602:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9603:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9604:         return;
 9605:     }
 9606:     my $canclone;
 9607:     if (@{$code_order} > 0) {
 9608:         my $instcoderegexp ='^';
 9609:         my @clonecodes = split(/\&/,$cloner);
 9610:         foreach my $item (@{$code_order}) {
 9611:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9612:                 foreach my $pair (@clonecodes) {
 9613:                     my ($key,$val) = split(/\=/,$pair,2);
 9614:                     $val = &unescape($val);
 9615:                     if ($key eq $item) {
 9616:                         $instcoderegexp .= '('.$val.')';
 9617:                         last;
 9618:                     }
 9619:                 }
 9620:             } else {
 9621:                 $instcoderegexp .= $codedefaults->{$item};
 9622:             }
 9623:         }
 9624:         $instcoderegexp .= '$';
 9625:         my (@from,@to);
 9626:         eval {
 9627:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9628:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9629:         };
 9630:         if ((@from > 0) && (@to > 0)) {
 9631:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9632:             if (!@diffs) {
 9633:                 $canclone = 1;
 9634:             }
 9635:         }
 9636:     }
 9637:     return $canclone;
 9638: }
 9639: 
 9640: sub default_instcode_cloning {
 9641:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9642:     my (%codedefaults,@code_order,$canclone);
 9643:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9644:         %codedefaults = %{$codedefaultsref};
 9645:         @code_order = @{$codeorderref};
 9646:     } elsif ($clonedom) {
 9647:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9648:     }
 9649:     if (($domdefclone) && (@code_order)) {
 9650:         my @clonecodes = split(/\+/,$domdefclone);
 9651:         my $instcoderegexp ='^';
 9652:         foreach my $item (@code_order) {
 9653:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9654:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9655:             } else {
 9656:                 $instcoderegexp .= $codedefaults{$item};
 9657:             }
 9658:         }
 9659:         $instcoderegexp .= '$';
 9660:         my (@from,@to);
 9661:         eval {
 9662:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9663:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9664:         };
 9665:         if ((@from > 0) && (@to > 0)) {
 9666:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9667:             if (!@diffs) {
 9668:                 $canclone = 1;
 9669:             }
 9670:         }
 9671:     }
 9672:     return $canclone;
 9673: }
 9674: 
 9675: # ------------------------------------------------------- Course Group routines
 9676: 
 9677: sub get_coursegroups {
 9678:     my ($cdom,$cnum,$group,$namespace) = @_;
 9679:     return(&dump($namespace,$cdom,$cnum,$group));
 9680: }
 9681: 
 9682: sub modify_coursegroup {
 9683:     my ($cdom,$cnum,$groupsettings) = @_;
 9684:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9685: }
 9686: 
 9687: sub toggle_coursegroup_status {
 9688:     my ($cdom,$cnum,$group,$action) = @_;
 9689:     my ($from_namespace,$to_namespace);
 9690:     if ($action eq 'delete') {
 9691:         $from_namespace = 'coursegroups';
 9692:         $to_namespace = 'deleted_groups';
 9693:     } else {
 9694:         $from_namespace = 'deleted_groups';
 9695:         $to_namespace = 'coursegroups';
 9696:     }
 9697:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9698:     if (my $tmp = &error(%curr_group)) {
 9699:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9700:         return ('read error',$tmp);
 9701:     } else {
 9702:         my %savedsettings = %curr_group; 
 9703:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9704:         my $deloutcome;
 9705:         if ($result eq 'ok') {
 9706:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9707:         } else {
 9708:             return ('write error',$result);
 9709:         }
 9710:         if ($deloutcome eq 'ok') {
 9711:             return 'ok';
 9712:         } else {
 9713:             return ('delete error',$deloutcome);
 9714:         }
 9715:     }
 9716: }
 9717: 
 9718: sub modify_group_roles {
 9719:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9720:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9721:     my $role = 'gr/'.&escape($userprivs);
 9722:     my ($uname,$udom) = split(/:/,$user);
 9723:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9724:     if ($result eq 'ok') {
 9725:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9726:     }
 9727:     return $result;
 9728: }
 9729: 
 9730: sub modify_coursegroup_membership {
 9731:     my ($cdom,$cnum,$membership) = @_;
 9732:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9733:     return $result;
 9734: }
 9735: 
 9736: sub get_active_groups {
 9737:     my ($udom,$uname,$cdom,$cnum) = @_;
 9738:     my $now = time;
 9739:     my %groups = ();
 9740:     foreach my $key (keys(%env)) {
 9741:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9742:             my ($start,$end) = split(/\./,$env{$key});
 9743:             if (($end!=0) && ($end<$now)) { next; }
 9744:             if (($start!=0) && ($start>$now)) { next; }
 9745:             if ($1 eq $cdom && $2 eq $cnum) {
 9746:                 $groups{$3} = $env{$key} ;
 9747:             }
 9748:         }
 9749:     }
 9750:     return %groups;
 9751: }
 9752: 
 9753: sub get_group_membership {
 9754:     my ($cdom,$cnum,$group) = @_;
 9755:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9756: }
 9757: 
 9758: sub get_users_groups {
 9759:     my ($udom,$uname,$courseid) = @_;
 9760:     my @usersgroups;
 9761:     my $cachetime=1800;
 9762: 
 9763:     my $hashid="$udom:$uname:$courseid";
 9764:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9765:     if (defined($cached)) {
 9766:         @usersgroups = split(/:/,$grouplist);
 9767:     } else {  
 9768:         $grouplist = '';
 9769:         my $courseurl = &courseid_to_courseurl($courseid);
 9770:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9771:         my $access_end = $env{'course.'.$courseid.
 9772:                               '.default_enrollment_end_date'};
 9773:         my $now = time;
 9774:         foreach my $key (keys(%roleshash)) {
 9775:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9776:                 my $group = $1;
 9777:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9778:                     my $start = $2;
 9779:                     my $end = $1;
 9780:                     if ($start == -1) { next; } # deleted from group
 9781:                     if (($start!=0) && ($start>$now)) { next; }
 9782:                     if (($end!=0) && ($end<$now)) {
 9783:                         if ($access_end && $access_end < $now) {
 9784:                             if ($access_end - $end < 86400) {
 9785:                                 push(@usersgroups,$group);
 9786:                             }
 9787:                         }
 9788:                         next;
 9789:                     }
 9790:                     push(@usersgroups,$group);
 9791:                 }
 9792:             }
 9793:         }
 9794:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9795:         $grouplist = join(':',@usersgroups);
 9796:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9797:     }
 9798:     return @usersgroups;
 9799: }
 9800: 
 9801: sub devalidate_getgroups_cache {
 9802:     my ($udom,$uname,$cdom,$cnum)=@_;
 9803:     my $courseid = $cdom.'_'.$cnum;
 9804: 
 9805:     my $hashid="$udom:$uname:$courseid";
 9806:     &devalidate_cache_new('getgroups',$hashid);
 9807: }
 9808: 
 9809: # ------------------------------------------------------------------ Plain Text
 9810: 
 9811: sub plaintext {
 9812:     my ($short,$type,$cid,$forcedefault) = @_;
 9813:     if ($short =~ m{^cr/}) {
 9814: 	return (split('/',$short))[-1];
 9815:     }
 9816:     if (!defined($cid)) {
 9817:         $cid = $env{'request.course.id'};
 9818:     }
 9819:     my %rolenames = (
 9820:                       Course    => 'std',
 9821:                       Community => 'alt1',
 9822:                       Placement => 'std',
 9823:                     );
 9824:     if ($cid ne '') {
 9825:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9826:             unless ($forcedefault) {
 9827:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9828:                 &Apache::lonlocal::mt_escape(\$roletext);
 9829:                 return &Apache::lonlocal::mt($roletext);
 9830:             }
 9831:         }
 9832:     }
 9833:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9834:         (defined($rolenames{$type})) && 
 9835:         (defined($prp{$short}{$rolenames{$type}}))) {
 9836:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9837:     } elsif ($cid ne '') {
 9838:         my $crstype = $env{'course.'.$cid.'.type'};
 9839:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9840:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9841:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9842:         }
 9843:     }
 9844:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9845: }
 9846: 
 9847: # ----------------------------------------------------------------- Assign Role
 9848: 
 9849: sub assignrole {
 9850:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9851:         $context)=@_;
 9852:     my $mrole;
 9853:     if ($role =~ /^cr\//) {
 9854:         my $cwosec=$url;
 9855:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9856: 	unless (&allowed('ccr',$cwosec)) {
 9857:            my $refused = 1;
 9858:            if ($context eq 'requestcourses') {
 9859:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9860:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9861:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9862:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9863:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9864:                            if ($crsenv{'internal.courseowner'} eq
 9865:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9866:                                $refused = '';
 9867:                            }
 9868:                        }
 9869:                    }
 9870:                }
 9871:            }
 9872:            if ($refused) {
 9873:                &logthis('Refused custom assignrole: '.
 9874:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9875:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9876:                return 'refused';
 9877:            }
 9878:         }
 9879:         $mrole='cr';
 9880:     } elsif ($role =~ /^gr\//) {
 9881:         my $cwogrp=$url;
 9882:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9883:         unless (&allowed('mdg',$cwogrp)) {
 9884:             &logthis('Refused group assignrole: '.
 9885:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9886:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9887:             return 'refused';
 9888:         }
 9889:         $mrole='gr';
 9890:     } else {
 9891:         my $cwosec=$url;
 9892:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9893:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9894:             my $refused;
 9895:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9896:                 if (!(&allowed('c'.$role,$url))) {
 9897:                     $refused = 1;
 9898:                 }
 9899:             } else {
 9900:                 $refused = 1;
 9901:             }
 9902:             if ($refused) {
 9903:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9904:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9905:                     my %crsenv;
 9906:                     if ($role eq 'cc' || $role eq 'co') {
 9907:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9908:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9909:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9910:                                 if ($crsenv{'internal.courseowner'} eq 
 9911:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9912:                                     $refused = '';
 9913:                                 }
 9914:                             }
 9915:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9916:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9917:                                 if ($crsenv{'internal.courseowner'} eq 
 9918:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9919:                                     $refused = '';
 9920:                                 }
 9921:                             }
 9922:                         }
 9923:                     }
 9924:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9925:                     if ($role eq 'st') {
 9926:                         $refused = '';
 9927:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9928:                         $refused = '';
 9929:                     }
 9930:                 } elsif ($context eq 'requestcourses') {
 9931:                     my @possroles = ('st','ta','ep','in','cc','co');
 9932:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9933:                         my $wrongcc;
 9934:                         if ($cnum =~ /^$match_community$/) {
 9935:                             $wrongcc = 1 if ($role eq 'cc');
 9936:                         } else {
 9937:                             $wrongcc = 1 if ($role eq 'co');
 9938:                         }
 9939:                         unless ($wrongcc) {
 9940:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9941:                             if ($crsenv{'internal.courseowner'} eq 
 9942:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9943:                                 $refused = '';
 9944:                             }
 9945:                         }
 9946:                     }
 9947:                 } elsif ($context eq 'requestauthor') {
 9948:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9949:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9950:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9951:                             $refused = '';
 9952:                         } else {
 9953:                             my %domdefaults = &get_domain_defaults($udom);
 9954:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9955:                                 my $checkbystatus;
 9956:                                 if ($env{'user.adv'}) { 
 9957:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9958:                                     if ($disposition eq 'automatic') {
 9959:                                         $refused = '';
 9960:                                     } elsif ($disposition eq '') {
 9961:                                         $checkbystatus = 1;
 9962:                                     } 
 9963:                                 } else {
 9964:                                     $checkbystatus = 1;
 9965:                                 }
 9966:                                 if ($checkbystatus) {
 9967:                                     if ($env{'environment.inststatus'}) {
 9968:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9969:                                         foreach my $type (@inststatuses) {
 9970:                                             if (($type ne '') &&
 9971:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9972:                                                 $refused = '';
 9973:                                             }
 9974:                                         }
 9975:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9976:                                         $refused = '';
 9977:                                     }
 9978:                                 }
 9979:                             }
 9980:                         }
 9981:                     }
 9982:                 }
 9983:                 if ($refused) {
 9984:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9985:                              ' '.$role.' '.$end.' '.$start.' by '.
 9986: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9987:                     return 'refused';
 9988:                 }
 9989:             }
 9990:         } elsif ($role eq 'au') {
 9991:             if ($url ne '/'.$udom.'/') {
 9992:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9993:                          ' to assign author role for '.$uname.':'.$udom.
 9994:                          ' in domain: '.$url.' refused (wrong domain).');
 9995:                 return 'refused';
 9996:             }
 9997:         }
 9998:         $mrole=$role;
 9999:     }
10000:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10001:                 "$udom:$uname:$url".'_'."$mrole=$role";
10002:     if ($end) { $command.='_'.$end; }
10003:     if ($start) {
10004: 	if ($end) { 
10005:            $command.='_'.$start; 
10006:         } else {
10007:            $command.='_0_'.$start;
10008:         }
10009:     }
10010:     my $origstart = $start;
10011:     my $origend = $end;
10012:     my $delflag;
10013: # actually delete
10014:     if ($deleteflag) {
10015: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10016: # modify command to delete the role
10017:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10018:                 "$udom:$uname:$url".'_'."$mrole";
10019: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10020: # set start and finish to negative values for userrolelog
10021:            $start=-1;
10022:            $end=-1;
10023:            $delflag = 1;
10024:         }
10025:     }
10026: # send command
10027:     my $answer=&reply($command,&homeserver($uname,$udom));
10028: # log new user role if status is ok
10029:     if ($answer eq 'ok') {
10030: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10031:         if (($role eq 'cc') || ($role eq 'in') ||
10032:             ($role eq 'ep') || ($role eq 'ad') ||
10033:             ($role eq 'ta') || ($role eq 'st') ||
10034:             ($role=~/^cr/) || ($role eq 'gr') ||
10035:             ($role eq 'co')) {
10036: # for course roles, perform group memberships changes triggered by role change.
10037:             unless ($role =~ /^gr/) {
10038:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10039:                                                  $origstart,$selfenroll,$context);
10040:             }
10041:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10042:                            $selfenroll,$context);
10043:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10044:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10045:                  ($role eq 'da')) {
10046:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10047:                            $context);
10048:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10049:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10050:                              $context); 
10051:         }
10052:         if ($role eq 'cc') {
10053:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10054:         }
10055:     }
10056:     return $answer;
10057: }
10058: 
10059: sub autoupdate_coowners {
10060:     my ($url,$end,$start,$uname,$udom) = @_;
10061:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10062:     if (($cdom ne '') && ($cnum ne '')) {
10063:         my $now = time;
10064:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10065:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10066:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10067:             my $instcode = $coursehash{'internal.coursecode'};
10068:             if ($instcode ne '') {
10069:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10070:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10071:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10072:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10073:                         if ($result eq 'valid') {
10074:                             if ($coursehash{'internal.co-owners'}) {
10075:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10076:                                     push(@newcoowners,$coowner);
10077:                                 }
10078:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10079:                                     push(@newcoowners,$uname.':'.$udom);
10080:                                 }
10081:                                 @newcoowners = sort(@newcoowners);
10082:                             } else {
10083:                                 push(@newcoowners,$uname.':'.$udom);
10084:                             }
10085:                         } else {
10086:                             if ($coursehash{'internal.co-owners'}) {
10087:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10088:                                     unless ($coowner eq $uname.':'.$udom) {
10089:                                         push(@newcoowners,$coowner);
10090:                                     }
10091:                                 }
10092:                                 unless (@newcoowners > 0) {
10093:                                     $delcoowners = 1;
10094:                                     $coowners = '';
10095:                                 }
10096:                             }
10097:                         }
10098:                         if (@newcoowners || $delcoowners) {
10099:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10100:                                             $delcoowners,@newcoowners);
10101:                         }
10102:                     }
10103:                 }
10104:             }
10105:         }
10106:     }
10107: }
10108: 
10109: sub store_coowners {
10110:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10111:     my $cid = $cdom.'_'.$cnum;
10112:     my ($coowners,$delresult,$putresult);
10113:     if (@newcoowners) {
10114:         $coowners = join(',',@newcoowners);
10115:         my %coownershash = (
10116:                             'internal.co-owners' => $coowners,
10117:                            );
10118:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10119:         if ($putresult eq 'ok') {
10120:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10121:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10122:             }
10123:         }
10124:     }
10125:     if ($delcoowners) {
10126:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10127:         if ($delresult eq 'ok') {
10128:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10129:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10130:             }
10131:         }
10132:     }
10133:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10134:         my %crsinfo =
10135:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10136:         if (ref($crsinfo{$cid}) eq 'HASH') {
10137:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10138:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10139:         }
10140:     }
10141: }
10142: 
10143: # -------------------------------------------------- Modify user authentication
10144: # Overrides without validation
10145: 
10146: sub modifyuserauth {
10147:     my ($udom,$uname,$umode,$upass)=@_;
10148:     my $uhome=&homeserver($uname,$udom);
10149:     my $allowed;
10150:     if (&allowed('mau',$udom)) {
10151:         $allowed = 1;
10152:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10153:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10154:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10155:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10156:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10157:         if (($cdom ne '') && ($cnum ne '')) {
10158:             my $is_owner = &is_course_owner($cdom,$cnum);
10159:             if ($is_owner) {
10160:                 $allowed = 1;
10161:             }
10162:         }
10163:     }
10164:     unless ($allowed) { return 'refused'; }
10165:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10166:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10167:              ' in domain '.$env{'request.role.domain'});  
10168:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10169: 		     &escape($upass),$uhome);
10170:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10171:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10172:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10173:     &log($udom,,$uname,$uhome,
10174:         'Authentication changed by '.$env{'user.domain'}.', '.
10175:                                      $env{'user.name'}.', '.$umode.
10176:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10177:     unless ($reply eq 'ok') {
10178:         &logthis('Authentication mode error: '.$reply);
10179: 	return 'error: '.$reply;
10180:     }   
10181:     return 'ok';
10182: }
10183: 
10184: # --------------------------------------------------------------- Modify a user
10185: 
10186: sub modifyuser {
10187:     my ($udom,    $uname, $uid,
10188:         $umode,   $upass, $first,
10189:         $middle,  $last,  $gene,
10190:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10191:     $udom= &LONCAPA::clean_domain($udom);
10192:     $uname=&LONCAPA::clean_username($uname);
10193:     my $showcandelete = 'none';
10194:     if (ref($candelete) eq 'ARRAY') {
10195:         if (@{$candelete} > 0) {
10196:             $showcandelete = join(', ',@{$candelete});
10197:         }
10198:     }
10199:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10200:              $umode.', '.$first.', '.$middle.', '.
10201: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10202:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10203:                                      ' desiredhome not specified'). 
10204:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10205:              ' in domain '.$env{'request.role.domain'});
10206:     my $uhome=&homeserver($uname,$udom,'true');
10207:     my $newuser;
10208:     if ($uhome eq 'no_host') {
10209:         $newuser = 1;
10210:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10211:                 ($umode eq 'lti')) {
10212:             return 'error: more information needed to create new user';
10213:         }
10214:     }
10215: # ----------------------------------------------------------------- Create User
10216:     if (($uhome eq 'no_host') && 
10217: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10218:         my $unhome='';
10219:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10220:             $unhome = $desiredhome;
10221: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10222: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10223:         } else { # load balancing routine for determining $unhome
10224:             my $loadm=10000000;
10225: 	    my %servers = &get_servers($udom,'library');
10226: 	    foreach my $tryserver (keys(%servers)) {
10227: 		my $answer=reply('load',$tryserver);
10228: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10229: 		    $loadm=$answer;
10230: 		    $unhome=$tryserver;
10231: 		}
10232: 	    }
10233:         }
10234:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10235: 	    return 'error: unable to find a home server for '.$uname.
10236:                    ' in domain '.$udom;
10237:         }
10238:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10239:                          &escape($upass),$unhome);
10240: 	unless ($reply eq 'ok') {
10241:             return 'error: '.$reply;
10242:         }   
10243:         $uhome=&homeserver($uname,$udom,'true');
10244:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10245: 	    return 'error: unable verify users home machine.';
10246:         }
10247:     }   # End of creation of new user
10248: # ---------------------------------------------------------------------- Add ID
10249:     if ($uid) {
10250:        $uid=~tr/A-Z/a-z/;
10251:        my %uidhash=&idrget($udom,$uname);
10252:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10253:          && (!$forceid)) {
10254: 	  unless ($uid eq $uidhash{$uname}) {
10255: 	      return 'error: user id "'.$uid.'" does not match '.
10256:                   'current user id "'.$uidhash{$uname}.'".';
10257:           }
10258:        } else {
10259: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10260:        }
10261:     }
10262: # -------------------------------------------------------------- Add names, etc
10263:     my @tmp=&get('environment',
10264: 		   ['firstname','middlename','lastname','generation','id',
10265:                     'permanentemail','inststatus'],
10266: 		   $udom,$uname);
10267:     my (%names,%oldnames);
10268:     if ($tmp[0] =~ m/^error:.*/) { 
10269:         %names=(); 
10270:     } else {
10271:         %names = @tmp;
10272:         %oldnames = %names;
10273:     }
10274: #
10275: # If name, email and/or uid are blank (e.g., because an uploaded file
10276: # of users did not contain them), do not overwrite existing values
10277: # unless field is in $candelete array ref.  
10278: #
10279: 
10280:     my @fields = ('firstname','middlename','lastname','generation',
10281:                   'permanentemail','id');
10282:     my %newvalues;
10283:     if (ref($candelete) eq 'ARRAY') {
10284:         foreach my $field (@fields) {
10285:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10286:                 if ($field eq 'firstname') {
10287:                     $names{$field} = $first;
10288:                 } elsif ($field eq 'middlename') {
10289:                     $names{$field} = $middle;
10290:                 } elsif ($field eq 'lastname') {
10291:                     $names{$field} = $last;
10292:                 } elsif ($field eq 'generation') { 
10293:                     $names{$field} = $gene;
10294:                 } elsif ($field eq 'permanentemail') {
10295:                     $names{$field} = $email;
10296:                 } elsif ($field eq 'id') {
10297:                     $names{$field}  = $uid;
10298:                 }
10299:             }
10300:         }
10301:     }
10302:     if ($first)  { $names{'firstname'}  = $first; }
10303:     if (defined($middle)) { $names{'middlename'} = $middle; }
10304:     if ($last)   { $names{'lastname'}   = $last; }
10305:     if (defined($gene))   { $names{'generation'} = $gene; }
10306:     if ($email) {
10307:        $email=~s/[^\w\@\.\-\,]//gs;
10308:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10309:     }
10310:     if ($uid) { $names{'id'}  = $uid; }
10311:     if (defined($inststatus)) {
10312:         $names{'inststatus'} = '';
10313:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10314:         if (ref($usertypes) eq 'HASH') {
10315:             my @okstatuses; 
10316:             foreach my $item (split(/:/,$inststatus)) {
10317:                 if (defined($usertypes->{$item})) {
10318:                     push(@okstatuses,$item);  
10319:                 }
10320:             }
10321:             if (@okstatuses) {
10322:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10323:             }
10324:         }
10325:     }
10326:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10327:                  $umode.', '.$first.', '.$middle.', '.
10328:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10329:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10330:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10331:     } else {
10332:         $logmsg .= ' during self creation';
10333:     }
10334:     my $changed;
10335:     if ($newuser) {
10336:         $changed = 1;
10337:     } else {
10338:         foreach my $field (@fields) {
10339:             if ($names{$field} ne $oldnames{$field}) {
10340:                 $changed = 1;
10341:                 last;
10342:             }
10343:         }
10344:     }
10345:     unless ($changed) {
10346:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10347:         &logthis($logmsg);
10348:         return 'ok';
10349:     }
10350:     my $reply = &put('environment', \%names, $udom,$uname);
10351:     if ($reply ne 'ok') { 
10352:         return 'error: '.$reply;
10353:     }
10354:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10355:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10356:     }
10357:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10358:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10359:     $logmsg = 'Success modifying user '.$logmsg;
10360:     &logthis($logmsg);
10361:     return 'ok';
10362: }
10363: 
10364: # -------------------------------------------------------------- Modify student
10365: 
10366: sub modifystudent {
10367:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10368:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10369:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10370:     if (!$cid) {
10371: 	unless ($cid=$env{'request.course.id'}) {
10372: 	    return 'not_in_class';
10373: 	}
10374:     }
10375: # --------------------------------------------------------------- Make the user
10376:     my $reply=&modifyuser
10377: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10378:          $desiredhome,$email,$inststatus);
10379:     unless ($reply eq 'ok') { return $reply; }
10380:     # This will cause &modify_student_enrollment to get the uid from the
10381:     # student's environment
10382:     $uid = undef if (!$forceid);
10383:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10384:                                         $gene,$usec,$end,$start,$type,$locktype,
10385:                                         $cid,$selfenroll,$context,$credits,$instsec);
10386:     return $reply;
10387: }
10388: 
10389: sub modify_student_enrollment {
10390:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10391:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10392:     my ($cdom,$cnum,$chome);
10393:     if (!$cid) {
10394: 	unless ($cid=$env{'request.course.id'}) {
10395: 	    return 'not_in_class';
10396: 	}
10397: 	$cdom=$env{'course.'.$cid.'.domain'};
10398: 	$cnum=$env{'course.'.$cid.'.num'};
10399:     } else {
10400: 	($cdom,$cnum)=split(/_/,$cid);
10401:     }
10402:     $chome=$env{'course.'.$cid.'.home'};
10403:     if (!$chome) {
10404: 	$chome=&homeserver($cnum,$cdom);
10405:     }
10406:     if (!$chome) { return 'unknown_course'; }
10407:     # Make sure the user exists
10408:     my $uhome=&homeserver($uname,$udom);
10409:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10410: 	return 'error: no such user';
10411:     }
10412:     # Get student data if we were not given enough information
10413:     if (!defined($first)  || $first  eq '' || 
10414:         !defined($last)   || $last   eq '' || 
10415:         !defined($uid)    || $uid    eq '' || 
10416:         !defined($middle) || $middle eq '' || 
10417:         !defined($gene)   || $gene   eq '') {
10418:         # They did not supply us with enough data to enroll the student, so
10419:         # we need to pick up more information.
10420:         my %tmp = &get('environment',
10421:                        ['firstname','middlename','lastname', 'generation','id']
10422:                        ,$udom,$uname);
10423: 
10424:         #foreach my $key (keys(%tmp)) {
10425:         #    &logthis("key $key = ".$tmp{$key});
10426:         #}
10427:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10428:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10429:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10430:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10431:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10432:     }
10433:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10434:     my $user = "$uname:$udom";
10435:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10436:     my $reply=cput('classlist',
10437: 		   {$user => 
10438: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10439: 		   $cdom,$cnum);
10440:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10441:         &devalidate_getsection_cache($udom,$uname,$cid);
10442:     } else { 
10443: 	return 'error: '.$reply;
10444:     }
10445:     # Add student role to user
10446:     my $uurl='/'.$cid;
10447:     $uurl=~s/\_/\//g;
10448:     if ($usec) {
10449: 	$uurl.='/'.$usec;
10450:     }
10451:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10452:                              $selfenroll,$context);
10453:     if ($result ne 'ok') {
10454:         if ($old_entry{$user} ne '') {
10455:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10456:         } else {
10457:             $reply = &del('classlist',[$user],$cdom,$cnum);
10458:         }
10459:     }
10460:     return $result; 
10461: }
10462: 
10463: sub format_name {
10464:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10465:     my $name;
10466:     if ($first ne 'lastname') {
10467: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10468:     } else {
10469: 	if ($lastname=~/\S/) {
10470: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10471: 	    $name=~s/\s+,/,/;
10472: 	} else {
10473: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10474: 	}
10475:     }
10476:     $name=~s/^\s+//;
10477:     $name=~s/\s+$//;
10478:     $name=~s/\s+/ /g;
10479:     return $name;
10480: }
10481: 
10482: # ------------------------------------------------- Write to course preferences
10483: 
10484: sub writecoursepref {
10485:     my ($courseid,%prefs)=@_;
10486:     $courseid=~s/^\///;
10487:     $courseid=~s/\_/\//g;
10488:     my ($cdomain,$cnum)=split(/\//,$courseid);
10489:     my $chome=homeserver($cnum,$cdomain);
10490:     if (($chome eq '') || ($chome eq 'no_host')) { 
10491: 	return 'error: no such course';
10492:     }
10493:     my $cstring='';
10494:     foreach my $pref (keys(%prefs)) {
10495: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10496:     }
10497:     $cstring=~s/\&$//;
10498:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10499: }
10500: 
10501: # ---------------------------------------------------------- Make/modify course
10502: 
10503: sub createcourse {
10504:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10505:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10506:     $url=&declutter($url);
10507:     my $cid='';
10508:     if ($context eq 'requestcourses') {
10509:         my $can_create = 0;
10510:         my ($ownername,$ownerdom) = split(':',$course_owner);
10511:         if ($udom eq $ownerdom) {
10512:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10513:                                   $context)) {
10514:                 $can_create = 1;
10515:             }
10516:         } else {
10517:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10518:                                            $category);
10519:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10520:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10521:                 if (@curr > 0) {
10522:                     my @options = qw(approval validate autolimit);
10523:                     my $optregex = join('|',@options);
10524:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10525:                         $can_create = 1;
10526:                     }
10527:                 }
10528:             }
10529:         }
10530:         if ($can_create) {
10531:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10532:                 unless (&allowed('ccc',$udom)) {
10533:                     return 'refused'; 
10534:                 }
10535:             }
10536:         } else {
10537:             return 'refused';
10538:         }
10539:     } elsif (!&allowed('ccc',$udom)) {
10540:         return 'refused';
10541:     }
10542: # --------------------------------------------------------------- Get Unique ID
10543:     my $uname;
10544:     if ($cnum =~ /^$match_courseid$/) {
10545:         my $chome=&homeserver($cnum,$udom,'true');
10546:         if (($chome eq '') || ($chome eq 'no_host')) {
10547:             $uname = $cnum;
10548:         } else {
10549:             $uname = &generate_coursenum($udom,$crstype);
10550:         }
10551:     } else {
10552:         $uname = &generate_coursenum($udom,$crstype);
10553:     }
10554:     return $uname if ($uname =~ /^error/);
10555: # -------------------------------------------------- Check supplied server name
10556:     if (!defined($course_server)) {
10557:         if (defined(&domain($udom,'primary'))) {
10558:             $course_server = &domain($udom,'primary');
10559:         } else {
10560:             $course_server = $env{'user.home'}; 
10561:         }
10562:     }
10563:     my %host_servers =
10564:         &Apache::lonnet::get_servers($udom,'library');
10565:     unless ($host_servers{$course_server}) {
10566:         return 'error: invalid home server for course: '.$course_server;
10567:     }
10568: # ------------------------------------------------------------- Make the course
10569:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10570:                       $course_server);
10571:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10572:     my $uhome=&homeserver($uname,$udom,'true');
10573:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10574: 	return 'error: no such course';
10575:     }
10576: # ----------------------------------------------------------------- Course made
10577: # log existence
10578:     my $now = time;
10579:     my $newcourse = {
10580:                     $udom.'_'.$uname => {
10581:                                      description => $description,
10582:                                      inst_code   => $inst_code,
10583:                                      owner       => $course_owner,
10584:                                      type        => $crstype,
10585:                                      creator     => $env{'user.name'}.':'.
10586:                                                     $env{'user.domain'},
10587:                                      created     => $now,
10588:                                      context     => $context,
10589:                                                 },
10590:                     };
10591:     &courseidput($udom,$newcourse,$uhome,'notime');
10592: # set toplevel url
10593:     my $topurl=$url;
10594:     unless ($nonstandard) {
10595: # ------------------------------------------ For standard courses, make top url
10596:         my $mapurl=&clutter($url);
10597:         if ($mapurl eq '/res/') { $mapurl=''; }
10598:         $env{'form.initmap'}=(<<ENDINITMAP);
10599: <map>
10600: <resource id="1" type="start"></resource>
10601: <resource id="2" src="$mapurl"></resource>
10602: <resource id="3" type="finish"></resource>
10603: <link index="1" from="1" to="2"></link>
10604: <link index="2" from="2" to="3"></link>
10605: </map>
10606: ENDINITMAP
10607:         $topurl=&declutter(
10608:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10609:                           );
10610:     }
10611: # ----------------------------------------------------------- Write preferences
10612:     &writecoursepref($udom.'_'.$uname,
10613:                      ('description'              => $description,
10614:                       'url'                      => $topurl,
10615:                       'internal.creator'         => $env{'user.name'}.':'.
10616:                                                     $env{'user.domain'},
10617:                       'internal.created'         => $now,
10618:                       'internal.creationcontext' => $context)
10619:                     );
10620:     return '/'.$udom.'/'.$uname;
10621: }
10622: 
10623: # ------------------------------------------------------------------- Create ID
10624: sub generate_coursenum {
10625:     my ($udom,$crstype) = @_;
10626:     my $domdesc = &domain($udom);
10627:     return 'error: invalid domain' if ($domdesc eq '');
10628:     my $first;
10629:     if ($crstype eq 'Community') {
10630:         $first = '0';
10631:     } else {
10632:         $first = int(1+rand(9)); 
10633:     } 
10634:     my $uname=$first.
10635:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10636:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10637:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10638: # ----------------------------------------------- Make sure that does not exist
10639:     my $uhome=&homeserver($uname,$udom,'true');
10640:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10641:         if ($crstype eq 'Community') {
10642:             $first = '0';
10643:         } else {
10644:             $first = int(1+rand(9));
10645:         }
10646:         $uname=$first.
10647:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10648:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10649:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10650:         $uhome=&homeserver($uname,$udom,'true');
10651:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10652:             return 'error: unable to generate unique course-ID';
10653:         }
10654:     }
10655:     return $uname;
10656: }
10657: 
10658: sub is_course {
10659:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10660:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10661: 
10662:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10663:     my $uhome=&homeserver($cnum,$cdom);
10664:     my $iscourse;
10665:     if (grep { $_ eq $uhome } current_machine_ids()) {
10666:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10667:     } else {
10668:         my $hashid = $cdom.':'.$cnum;
10669:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10670:         unless (defined($cached)) {
10671:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10672:                                         $cnum,undef,undef,'.');
10673:             $iscourse = 0;
10674:             if (exists($courses{$cdom.'_'.$cnum})) {
10675:                 $iscourse = 1;
10676:             }
10677:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10678:         }
10679:     }
10680:     return unless ($iscourse);
10681:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10682: }
10683: 
10684: sub store_userdata {
10685:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10686:     my $result;
10687:     if ($datakey ne '') {
10688:         if (ref($storehash) eq 'HASH') {
10689:             if ($udom eq '' || $uname eq '') {
10690:                 $udom = $env{'user.domain'};
10691:                 $uname = $env{'user.name'};
10692:             }
10693:             my $uhome=&homeserver($uname,$udom);
10694:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10695:                 $result = 'error: no_host';
10696:             } else {
10697:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10698:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10699: 
10700:                 my $namevalue='';
10701:                 foreach my $key (keys(%{$storehash})) {
10702:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10703:                 }
10704:                 $namevalue=~s/\&$//;
10705:                 unless ($namespace eq 'courserequests') {
10706:                     $datakey = &escape($datakey);
10707:                 }
10708:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10709:                                   $namevalue,$uhome);
10710:             }
10711:         } else {
10712:             $result = 'error: data to store was not a hash reference'; 
10713:         }
10714:     } else {
10715:         $result= 'error: invalid requestkey'; 
10716:     }
10717:     return $result;
10718: }
10719: 
10720: # ---------------------------------------------------------- Assign Custom Role
10721: 
10722: sub assigncustomrole {
10723:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10724:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10725:                        $end,$start,$deleteflag,$selfenroll,$context);
10726: }
10727: 
10728: # ----------------------------------------------------------------- Revoke Role
10729: 
10730: sub revokerole {
10731:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10732:     my $now=time;
10733:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10734: }
10735: 
10736: # ---------------------------------------------------------- Revoke Custom Role
10737: 
10738: sub revokecustomrole {
10739:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10740:     my $now=time;
10741:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10742:            $deleteflag,$selfenroll,$context);
10743: }
10744: 
10745: # ------------------------------------------------------------ Disk usage
10746: sub diskusage {
10747:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10748:     $directorypath =~ s/\/$//;
10749:     my $listing=&reply('du2:'.&escape($directorypath).':'
10750:                        .&escape($getpropath).':'.&escape($uname).':'
10751:                        .&escape($udom),homeserver($uname,$udom));
10752:     if ($listing eq 'unknown_cmd') {
10753:         if ($getpropath) {
10754:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10755:         }
10756:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10757:     }
10758:     return $listing;
10759: }
10760: 
10761: sub is_locked {
10762:     my ($file_name, $domain, $user, $which) = @_;
10763:     my @check;
10764:     my $is_locked;
10765:     push (@check,$file_name);
10766:     my %locked = &get('file_permissions',\@check,
10767: 		      $env{'user.domain'},$env{'user.name'});
10768:     my ($tmp)=keys(%locked);
10769:     if ($tmp=~/^error:/) { undef(%locked); }
10770:     
10771:     if (ref($locked{$file_name}) eq 'ARRAY') {
10772:         $is_locked = 'false';
10773:         foreach my $entry (@{$locked{$file_name}}) {
10774:            if (ref($entry) eq 'ARRAY') {
10775:                $is_locked = 'true';
10776:                if (ref($which) eq 'ARRAY') {
10777:                    push(@{$which},$entry);
10778:                } else {
10779:                    last;
10780:                }
10781:            }
10782:        }
10783:     } else {
10784:         $is_locked = 'false';
10785:     }
10786:     return $is_locked;
10787: }
10788: 
10789: sub declutter_portfile {
10790:     my ($file) = @_;
10791:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10792:     return $file;
10793: }
10794: 
10795: # ------------------------------------------------------------- Mark as Read Only
10796: 
10797: sub mark_as_readonly {
10798:     my ($domain,$user,$files,$what) = @_;
10799:     my %current_permissions = &dump('file_permissions',$domain,$user);
10800:     my ($tmp)=keys(%current_permissions);
10801:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10802:     foreach my $file (@{$files}) {
10803: 	$file = &declutter_portfile($file);
10804:         push(@{$current_permissions{$file}},$what);
10805:     }
10806:     &put('file_permissions',\%current_permissions,$domain,$user);
10807:     return;
10808: }
10809: 
10810: # ------------------------------------------------------------Save Selected Files
10811: 
10812: sub save_selected_files {
10813:     my ($user, $path, @files) = @_;
10814:     my $filename = $user."savedfiles";
10815:     my @other_files = &files_not_in_path($user, $path);
10816:     open (OUT,'>',LONCAPA::tempdir().$filename);
10817:     foreach my $file (@files) {
10818:         print (OUT $env{'form.currentpath'}.$file."\n");
10819:     }
10820:     foreach my $file (@other_files) {
10821:         print (OUT $file."\n");
10822:     }
10823:     close (OUT);
10824:     return 'ok';
10825: }
10826: 
10827: sub clear_selected_files {
10828:     my ($user) = @_;
10829:     my $filename = $user."savedfiles";
10830:     open (OUT,'>',LONCAPA::tempdir().$filename);
10831:     print (OUT undef);
10832:     close (OUT);
10833:     return ("ok");    
10834: }
10835: 
10836: sub files_in_path {
10837:     my ($user, $path) = @_;
10838:     my $filename = $user."savedfiles";
10839:     my %return_files;
10840:     open (IN,'<',LONCAPA::tempdir().$filename);
10841:     while (my $line_in = <IN>) {
10842:         chomp ($line_in);
10843:         my @paths_and_file = split (m!/!, $line_in);
10844:         my $file_part = pop (@paths_and_file);
10845:         my $path_part = join ('/', @paths_and_file);
10846:         $path_part.='/';
10847:         my $path_and_file = $path_part.$file_part;
10848:         if ($path_part eq $path) {
10849:             $return_files{$file_part}= 'selected';
10850:         }
10851:     }
10852:     close (IN);
10853:     return (\%return_files);
10854: }
10855: 
10856: # called in portfolio select mode, to show files selected NOT in current directory
10857: sub files_not_in_path {
10858:     my ($user, $path) = @_;
10859:     my $filename = $user."savedfiles";
10860:     my @return_files;
10861:     my $path_part;
10862:     open(IN, '<',LONCAPA::tempdir().$filename);
10863:     while (my $line = <IN>) {
10864:         #ok, I know it's clunky, but I want it to work
10865:         my @paths_and_file = split(m|/|, $line);
10866:         my $file_part = pop(@paths_and_file);
10867:         chomp($file_part);
10868:         my $path_part = join('/', @paths_and_file);
10869:         $path_part .= '/';
10870:         my $path_and_file = $path_part.$file_part;
10871:         if ($path_part ne $path) {
10872:             push(@return_files, ($path_and_file));
10873:         }
10874:     }
10875:     close(OUT);
10876:     return (@return_files);
10877: }
10878: 
10879: #------------------------------Submitted/Handedback Portfolio Files Versioning
10880:  
10881: sub portfiles_versioning {
10882:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10883:     my $portfolio_root = '/userfiles/portfolio';
10884:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10885:     foreach my $file (@{$portfiles}) {
10886:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10887:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10888:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10889:         my $getpropath = 1;
10890:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10891:                                              $stu_name,$getpropath);
10892:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10893:         my $new_answer = 
10894:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10895:         if ($new_answer ne 'problem getting file') {
10896:             push(@{$versioned_portfiles}, $directory.$new_answer);
10897:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10898:                               [$symb,$env{'request.course.id'},'graded']);
10899:         }
10900:     }
10901: }
10902: 
10903: sub get_next_version {
10904:     my ($answer_name, $answer_ext, $dir_list) = @_;
10905:     my $version;
10906:     if (ref($dir_list) eq 'ARRAY') {
10907:         foreach my $row (@{$dir_list}) {
10908:             my ($file) = split(/\&/,$row,2);
10909:             my ($file_name,$file_version,$file_ext) =
10910:                 &file_name_version_ext($file);
10911:             if (($file_name eq $answer_name) &&
10912:                 ($file_ext eq $answer_ext)) {
10913:                      # gets here if filename and extension match,
10914:                      # regardless of version
10915:                 if ($file_version ne '') {
10916:                     # a versioned file is found  so save it for later
10917:                     if ($file_version > $version) {
10918:                         $version = $file_version;
10919:                     }
10920:                 }
10921:             }
10922:         }
10923:     }
10924:     $version ++;
10925:     return($version);
10926: }
10927: 
10928: sub version_selected_portfile {
10929:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10930:     my ($answer_name,$answer_ver,$answer_ext) =
10931:         &file_name_version_ext($file_name);
10932:     my $new_answer;
10933:     $env{'form.copy'} =
10934:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10935:     if($env{'form.copy'} eq '-1') {
10936:         $new_answer = 'problem getting file';
10937:     } else {
10938:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10939:         my $copy_result = 
10940:             &finishuserfileupload($stu_name,$domain,'copy',
10941:                                   '/portfolio'.$directory.$new_answer);
10942:     }
10943:     undef($env{'form.copy'});
10944:     return ($new_answer);
10945: }
10946: 
10947: sub file_name_version_ext {
10948:     my ($file)=@_;
10949:     my @file_parts = split(/\./, $file);
10950:     my ($name,$version,$ext);
10951:     if (@file_parts > 1) {
10952:         $ext=pop(@file_parts);
10953:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10954:             $version=pop(@file_parts);
10955:         }
10956:         $name=join('.',@file_parts);
10957:     } else {
10958:         $name=join('.',@file_parts);
10959:     }
10960:     return($name,$version,$ext);
10961: }
10962: 
10963: #----------------------------------------------Get portfolio file permissions
10964: 
10965: sub get_portfile_permissions {
10966:     my ($domain,$user) = @_;
10967:     my %current_permissions = &dump('file_permissions',$domain,$user);
10968:     my ($tmp)=keys(%current_permissions);
10969:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10970:     return \%current_permissions;
10971: }
10972: 
10973: #---------------------------------------------Get portfolio file access controls
10974: 
10975: sub get_access_controls {
10976:     my ($current_permissions,$group,$file) = @_;
10977:     my %access;
10978:     my $real_file = $file;
10979:     $file =~ s/\.meta$//;
10980:     if (defined($file)) {
10981:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10982:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10983:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10984:             }
10985:         }
10986:     } else {
10987:         foreach my $key (keys(%{$current_permissions})) {
10988:             if ($key =~ /\0accesscontrol$/) {
10989:                 if (defined($group)) {
10990:                     if ($key !~ m-^\Q$group\E/-) {
10991:                         next;
10992:                     }
10993:                 }
10994:                 my ($fullpath) = split(/\0/,$key);
10995:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10996:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10997:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10998:                     }
10999:                 }
11000:             }
11001:         }
11002:     }
11003:     return %access;
11004: }
11005: 
11006: sub modify_access_controls {
11007:     my ($file_name,$changes,$domain,$user)=@_;
11008:     my ($outcome,$deloutcome);
11009:     my %store_permissions;
11010:     my %new_values;
11011:     my %new_control;
11012:     my %translation;
11013:     my @deletions = ();
11014:     my $now = time;
11015:     if (exists($$changes{'activate'})) {
11016:         if (ref($$changes{'activate'}) eq 'HASH') {
11017:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11018:             my $numnew = scalar(@newitems);
11019:             for (my $i=0; $i<$numnew; $i++) {
11020:                 my $newkey = $newitems[$i];
11021:                 my $newid = &Apache::loncommon::get_cgi_id();
11022:                 if ($newkey =~ /^\d+:/) { 
11023:                     $newkey =~ s/^(\d+)/$newid/;
11024:                     $translation{$1} = $newid;
11025:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11026:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11027:                     $translation{$1} = $newid;
11028:                 }
11029:                 $new_values{$file_name."\0".$newkey} = 
11030:                                           $$changes{'activate'}{$newitems[$i]};
11031:                 $new_control{$newkey} = $now;
11032:             }
11033:         }
11034:     }
11035:     my %todelete;
11036:     my %changed_items;
11037:     foreach my $action ('delete','update') {
11038:         if (exists($$changes{$action})) {
11039:             if (ref($$changes{$action}) eq 'HASH') {
11040:                 foreach my $key (keys(%{$$changes{$action}})) {
11041:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11042:                     if ($action eq 'delete') { 
11043:                         $todelete{$itemnum} = 1;
11044:                     } else {
11045:                         $changed_items{$itemnum} = $key;
11046:                     }
11047:                 }
11048:             }
11049:         }
11050:     }
11051:     # get lock on access controls for file.
11052:     my $lockhash = {
11053:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11054:                                                        ':'.$env{'user.domain'},
11055:                    }; 
11056:     my $tries = 0;
11057:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11058:    
11059:     while (($gotlock ne 'ok') && $tries < 10) {
11060:         $tries ++;
11061:         sleep(0.1);
11062:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11063:     }
11064:     if ($gotlock eq 'ok') {
11065:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11066:         my ($tmp)=keys(%curr_permissions);
11067:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11068:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11069:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11070:             if (ref($curr_controls) eq 'HASH') {
11071:                 foreach my $control_item (keys(%{$curr_controls})) {
11072:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11073:                     if (defined($todelete{$itemnum})) {
11074:                         push(@deletions,$file_name."\0".$control_item);
11075:                     } else {
11076:                         if (defined($changed_items{$itemnum})) {
11077:                             $new_control{$changed_items{$itemnum}} = $now;
11078:                             push(@deletions,$file_name."\0".$control_item);
11079:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11080:                         } else {
11081:                             $new_control{$control_item} = $$curr_controls{$control_item};
11082:                         }
11083:                     }
11084:                 }
11085:             }
11086:         }
11087:         my ($group);
11088:         if (&is_course($domain,$user)) {
11089:             ($group,my $file) = split(/\//,$file_name,2);
11090:         }
11091:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11092:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11093:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11094:         #  remove lock
11095:         my @del_lock = ($file_name."\0".'locked_access_records');
11096:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11097:         my $sqlresult =
11098:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11099:                                     $group);
11100:     } else {
11101:         $outcome = "error: could not obtain lockfile\n";  
11102:     }
11103:     return ($outcome,$deloutcome,\%new_values,\%translation);
11104: }
11105: 
11106: sub make_public_indefinitely {
11107:     my (@requrl) = @_;
11108:     return &automated_portfile_access('public',\@requrl);
11109: }
11110: 
11111: sub automated_portfile_access {
11112:     my ($accesstype,$addsref,$delsref,$info) = @_;
11113:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11114:         return 'invalid';
11115:     }
11116:     my %urls;
11117:     if (ref($addsref) eq 'ARRAY') {
11118:         foreach my $requrl (@{$addsref}) {
11119:             if (&is_portfolio_url($requrl)) {
11120:                 unless (exists($urls{$requrl})) {
11121:                     $urls{$requrl} = 'add';
11122:                 }
11123:             }
11124:         }
11125:     }
11126:     if (ref($delsref) eq 'ARRAY') {
11127:         foreach my $requrl (@{$delsref}) { 
11128:             if (&is_portfolio_url($requrl)) {
11129:                 unless (exists($urls{$requrl})) {
11130:                     $urls{$requrl} = 'delete'; 
11131:                 }
11132:             }
11133:         }
11134:     }
11135:     unless (keys(%urls)) {
11136:         return 'invalid';
11137:     }
11138:     my $ip;
11139:     if ($accesstype eq 'ip') {
11140:         if (ref($info) eq 'HASH') {
11141:             if ($info->{'ip'} ne '') {
11142:                 $ip = $info->{'ip'};
11143:             }
11144:         }
11145:         if ($ip eq '') {
11146:             return 'invalid';
11147:         }
11148:     }
11149:     my $errors;
11150:     my $now = time;
11151:     my %current_perms;
11152:     foreach my $requrl (sort(keys(%urls))) {
11153:         my $action;
11154:         if ($urls{$requrl} eq 'add') {
11155:             $action = 'activate';
11156:         } else {
11157:             $action = 'none';
11158:         }
11159:         my $aclnum = 0;
11160:         my (undef,$udom,$unum,$file_name,$group) =
11161:             &parse_portfolio_url($requrl);
11162:         unless (exists($current_perms{$unum.':'.$udom})) {
11163:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11164:         }
11165:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11166:                                                    $group,$file_name);
11167:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11168:             my ($num,$scope,$end,$start) = 
11169:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11170:             if ($scope eq $accesstype) {
11171:                 if (($start <= $now) && ($end == 0)) {
11172:                     if ($accesstype eq 'ip') {
11173:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11174:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11175:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11176:                                     if ($urls{$requrl} eq 'add') {
11177:                                         $action = 'none';
11178:                                         last;
11179:                                     } else {
11180:                                         $action = 'delete';
11181:                                         $aclnum = $num;
11182:                                         last;
11183:                                     }
11184:                                 }
11185:                             }
11186:                         }
11187:                     } elsif ($accesstype eq 'public') {
11188:                         if ($urls{$requrl} eq 'add') {
11189:                             $action = 'none';
11190:                             last;
11191:                         } else {
11192:                             $action = 'delete';
11193:                             $aclnum = $num;
11194:                             last;
11195:                         }
11196:                     }
11197:                 } elsif ($accesstype eq 'public') {
11198:                     $action = 'update';
11199:                     $aclnum = $num;
11200:                     last;
11201:                 }
11202:             }
11203:         }
11204:         if ($action eq 'none') {
11205:             next;
11206:         } else {
11207:             my %changes;
11208:             my $newend = 0;
11209:             my $newstart = $now;
11210:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11211:             $changes{$action}{$newkey} = {
11212:                 type => $accesstype,
11213:                 time => {
11214:                     start => $newstart,
11215:                     end   => $newend,
11216:                 },
11217:             };
11218:             if ($accesstype eq 'ip') {
11219:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11220:             }
11221:             my ($outcome,$deloutcome,$new_values,$translation) =
11222:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11223:             unless ($outcome eq 'ok') {
11224:                 $errors .= $outcome.' ';
11225:             }
11226:         }
11227:     }
11228:     if ($errors) {
11229:         $errors =~ s/\s$//;
11230:         return $errors;
11231:     } else {
11232:         return 'ok';
11233:     }
11234: }
11235: 
11236: #------------------------------------------------------Get Marked as Read Only
11237: 
11238: sub get_marked_as_readonly {
11239:     my ($domain,$user,$what,$group) = @_;
11240:     my $current_permissions = &get_portfile_permissions($domain,$user);
11241:     my @readonly_files;
11242:     my $cmp1=$what;
11243:     if (ref($what)) { $cmp1=join('',@{$what}) };
11244:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11245:         if (defined($group)) {
11246:             if ($file_name !~ m-^\Q$group\E/-) {
11247:                 next;
11248:             }
11249:         }
11250:         if (ref($value) eq "ARRAY"){
11251:             foreach my $stored_what (@{$value}) {
11252:                 my $cmp2=$stored_what;
11253:                 if (ref($stored_what) eq 'ARRAY') {
11254:                     $cmp2=join('',@{$stored_what});
11255:                 }
11256:                 if ($cmp1 eq $cmp2) {
11257:                     push(@readonly_files, $file_name);
11258:                     last;
11259:                 } elsif (!defined($what)) {
11260:                     push(@readonly_files, $file_name);
11261:                     last;
11262:                 }
11263:             }
11264:         }
11265:     }
11266:     return @readonly_files;
11267: }
11268: #-----------------------------------------------------------Get Marked as Read Only Hash
11269: 
11270: sub get_marked_as_readonly_hash {
11271:     my ($current_permissions,$group,$what) = @_;
11272:     my %readonly_files;
11273:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11274:         if (defined($group)) {
11275:             if ($file_name !~ m-^\Q$group\E/-) {
11276:                 next;
11277:             }
11278:         }
11279:         if (ref($value) eq "ARRAY"){
11280:             foreach my $stored_what (@{$value}) {
11281:                 if (ref($stored_what) eq 'ARRAY') {
11282:                     foreach my $lock_descriptor(@{$stored_what}) {
11283:                         if ($lock_descriptor eq 'graded') {
11284:                             $readonly_files{$file_name} = 'graded';
11285:                         } elsif ($lock_descriptor eq 'handback') {
11286:                             $readonly_files{$file_name} = 'handback';
11287:                         } else {
11288:                             if (!exists($readonly_files{$file_name})) {
11289:                                 $readonly_files{$file_name} = 'locked';
11290:                             }
11291:                         }
11292:                     }
11293:                 } 
11294:             }
11295:         } 
11296:     }
11297:     return %readonly_files;
11298: }
11299: # ------------------------------------------------------------ Unmark as Read Only
11300: 
11301: sub unmark_as_readonly {
11302:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11303:     # for portfolio submissions, $what contains [$symb,$crsid] 
11304:     my ($domain,$user,$what,$file_name,$group) = @_;
11305:     $file_name = &declutter_portfile($file_name);
11306:     my $symb_crs = $what;
11307:     if (ref($what)) { $symb_crs=join('',@$what); }
11308:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11309:     my ($tmp)=keys(%current_permissions);
11310:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11311:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11312:     foreach my $file (@readonly_files) {
11313: 	my $clean_file = &declutter_portfile($file);
11314: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11315: 	my $current_locks = $current_permissions{$file};
11316:         my @new_locks;
11317:         my @del_keys;
11318:         if (ref($current_locks) eq "ARRAY"){
11319:             foreach my $locker (@{$current_locks}) {
11320:                 my $compare=$locker;
11321:                 if (ref($locker) eq 'ARRAY') {
11322:                     $compare=join('',@{$locker});
11323:                     if ($compare ne $symb_crs) {
11324:                         push(@new_locks, $locker);
11325:                     }
11326:                 }
11327:             }
11328:             if (scalar(@new_locks) > 0) {
11329:                 $current_permissions{$file} = \@new_locks;
11330:             } else {
11331:                 push(@del_keys, $file);
11332:                 &del('file_permissions',\@del_keys, $domain, $user);
11333:                 delete($current_permissions{$file});
11334:             }
11335:         }
11336:     }
11337:     &put('file_permissions',\%current_permissions,$domain,$user);
11338:     return;
11339: }
11340: 
11341: # ------------------------------------------------------------ Directory lister
11342: 
11343: sub dirlist {
11344:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11345:     $uri=~s/^\///;
11346:     $uri=~s/\/$//;
11347:     my ($udom, $uname);
11348:     if ($getuserdir) {
11349:         $udom = $userdomain;
11350:         $uname = $username;
11351:     } else {
11352:         (undef,$udom,$uname)=split(/\//,$uri);
11353:         if(defined($userdomain)) {
11354:             $udom = $userdomain;
11355:         }
11356:         if(defined($username)) {
11357:             $uname = $username;
11358:         }
11359:     }
11360:     my ($dirRoot,$listing,@listing_results);
11361: 
11362:     $dirRoot = $perlvar{'lonDocRoot'};
11363:     if (defined($getpropath)) {
11364:         $dirRoot = &propath($udom,$uname);
11365:         $dirRoot =~ s/\/$//;
11366:     } elsif (defined($getuserdir)) {
11367:         my $subdir=$uname.'__';
11368:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11369:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11370:                    ."/$udom/$subdir/$uname";
11371:     } elsif (defined($alternateRoot)) {
11372:         $dirRoot = $alternateRoot;
11373:     }
11374: 
11375:     if($udom) {
11376:         if($uname) {
11377:             my $uhome = &homeserver($uname,$udom);
11378:             if ($uhome eq 'no_host') {
11379:                 return ([],'no_host');
11380:             }
11381:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11382:                               .$getuserdir.':'.&escape($dirRoot)
11383:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11384:             if ($listing eq 'unknown_cmd') {
11385:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11386:             } else {
11387:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11388:             }
11389:             if ($listing eq 'unknown_cmd') {
11390:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11391:                 @listing_results = split(/:/,$listing);
11392:             } else {
11393:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11394:             }
11395:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11396:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11397:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11398:                 return ([],$listing);
11399:             } else {
11400:                 return (\@listing_results);
11401:             }
11402:         } elsif(!$alternateRoot) {
11403:             my (%allusers,%listerror);
11404: 	    my %servers = &get_servers($udom,'library');
11405:  	    foreach my $tryserver (keys(%servers)) {
11406:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11407:                                   &escape($udom),$tryserver);
11408:                 if ($listing eq 'unknown_cmd') {
11409: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11410: 				      $udom, $tryserver);
11411:                 } else {
11412:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11413:                 }
11414: 		if ($listing eq 'unknown_cmd') {
11415: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11416: 				      $udom, $tryserver);
11417: 		    @listing_results = split(/:/,$listing);
11418: 		} else {
11419: 		    @listing_results =
11420: 			map { &unescape($_); } split(/:/,$listing);
11421: 		}
11422:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11423:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11424:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11425:                     $listerror{$tryserver} = $listing;
11426:                 } else {
11427: 		    foreach my $line (@listing_results) {
11428: 			my ($entry) = split(/&/,$line,2);
11429: 			$allusers{$entry} = 1;
11430: 		    }
11431: 		}
11432:             }
11433:             my @alluserslist=();
11434:             foreach my $user (sort(keys(%allusers))) {
11435:                 push(@alluserslist,$user.'&user');
11436:             }
11437: 
11438:             if (!%listerror) {
11439:                 # no errors
11440:                 return (\@alluserslist);
11441:             } elsif (scalar(keys(%servers)) == 1) {
11442:                 # one library server, one error 
11443:                 my ($key) = keys(%listerror);
11444:                 return (\@alluserslist, $listerror{$key});
11445:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11446:                 # con_lost indicates that we might miss data from at least one
11447:                 # library server
11448:                 return (\@alluserslist, 'con_lost');
11449:             } else {
11450:                 # multiple library servers and no con_lost -> data should be
11451:                 # complete. 
11452:                 return (\@alluserslist);
11453:             }
11454: 
11455:         } else {
11456:             return ([],'missing username');
11457:         }
11458:     } elsif(!defined($getpropath)) {
11459:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11460:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11461:         return (\@all_domains);
11462:     } else {
11463:         return ([],'missing domain');
11464:     }
11465: }
11466: 
11467: # --------------------------------------------- GetFileTimestamp
11468: # This function utilizes dirlist and returns the date stamp for
11469: # when it was last modified.  It will also return an error of -1
11470: # if an error occurs
11471: 
11472: sub GetFileTimestamp {
11473:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11474:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11475:     $studentName   = &LONCAPA::clean_username($studentName);
11476:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11477:                                     undef,$getuserdir);
11478:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11479:         return -1;
11480:     }
11481:     if (ref($fileref) eq 'ARRAY') {
11482:         my @stats = split('&',$fileref->[0]);
11483:         # @stats contains first the filename, then the stat output
11484:         return $stats[10]; # so this is 10 instead of 9.
11485:     } else {
11486:         return -1;
11487:     }
11488: }
11489: 
11490: sub stat_file {
11491:     my ($uri) = @_;
11492:     $uri = &clutter_with_no_wrapper($uri);
11493: 
11494:     my ($udom,$uname,$file);
11495:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11496: 	($udom,$uname,$file) =
11497: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11498: 	$file = 'userfiles/'.$file;
11499:     }
11500:     if ($uri =~ m-^/res/-) {
11501: 	($udom,$uname) = 
11502: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11503: 	$file = $uri;
11504:     }
11505: 
11506:     if (!$udom || !$uname || !$file) {
11507: 	# unable to handle the uri
11508: 	return ();
11509:     }
11510:     my $getpropath;
11511:     if ($file =~ /^userfiles\//) {
11512:         $getpropath = 1;
11513:     }
11514:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11515:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11516:         return ();
11517:     } else {
11518:         if (ref($listref) eq 'ARRAY') {
11519:             my @stats = split('&',$listref->[0]);
11520: 	    shift(@stats); #filename is first
11521: 	    return @stats;
11522:         }
11523:     }
11524:     return ();
11525: }
11526: 
11527: # --------------------------------------------------------- recursedirs
11528: # Recursive function to traverse either a specific user's Authoring Space
11529: # or corresponding Published Resource Space, and populate the hash ref:
11530: # $dirhashref with URLs of all directories, and if $filehashref hash
11531: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11532: # or .rights files in resource space, and .meta, .save, .log, and .bak
11533: # files in Authoring Space.
11534: #
11535: # Inputs:
11536: #
11537: # $is_home - true if current server is home server for user's space
11538: # $context - either: priv, or res respectively for Authoring or Resource Space.
11539: # $docroot - Document root (i.e., /home/httpd/html
11540: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11541: # $relpath - Current path (relative to top level).
11542: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11543: # $filehashref - reference to hash to populate with URLs of files (Optional)
11544: #
11545: # Returns: nothing
11546: #
11547: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11548: #
11549: # Currently used by interface/londocs.pm to create linked select boxes for
11550: # directory and filename to import a Course "Author" resource into a course, and
11551: # also to create linked select boxes for Authoring Space and Directory to choose
11552: # save location for creation of a new "standard" problem from the Course Editor.
11553: #
11554: 
11555: sub recursedirs {
11556:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11557:     return unless (ref($dirhashref) eq 'HASH');
11558:     my $currpath = $docroot.$toppath;
11559:     if ($relpath) {
11560:         $currpath .= "/$relpath";
11561:     }
11562:     my $savefile;
11563:     if (ref($filehashref)) {
11564:         $savefile = 1;
11565:     }
11566:     if ($is_home) {
11567:         if (opendir(my $dirh,$currpath)) {
11568:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11569:                 next if ($item eq '');
11570:                 if (-d "$currpath/$item") {
11571:                     my $newpath;
11572:                     if ($relpath) {
11573:                         $newpath = "$relpath/$item";
11574:                     } else {
11575:                         $newpath = $item;
11576:                     }
11577:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11578:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11579:                 } elsif ($savefile) {
11580:                     if ($context eq 'priv') {
11581:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11582:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11583:                         }
11584:                     } else {
11585:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11586:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11587:                         }
11588:                     }
11589:                 }
11590:             }
11591:             closedir($dirh);
11592:         }
11593:     } else {
11594:         my ($dirlistref,$listerror) =
11595:             &dirlist($toppath.$relpath);
11596:         my @dir_lines;
11597:         my $dirptr=16384;
11598:         if (ref($dirlistref) eq 'ARRAY') {
11599:             foreach my $dir_line (sort
11600:                               {
11601:                                   my ($afile)=split('&',$a,2);
11602:                                   my ($bfile)=split('&',$b,2);
11603:                                   return (lc($afile) cmp lc($bfile));
11604:                               } (@{$dirlistref})) {
11605:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11606:                     split(/\&/,$dir_line,16);
11607:                 $item =~ s/\s+$//;
11608:                 next if (($item =~ /^\.\.?$/) || ($obs));
11609:                 if ($dirptr&$testdir) {
11610:                     my $newpath;
11611:                     if ($relpath) {
11612:                         $newpath = "$relpath/$item";
11613:                     } else {
11614:                         $relpath = '/';
11615:                         $newpath = $item;
11616:                     }
11617:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11618:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11619:                 } elsif ($savefile) {
11620:                     if ($context eq 'priv') {
11621:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11622:                             $filehashref->{$relpath}{$item} = 1;
11623:                         }
11624:                     } else {
11625:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11626:                             $filehashref->{$relpath}{$item} = 1;
11627:                         }
11628:                     }
11629:                 }
11630:             }
11631:         }
11632:     }
11633:     return;
11634: }
11635: 
11636: # -------------------------------------------------------- Value of a Condition
11637: 
11638: # gets the value of a specific preevaluated condition
11639: #    stored in the string  $env{user.state.<cid>}
11640: # or looks up a condition reference in the bighash and if if hasn't
11641: # already been evaluated recurses into docondval to get the value of
11642: # the condition, then memoizing it to 
11643: #   $env{user.state.<cid>.<condition>}
11644: sub directcondval {
11645:     my $number=shift;
11646:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11647: 	&Apache::lonuserstate::evalstate();
11648:     }
11649:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11650: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11651:     } elsif ($number =~ /^_/) {
11652: 	my $sub_condition;
11653: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11654: 		&GDBM_READER(),0640)) {
11655: 	    $sub_condition=$bighash{'conditions'.$number};
11656: 	    untie(%bighash);
11657: 	}
11658: 	my $value = &docondval($sub_condition);
11659: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11660: 	return $value;
11661:     }
11662:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11663:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11664:     } else {
11665:        return 2;
11666:     }
11667: }
11668: 
11669: # get the collection of conditions for this resource
11670: sub condval {
11671:     my $condidx=shift;
11672:     my $allpathcond='';
11673:     foreach my $cond (split(/\|/,$condidx)) {
11674: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11675: 	    $allpathcond.=
11676: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11677: 	}
11678:     }
11679:     $allpathcond=~s/\|$//;
11680:     return &docondval($allpathcond);
11681: }
11682: 
11683: #evaluates an expression of conditions
11684: sub docondval {
11685:     my ($allpathcond) = @_;
11686:     my $result=0;
11687:     if ($env{'request.course.id'}
11688: 	&& defined($allpathcond)) {
11689: 	my $operand='|';
11690: 	my @stack;
11691: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11692: 	    if ($chunk eq '(') {
11693: 		push @stack,($operand,$result);
11694: 	    } elsif ($chunk eq ')') {
11695: 		my $before=pop @stack;
11696: 		if (pop @stack eq '&') {
11697: 		    $result=$result>$before?$before:$result;
11698: 		} else {
11699: 		    $result=$result>$before?$result:$before;
11700: 		}
11701: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11702: 		$operand=$chunk;
11703: 	    } else {
11704: 		my $new=directcondval($chunk);
11705: 		if ($operand eq '&') {
11706: 		    $result=$result>$new?$new:$result;
11707: 		} else {
11708: 		    $result=$result>$new?$result:$new;
11709: 		}
11710: 	    }
11711: 	}
11712:     }
11713:     return $result;
11714: }
11715: 
11716: # ---------------------------------------------------- Devalidate courseresdata
11717: 
11718: sub devalidatecourseresdata {
11719:     my ($coursenum,$coursedomain)=@_;
11720:     my $hashid=$coursenum.':'.$coursedomain;
11721:     &devalidate_cache_new('courseres',$hashid);
11722: }
11723: 
11724: 
11725: # --------------------------------------------------- Course Resourcedata Query
11726: #
11727: #  Parameters:
11728: #      $coursenum    - Number of the course.
11729: #      $coursedomain - Domain at which the course was created.
11730: #  Returns:
11731: #     A hash of the course parameters along (I think) with timestamps
11732: #     and version info.
11733: 
11734: sub get_courseresdata {
11735:     my ($coursenum,$coursedomain)=@_;
11736:     my $coursehom=&homeserver($coursenum,$coursedomain);
11737:     my $hashid=$coursenum.':'.$coursedomain;
11738:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11739:     my %dumpreply;
11740:     unless (defined($cached)) {
11741: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11742: 	$result=\%dumpreply;
11743: 	my ($tmp) = keys(%dumpreply);
11744: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11745: 	    &do_cache_new('courseres',$hashid,$result,600);
11746: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11747: 	    return $tmp;
11748: 	} elsif ($tmp =~ /^(error)/) {
11749: 	    $result=undef;
11750: 	    &do_cache_new('courseres',$hashid,$result,600);
11751: 	}
11752:     }
11753:     return $result;
11754: }
11755: 
11756: sub devalidateuserresdata {
11757:     my ($uname,$udom)=@_;
11758:     my $hashid="$udom:$uname";
11759:     &devalidate_cache_new('userres',$hashid);
11760: }
11761: 
11762: sub get_userresdata {
11763:     my ($uname,$udom)=@_;
11764:     #most student don\'t have any data set, check if there is some data
11765:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11766: 
11767:     my $hashid="$udom:$uname";
11768:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11769:     if (!defined($cached)) {
11770: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11771: 	$result=\%resourcedata;
11772: 	&do_cache_new('userres',$hashid,$result,600);
11773:     }
11774:     my ($tmp)=keys(%$result);
11775:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11776: 	return $result;
11777:     }
11778:     #error 2 occurs when the .db doesn't exist
11779:     if ($tmp!~/error: 2 /) {
11780:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11781: 	    &logthis("<font color=\"blue\">WARNING:".
11782: 		     " Trying to get resource data for ".
11783: 		     $uname." at ".$udom.": ".
11784: 		     $tmp."</font>");
11785:         }
11786:     } elsif ($tmp=~/error: 2 /) {
11787: 	#&EXT_cache_set($udom,$uname);
11788: 	&do_cache_new('userres',$hashid,undef,600);
11789: 	undef($tmp); # not really an error so don't send it back
11790:     }
11791:     return $tmp;
11792: }
11793: #----------------------------------------------- resdata - return resource data
11794: #  Purpose:
11795: #    Return resource data for either users or for a course.
11796: #  Parameters:
11797: #     $name      - Course/user name.
11798: #     $domain    - Name of the domain the user/course is registered on.
11799: #     $type      - Type of thing $name is (must be 'course' or 'user')
11800: #     $mapp      - decluttered URL of enclosing map  
11801: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11802: #     $recurseup - Ref to array of map URLs, starting with map containing
11803: #                  $mapp up through hierarchy of nested maps to top level map.  
11804: #     $courseid  - CourseID (first part of param identifier).
11805: #     $modifier  - Middle part of param identifier.
11806: #     $what      - Last part of param identifier.
11807: #     @which     - Array of names of resources desired.
11808: #  Returns:
11809: #     The value of the first reasource in @which that is found in the
11810: #     resource hash.
11811: #  Exceptional Conditions:
11812: #     If the $type passed in is not valid (not the string 'course' or 
11813: #     'user', an undefined  reference is returned.
11814: #     If none of the resources are found, an undef is returned
11815: sub resdata {
11816:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11817:         $modifier,$what,@which)=@_;
11818:     my $result;
11819:     if ($type eq 'course') {
11820: 	$result=&get_courseresdata($name,$domain);
11821:     } elsif ($type eq 'user') {
11822: 	$result=&get_userresdata($name,$domain);
11823:     }
11824:     if (!ref($result)) { return $result; }    
11825:     foreach my $item (@which) {
11826:         if ($item->[1] eq 'course') {
11827:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11828:                 unless ($$recursed) {
11829:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11830:                     $$recursed = 1;
11831:                 }
11832:                 foreach my $item (@${recurseup}) {
11833:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11834:                     last if (defined($result->{$norecursechk}));
11835:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11836:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11837:                 }
11838:             }
11839:         }
11840:         if (defined($result->{$item->[0]})) {
11841: 	    return [$result->{$item->[0]},$item->[1]];
11842: 	}
11843:     }
11844:     return undef;
11845: }
11846: 
11847: sub get_domain_lti {
11848:     my ($cdom,$context) = @_;
11849:     my ($name,%lti);
11850:     if ($context eq 'consumer') {
11851:         $name = 'ltitools';
11852:     } elsif ($context eq 'provider') {
11853:         $name = 'lti';
11854:     } else {
11855:         return %lti;
11856:     }
11857:     my ($result,$cached)=&is_cached_new($name,$cdom);
11858:     if (defined($cached)) {
11859:         if (ref($result) eq 'HASH') {
11860:             %lti = %{$result};
11861:         }
11862:     } else {
11863:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11864:         if (ref($domconfig{$name}) eq 'HASH') {
11865:             %lti = %{$domconfig{$name}};
11866:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11867:             if (ref($encdomconfig{$name}) eq 'HASH') {
11868:                 foreach my $id (keys(%lti)) {
11869:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11870:                         foreach my $item ('key','secret') {
11871:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11872:                         }
11873:                     }
11874:                 }
11875:             }
11876:         }
11877:         my $cachetime = 24*60*60;
11878:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11879:     }
11880:     return %lti;
11881: }
11882: 
11883: sub get_numsuppfiles {
11884:     my ($cnum,$cdom,$ignorecache)=@_;
11885:     my $hashid=$cnum.':'.$cdom;
11886:     my ($suppcount,$cached);
11887:     unless ($ignorecache) {
11888:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11889:     }
11890:     unless (defined($cached)) {
11891:         my $chome=&homeserver($cnum,$cdom);
11892:         unless ($chome eq 'no_host') {
11893:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11894:             my $suppmap = 'supplemental.sequence';
11895:             ($suppcount,$supptools,$errors) =
11896:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11897:                                                          $supptools,$errors);
11898:         }
11899:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11900:     }
11901:     return $suppcount;
11902: }
11903: 
11904: #
11905: # EXT resource caching routines
11906: #
11907: 
11908: {
11909: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11910: #
11911: # The course for which we cache
11912: my $cachedmapkey='';
11913: # The cached recursive maps for this course
11914: my %cachedmaps=();
11915: # When this was last done
11916: my $cachedmaptime='';
11917: 
11918: sub clear_EXT_cache_status {
11919:     &delenv('cache.EXT.');
11920: }
11921: 
11922: sub EXT_cache_status {
11923:     my ($target_domain,$target_user) = @_;
11924:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11925:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11926:         # We know already the user has no data
11927:         return 1;
11928:     } else {
11929:         return 0;
11930:     }
11931: }
11932: 
11933: sub EXT_cache_set {
11934:     my ($target_domain,$target_user) = @_;
11935:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11936:     #&appenv({$cachename => time});
11937: }
11938: 
11939: # --------------------------------------------------------- Value of a Variable
11940: sub EXT {
11941: 
11942:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11943:     unless ($varname) { return ''; }
11944:     #get real user name/domain, courseid and symb
11945:     my $courseid;
11946:     my $publicuser;
11947:     if ($symbparm) {
11948: 	$symbparm=&get_symb_from_alias($symbparm);
11949:     }
11950:     if (!($uname && $udom)) {
11951:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11952:       if (!$symbparm) {	$symbparm=$cursymb; }
11953:     } else {
11954: 	$courseid=$env{'request.course.id'};
11955:     }
11956:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11957:     my $rest;
11958:     if (defined($therest[0])) {
11959:        $rest=join('.',@therest);
11960:     } else {
11961:        $rest='';
11962:     }
11963: 
11964:     my $qualifierrest=$qualifier;
11965:     if ($rest) { $qualifierrest.='.'.$rest; }
11966:     my $spacequalifierrest=$space;
11967:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11968:     if ($realm eq 'user') {
11969: # --------------------------------------------------------------- user.resource
11970: 	if ($space eq 'resource') {
11971: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11972: 		  || defined($Apache::lonhomework::parsing_a_task))
11973: 		 &&
11974: 		 ($symbparm eq &symbread()) ) {	
11975: 		# if we are in the middle of processing the resource the
11976: 		# get the value we are planning on committing
11977:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11978:                     return $Apache::lonhomework::results{$qualifierrest};
11979:                 } else {
11980:                     return $Apache::lonhomework::history{$qualifierrest};
11981:                 }
11982: 	    } else {
11983: 		my %restored;
11984: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11985: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11986: 		} else {
11987: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11988: 		}
11989: 		return $restored{$qualifierrest};
11990: 	    }
11991: # ----------------------------------------------------------------- user.access
11992:         } elsif ($space eq 'access') {
11993: 	    # FIXME - not supporting calls for a specific user
11994:             return &allowed($qualifier,$rest);
11995: # ------------------------------------------ user.preferences, user.environment
11996:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11997: 	    if (($uname eq $env{'user.name'}) &&
11998: 		($udom eq $env{'user.domain'})) {
11999: 		return $env{join('.',('environment',$qualifierrest))};
12000: 	    } else {
12001: 		my %returnhash;
12002: 		if (!$publicuser) {
12003: 		    %returnhash=&userenvironment($udom,$uname,
12004: 						 $qualifierrest);
12005: 		}
12006: 		return $returnhash{$qualifierrest};
12007: 	    }
12008: # ----------------------------------------------------------------- user.course
12009:         } elsif ($space eq 'course') {
12010: 	    # FIXME - not supporting calls for a specific user
12011:             return $env{join('.',('request.course',$qualifier))};
12012: # ------------------------------------------------------------------- user.role
12013:         } elsif ($space eq 'role') {
12014: 	    # FIXME - not supporting calls for a specific user
12015:             my ($role,$where)=split(/\./,$env{'request.role'});
12016:             if ($qualifier eq 'value') {
12017: 		return $role;
12018:             } elsif ($qualifier eq 'extent') {
12019:                 return $where;
12020:             }
12021: # ----------------------------------------------------------------- user.domain
12022:         } elsif ($space eq 'domain') {
12023:             return $udom;
12024: # ------------------------------------------------------------------- user.name
12025:         } elsif ($space eq 'name') {
12026:             return $uname;
12027: # ---------------------------------------------------- Any other user namespace
12028:         } else {
12029: 	    my %reply;
12030: 	    if (!$publicuser) {
12031: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12032: 	    }
12033: 	    return $reply{$qualifierrest};
12034:         }
12035:     } elsif ($realm eq 'query') {
12036: # ---------------------------------------------- pull stuff out of query string
12037:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12038: 						[$spacequalifierrest]);
12039: 	return $env{'form.'.$spacequalifierrest}; 
12040:    } elsif ($realm eq 'request') {
12041: # ------------------------------------------------------------- request.browser
12042:         if ($space eq 'browser') {
12043:             return $env{'browser.'.$qualifier};
12044: # ------------------------------------------------------------ request.filename
12045:         } else {
12046:             return $env{'request.'.$spacequalifierrest};
12047:         }
12048:     } elsif ($realm eq 'course') {
12049: # ---------------------------------------------------------- course.description
12050:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12051:     } elsif ($realm eq 'resource') {
12052: 
12053: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12054: 	    if (!$symbparm) { $symbparm=&symbread(); }
12055: 	}
12056: 
12057:         if ($qualifier eq '') {
12058: 	    if ($space eq 'title') {
12059: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12060: 	        return &gettitle($symbparm);
12061: 	    }
12062: 	
12063: 	    if ($space eq 'map') {
12064: 	        my ($map) = &decode_symb($symbparm);
12065: 	        return &symbread($map);
12066: 	    }
12067:             if ($space eq 'maptitle') {
12068:                 my ($map) = &decode_symb($symbparm);
12069:                 return &gettitle($map);
12070:             }
12071: 	    if ($space eq 'filename') {
12072: 	        if ($symbparm) {
12073: 		    return &clutter((&decode_symb($symbparm))[2]);
12074: 	        }
12075: 	        return &hreflocation('',$env{'request.filename'});
12076: 	    }
12077: 
12078:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12079:                 if ($space eq 'visibleparts') {
12080:                     my $navmap = Apache::lonnavmaps::navmap->new();
12081:                     my $item;
12082:                     if (ref($navmap)) {
12083:                         my $res = $navmap->getBySymb($symbparm);
12084:                         my $parts = $res->parts();
12085:                         if (ref($parts) eq 'ARRAY') {
12086:                             $item = join(',',@{$parts});
12087:                         }
12088:                         undef($navmap);
12089:                     }
12090:                     return $item;
12091:                 }
12092:             }
12093:         }
12094: 
12095: 	my ($section, $group, @groups, @recurseup, $recursed);
12096: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12097:         if (($courseid eq '') && ($cid)) {
12098:             $courseid = $cid;
12099:         }
12100: 	if (($symbparm && $courseid) && 
12101: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12102: 
12103: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12104: 
12105: # ----------------------------------------------------- Cascading lookup scheme
12106: 	    my $symbp=$symbparm;
12107: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12108: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12109:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12110: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12111: 	    if (($env{'user.name'} eq $uname) &&
12112: 		($env{'user.domain'} eq $udom)) {
12113: 		$section=$env{'request.course.sec'};
12114:                 @groups = split(/:/,$env{'request.course.groups'});  
12115:                 @groups=&sort_course_groups($courseid,@groups); 
12116: 	    } else {
12117: 		if (! defined($usection)) {
12118: 		    $section=&getsection($udom,$uname,$courseid);
12119: 		} else {
12120: 		    $section = $usection;
12121: 		}
12122:                 @groups = &get_users_groups($udom,$uname,$courseid);
12123: 	    }
12124: 
12125: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12126: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12127:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12128: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12129: 
12130: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12131: 	    my $courselevelr=$courseid.'.'.$symbparm;
12132:             $courseleveli=$courseid.'.'.$recurseparm;
12133: 	    $courselevelm=$courseid.'.'.$mapparm;
12134: 
12135: # ----------------------------------------------------------- first, check user
12136: 
12137: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12138:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12139: 				       ([$courselevelr,'resource'],
12140: 					[$courselevelm,'map'     ],
12141:                                         [$courseleveli,'map'     ],
12142: 					[$courselevel, 'course'  ]));
12143: 	    if (defined($userreply)) { return &get_reply($userreply); }
12144: 
12145: # ------------------------------------------------ second, check some of course
12146:             my $coursereply;
12147:             if (@groups > 0) {
12148:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12149:                                        $recurseparm,$mapparm,$spacequalifierrest,
12150:                                        $mapp,\$recursed,\@recurseup);
12151:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12152:             }
12153: 
12154: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12155: 				  $env{'course.'.$courseid.'.domain'},
12156: 				  'course',$mapp,\$recursed,\@recurseup,
12157:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12158: 				  ([$seclevelr,   'resource'],
12159: 				   [$seclevelm,   'map'     ],
12160:                                    [$secleveli,   'map'     ],
12161: 				   [$seclevel,    'course'  ],
12162: 				   [$courselevelr,'resource']));
12163: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12164: 
12165: # ------------------------------------------------------ third, check map parms
12166: 	    my %parmhash=();
12167: 	    my $thisparm='';
12168: 	    if (tie(%parmhash,'GDBM_File',
12169: 		    $env{'request.course.fn'}.'_parms.db',
12170: 		    &GDBM_READER(),0640)) {
12171: 		$thisparm=$parmhash{$symbparm};
12172: 		untie(%parmhash);
12173: 	    }
12174: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12175: 	}
12176: # ------------------------------------------ fourth, look in resource metadata
12177:  
12178:         my $what = $spacequalifierrest;
12179: 	$what=~s/\./\_/;
12180: 	my $filename;
12181: 	if (!$symbparm) { $symbparm=&symbread(); }
12182: 	if ($symbparm) {
12183: 	    $filename=(&decode_symb($symbparm))[2];
12184: 	} else {
12185: 	    $filename=$env{'request.filename'};
12186: 	}
12187:         my $toolsymb;
12188:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12189:             $toolsymb = $symbparm;
12190:         }
12191: 	my $metadata=&metadata($filename,$what,$toolsymb);
12192: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12193: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12194: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12195: 
12196: # ----------------------------------------------- fifth, look in rest of course
12197: 	if ($symbparm && defined($courseid) && 
12198: 	    $courseid eq $env{'request.course.id'}) {
12199: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12200: 				     $env{'course.'.$courseid.'.domain'},
12201: 				     'course',$mapp,\$recursed,\@recurseup,
12202:                                      $courseid,'.',$spacequalifierrest,
12203: 				     ([$courselevelm,'map'   ],
12204:                                       [$courseleveli,'map'   ],
12205: 				      [$courselevel, 'course']));
12206: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12207: 	}
12208: # ------------------------------------------------------------------ Cascade up
12209: 	unless ($space eq '0') {
12210: 	    my @parts=split(/_/,$space);
12211: 	    my $id=pop(@parts);
12212: 	    my $part=join('_',@parts);
12213: 	    if ($part eq '') { $part='0'; }
12214: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12215: 				 $symbparm,$udom,$uname,$section,1);
12216: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12217: 	}
12218: 	if ($recurse) { return undef; }
12219: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12220: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12221: # ---------------------------------------------------- Any other user namespace
12222:     } elsif ($realm eq 'environment') {
12223: # ----------------------------------------------------------------- environment
12224: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12225: 	    return $env{'environment.'.$spacequalifierrest};
12226: 	} else {
12227: 	    if ($uname eq 'anonymous' && $udom eq '') {
12228: 		return '';
12229: 	    }
12230: 	    my %returnhash=&userenvironment($udom,$uname,
12231: 					    $spacequalifierrest);
12232: 	    return $returnhash{$spacequalifierrest};
12233: 	}
12234:     } elsif ($realm eq 'system') {
12235: # ----------------------------------------------------------------- system.time
12236: 	if ($space eq 'time') {
12237: 	    return time;
12238:         }
12239:     } elsif ($realm eq 'server') {
12240: # ----------------------------------------------------------------- system.time
12241: 	if ($space eq 'name') {
12242: 	    return $ENV{'SERVER_NAME'};
12243:         }
12244:     }
12245:     return '';
12246: }
12247: 
12248: sub get_reply {
12249:     my ($reply_value) = @_;
12250:     if (ref($reply_value) eq 'ARRAY') {
12251:         if (wantarray) {
12252: 	    return @$reply_value;
12253:         }
12254:         return $reply_value->[0];
12255:     } else {
12256:         return $reply_value;
12257:     }
12258: }
12259: 
12260: sub check_group_parms {
12261:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12262:         $recursed,$recurseupref) = @_;
12263:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12264:                   [$what,'course']);
12265:     my $coursereply;
12266:     foreach my $group (@{$groups}) {
12267:         my @groupitems = ();
12268:         foreach my $level (@levels) {
12269:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12270:              push(@groupitems,[$item,$level->[1]]);
12271:         }
12272:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12273:                                    $env{'course.'.$courseid.'.domain'},
12274:                                    'course',$mapp,$recursed,$recurseupref,
12275:                                    $courseid,'.['.$group.'].',$what,
12276:                                    @groupitems);
12277:         last if (defined($coursereply));
12278:     }
12279:     return $coursereply;
12280: }
12281: 
12282: sub get_map_hierarchy {
12283:     my ($mapname,$courseid) = @_;
12284:     my @recurseup = ();
12285:     if ($mapname) {
12286:         if (($cachedmapkey eq $courseid) &&
12287:             (abs($cachedmaptime-time)<5)) {
12288:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12289:                 return @{$cachedmaps{$mapname}};
12290:             }
12291:         }
12292:         my $navmap = Apache::lonnavmaps::navmap->new();
12293:         if (ref($navmap)) {
12294:             @recurseup = $navmap->recurseup_maps($mapname);
12295:             undef($navmap);
12296:             $cachedmaps{$mapname} = \@recurseup;
12297:             $cachedmaptime=time;
12298:             $cachedmapkey=$courseid;
12299:         }
12300:     }
12301:     return @recurseup;
12302: }
12303: 
12304: }
12305: 
12306: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12307:     my ($courseid,@groups) = @_;
12308:     @groups = sort(@groups);
12309:     return @groups;
12310: }
12311: 
12312: sub packages_tab_default {
12313:     my ($uri,$varname,$toolsymb)=@_;
12314:     my (undef,$part,$name)=split(/\./,$varname);
12315: 
12316:     my (@extension,@specifics,$do_default);
12317:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12318: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12319: 	if ($pack_type eq 'default') {
12320: 	    $do_default=1;
12321: 	} elsif ($pack_type eq 'extension') {
12322: 	    push(@extension,[$package,$pack_type,$pack_part]);
12323: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12324: 	    # only look at packages defaults for packages that this id is
12325: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12326: 	}
12327:     }
12328:     # first look for a package that matches the requested part id
12329:     foreach my $package (@specifics) {
12330: 	my (undef,$pack_type,$pack_part)=@{$package};
12331: 	next if ($pack_part ne $part);
12332: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12333: 	    return $packagetab{"$pack_type&$name&default"};
12334: 	}
12335:     }
12336:     # look for any possible matching non extension_ package
12337:     foreach my $package (@specifics) {
12338: 	my (undef,$pack_type,$pack_part)=@{$package};
12339: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12340: 	    return $packagetab{"$pack_type&$name&default"};
12341: 	}
12342: 	if ($pack_type eq 'part') { $pack_part='0'; }
12343: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12344: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12345: 	}
12346:     }
12347:     # look for any posible extension_ match
12348:     foreach my $package (@extension) {
12349: 	my ($package,$pack_type)=@{$package};
12350: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12351: 	    return $packagetab{"$pack_type&$name&default"};
12352: 	}
12353: 	if (defined($packagetab{$package."&$name&default"})) {
12354: 	    return $packagetab{$package."&$name&default"};
12355: 	}
12356:     }
12357:     # look for a global default setting
12358:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12359: 	return $packagetab{"default&$name&default"};
12360:     }
12361:     return undef;
12362: }
12363: 
12364: sub add_prefix_and_part {
12365:     my ($prefix,$part)=@_;
12366:     my $keyroot;
12367:     if (defined($prefix) && $prefix !~ /^__/) {
12368: 	# prefix that has a part already
12369: 	$keyroot=$prefix;
12370:     } elsif (defined($prefix)) {
12371: 	# prefix that is missing a part
12372: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12373:     } else {
12374: 	# no prefix at all
12375: 	if (defined($part)) { $keyroot='_'.$part; }
12376:     }
12377:     return $keyroot;
12378: }
12379: 
12380: # ---------------------------------------------------------------- Get metadata
12381: 
12382: my %metaentry;
12383: my %importedpartids;
12384: my %importedrespids;
12385: sub metadata {
12386:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12387:     $uri=&declutter($uri);
12388:     # if it is a non metadata possible uri return quickly
12389:     if (($uri eq '') || 
12390: 	(($uri =~ m|^/*adm/|) && 
12391: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12392:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12393: 	return undef;
12394:     }
12395:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12396: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12397: 	return undef;
12398:     }
12399:     my $filename=$uri;
12400:     $uri=~s/\.meta$//;
12401: #
12402: # Is the metadata already cached?
12403: # Look at timestamp of caching
12404: # Everything is cached by the main uri, libraries are never directly cached
12405: #
12406:     if (!defined($liburi)) {
12407: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12408: 	if (defined($cached)) { return $result->{':'.$what}; }
12409:     }
12410: 
12411: #
12412: # If the uri is for an external tool the file from
12413: # which metadata should be retrieved depends on whether
12414: # the tool had been configured to be gradable (set in the Course
12415: # Editor or Resource Editor).
12416: #
12417: # If a valid symb has been included as the third arg in the call
12418: # to &metadata() that can be used to retrieve the value of
12419: # parameter_0_gradable set for the resource, and included in the
12420: # uploaded map containing the tool. The value is retrieved via
12421: # &EXT(), if a valid symb is available.  Otherwise the value of
12422: # gradable in the exttool_$marker.db file for the tool instance
12423: # is retrieved via &get().
12424: #
12425: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12426: # hiddenresource and encrypturl (during course initialization)
12427: # the map-level parameter for resource.0.gradable included in the 
12428: # uploaded map containing the tool will not yet have been stored
12429: # in the user_course_parms.db file for the user's session, so in 
12430: # this case fall back to retrieving gradable status from the
12431: # exttool_$marker.db file.
12432: #
12433: # In order to avoid an infinite loop, &metadata() will return
12434: # before a call to &EXT(), if the uri is for an external tool
12435: # and the $what for which metadata is being requested is
12436: # parameter_0_gradable or 0_gradable.
12437: #
12438: 
12439:     if ($uri =~ /ext\.tool$/) {
12440:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12441:             return;
12442:         } else {
12443:             my ($checked,$use_passback);
12444:             if ($toolsymb ne '') {
12445:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12446:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12447:                     $checked = 1;
12448:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12449:                         $use_passback = 1;
12450:                     }
12451:                 }
12452:             }
12453:             unless ($checked) {
12454:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12455:                 $marker=~s/\D//g;
12456:                 if ($marker) {
12457:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12458:                     $use_passback = $toolsettings{'gradable'};
12459:                 }
12460:             }
12461:             if ($use_passback) {
12462:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12463:             } else {
12464:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12465:             }
12466:         }
12467:     }
12468: 
12469:     {
12470: # Imported parts would go here
12471:         my @origfiletagids=();
12472:         my $importedparts=0;
12473: 
12474: # Imported responseids would go here
12475:         my $importedresponses=0;
12476: #
12477: # Is this a recursive call for a library?
12478: #
12479: #	if (! exists($metacache{$uri})) {
12480: #	    $metacache{$uri}={};
12481: #	}
12482: 	my $cachetime = 60*60;
12483:         if ($liburi) {
12484: 	    $liburi=&declutter($liburi);
12485:             $filename=$liburi;
12486:         } else {
12487: 	    &devalidate_cache_new('meta',$uri);
12488: 	    undef(%metaentry);
12489: 	}
12490:         my %metathesekeys=();
12491:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12492: 	my $metastring;
12493: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12494: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12495: 	    $metastring = 
12496: 		&Apache::lonnet::ssi_body($which,
12497: 					  ('grade_target' => 'meta'));
12498: 	    $cachetime = 1; # only want this cached in the child not long term
12499: 	} elsif (($uri !~ m -^(editupload)/-) && 
12500:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12501: 	    my $file=&filelocation('',&clutter($filename));
12502: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12503: 	    $metastring=&getfile($file);
12504: 	}
12505:         my $parser=HTML::LCParser->new(\$metastring);
12506:         my $token;
12507:         undef %metathesekeys;
12508:         while ($token=$parser->get_token) {
12509: 	    if ($token->[0] eq 'S') {
12510: 		if (defined($token->[2]->{'package'})) {
12511: #
12512: # This is a package - get package info
12513: #
12514: 		    my $package=$token->[2]->{'package'};
12515: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12516: 		    if (defined($token->[2]->{'id'})) { 
12517: 			$keyroot.='_'.$token->[2]->{'id'}; 
12518: 		    }
12519: 		    if ($metaentry{':packages'}) {
12520: 			$metaentry{':packages'}.=','.$package.$keyroot;
12521: 		    } else {
12522: 			$metaentry{':packages'}=$package.$keyroot;
12523: 		    }
12524: 		    foreach my $pack_entry (keys(%packagetab)) {
12525: 			my $part=$keyroot;
12526: 			$part=~s/^\_//;
12527: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12528: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12529: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12530: 			    # ignore package.tab specified default values
12531:                             # here &package_tab_default() will fetch those
12532: 			    if ($subp eq 'default') { next; }
12533: 			    my $value=$packagetab{$pack_entry};
12534: 			    my $unikey;
12535: 			    if ($pack =~ /_0$/) {
12536: 				$unikey='parameter_0_'.$name;
12537: 				$part=0;
12538: 			    } else {
12539: 				$unikey='parameter'.$keyroot.'_'.$name;
12540: 			    }
12541: 			    if ($subp eq 'display') {
12542: 				$value.=' [Part: '.$part.']';
12543: 			    }
12544: 			    $metaentry{':'.$unikey.'.part'}=$part;
12545: 			    $metathesekeys{$unikey}=1;
12546: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12547: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12548: 			    }
12549: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12550: 				$metaentry{':'.$unikey}=
12551: 				    $metaentry{':'.$unikey.'.default'};
12552: 			    }
12553: 			}
12554: 		    }
12555: 		} else {
12556: #
12557: # This is not a package - some other kind of start tag
12558: #
12559: 		    my $entry=$token->[1];
12560: 		    my $unikey='';
12561: 
12562: 		    if ($entry eq 'import') {
12563: #
12564: # Importing a library here
12565: #
12566:                         my $location=$parser->get_text('/import');
12567:                         my $dir=$filename;
12568:                         $dir=~s|[^/]*$||;
12569:                         $location=&filelocation($dir,$location);
12570: 
12571:                         my $importid=$token->[2]->{'id'};
12572:                         my $importmode=$token->[2]->{'importmode'};
12573: #
12574: # Check metadata for imported file to
12575: # see if it contained response items
12576: #
12577:                         my ($origfile,@libfilekeys);
12578:                         my %currmetaentry = %metaentry;
12579:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12580:                                                            $depthcount+1));
12581:                         if (grep(/^responseorder$/,@libfilekeys)) {
12582:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12583:                                                              undef,$depthcount+1);
12584:                             if ($libresponseorder ne '') {
12585:                                 if ($#origfiletagids<0) {
12586:                                     undef(%importedrespids);
12587:                                     undef(%importedpartids);
12588:                                 }
12589:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12590:                                 if (@respids) {
12591:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12592:                                 }
12593:                                 if ($importedrespids{$importid} ne '') {
12594:                                     $importedresponses = 1;
12595: # We need to get the original file and the imported file to get the response order correct
12596: # Load and inspect original file
12597:                                     if ($#origfiletagids<0) {
12598:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12599:                                         $origfile=&getfile($origfilelocation);
12600:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12601:                                     }
12602:                                 }
12603:                             }
12604:                         }
12605: # Do not overwrite contents of %metaentry hash for resource itself with 
12606: # hash populated for imported library file
12607:                         %metaentry = %currmetaentry;
12608:                         undef(%currmetaentry);
12609:                         if ($importmode eq 'part') {
12610: # Import as part(s)
12611:                            $importedparts=1;
12612: # We need to get the original file and the imported file to get the part order correct
12613: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12614: # Load and inspect original file if we didn't do that already
12615:                            if ($#origfiletagids<0) {
12616:                                undef(%importedrespids);
12617:                                undef(%importedpartids);
12618:                                if ($origfile eq '') {
12619:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12620:                                    $origfile=&getfile($origfilelocation);
12621:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12622:                                }
12623:                            }
12624:                            my @impfilepartids;
12625: # If <partorder> tag is included in metadata for the imported file
12626: # get the parts in the imported file from that.
12627:                            if (grep(/^partorder$/,@libfilekeys)) {
12628:                                %currmetaentry = %metaentry;
12629:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12630:                                                             $depthcount+1);
12631:                                %metaentry = %currmetaentry;
12632:                                undef(%currmetaentry);
12633:                                if ($libpartorder ne '') {
12634:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12635:                                }
12636:                            } else {
12637: # If no <partorder> tag available, load and inspect imported file
12638:                                my $impfile=&getfile($location);
12639:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12640:                            }
12641:                            if ($#impfilepartids>=0) {
12642: # This problem had parts
12643:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12644:                            } else {
12645: # Importing by turning a single problem into a problem part
12646: # It gets the import-tags ID as part-ID
12647:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12648:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12649:                            }
12650:                         } else {
12651: # Import as problem or as normal import
12652:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12653:                             unless ($importmode eq 'problem') {
12654: # Normal import
12655:                                 if (defined($token->[2]->{'id'})) {
12656:                                     $unikey.='_'.$token->[2]->{'id'};
12657:                                 }
12658:                             }
12659: # Check metadata for imported file to
12660: # see if it contained parts
12661:                             if (grep(/^partorder$/,@libfilekeys)) {
12662:                                 %currmetaentry = %metaentry;
12663:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12664:                                                              $depthcount+1);
12665:                                 %metaentry = %currmetaentry;
12666:                                 undef(%currmetaentry);
12667:                                 if ($libpartorder ne '') {
12668:                                     $importedparts = 1;
12669:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12670:                                 }
12671:                             }
12672:                         }
12673: 			if ($depthcount<20) {
12674: 			    my $metadata = 
12675: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12676: 					  $depthcount+1);
12677: 			    foreach my $meta (split(',',$metadata)) {
12678: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12679: 				$metathesekeys{$meta}=1;
12680: 			    }
12681:                         }
12682: 		    } else {
12683: #
12684: # Not importing, some other kind of non-package, non-library start tag
12685: # 
12686:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12687:                         if (defined($token->[2]->{'id'})) {
12688:                             $unikey.='_'.$token->[2]->{'id'};
12689:                         }
12690: 			if (defined($token->[2]->{'name'})) { 
12691: 			    $unikey.='_'.$token->[2]->{'name'}; 
12692: 			}
12693: 			$metathesekeys{$unikey}=1;
12694: 			foreach my $param (@{$token->[3]}) {
12695: 			    $metaentry{':'.$unikey.'.'.$param} =
12696: 				$token->[2]->{$param};
12697: 			}
12698: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12699: 			my $default=$metaentry{':'.$unikey.'.default'};
12700: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12701: 		 # only ws inside the tag, and not in default, so use default
12702: 		 # as value
12703: 			    $metaentry{':'.$unikey}=$default;
12704: 			} elsif ( $internaltext =~ /\S/ ) {
12705: 		  # something interesting inside the tag
12706: 			    $metaentry{':'.$unikey}=$internaltext;
12707: 			} else {
12708: 		  # no interesting values, don't set a default
12709: 			}
12710: # end of not-a-package not-a-library import
12711: 		    }
12712: # end of not-a-package start tag
12713: 		}
12714: # the next is the end of "start tag"
12715: 	    }
12716: 	}
12717: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12718: 	$extension = lc($extension);
12719: 	if ($extension eq 'htm') { $extension='html'; }
12720: 
12721: 	foreach my $key (keys(%packagetab)) {
12722: 	    #no specific packages #how's our extension
12723: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12724: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12725: 					 \%metathesekeys);
12726: 	}
12727: 
12728: 	if (!exists($metaentry{':packages'})
12729: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12730: 	    foreach my $key (keys(%packagetab)) {
12731: 		#no specific packages well let's get default then
12732: 		if ($key!~/^default&/) { next; }
12733: 		&metadata_create_package_def($uri,$key,'default',
12734: 					     \%metathesekeys);
12735: 	    }
12736: 	}
12737: # are there custom rights to evaluate
12738: 	if ($metaentry{':copyright'} eq 'custom') {
12739: 
12740:     #
12741:     # Importing a rights file here
12742:     #
12743: 	    unless ($depthcount) {
12744: 		my $location=$metaentry{':customdistributionfile'};
12745: 		my $dir=$filename;
12746: 		$dir=~s|[^/]*$||;
12747: 		$location=&filelocation($dir,$location);
12748: 		my $rights_metadata =
12749: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12750: 			      $depthcount+1);
12751: 		foreach my $rights (split(',',$rights_metadata)) {
12752: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12753: 		    $metathesekeys{$rights}=1;
12754: 		}
12755: 	    }
12756: 	}
12757: 	# uniqifiy package listing
12758: 	my %seen;
12759: 	my @uniq_packages =
12760: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12761: 	$metaentry{':packages'} = join(',',@uniq_packages);
12762: 
12763:         if (($importedresponses) || ($importedparts)) {
12764:             if ($importedparts) {
12765: # We had imported parts and need to rebuild partorder
12766:                 $metaentry{':partorder'}='';
12767:                 $metathesekeys{'partorder'}=1;
12768:             }
12769:             if ($importedresponses) {
12770: # We had imported responses and need to rebuil responseorder
12771:                 $metaentry{':responseorder'}='';
12772:                 $metathesekeys{'responseorder'}=1;
12773:             }
12774:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12775:                 my $origid = $origfiletagids[$index+1];
12776:                 if ($origfiletagids[$index] eq 'part') {
12777: # Original part, part of the problem
12778:                     if ($importedparts) {
12779:                         $metaentry{':partorder'}.=','.$origid;
12780:                     }
12781:                 } elsif ($origfiletagids[$index] eq 'import') {
12782:                     if ($importedparts) {
12783: # We have imported parts at this position
12784:                         if ($importedpartids{$origid} ne '') {
12785:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12786:                         }
12787:                     }
12788:                     if ($importedresponses) {
12789: # We have imported responses at this position
12790:                         if ($importedrespids{$origid} ne '') {
12791:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12792:                         }
12793:                     }
12794:                 } else {
12795: # Original response item, part of the problem
12796:                     if ($importedresponses) {
12797:                         $metaentry{':responseorder'}.=','.$origid;
12798:                     }
12799:                 }
12800:             }
12801:             if ($importedparts) {
12802:                 $metaentry{':partorder'}=~s/^\,//;
12803:             }
12804:             if ($importedresponses) {
12805:                 $metaentry{':responseorder'}=~s/^\,//;
12806:             }
12807:         }
12808: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12809: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12810: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12811:         unless ($liburi) {
12812: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12813:         }
12814: # this is the end of "was not already recently cached
12815:     }
12816:     return $metaentry{':'.$what};
12817: }
12818: 
12819: sub metadata_create_package_def {
12820:     my ($uri,$key,$package,$metathesekeys)=@_;
12821:     my ($pack,$name,$subp)=split(/\&/,$key);
12822:     if ($subp eq 'default') { next; }
12823:     
12824:     if (defined($metaentry{':packages'})) {
12825: 	$metaentry{':packages'}.=','.$package;
12826:     } else {
12827: 	$metaentry{':packages'}=$package;
12828:     }
12829:     my $value=$packagetab{$key};
12830:     my $unikey;
12831:     $unikey='parameter_0_'.$name;
12832:     $metaentry{':'.$unikey.'.part'}=0;
12833:     $$metathesekeys{$unikey}=1;
12834:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12835: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12836:     }
12837:     if (defined($metaentry{':'.$unikey.'.default'})) {
12838: 	$metaentry{':'.$unikey}=
12839: 	    $metaentry{':'.$unikey.'.default'};
12840:     }
12841: }
12842: 
12843: sub metadata_generate_part0 {
12844:     my ($metadata,$metacache,$uri) = @_;
12845:     my %allnames;
12846:     foreach my $metakey (keys(%$metadata)) {
12847: 	if ($metakey=~/^parameter\_(.*)/) {
12848: 	  my $part=$$metacache{':'.$metakey.'.part'};
12849: 	  my $name=$$metacache{':'.$metakey.'.name'};
12850: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12851: 	    $allnames{$name}=$part;
12852: 	  }
12853: 	}
12854:     }
12855:     foreach my $name (keys(%allnames)) {
12856:       $$metadata{"parameter_0_$name"}=1;
12857:       my $key=":parameter_0_$name";
12858:       $$metacache{"$key.part"}='0';
12859:       $$metacache{"$key.name"}=$name;
12860:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12861: 					   $allnames{$name}.'_'.$name.
12862: 					   '.type'};
12863:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12864: 			     '.display'};
12865:       my $expr='[Part: '.$allnames{$name}.']';
12866:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12867:       $$metacache{"$key.display"}=$olddis;
12868:     }
12869: }
12870: 
12871: # ------------------------------------------------------ Devalidate title cache
12872: 
12873: sub devalidate_title_cache {
12874:     my ($url)=@_;
12875:     if (!$env{'request.course.id'}) { return; }
12876:     my $symb=&symbread($url);
12877:     if (!$symb) { return; }
12878:     my $key=$env{'request.course.id'}."\0".$symb;
12879:     &devalidate_cache_new('title',$key);
12880: }
12881: 
12882: # ------------------------------------------------- Get the title of a course
12883: 
12884: sub current_course_title {
12885:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12886: }
12887: # ------------------------------------------------- Get the title of a resource
12888: 
12889: sub gettitle {
12890:     my $urlsymb=shift;
12891:     my $symb=&symbread($urlsymb);
12892:     if ($symb) {
12893: 	my $key=$env{'request.course.id'}."\0".$symb;
12894: 	my ($result,$cached)=&is_cached_new('title',$key);
12895: 	if (defined($cached)) { 
12896: 	    return $result;
12897: 	}
12898: 	my ($map,$resid,$url)=&decode_symb($symb);
12899: 	my $title='';
12900: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12901: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12902: 	} else {
12903: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12904: 		    &GDBM_READER(),0640)) {
12905: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12906: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12907: 		untie(%bighash);
12908: 	    }
12909: 	}
12910: 	$title=~s/\&colon\;/\:/gs;
12911: 	if ($title) {
12912: # Remember both $symb and $title for dynamic metadata
12913:             $accesshash{$symb.'___crstitle'}=$title;
12914:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12915: # Cache this title and then return it
12916: 	    return &do_cache_new('title',$key,$title,600);
12917: 	}
12918: 	$urlsymb=$url;
12919:     }
12920:     my $title=&metadata($urlsymb,'title');
12921:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12922:     return $title;
12923: }
12924: 
12925: sub get_slot {
12926:     my ($which,$cnum,$cdom)=@_;
12927:     if (!$cnum || !$cdom) {
12928: 	(undef,my $courseid)=&whichuser();
12929: 	$cdom=$env{'course.'.$courseid.'.domain'};
12930: 	$cnum=$env{'course.'.$courseid.'.num'};
12931:     }
12932:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12933:     my %slotinfo;
12934:     if (exists($remembered{$key})) {
12935: 	$slotinfo{$which} = $remembered{$key};
12936:     } else {
12937: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12938: 	&Apache::lonhomework::showhash(%slotinfo);
12939: 	my ($tmp)=keys(%slotinfo);
12940: 	if ($tmp=~/^error:/) { return (); }
12941: 	$remembered{$key} = $slotinfo{$which};
12942:     }
12943:     if (ref($slotinfo{$which}) eq 'HASH') {
12944: 	return %{$slotinfo{$which}};
12945:     }
12946:     return $slotinfo{$which};
12947: }
12948: 
12949: sub get_reservable_slots {
12950:     my ($cnum,$cdom,$uname,$udom) = @_;
12951:     my $now = time;
12952:     my $reservable_info;
12953:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12954:     if (exists($remembered{$key})) {
12955:         $reservable_info = $remembered{$key};
12956:     } else {
12957:         my %resv;
12958:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12959:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12960:         $reservable_info = \%resv;
12961:         $remembered{$key} = $reservable_info;
12962:     }
12963:     return $reservable_info;
12964: }
12965: 
12966: sub get_course_slots {
12967:     my ($cnum,$cdom) = @_;
12968:     my $hashid=$cnum.':'.$cdom;
12969:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12970:     if (defined($cached)) {
12971:         if (ref($result) eq 'HASH') {
12972:             return %{$result};
12973:         }
12974:     } else {
12975:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12976:         my ($tmp) = keys(%slots);
12977:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12978:             &do_cache_new('allslots',$hashid,\%slots,600);
12979:             return %slots;
12980:         }
12981:     }
12982:     return;
12983: }
12984: 
12985: sub devalidate_slots_cache {
12986:     my ($cnum,$cdom)=@_;
12987:     my $hashid=$cnum.':'.$cdom;
12988:     &devalidate_cache_new('allslots',$hashid);
12989: }
12990: 
12991: sub get_coursechange {
12992:     my ($cdom,$cnum) = @_;
12993:     if ($cdom eq '' || $cnum eq '') {
12994:         return unless ($env{'request.course.id'});
12995:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12996:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12997:     }
12998:     my $hashid=$cdom.'_'.$cnum;
12999:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13000:     if ((defined($cached)) && ($change ne '')) {
13001:         return $change;
13002:     } else {
13003:         my %crshash;
13004:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13005:         if ($crshash{'internal.contentchange'} eq '') {
13006:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13007:             if ($change eq '') {
13008:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13009:                 $change = $crshash{'internal.created'};
13010:             }
13011:         } else {
13012:             $change = $crshash{'internal.contentchange'};
13013:         }
13014:         my $cachetime = 600;
13015:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13016:     }
13017:     return $change;
13018: }
13019: 
13020: sub devalidate_coursechange_cache {
13021:     my ($cnum,$cdom)=@_;
13022:     my $hashid=$cnum.':'.$cdom;
13023:     &devalidate_cache_new('crschange',$hashid);
13024: }
13025: 
13026: # ------------------------------------------------- Update symbolic store links
13027: 
13028: sub symblist {
13029:     my ($mapname,%newhash)=@_;
13030:     $mapname=&deversion(&declutter($mapname));
13031:     my %hash;
13032:     if (($env{'request.course.fn'}) && (%newhash)) {
13033:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13034:                       &GDBM_WRCREAT(),0640)) {
13035: 	    foreach my $url (keys(%newhash)) {
13036: 		next if ($url eq 'last_known'
13037: 			 && $env{'form.no_update_last_known'});
13038: 		$hash{declutter($url)}=&encode_symb($mapname,
13039: 						    $newhash{$url}->[1],
13040: 						    $newhash{$url}->[0]);
13041:             }
13042:             if (untie(%hash)) {
13043: 		return 'ok';
13044:             }
13045:         }
13046:     }
13047:     return 'error';
13048: }
13049: 
13050: # --------------------------------------------------------------- Verify a symb
13051: 
13052: sub symbverify {
13053:     my ($symb,$thisurl,$encstate)=@_;
13054:     my $thisfn=$thisurl;
13055:     $thisfn=&declutter($thisfn);
13056: # direct jump to resource in page or to a sequence - will construct own symbs
13057:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13058: # check URL part
13059:     my ($map,$resid,$url)=&decode_symb($symb);
13060: 
13061:     unless ($url eq $thisfn) { return 0; }
13062: 
13063:     $symb=&symbclean($symb);
13064:     $thisurl=&deversion($thisurl);
13065:     $thisfn=&deversion($thisfn);
13066: 
13067:     my %bighash;
13068:     my $okay=0;
13069: 
13070:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13071:                             &GDBM_READER(),0640)) {
13072:         my $noclutter;
13073:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13074:             $thisurl =~ s/\?.+$//;
13075:             if ($map =~ m{^uploaded/.+\.page$}) {
13076:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13077:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13078:                 $noclutter = 1;
13079:             }
13080:         }
13081:         my $ids;
13082:         if ($noclutter) {
13083:             $ids=$bighash{'ids_'.$thisurl};
13084:         } else {
13085:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13086:         }
13087:         unless ($ids) {
13088:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13089:             $ids=$bighash{$idkey};
13090:         }
13091:         if ($ids) {
13092: # ------------------------------------------------------------------- Has ID(s)
13093:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13094:                 $symb =~ s/\?.+$//;
13095:             }
13096: 	    foreach my $id (split(/\,/,$ids)) {
13097: 	       my ($mapid,$resid)=split(/\./,$id);
13098:                if (
13099:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13100:    eq $symb) {
13101:                    if (ref($encstate)) {
13102:                        $$encstate = $bighash{'encrypted_'.$id};
13103:                    }
13104: 		   if (($env{'request.role.adv'}) ||
13105: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13106:                        ($thisurl eq '/adm/navmaps')) {
13107: 		       $okay=1;
13108:                        last;
13109: 		   }
13110: 	       }
13111: 	   }
13112:         }
13113: 	untie(%bighash);
13114:     }
13115:     return $okay;
13116: }
13117: 
13118: # --------------------------------------------------------------- Clean-up symb
13119: 
13120: sub symbclean {
13121:     my $symb=shift;
13122:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13123: # remove version from map
13124:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13125: 
13126: # remove version from URL
13127:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13128: 
13129: # remove wrapper
13130: 
13131:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13132:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13133:     return $symb;
13134: }
13135: 
13136: # ---------------------------------------------- Split symb to find map and url
13137: 
13138: sub encode_symb {
13139:     my ($map,$resid,$url)=@_;
13140:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13141: }
13142: 
13143: sub decode_symb {
13144:     my $symb=shift;
13145:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13146:     my ($map,$resid,$url)=split(/___/,$symb);
13147:     return (&fixversion($map),$resid,&fixversion($url));
13148: }
13149: 
13150: sub fixversion {
13151:     my $fn=shift;
13152:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13153:     my %bighash;
13154:     my $uri=&clutter($fn);
13155:     my $key=$env{'request.course.id'}.'_'.$uri;
13156: # is this cached?
13157:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13158:     if (defined($cached)) { return $result; }
13159: # unfortunately not cached, or expired
13160:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13161: 	    &GDBM_READER(),0640)) {
13162:  	if ($bighash{'version_'.$uri}) {
13163:  	    my $version=$bighash{'version_'.$uri};
13164:  	    unless (($version eq 'mostrecent') || 
13165: 		    ($version==&getversion($uri))) {
13166:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13167:  	    }
13168:  	}
13169:  	untie %bighash;
13170:     }
13171:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13172: }
13173: 
13174: sub deversion {
13175:     my $url=shift;
13176:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13177:     return $url;
13178: }
13179: 
13180: # ------------------------------------------------------ Return symb list entry
13181: 
13182: sub symbread {
13183:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13184:     my $cache_str='request.symbread.cached.'.$thisfn;
13185:     if (defined($env{$cache_str})) {
13186:         if ($ignorecachednull) {
13187:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13188:         } else {
13189:             return $env{$cache_str};
13190:         }
13191:     }
13192: # no filename provided? try from environment
13193:     unless ($thisfn) {
13194:         if ($env{'request.symb'}) {
13195: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13196: 	}
13197: 	$thisfn=$env{'request.filename'};
13198:     }
13199:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13200: # is that filename actually a symb? Verify, clean, and return
13201:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13202: 	if (&symbverify($thisfn,$1)) {
13203: 	    return $env{$cache_str}=&symbclean($thisfn);
13204: 	}
13205:     }
13206:     $thisfn=declutter($thisfn);
13207:     my %hash;
13208:     my %bighash;
13209:     my $syval='';
13210:     if (($env{'request.course.fn'}) && ($thisfn)) {
13211:         my $targetfn = $thisfn;
13212:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13213:             $targetfn = 'adm/wrapper/'.$thisfn;
13214:         }
13215: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13216: 	    $targetfn=$1;
13217: 	}
13218:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13219:                       &GDBM_READER(),0640)) {
13220: 	    $syval=$hash{$targetfn};
13221:             untie(%hash);
13222:         }
13223: # ---------------------------------------------------------- There was an entry
13224:         if ($syval) {
13225: 	    #unless ($syval=~/\_\d+$/) {
13226: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13227: 		    #&appenv({'request.ambiguous' => $thisfn});
13228: 		    #return $env{$cache_str}='';
13229: 		#}    
13230: 		#$syval.=$1;
13231: 	    #}
13232:         } else {
13233: # ------------------------------------------------------- Was not in symb table
13234:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13235:                             &GDBM_READER(),0640)) {
13236: # ---------------------------------------------- Get ID(s) for current resource
13237:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13238:               unless ($ids) { 
13239:                  $ids=$bighash{'ids_/'.$thisfn};
13240:               }
13241:               unless ($ids) {
13242: # alias?
13243: 		  $ids=$bighash{'mapalias_'.$thisfn};
13244:               }
13245:               if ($ids) {
13246: # ------------------------------------------------------------------- Has ID(s)
13247:                  my @possibilities=split(/\,/,$ids);
13248:                  if ($#possibilities==0) {
13249: # ----------------------------------------------- There is only one possibility
13250: 		     my ($mapid,$resid)=split(/\./,$ids);
13251: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13252: 						    $resid,$thisfn);
13253:                      if (ref($possibles) eq 'HASH') {
13254:                          $possibles->{$syval} = 1;    
13255:                      }
13256:                      if ($checkforblock) {
13257:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13258:                          if (@blockers) {
13259:                              $syval = '';
13260:                              return;
13261:                          }
13262:                      }
13263:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13264: # ------------------------------------------ There is more than one possibility
13265:                      my $realpossible=0;
13266:                      foreach my $id (@possibilities) {
13267: 			 my $file=$bighash{'src_'.$id};
13268:                          my $canaccess;
13269:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13270:                              $canaccess = 1;
13271:                          } else { 
13272:                              $canaccess = &allowed('bre',$file);
13273:                          }
13274:                          if ($canaccess) {
13275:          		     my ($mapid,$resid)=split(/\./,$id);
13276:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13277:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13278: 						             $resid,$thisfn);
13279:                                  if (ref($possibles) eq 'HASH') {
13280:                                      $possibles->{$syval} = 1;
13281:                                  }
13282:                                  if ($checkforblock) {
13283:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13284:                                      unless (@blockers > 0) {
13285:                                          $syval = $poss_syval;
13286:                                          $realpossible++;
13287:                                      }
13288:                                  } else {
13289:                                      $syval = $poss_syval;
13290:                                      $realpossible++;
13291:                                  }
13292:                              }
13293: 			 }
13294:                      }
13295: 		     if ($realpossible!=1) { $syval=''; }
13296:                  } else {
13297:                      $syval='';
13298:                  }
13299: 	      }
13300:               untie(%bighash);
13301:            }
13302:         }
13303:         if ($syval) {
13304: 	    return $env{$cache_str}=$syval;
13305:         }
13306:     }
13307:     &appenv({'request.ambiguous' => $thisfn});
13308:     return $env{$cache_str}='';
13309: }
13310: 
13311: # ---------------------------------------------------------- Return random seed
13312: 
13313: sub numval {
13314:     my $txt=shift;
13315:     $txt=~tr/A-J/0-9/;
13316:     $txt=~tr/a-j/0-9/;
13317:     $txt=~tr/K-T/0-9/;
13318:     $txt=~tr/k-t/0-9/;
13319:     $txt=~tr/U-Z/0-5/;
13320:     $txt=~tr/u-z/0-5/;
13321:     $txt=~s/\D//g;
13322:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13323:     return int($txt);
13324: }
13325: 
13326: sub numval2 {
13327:     my $txt=shift;
13328:     $txt=~tr/A-J/0-9/;
13329:     $txt=~tr/a-j/0-9/;
13330:     $txt=~tr/K-T/0-9/;
13331:     $txt=~tr/k-t/0-9/;
13332:     $txt=~tr/U-Z/0-5/;
13333:     $txt=~tr/u-z/0-5/;
13334:     $txt=~s/\D//g;
13335:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13336:     my $total;
13337:     foreach my $val (@txts) { $total+=$val; }
13338:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13339:     return int($total);
13340: }
13341: 
13342: sub numval3 {
13343:     use integer;
13344:     my $txt=shift;
13345:     $txt=~tr/A-J/0-9/;
13346:     $txt=~tr/a-j/0-9/;
13347:     $txt=~tr/K-T/0-9/;
13348:     $txt=~tr/k-t/0-9/;
13349:     $txt=~tr/U-Z/0-5/;
13350:     $txt=~tr/u-z/0-5/;
13351:     $txt=~s/\D//g;
13352:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13353:     my $total;
13354:     foreach my $val (@txts) { $total+=$val; }
13355:     if ($_64bit) { $total=(($total<<32)>>32); }
13356:     return $total;
13357: }
13358: 
13359: sub digest {
13360:     my ($data)=@_;
13361:     my $digest=&Digest::MD5::md5($data);
13362:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13363:     my ($e,$f);
13364:     {
13365:         use integer;
13366:         $e=($a+$b);
13367:         $f=($c+$d);
13368:         if ($_64bit) {
13369:             $e=(($e<<32)>>32);
13370:             $f=(($f<<32)>>32);
13371:         }
13372:     }
13373:     if (wantarray) {
13374: 	return ($e,$f);
13375:     } else {
13376: 	my $g;
13377: 	{
13378: 	    use integer;
13379: 	    $g=($e+$f);
13380: 	    if ($_64bit) {
13381: 		$g=(($g<<32)>>32);
13382: 	    }
13383: 	}
13384: 	return $g;
13385:     }
13386: }
13387: 
13388: sub latest_rnd_algorithm_id {
13389:     return '64bit5';
13390: }
13391: 
13392: sub get_rand_alg {
13393:     my ($courseid)=@_;
13394:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13395:     if ($courseid) {
13396: 	return $env{"course.$courseid.rndseed"};
13397:     }
13398:     return &latest_rnd_algorithm_id();
13399: }
13400: 
13401: sub validCODE {
13402:     my ($CODE)=@_;
13403:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13404:     return 0;
13405: }
13406: 
13407: sub getCODE {
13408:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13409:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13410: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13411: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13412: 	return $Apache::lonhomework::history{'resource.CODE'};
13413:     }
13414:     return undef;
13415: }
13416: #
13417: #  Determines the random seed for a specific context:
13418: #
13419: # parameters:
13420: #   symb      - in course context the symb for the seed.
13421: #   course_id - The course id of the form domain_coursenum.
13422: #   domain    - Domain for the user.
13423: #   course    - Course for the user.
13424: #   cenv      - environment of the course.
13425: #
13426: # NOTE:
13427: #   All parameters are picked out of the environment if missing
13428: #   or not defined.
13429: #   If a symb cannot be determined the current time is used instead.
13430: #
13431: #  For a given well defined symb, courside, domain, username,
13432: #  and course environment, the seed is reproducible.
13433: #
13434: sub rndseed {
13435:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13436:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13437:     if (!defined($symb)) {
13438: 	unless ($symb=$wsymb) { return time; }
13439:     }
13440:     if (!defined $courseid) { 
13441: 	$courseid=$wcourseid; 
13442:     }
13443:     if (!defined $domain) { $domain=$wdomain; }
13444:     if (!defined $username) { $username=$wusername }
13445: 
13446:     my $which;
13447:     if (defined($cenv->{'rndseed'})) {
13448: 	$which = $cenv->{'rndseed'};
13449:     } else {
13450: 	$which =&get_rand_alg($courseid);
13451:     }
13452:     if (defined(&getCODE())) {
13453: 
13454: 	if ($which eq '64bit5') {
13455: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13456: 	} elsif ($which eq '64bit4') {
13457: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13458: 	} else {
13459: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13460: 	}
13461:     } elsif ($which eq '64bit5') {
13462: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13463:     } elsif ($which eq '64bit4') {
13464: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13465:     } elsif ($which eq '64bit3') {
13466: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13467:     } elsif ($which eq '64bit2') {
13468: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13469:     } elsif ($which eq '64bit') {
13470: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13471:     }
13472:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13473: }
13474: 
13475: sub rndseed_32bit {
13476:     my ($symb,$courseid,$domain,$username)=@_;
13477:     {
13478: 	use integer;
13479: 	my $symbchck=unpack("%32C*",$symb) << 27;
13480: 	my $symbseed=numval($symb) << 22;
13481: 	my $namechck=unpack("%32C*",$username) << 17;
13482: 	my $nameseed=numval($username) << 12;
13483: 	my $domainseed=unpack("%32C*",$domain) << 7;
13484: 	my $courseseed=unpack("%32C*",$courseid);
13485: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13486: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13487: 	#&logthis("rndseed :$num:$symb");
13488: 	if ($_64bit) { $num=(($num<<32)>>32); }
13489: 	return $num;
13490:     }
13491: }
13492: 
13493: sub rndseed_64bit {
13494:     my ($symb,$courseid,$domain,$username)=@_;
13495:     {
13496: 	use integer;
13497: 	my $symbchck=unpack("%32S*",$symb) << 21;
13498: 	my $symbseed=numval($symb) << 10;
13499: 	my $namechck=unpack("%32S*",$username);
13500: 	
13501: 	my $nameseed=numval($username) << 21;
13502: 	my $domainseed=unpack("%32S*",$domain) << 10;
13503: 	my $courseseed=unpack("%32S*",$courseid);
13504: 	
13505: 	my $num1=$symbchck+$symbseed+$namechck;
13506: 	my $num2=$nameseed+$domainseed+$courseseed;
13507: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13508: 	#&logthis("rndseed :$num:$symb");
13509: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13510: 	return "$num1,$num2";
13511:     }
13512: }
13513: 
13514: sub rndseed_64bit2 {
13515:     my ($symb,$courseid,$domain,$username)=@_;
13516:     {
13517: 	use integer;
13518: 	# strings need to be an even # of cahracters long, it it is odd the
13519:         # last characters gets thrown away
13520: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13521: 	my $symbseed=numval($symb) << 10;
13522: 	my $namechck=unpack("%32S*",$username.' ');
13523: 	
13524: 	my $nameseed=numval($username) << 21;
13525: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13526: 	my $courseseed=unpack("%32S*",$courseid.' ');
13527: 	
13528: 	my $num1=$symbchck+$symbseed+$namechck;
13529: 	my $num2=$nameseed+$domainseed+$courseseed;
13530: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13531: 	#&logthis("rndseed :$num:$symb");
13532: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13533: 	return "$num1,$num2";
13534:     }
13535: }
13536: 
13537: sub rndseed_64bit3 {
13538:     my ($symb,$courseid,$domain,$username)=@_;
13539:     {
13540: 	use integer;
13541: 	# strings need to be an even # of cahracters long, it it is odd the
13542:         # last characters gets thrown away
13543: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13544: 	my $symbseed=numval2($symb) << 10;
13545: 	my $namechck=unpack("%32S*",$username.' ');
13546: 	
13547: 	my $nameseed=numval2($username) << 21;
13548: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13549: 	my $courseseed=unpack("%32S*",$courseid.' ');
13550: 	
13551: 	my $num1=$symbchck+$symbseed+$namechck;
13552: 	my $num2=$nameseed+$domainseed+$courseseed;
13553: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13554: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13555: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13556: 	
13557: 	return "$num1:$num2";
13558:     }
13559: }
13560: 
13561: sub rndseed_64bit4 {
13562:     my ($symb,$courseid,$domain,$username)=@_;
13563:     {
13564: 	use integer;
13565: 	# strings need to be an even # of cahracters long, it it is odd the
13566:         # last characters gets thrown away
13567: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13568: 	my $symbseed=numval3($symb) << 10;
13569: 	my $namechck=unpack("%32S*",$username.' ');
13570: 	
13571: 	my $nameseed=numval3($username) << 21;
13572: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13573: 	my $courseseed=unpack("%32S*",$courseid.' ');
13574: 	
13575: 	my $num1=$symbchck+$symbseed+$namechck;
13576: 	my $num2=$nameseed+$domainseed+$courseseed;
13577: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13578: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13579: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13580: 	
13581: 	return "$num1:$num2";
13582:     }
13583: }
13584: 
13585: sub rndseed_64bit5 {
13586:     my ($symb,$courseid,$domain,$username)=@_;
13587:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13588:     return "$num1:$num2";
13589: }
13590: 
13591: sub rndseed_CODE_64bit {
13592:     my ($symb,$courseid,$domain,$username)=@_;
13593:     {
13594: 	use integer;
13595: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13596: 	my $symbseed=numval2($symb);
13597: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13598: 	my $CODEseed=numval(&getCODE());
13599: 	my $courseseed=unpack("%32S*",$courseid.' ');
13600: 	my $num1=$symbseed+$CODEchck;
13601: 	my $num2=$CODEseed+$courseseed+$symbchck;
13602: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13603: 	#&logthis("rndseed :$num1:$num2:$symb");
13604: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13605: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13606: 	return "$num1:$num2";
13607:     }
13608: }
13609: 
13610: sub rndseed_CODE_64bit4 {
13611:     my ($symb,$courseid,$domain,$username)=@_;
13612:     {
13613: 	use integer;
13614: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13615: 	my $symbseed=numval3($symb);
13616: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13617: 	my $CODEseed=numval3(&getCODE());
13618: 	my $courseseed=unpack("%32S*",$courseid.' ');
13619: 	my $num1=$symbseed+$CODEchck;
13620: 	my $num2=$CODEseed+$courseseed+$symbchck;
13621: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13622: 	#&logthis("rndseed :$num1:$num2:$symb");
13623: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13624: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13625: 	return "$num1:$num2";
13626:     }
13627: }
13628: 
13629: sub rndseed_CODE_64bit5 {
13630:     my ($symb,$courseid,$domain,$username)=@_;
13631:     my $code = &getCODE();
13632:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13633:     return "$num1:$num2";
13634: }
13635: 
13636: sub setup_random_from_rndseed {
13637:     my ($rndseed)=@_;
13638:     if ($rndseed =~/([,:])/) {
13639:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13640:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13641:             &Math::Random::random_set_seed_from_phrase($rndseed);
13642:         } else {
13643:             &Math::Random::random_set_seed($num1,$num2);
13644:         }
13645:     } else {
13646: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13647:     }
13648: }
13649: 
13650: sub latest_receipt_algorithm_id {
13651:     return 'receipt3';
13652: }
13653: 
13654: sub recunique {
13655:     my $fucourseid=shift;
13656:     my $unique;
13657:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13658: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13659: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13660:     } else {
13661: 	$unique=$perlvar{'lonReceipt'};
13662:     }
13663:     return unpack("%32C*",$unique);
13664: }
13665: 
13666: sub recprefix {
13667:     my $fucourseid=shift;
13668:     my $prefix;
13669:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13670: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13671: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13672:     } else {
13673: 	$prefix=$perlvar{'lonHostID'};
13674:     }
13675:     return unpack("%32C*",$prefix);
13676: }
13677: 
13678: sub ireceipt {
13679:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13680: 
13681:     my $return =&recprefix($fucourseid).'-';
13682: 
13683:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13684: 	$env{'request.state'} eq 'construct') {
13685: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13686: 	return $return;
13687:     }
13688: 
13689:     my $cuname=unpack("%32C*",$funame);
13690:     my $cudom=unpack("%32C*",$fudom);
13691:     my $cucourseid=unpack("%32C*",$fucourseid);
13692:     my $cusymb=unpack("%32C*",$fusymb);
13693:     my $cunique=&recunique($fucourseid);
13694:     my $cpart=unpack("%32S*",$part);
13695:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13696: 
13697: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13698: 			       
13699: 	$return.= ($cunique%$cuname+
13700: 		   $cunique%$cudom+
13701: 		   $cusymb%$cuname+
13702: 		   $cusymb%$cudom+
13703: 		   $cucourseid%$cuname+
13704: 		   $cucourseid%$cudom+
13705: 		   $cpart%$cuname+
13706: 		   $cpart%$cudom);
13707:     } else {
13708: 	$return.= ($cunique%$cuname+
13709: 		   $cunique%$cudom+
13710: 		   $cusymb%$cuname+
13711: 		   $cusymb%$cudom+
13712: 		   $cucourseid%$cuname+
13713: 		   $cucourseid%$cudom);
13714:     }
13715:     return $return;
13716: }
13717: 
13718: sub receipt {
13719:     my ($part)=@_;
13720:     my ($symb,$courseid,$domain,$name) = &whichuser();
13721:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13722: }
13723: 
13724: sub whichuser {
13725:     my ($passedsymb)=@_;
13726:     my ($symb,$courseid,$domain,$name,$publicuser);
13727:     if (defined($env{'form.grade_symb'})) {
13728: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13729: 	my $allowed=&allowed('vgr',$tmp_courseid);
13730: 	if (!$allowed &&
13731: 	    exists($env{'request.course.sec'}) &&
13732: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13733: 	    $allowed=&allowed('vgr',$tmp_courseid.
13734: 			      '/'.$env{'request.course.sec'});
13735: 	}
13736: 	if ($allowed) {
13737: 	    ($symb)=&get_env_multiple('form.grade_symb');
13738: 	    $courseid=$tmp_courseid;
13739: 	    ($domain)=&get_env_multiple('form.grade_domain');
13740: 	    ($name)=&get_env_multiple('form.grade_username');
13741: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13742: 	}
13743:     }
13744:     if (!$passedsymb) {
13745: 	$symb=&symbread();
13746:     } else {
13747: 	$symb=$passedsymb;
13748:     }
13749:     $courseid=$env{'request.course.id'};
13750:     $domain=$env{'user.domain'};
13751:     $name=$env{'user.name'};
13752:     if ($name eq 'public' && $domain eq 'public') {
13753: 	if (!defined($env{'form.username'})) {
13754: 	    $env{'form.username'}.=time.rand(10000000);
13755: 	}
13756: 	$name.=$env{'form.username'};
13757:     }
13758:     return ($symb,$courseid,$domain,$name,$publicuser);
13759: 
13760: }
13761: 
13762: # ------------------------------------------------------------ Serves up a file
13763: # returns either the contents of the file or 
13764: # -1 if the file doesn't exist
13765: #
13766: # if the target is a file that was uploaded via DOCS, 
13767: # a check will be made to see if a current copy exists on the local server,
13768: # if it does this will be served, otherwise a copy will be retrieved from
13769: # the home server for the course and stored in /home/httpd/html/userfiles on
13770: # the local server.   
13771: 
13772: sub getfile {
13773:     my ($file) = @_;
13774:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13775:     &repcopy($file);
13776:     return &readfile($file);
13777: }
13778: 
13779: sub repcopy_userfile {
13780:     my ($file)=@_;
13781:     my $londocroot = $perlvar{'lonDocRoot'};
13782:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13783:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13784:     my ($cdom,$cnum,$filename) = 
13785: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13786:     my $uri="/uploaded/$cdom/$cnum/$filename";
13787:     if (-e "$file") {
13788: # we already have a local copy, check it out
13789: 	my @fileinfo = stat($file);
13790: 	my $rtncode;
13791: 	my $info;
13792: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13793: 	if ($lwpresp ne 'ok') {
13794: # there is no such file anymore, even though we had a local copy
13795: 	    if ($rtncode eq '404') {
13796: 		unlink($file);
13797: 	    }
13798: 	    return -1;
13799: 	}
13800: 	if ($info < $fileinfo[9]) {
13801: # nice, the file we have is up-to-date, just say okay
13802: 	    return 'ok';
13803: 	} else {
13804: # the file is outdated, get rid of it
13805: 	    unlink($file);
13806: 	}
13807:     }
13808: # one way or the other, at this point, we don't have the file
13809: # construct the correct path for the file
13810:     my @parts = ($cdom,$cnum); 
13811:     if ($filename =~ m|^(.+)/[^/]+$|) {
13812: 	push @parts, split(/\//,$1);
13813:     }
13814:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13815:     foreach my $part (@parts) {
13816: 	$path .= '/'.$part;
13817: 	if (!-e $path) {
13818: 	    mkdir($path,0770);
13819: 	}
13820:     }
13821: # now the path exists for sure
13822: # get a user agent
13823:     my $transferfile=$file.'.in.transfer';
13824: # FIXME: this should flock
13825:     if (-e $transferfile) { return 'ok'; }
13826:     my $request;
13827:     $uri=~s/^\///;
13828:     my $homeserver = &homeserver($cnum,$cdom);
13829:     my $hostname = &hostname($homeserver);
13830:     my $protocol = $protocol{$homeserver};
13831:     $protocol = 'http' if ($protocol ne 'https');
13832:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13833:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13834: # did it work?
13835:     if ($response->is_error()) {
13836: 	unlink($transferfile);
13837: 	&logthis("Userfile repcopy failed for $uri");
13838: 	return -1;
13839:     }
13840: # worked, rename the transfer file
13841:     rename($transferfile,$file);
13842:     return 'ok';
13843: }
13844: 
13845: sub tokenwrapper {
13846:     my $uri=shift;
13847:     $uri=~s|^https?\://([^/]+)||;
13848:     $uri=~s|^/||;
13849:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13850:     my $token=$1;
13851:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13852:     if ($udom && $uname && $file) {
13853: 	$file=~s|(\?\.*)*$||;
13854:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13855:         my $homeserver = &homeserver($uname,$udom);
13856:         my $hostname = &hostname($homeserver);
13857:         my $protocol = $protocol{$homeserver};
13858:         $protocol = 'http' if ($protocol ne 'https');
13859:         return $protocol.'://'.$hostname.'/'.$uri.
13860:                (($uri=~/\?/)?'&':'?').'token='.$token.
13861:                                '&tokenissued='.$perlvar{'lonHostID'};
13862:     } else {
13863:         return '/adm/notfound.html';
13864:     }
13865: }
13866: 
13867: # call with reqtype HEAD: get last modification time
13868: # call with reqtype GET: get the file contents
13869: # Do not call this with reqtype GET for large files! It loads everything into memory
13870: #
13871: sub getuploaded {
13872:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13873:     $uri=~s/^\///;
13874:     my $homeserver = &homeserver($cnum,$cdom);
13875:     my $hostname = &hostname($homeserver);
13876:     my $protocol = $protocol{$homeserver};
13877:     $protocol = 'http' if ($protocol ne 'https');
13878:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13879:     my $request=new HTTP::Request($reqtype,$uri);
13880:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13881:     $$rtncode = $response->code;
13882:     if (! $response->is_success()) {
13883: 	return 'failed';
13884:     }      
13885:     if ($reqtype eq 'HEAD') {
13886: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13887:     } elsif ($reqtype eq 'GET') {
13888: 	$$info = $response->content;
13889:     }
13890:     return 'ok';
13891: }
13892: 
13893: sub readfile {
13894:     my $file = shift;
13895:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13896:     my $fh;
13897:     open($fh,"<",$file);
13898:     my $a='';
13899:     while (my $line = <$fh>) { $a .= $line; }
13900:     return $a;
13901: }
13902: 
13903: sub filelocation {
13904:     my ($dir,$file) = @_;
13905:     my $location;
13906:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13907: 
13908:     if ($file =~ m-^/adm/-) {
13909: 	$file=~s-^/adm/wrapper/-/-;
13910: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13911:     }
13912: 
13913:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13914:         $location = $file;
13915:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13916:         my ($udom,$uname,$filename)=
13917:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13918:         my $home=&homeserver($uname,$udom);
13919:         my $is_me=0;
13920:         my @ids=&current_machine_ids();
13921:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13922:         if ($is_me) {
13923:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13924:         } else {
13925:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13926:   	      $udom.'/'.$uname.'/'.$filename;
13927:         }
13928:     } elsif ($file =~ m-^/adm/-) {
13929: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13930:     } else {
13931:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13932:         $file=~s:^/(res|priv)/:/:;
13933:         my $space=$1;
13934:         if ( !( $file =~ m:^/:) ) {
13935:             $location = $dir. '/'.$file;
13936:         } else {
13937:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13938:         }
13939:     }
13940:     $location=~s://+:/:g; # remove duplicate /
13941:     while ($location=~m{/\.\./}) {
13942: 	if ($location =~ m{/[^/]+/\.\./}) {
13943: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13944: 	} else {
13945: 	    $location=~ s{/\.\./}{/}g;
13946: 	}
13947:     } #remove dir/..
13948:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13949:     return $location;
13950: }
13951: 
13952: sub hreflocation {
13953:     my ($dir,$file)=@_;
13954:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13955: 	$file=filelocation($dir,$file);
13956:     } elsif ($file=~m-^/adm/-) {
13957: 	$file=~s-^/adm/wrapper/-/-;
13958: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13959:     }
13960:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13961: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13962:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13963: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13964: 	        {/uploaded/$1/$2/}x;
13965:     }
13966:     if ($file=~ m{^/userfiles/}) {
13967: 	$file =~ s{^/userfiles/}{/uploaded/};
13968:     }
13969:     return $file;
13970: }
13971: 
13972: 
13973: 
13974: 
13975: 
13976: sub current_machine_domains {
13977:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13978: }
13979: 
13980: sub machine_domains {
13981:     my ($hostname) = @_;
13982:     my @domains;
13983:     my %hostname = &all_hostnames();
13984:     while( my($id, $name) = each(%hostname)) {
13985: #	&logthis("-$id-$name-$hostname-");
13986: 	if ($hostname eq $name) {
13987: 	    push(@domains,&host_domain($id));
13988: 	}
13989:     }
13990:     return @domains;
13991: }
13992: 
13993: sub current_machine_ids {
13994:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13995: }
13996: 
13997: sub machine_ids {
13998:     my ($hostname) = @_;
13999:     $hostname ||= &hostname($perlvar{'lonHostID'});
14000:     my @ids;
14001:     my %name_to_host = &all_names();
14002:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14003: 	return @{ $name_to_host{$hostname} };
14004:     }
14005:     return;
14006: }
14007: 
14008: sub additional_machine_domains {
14009:     my @domains;
14010:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14011:     while( my $line = <$fh>) {
14012:         $line =~ s/\s//g;
14013:         push(@domains,$line);
14014:     }
14015:     return @domains;
14016: }
14017: 
14018: sub default_login_domain {
14019:     my $domain = $perlvar{'lonDefDomain'};
14020:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14021:     foreach my $posdom (&current_machine_domains(),
14022:                         &additional_machine_domains()) {
14023:         if (lc($posdom) eq lc($testdomain)) {
14024:             $domain=$posdom;
14025:             last;
14026:         }
14027:     }
14028:     return $domain;
14029: }
14030: 
14031: sub uses_sts {
14032:     my ($ignore_cache) = @_;
14033:     my $lonhost = $perlvar{'lonHostID'};
14034:     my $hostname = &hostname($lonhost);
14035:     my $sts_on;
14036:     if ($protocol{$lonhost} eq 'https') {
14037:         my $cachetime = 12*3600;
14038:         if (!$ignore_cache) {
14039:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14040:             if (defined($cached)) {
14041:                 return $sts_on;
14042:             }
14043:         }
14044:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14045:         my $request=new HTTP::Request('HEAD',$url);
14046:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14047:         if ($response->is_success) {
14048:             my $has_sts = $response->header('Strict-Transport-Security');
14049:             if ($has_sts eq '') {
14050:                 $sts_on = 0;
14051:             } else {
14052:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14053:                     my $maxage = $1;
14054:                     if ($maxage) {
14055:                         $sts_on = 1;
14056:                     } else {
14057:                         $sts_on = 0;
14058:                     }
14059:                 } else {
14060:                     $sts_on = 0;
14061:                 }
14062:             }
14063:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14064:         }
14065:     }
14066:     return;
14067: }
14068: 
14069: # ------------------------------------------------------------- Declutters URLs
14070: 
14071: sub declutter {
14072:     my $thisfn=shift;
14073:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14074:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14075:         $thisfn=~s{^/home/httpd/html}{};
14076:     }
14077:     $thisfn=~s/^\///;
14078:     $thisfn=~s|^adm/wrapper/||;
14079:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14080:     $thisfn=~s/^res\///;
14081:     $thisfn=~s/^priv\///;
14082:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14083:         $thisfn=~s/\?.+$//;
14084:     }
14085:     return $thisfn;
14086: }
14087: 
14088: # ------------------------------------------------------------- Clutter up URLs
14089: 
14090: sub clutter {
14091:     my $thisfn='/'.&declutter(shift);
14092:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14093: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14094:        $thisfn='/res'.$thisfn; 
14095:     }
14096:     if ($thisfn !~m|^/adm|) {
14097: 	if ($thisfn =~ m|^/ext/|) {
14098: 	    $thisfn='/adm/wrapper'.$thisfn;
14099: 	} else {
14100: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14101: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14102: 	    if ($embstyle eq 'ssi'
14103: 		|| ($embstyle eq 'hdn')
14104: 		|| ($embstyle eq 'rat')
14105: 		|| ($embstyle eq 'prv')
14106: 		|| ($embstyle eq 'ign')) {
14107: 		#do nothing with these
14108: 	    } elsif (($embstyle eq 'img') 
14109: 		|| ($embstyle eq 'emb')
14110: 		|| ($embstyle eq 'wrp')) {
14111: 		$thisfn='/adm/wrapper'.$thisfn;
14112: 	    } elsif ($embstyle eq 'unk'
14113: 		     && $thisfn!~/\.(sequence|page)$/) {
14114: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14115: 	    } else {
14116: #		&logthis("Got a blank emb style");
14117: 	    }
14118: 	}
14119:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14120:         $thisfn='/adm/wrapper'.$thisfn;
14121:     }
14122:     return $thisfn;
14123: }
14124: 
14125: sub clutter_with_no_wrapper {
14126:     my $uri = &clutter(shift);
14127:     if ($uri =~ m-^/adm/-) {
14128: 	$uri =~ s-^/adm/wrapper/-/-;
14129: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14130:     }
14131:     return $uri;
14132: }
14133: 
14134: sub freeze_escape {
14135:     my ($value)=@_;
14136:     if (ref($value)) {
14137: 	$value=&nfreeze($value);
14138: 	return '__FROZEN__'.&escape($value);
14139:     }
14140:     return &escape($value);
14141: }
14142: 
14143: 
14144: sub thaw_unescape {
14145:     my ($value)=@_;
14146:     if ($value =~ /^__FROZEN__/) {
14147: 	substr($value,0,10,undef);
14148: 	$value=&unescape($value);
14149: 	return &thaw($value);
14150:     }
14151:     return &unescape($value);
14152: }
14153: 
14154: sub correct_line_ends {
14155:     my ($result)=@_;
14156:     $$result =~s/\r\n/\n/mg;
14157:     $$result =~s/\r/\n/mg;
14158: }
14159: # ================================================================ Main Program
14160: 
14161: sub goodbye {
14162:    &logthis("Starting Shut down");
14163: #not converted to using infrastruture and probably shouldn't be
14164:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14165: #converted
14166: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14167:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14168: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14169: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14170: #1.1 only
14171: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14172: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14173: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14174: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14175:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14176:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14177:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14178:    &flushcourselogs();
14179:    &logthis("Shutting down");
14180: }
14181: 
14182: sub get_dns {
14183:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14184:     if (!$ignore_cache) {
14185: 	my ($content,$cached)=
14186: 	    &Apache::lonnet::is_cached_new('dns',$url);
14187: 	if ($cached) {
14188: 	    &$func($content,$hashref);
14189: 	    return;
14190: 	}
14191:     }
14192: 
14193:     my %alldns;
14194:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14195:         foreach my $dns (<$config>) {
14196: 	    next if ($dns !~ /^\^(\S*)/x);
14197:             my $line = $1;
14198:             my ($host,$protocol) = split(/:/,$line);
14199:             if ($protocol ne 'https') {
14200:                 $protocol = 'http';
14201:             }
14202: 	    $alldns{$host} = $protocol;
14203:         }
14204:         close($config);
14205:     }
14206:     while (%alldns) {
14207: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14208: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14209:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14210:         delete($alldns{$dns});
14211: 	next if ($response->is_error());
14212:         if ($url eq '/adm/dns/loncapaCRL') {
14213:             return &$func($response);
14214:         } else {
14215: 	    my @content = split("\n",$response->content);
14216: 	    unless ($nocache) {
14217: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14218: 	    }
14219: 	    &$func(\@content,$hashref);
14220:             return;
14221:         }
14222:     }
14223:     my $which = (split('/',$url,4))[3];
14224:     if ($which eq 'loncapaCRL') {
14225:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14226:         if (-e $diskfile) {
14227:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14228:         } else {
14229:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14230:         }
14231:     } else {
14232:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14233:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14234:             my @content = <$config>;
14235:             close($config);
14236:             &$func(\@content,$hashref);
14237:         }
14238:     }
14239:     return;
14240: }
14241: 
14242: # ------------------------------------------------------Get DNS checksums file
14243: sub parse_dns_checksums_tab {
14244:     my ($lines,$hashref) = @_;
14245:     my $lonhost = $perlvar{'lonHostID'};
14246:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14247:     my $loncaparev = &get_server_loncaparev($machine_dom);
14248:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14249:     my $webconfdir = '/etc/httpd/conf';
14250:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14251:         $webconfdir = '/etc/apache2';
14252:     } elsif ($distro =~ /^sles(\d+)$/) {
14253:         if ($1 >= 10) {
14254:             $webconfdir = '/etc/apache2';
14255:         }
14256:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14257:         if ($1 >= 10.0) {
14258:             $webconfdir = '/etc/apache2';
14259:         }
14260:     }
14261:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14262:     my (%chksum,%revnum);
14263:     if (ref($lines) eq 'ARRAY') {
14264:         chomp(@{$lines});
14265:         my $version = shift(@{$lines});
14266:         if ($version eq $release) {  
14267:             foreach my $line (@{$lines}) {
14268:                 my ($file,$version,$shasum) = split(/,/,$line);
14269:                 if ($file =~ m{^/etc/httpd/conf}) {
14270:                     if ($webconfdir eq '/etc/apache2') {
14271:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14272:                     }
14273:                 }
14274:                 $chksum{$file} = $shasum;
14275:                 $revnum{$file} = $version;
14276:             }
14277:             if (ref($hashref) eq 'HASH') {
14278:                 %{$hashref} = (
14279:                                 sums     => \%chksum,
14280:                                 versions => \%revnum,
14281:                               );
14282:             }
14283:         }
14284:     }
14285:     return;
14286: }
14287: 
14288: sub fetch_dns_checksums {
14289:     my %checksums;
14290:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14291:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14292:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14293:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14294:              \%checksums);
14295:     return \%checksums;
14296: }
14297: 
14298: sub fetch_crl_pemfile {
14299:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14300: }
14301: 
14302: sub save_crl_pem {
14303:     my ($response) = @_;
14304:     my ($msg,$hadchanges);
14305:     if (ref($response)) {
14306:         my $now = time;
14307:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14308:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14309:         if (open(my $fh,'>',"$tmpcrl")) {
14310:             print $fh $response->content;
14311:             close($fh);
14312:             if (-e $lonca) {
14313:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14314:                     my $check = <PIPE>;
14315:                     close(PIPE);
14316:                     chomp($check);
14317:                     if ($check eq 'verify OK') {
14318:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14319:                         my $backup;
14320:                         if (-e $dest) {
14321:                             if (&File::Copy::move($dest,"$dest.bak")) {
14322:                                 $backup = 'ok';
14323:                             }
14324:                         }
14325:                         if (&File::Copy::move($tmpcrl,$dest)) {
14326:                             $msg = 'ok';
14327:                             if ($backup) {
14328:                                 my (%oldnums,%newnums);
14329:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14330:                                     while (<PIPE>) {
14331:                                         $oldnums{(split(/:/))[1]} = 1;
14332:                                     }
14333:                                     close(PIPE);
14334:                                 }
14335:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14336:                                     while(<PIPE>) {
14337:                                         $newnums{(split(/:/))[1]} = 1;
14338:                                     }
14339:                                     close(PIPE);
14340:                                 }
14341:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14342:                                     unless (exists($oldnums{$key})) {
14343:                                         $hadchanges = 1;
14344:                                         last;
14345:                                     }
14346:                                 }
14347:                                 unless ($hadchanges) {
14348:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14349:                                         unless (exists($newnums{$key})) {
14350:                                             $hadchanges = 1;
14351:                                             last;
14352:                                         }
14353:                                     }
14354:                                 }
14355:                             }
14356:                         }
14357:                     } else {
14358:                         unlink($tmpcrl);
14359:                     }
14360:                 } else {
14361:                     unlink($tmpcrl);
14362:                 }
14363:             } else {
14364:                 unlink($tmpcrl);
14365:             }
14366:         }
14367:     }
14368:     return ($msg,$hadchanges);
14369: }
14370: 
14371: # ------------------------------------------------------------ Read domain file
14372: {
14373:     my $loaded;
14374:     my %domain;
14375: 
14376:     sub parse_domain_tab {
14377: 	my ($lines) = @_;
14378: 	foreach my $line (@$lines) {
14379: 	    next if ($line =~ /^(\#|\s*$ )/x);
14380: 
14381: 	    chomp($line);
14382: 	    my ($name,@elements) = split(/:/,$line,9);
14383: 	    my %this_domain;
14384: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14385: 			       'lang_def', 'city', 'longi', 'lati',
14386: 			       'primary') {
14387: 		$this_domain{$field} = shift(@elements);
14388: 	    }
14389: 	    $domain{$name} = \%this_domain;
14390: 	}
14391:     }
14392: 
14393:     sub reset_domain_info {
14394: 	undef($loaded);
14395: 	undef(%domain);
14396:     }
14397: 
14398:     sub load_domain_tab {
14399: 	my ($ignore_cache,$nocache) = @_;
14400: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14401: 	my $fh;
14402: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14403: 	    my @lines = <$fh>;
14404: 	    &parse_domain_tab(\@lines);
14405: 	}
14406: 	close($fh);
14407: 	$loaded = 1;
14408:     }
14409: 
14410:     sub domain {
14411: 	&load_domain_tab() if (!$loaded);
14412: 
14413: 	my ($name,$what) = @_;
14414: 	return if ( !exists($domain{$name}) );
14415: 
14416: 	if (!$what) {
14417: 	    return $domain{$name}{'description'};
14418: 	}
14419: 	return $domain{$name}{$what};
14420:     }
14421: 
14422:     sub domain_info {
14423:         &load_domain_tab() if (!$loaded);
14424:         return %domain;
14425:     }
14426: 
14427: }
14428: 
14429: 
14430: # ------------------------------------------------------------- Read hosts file
14431: {
14432:     my %hostname;
14433:     my %hostdom;
14434:     my %libserv;
14435:     my $loaded;
14436:     my %name_to_host;
14437:     my %internetdom;
14438:     my %LC_dns_serv;
14439: 
14440:     sub parse_hosts_tab {
14441: 	my ($file) = @_;
14442: 	foreach my $configline (@$file) {
14443: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14444:             chomp($configline);
14445: 	    if ($configline =~ /^\^/) {
14446:                 if ($configline =~ /^\^([\w.\-]+)/) {
14447:                     $LC_dns_serv{$1} = 1;
14448:                 }
14449:                 next;
14450:             }
14451: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14452: 	    $name=~s/\s//g;
14453: 	    if ($id && $domain && $role && $name) {
14454:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14455:                     my $curr = $hostname{$id};
14456:                     my $skip;
14457:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14458:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14459:                             $skip = 1;
14460:                         } else {
14461:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14462:                         }
14463:                     }
14464:                     unless ($skip) {
14465:                         push(@{$name_to_host{$name}},$id);
14466:                     }
14467:                 } else {
14468:                     push(@{$name_to_host{$name}},$id);
14469:                 }
14470: 		$hostname{$id}=$name;
14471: 		$hostdom{$id}=$domain;
14472: 		if ($role eq 'library') { $libserv{$id}=$name; }
14473:                 if (defined($protocol)) {
14474:                     if ($protocol eq 'https') {
14475:                         $protocol{$id} = $protocol;
14476:                     } else {
14477:                         $protocol{$id} = 'http'; 
14478:                     }
14479:                 } else {
14480:                     $protocol{$id} = 'http';
14481:                 }
14482:                 if (defined($intdom)) {
14483:                     $internetdom{$id} = $intdom;
14484:                 }
14485: 	    }
14486: 	}
14487:     }
14488:     
14489:     sub reset_hosts_info {
14490: 	&purge_remembered();
14491: 	&reset_domain_info();
14492: 	&reset_hosts_ip_info();
14493:         undef(%internetdom);
14494: 	undef(%name_to_host);
14495: 	undef(%hostname);
14496: 	undef(%hostdom);
14497: 	undef(%libserv);
14498: 	undef($loaded);
14499:     }
14500: 
14501:     sub load_hosts_tab {
14502: 	my ($ignore_cache,$nocache) = @_;
14503: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14504: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14505: 	my @config = <$config>;
14506: 	&parse_hosts_tab(\@config);
14507: 	close($config);
14508: 	$loaded=1;
14509:     }
14510: 
14511:     sub hostname {
14512: 	&load_hosts_tab() if (!$loaded);
14513: 
14514: 	my ($lonid) = @_;
14515: 	return $hostname{$lonid};
14516:     }
14517: 
14518:     sub all_hostnames {
14519: 	&load_hosts_tab() if (!$loaded);
14520: 
14521: 	return %hostname;
14522:     }
14523: 
14524:     sub all_names {
14525:         my ($ignore_cache,$nocache) = @_;
14526: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14527: 
14528: 	return %name_to_host;
14529:     }
14530: 
14531:     sub all_host_domain {
14532:         &load_hosts_tab() if (!$loaded);
14533:         return %hostdom;
14534:     }
14535: 
14536:     sub all_host_intdom {
14537:         &load_hosts_tab() if (!$loaded);
14538:         return %internetdom;
14539:     }
14540: 
14541:     sub is_library {
14542: 	&load_hosts_tab() if (!$loaded);
14543: 
14544: 	return exists($libserv{$_[0]});
14545:     }
14546: 
14547:     sub all_library {
14548: 	&load_hosts_tab() if (!$loaded);
14549: 
14550: 	return %libserv;
14551:     }
14552: 
14553:     sub unique_library {
14554: 	#2x reverse removes all hostnames that appear more than once
14555:         my %unique = reverse &all_library();
14556:         return reverse %unique;
14557:     }
14558: 
14559:     sub get_servers {
14560: 	&load_hosts_tab() if (!$loaded);
14561: 
14562: 	my ($domain,$type) = @_;
14563: 	my %possible_hosts = ($type eq 'library') ? %libserv
14564: 	                                          : %hostname;
14565: 	my %result;
14566: 	if (ref($domain) eq 'ARRAY') {
14567: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14568: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14569: 		    $result{$host} = $hostname;
14570: 		}
14571: 	    }
14572: 	} else {
14573: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14574: 		if ($hostdom{$host} eq $domain) {
14575: 		    $result{$host} = $hostname;
14576: 		}
14577: 	    }
14578: 	}
14579: 	return %result;
14580:     }
14581: 
14582:     sub get_unique_servers {
14583:         my %unique = reverse &get_servers(@_);
14584: 	return reverse %unique;
14585:     }
14586: 
14587:     sub host_domain {
14588: 	&load_hosts_tab() if (!$loaded);
14589: 
14590: 	my ($lonid) = @_;
14591: 	return $hostdom{$lonid};
14592:     }
14593: 
14594:     sub all_domains {
14595: 	&load_hosts_tab() if (!$loaded);
14596: 
14597: 	my %seen;
14598: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14599: 	return @uniq;
14600:     }
14601: 
14602:     sub internet_dom {
14603:         &load_hosts_tab() if (!$loaded);
14604: 
14605:         my ($lonid) = @_;
14606:         return $internetdom{$lonid};
14607:     }
14608: 
14609:     sub is_LC_dns {
14610:         &load_hosts_tab() if (!$loaded);
14611: 
14612:         my ($hostname) = @_;
14613:         return exists($LC_dns_serv{$hostname});
14614:     }
14615: 
14616: }
14617: 
14618: { 
14619:     my %iphost;
14620:     my %name_to_ip;
14621:     my %lonid_to_ip;
14622: 
14623:     sub get_hosts_from_ip {
14624: 	my ($ip) = @_;
14625: 	my %iphosts = &get_iphost();
14626: 	if (ref($iphosts{$ip})) {
14627: 	    return @{$iphosts{$ip}};
14628: 	}
14629: 	return;
14630:     }
14631:     
14632:     sub reset_hosts_ip_info {
14633: 	undef(%iphost);
14634: 	undef(%name_to_ip);
14635: 	undef(%lonid_to_ip);
14636:     }
14637: 
14638:     sub get_host_ip {
14639: 	my ($lonid) = @_;
14640: 	if (exists($lonid_to_ip{$lonid})) {
14641: 	    return $lonid_to_ip{$lonid};
14642: 	}
14643: 	my $name=&hostname($lonid);
14644:    	my $ip = gethostbyname($name);
14645: 	return if (!$ip || length($ip) ne 4);
14646: 	$ip=inet_ntoa($ip);
14647: 	$name_to_ip{$name}   = $ip;
14648: 	$lonid_to_ip{$lonid} = $ip;
14649: 	return $ip;
14650:     }
14651:     
14652:     sub get_iphost {
14653: 	my ($ignore_cache,$nocache) = @_;
14654: 
14655: 	if (!$ignore_cache) {
14656: 	    if (%iphost) {
14657: 		return %iphost;
14658: 	    }
14659: 	    my ($ip_info,$cached)=
14660: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14661: 	    if ($cached) {
14662: 		%iphost      = %{$ip_info->[0]};
14663: 		%name_to_ip  = %{$ip_info->[1]};
14664: 		%lonid_to_ip = %{$ip_info->[2]};
14665: 		return %iphost;
14666: 	    }
14667: 	}
14668: 
14669: 	# get yesterday's info for fallback
14670: 	my %old_name_to_ip;
14671: 	my ($ip_info,$cached)=
14672: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14673: 	if ($cached) {
14674: 	    %old_name_to_ip = %{$ip_info->[1]};
14675: 	}
14676: 
14677: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14678: 	foreach my $name (keys(%name_to_host)) {
14679: 	    my $ip;
14680: 	    if (!exists($name_to_ip{$name})) {
14681: 		$ip = gethostbyname($name);
14682: 		if (!$ip || length($ip) ne 4) {
14683: 		    if (defined($old_name_to_ip{$name})) {
14684: 			$ip = $old_name_to_ip{$name};
14685: 			&logthis("Can't find $name defaulting to old $ip");
14686: 		    } else {
14687: 			&logthis("Name $name no IP found");
14688: 			next;
14689: 		    }
14690: 		} else {
14691: 		    $ip=inet_ntoa($ip);
14692: 		}
14693: 		$name_to_ip{$name} = $ip;
14694: 	    } else {
14695: 		$ip = $name_to_ip{$name};
14696: 	    }
14697: 	    foreach my $id (@{ $name_to_host{$name} }) {
14698: 		$lonid_to_ip{$id} = $ip;
14699: 	    }
14700: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14701: 	}
14702:         unless ($nocache) {
14703: 	    &do_cache_new('iphost','iphost',
14704: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14705: 		          48*60*60);
14706:         }
14707: 
14708: 	return %iphost;
14709:     }
14710: 
14711:     #
14712:     #  Given a DNS returns the loncapa host name for that DNS 
14713:     # 
14714:     sub host_from_dns {
14715:         my ($dns) = @_;
14716:         my @hosts;
14717:         my $ip;
14718: 
14719:         if (exists($name_to_ip{$dns})) {
14720:             $ip = $name_to_ip{$dns};
14721:         }
14722:         if (!$ip) {
14723:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14724:             if (length($ip) == 4) { 
14725: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14726:             }
14727:         }
14728:         if ($ip) {
14729: 	    @hosts = get_hosts_from_ip($ip);
14730: 	    return $hosts[0];
14731:         }
14732:         return undef;
14733:     }
14734: 
14735:     sub get_internet_names {
14736:         my ($lonid) = @_;
14737:         return if ($lonid eq '');
14738:         my ($idnref,$cached)=
14739:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14740:         if ($cached) {
14741:             return $idnref;
14742:         }
14743:         my $ip = &get_host_ip($lonid);
14744:         my @hosts = &get_hosts_from_ip($ip);
14745:         my %iphost = &get_iphost();
14746:         my (@idns,%seen);
14747:         foreach my $id (@hosts) {
14748:             my $dom = &host_domain($id);
14749:             my $prim_id = &domain($dom,'primary');
14750:             my $prim_ip = &get_host_ip($prim_id);
14751:             next if ($seen{$prim_ip});
14752:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14753:                 foreach my $id (@{$iphost{$prim_ip}}) {
14754:                     my $intdom = &internet_dom($id);
14755:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14756:                         push(@idns,$intdom);
14757:                     }
14758:                 }
14759:             }
14760:             $seen{$prim_ip} = 1;
14761:         }
14762:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14763:     }
14764: 
14765: }
14766: 
14767: sub all_loncaparevs {
14768:     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);
14769: }
14770: 
14771: # ---------------------------------------------------------- Read loncaparev table
14772: {
14773:     sub load_loncaparevs { 
14774:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14775:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14776:                 while (my $configline=<$config>) {
14777:                     chomp($configline);
14778:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14779:                     $loncaparevs{$hostid}=$loncaparev;
14780:                 }
14781:                 close($config);
14782:             }
14783:         }
14784:     }
14785: }
14786: 
14787: # ---------------------------------------------------------- Read serverhostID table
14788: {
14789:     sub load_serverhomeIDs {
14790:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14791:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14792:                 while (my $configline=<$config>) {
14793:                     chomp($configline);
14794:                     my ($name,$id)=split(/:/,$configline);
14795:                     $serverhomeIDs{$name}=$id;
14796:                 }
14797:                 close($config);
14798:             }
14799:         }
14800:     }
14801: }
14802: 
14803: 
14804: BEGIN {
14805: 
14806: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14807:     unless ($readit) {
14808: {
14809:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14810:     %perlvar = (%perlvar,%{$configvars});
14811: }
14812: 
14813: 
14814: # ------------------------------------------------------ Read spare server file
14815: {
14816:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14817: 
14818:     while (my $configline=<$config>) {
14819:        chomp($configline);
14820:        if ($configline) {
14821: 	   my ($host,$type) = split(':',$configline,2);
14822: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14823: 	   push(@{ $spareid{$type} }, $host);
14824:        }
14825:     }
14826:     close($config);
14827: }
14828: # ------------------------------------------------------------ Read permissions
14829: {
14830:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14831: 
14832:     while (my $configline=<$config>) {
14833: 	chomp($configline);
14834: 	if ($configline) {
14835: 	    my ($role,$perm)=split(/ /,$configline);
14836: 	    if ($perm ne '') { $pr{$role}=$perm; }
14837: 	}
14838:     }
14839:     close($config);
14840: }
14841: 
14842: # -------------------------------------------- Read plain texts for permissions
14843: {
14844:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14845: 
14846:     while (my $configline=<$config>) {
14847: 	chomp($configline);
14848: 	if ($configline) {
14849: 	    my ($short,@plain)=split(/:/,$configline);
14850:             %{$prp{$short}} = ();
14851: 	    if (@plain > 0) {
14852:                 $prp{$short}{'std'} = $plain[0];
14853:                 for (my $i=1; $i<@plain; $i++) {
14854:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14855:                 }
14856:             }
14857: 	}
14858:     }
14859:     close($config);
14860: }
14861: 
14862: # ---------------------------------------------------------- Read package table
14863: {
14864:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14865: 
14866:     while (my $configline=<$config>) {
14867: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14868: 	chomp($configline);
14869: 	my ($short,$plain)=split(/:/,$configline);
14870: 	my ($pack,$name)=split(/\&/,$short);
14871: 	if ($plain ne '') {
14872: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14873: 	    $packagetab{$short}=$plain; 
14874: 	}
14875:     }
14876:     close($config);
14877: }
14878: 
14879: # ---------------------------------------------------------- Read loncaparev table
14880: 
14881: &load_loncaparevs();
14882: 
14883: # ---------------------------------------------------------- Read serverhostID table
14884: 
14885: &load_serverhomeIDs();
14886: 
14887: # ---------------------------------------------------------- Read releaseslist XML
14888: {
14889:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14890:     if (-e $file) {
14891:         my $parser = HTML::LCParser->new($file);
14892:         while (my $token = $parser->get_token()) {
14893:             if ($token->[0] eq 'S') {
14894:                 my $item = $token->[1];
14895:                 my $name = $token->[2]{'name'};
14896:                 my $value = $token->[2]{'value'};
14897:                 my $valuematch = $token->[2]{'valuematch'};
14898:                 my $namematch = $token->[2]{'namematch'};
14899:                 if ($item eq 'parameter') {
14900:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14901:                         my $release = $parser->get_text();
14902:                         $release =~ s/(^\s*|\s*$ )//gx;
14903:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14904:                     }
14905:                 } elsif ($item ne '' && $name ne '') {
14906:                     my $release = $parser->get_text();
14907:                     $release =~ s/(^\s*|\s*$ )//gx;
14908:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14909:                 }
14910:             }
14911:         }
14912:     }
14913: }
14914: 
14915: # ---------------------------------------------------------- Read managers table
14916: {
14917:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14918:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14919:             while (my $configline=<$config>) {
14920:                 chomp($configline);
14921:                 next if ($configline =~ /^\#/);
14922:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14923:                     $managerstab{$configline} = 1;
14924:                 }
14925:             }
14926:             close($config);
14927:         }
14928:     }
14929: }
14930: 
14931: # ------------- set up temporary directory
14932: {
14933:     $tmpdir = LONCAPA::tempdir();
14934: 
14935: }
14936: 
14937: # ------------- set default texengine (domain default overrides this)
14938: {
14939:     $deftex = LONCAPA::texengine();
14940: }
14941: 
14942: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14943: 				'compress_threshold'=> 20_000,
14944:  			        });
14945: 
14946: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14947: $dumpcount=0;
14948: $locknum=0;
14949: 
14950: &logtouch();
14951: &logthis('<font color="yellow">INFO: Read configuration</font>');
14952: $readit=1;
14953:     {
14954: 	use integer;
14955: 	my $test=(2**32)+1;
14956: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14957: 	&logthis(" Detected 64bit platform ($_64bit)");
14958:     }
14959: }
14960: }
14961: 
14962: 1;
14963: __END__
14964: 
14965: =pod
14966: 
14967: =head1 NAME
14968: 
14969: Apache::lonnet - Subroutines to ask questions about things in the network.
14970: 
14971: =head1 SYNOPSIS
14972: 
14973: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14974: 
14975:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14976: 
14977: Common parameters:
14978: 
14979: =over 4
14980: 
14981: =item *
14982: 
14983: $uname : an internal username (if $cname expecting a course Id specifically)
14984: 
14985: =item *
14986: 
14987: $udom : a domain (if $cdom expecting a course's domain specifically)
14988: 
14989: =item *
14990: 
14991: $symb : a resource instance identifier
14992: 
14993: =item *
14994: 
14995: $namespace : the name of a .db file that contains the data needed or
14996: being set.
14997: 
14998: =back
14999: 
15000: =head1 OVERVIEW
15001: 
15002: lonnet provides subroutines which interact with the
15003: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15004: about classes, users, and resources.
15005: 
15006: For many of these objects you can also use this to store data about
15007: them or modify them in various ways.
15008: 
15009: =head2 Symbs
15010: 
15011: To identify a specific instance of a resource, LON-CAPA uses symbols
15012: or "symbs"X<symb>. These identifiers are built from the URL of the
15013: map, the resource number of the resource in the map, and the URL of
15014: the resource itself. The latter is somewhat redundant, but might help
15015: if maps change.
15016: 
15017: An example is
15018: 
15019:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15020: 
15021: The respective map entry is
15022: 
15023:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15024:   title="Problem 2">
15025:  </resource>
15026: 
15027: Symbs are used by the random number generator, as well as to store and
15028: restore data specific to a certain instance of for example a problem.
15029: 
15030: =head2 Storing And Retrieving Data
15031: 
15032: X<store()>X<cstore()>X<restore()>Three of the most important functions
15033: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15034: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15035: is is the non-critical message twin of cstore. These functions are for
15036: handlers to store a perl hash to a user's permanent data space in an
15037: easy manner, and to retrieve it again on another call. It is expected
15038: that a handler would use this once at the beginning to retrieve data,
15039: and then again once at the end to send only the new data back.
15040: 
15041: The data is stored in the user's data directory on the user's
15042: homeserver under the ID of the course.
15043: 
15044: The hash that is returned by restore will have all of the previous
15045: value for all of the elements of the hash.
15046: 
15047: Example:
15048: 
15049:  #creating a hash
15050:  my %hash;
15051:  $hash{'foo'}='bar';
15052: 
15053:  #storing it
15054:  &Apache::lonnet::cstore(\%hash);
15055: 
15056:  #changing a value
15057:  $hash{'foo'}='notbar';
15058: 
15059:  #adding a new value
15060:  $hash{'bar'}='foo';
15061:  &Apache::lonnet::cstore(\%hash);
15062: 
15063:  #retrieving the hash
15064:  my %history=&Apache::lonnet::restore();
15065: 
15066:  #print the hash
15067:  foreach my $key (sort(keys(%history))) {
15068:    print("\%history{$key} = $history{$key}");
15069:  }
15070: 
15071: Will print out:
15072: 
15073:  %history{1:foo} = bar
15074:  %history{1:keys} = foo:timestamp
15075:  %history{1:timestamp} = 990455579
15076:  %history{2:bar} = foo
15077:  %history{2:foo} = notbar
15078:  %history{2:keys} = foo:bar:timestamp
15079:  %history{2:timestamp} = 990455580
15080:  %history{bar} = foo
15081:  %history{foo} = notbar
15082:  %history{timestamp} = 990455580
15083:  %history{version} = 2
15084: 
15085: Note that the special hash entries C<keys>, C<version> and
15086: C<timestamp> were added to the hash. C<version> will be equal to the
15087: total number of versions of the data that have been stored. The
15088: C<timestamp> attribute will be the UNIX time the hash was
15089: stored. C<keys> is available in every historical section to list which
15090: keys were added or changed at a specific historical revision of a
15091: hash.
15092: 
15093: B<Warning>: do not store the hash that restore returns directly. This
15094: will cause a mess since it will restore the historical keys as if the
15095: were new keys. I.E. 1:foo will become 1:1:foo etc.
15096: 
15097: Calling convention:
15098: 
15099:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15100:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15101: 
15102: For more detailed information, see lonnet specific documentation.
15103: 
15104: =head1 RETURN MESSAGES
15105: 
15106: =over 4
15107: 
15108: =item * B<con_lost>: unable to contact remote host
15109: 
15110: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15111: when the connection is brought back up
15112: 
15113: =item * B<con_failed>: unable to contact remote host and unable to save message
15114: for later delivery
15115: 
15116: =item * B<error:>: an error a occurred, a description of the error follows the :
15117: 
15118: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15119: that was requested
15120: 
15121: =back
15122: 
15123: =head1 PUBLIC SUBROUTINES
15124: 
15125: =head2 Session Environment Functions
15126: 
15127: =over 4
15128: 
15129: =item * 
15130: X<appenv()>
15131: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15132: the user envirnoment file, and will be restored for each access this
15133: user makes during this session, also modifies the %env for the current
15134: process. Optional rolesarrayref - if defined contains a reference to an array
15135: of roles which are exempt from the restriction on modifying user.role entries 
15136: in the user's environment.db and in %env.    
15137: 
15138: =item *
15139: X<delenv()>
15140: B<delenv($delthis,$regexp)>: removes all items from the session
15141: environment file that begin with $delthis. If the 
15142: optional second arg - $regexp - is true, $delthis is treated as a 
15143: regular expression, otherwise \Q$delthis\E is used. 
15144: The values are also deleted from the current processes %env.
15145: 
15146: =item * get_env_multiple($name) 
15147: 
15148: gets $name from the %env hash, it seemlessly handles the cases where multiple
15149: values may be defined and end up as an array ref.
15150: 
15151: returns an array of values
15152: 
15153: =back
15154: 
15155: =head2 User Information
15156: 
15157: =over 4
15158: 
15159: =item *
15160: X<queryauthenticate()>
15161: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15162: authentication scheme
15163: 
15164: =item *
15165: X<authenticate()>
15166: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15167: authenticate user from domain's lib servers (first use the current
15168: one). C<$upass> should be the users password.
15169: $checkdefauth is optional (value is 1 if a check should be made to
15170:    authenticate user using default authentication method, and allow
15171:    account creation if username does not have account in the domain).
15172: $clientcancheckhost is optional (value is 1 if checking whether the
15173:    server can host will occur on the client side in lonauth.pm).   
15174: 
15175: =item *
15176: X<homeserver()>
15177: B<homeserver($uname,$udom)>: find the server which has
15178: the user's directory and files (there must be only one), this caches
15179: the answer, and also caches if there is a borken connection.
15180: 
15181: =item *
15182: X<idget()>
15183: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15184: a list of student/employee IDs or clicker IDs
15185: (student/employee IDs are a unique resource in a domain, there must be 
15186: only 1 ID per username, and only 1 username per ID in a specific domain).
15187: clickerIDs are not necessarily unique, as students might share clickers.
15188: (returns hash: id=>name,id=>name)
15189: 
15190: =item *
15191: X<idrget()>
15192: B<idrget($udom,@unames)>: find the IDs behind a list of
15193: usernames (returns hash: name=>id,name=>id)
15194: 
15195: =item *
15196: X<idput()>
15197: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15198: names and associated student/employee IDs or clicker IDs.
15199: 
15200: =item *
15201: X<iddel()>
15202: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15203: student/employee ID or clicker ID username look-ups from domain.
15204: The homeserver ($uhome) and namespace ($namespace) are optional.
15205: If no $uhome is provided, it will be determined usig &homeserver()
15206: for each user.  If no $namespace is provided, the default is ids.
15207: 
15208: =item *
15209: X<updateclickers()>
15210: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15211: clicker ID-to-username look-ups in clickers.db on library server.
15212: Permitted actions are add or del (i.e., add or delete). The 
15213: clickers.db contains clickerID as keys (escaped), and each corresponding
15214: value is an escaped comma-separated list of usernames (for whom the
15215: library server is the homeserver), who registered that particular ID.
15216: If $critical is true, the update will be sent via &critical, otherwise
15217: &reply() will be used.
15218: 
15219: =item *
15220: X<rolesinit()>
15221: B<rolesinit($udom,$username)>: get user privileges.
15222: returns user role, first access and timer interval hashes
15223: 
15224: =item *
15225: X<privileged()>
15226: B<privileged($username,$domain)>: returns a true if user has a
15227: privileged and active role (i.e. su or dc), false otherwise.
15228: 
15229: =item *
15230: X<getsection()>
15231: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15232: course $cname, return section name/number or '' for "not in course"
15233: and '-1' for "no section"
15234: 
15235: =item *
15236: X<userenvironment()>
15237: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15238: passed in @what from the requested user's environment, returns a hash
15239: 
15240: =item * 
15241: X<userlog_query()>
15242: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15243: activity.log file. %filters defines filters applied when parsing the
15244: log file. These can be start or end timestamps, or the type of action
15245: - log to look for Login or Logout events, check for Checkin or
15246: Checkout, role for role selection. The response is in the form
15247: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15248: escaped strings of the action recorded in the activity.log file.
15249: 
15250: =back
15251: 
15252: =head2 User Roles
15253: 
15254: =over 4
15255: 
15256: =item *
15257: 
15258: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15259: returns codes for allowed actions.
15260: 
15261: The first argument is required, all others are optional.
15262: 
15263: $priv is the privilege being checked.
15264: $uri contains additional information about what is being checked for access (e.g.,
15265: URL, course ID etc.). 
15266: $symb is the unique resource instance identifier in a course; if needed,
15267: but not provided, it will be retrieved via a call to &symbread(). 
15268: $role is the role for which a priv is being checked (only used if priv is evb). 
15269: $clientip is the user's IP address (only used when checking for access to portfolio 
15270: files).
15271: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15272: prevents recursive calls to &allowed.
15273: 
15274:  F: full access
15275:  U,I,K: authentication modes (cxx only)
15276:  '': forbidden
15277:  1: user needs to choose course
15278:  2: browse allowed
15279:  A: passphrase authentication needed
15280:  B: access temporarily blocked because of a blocking event in a course.
15281:  D: access blocked because access is required via session initiated via deep-link 
15282: 
15283: =item *
15284: 
15285: constructaccess($url,$setpriv) : check for access to construction space URL
15286: 
15287: See if the owner domain and name in the URL match those in the
15288: expected environment.  If so, return three element list
15289: ($ownername,$ownerdomain,$ownerhome).
15290: 
15291: Otherwise return the null string.
15292: 
15293: If second argument 'setpriv' is true, it assigns the privileges,
15294: and returns the same three element list, unless the owner has
15295: blocked "ad hoc" Domain Coordinator access to the Author Space,
15296: in which case the null string is returned.
15297: 
15298: =item *
15299: 
15300: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15301: define a custom role rolename set privileges in format of lonTabs/roles.tab
15302: for system, domain, and course level. $uname and $udom are optional (current
15303: user's username and domain will be used when either of $uname or $udom are absent.
15304: 
15305: =item *
15306: 
15307: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15308: (rolesplain.tab); plain text explanation of a user role term.
15309: $type is Course (default) or Community.
15310: If $forcedefault evaluates to true, text returned will be default 
15311: text for $type. Otherwise, if this is a course, the text returned 
15312: will be a custom name for the role (if defined in the course's 
15313: environment).  If no custom name is defined the default is returned.
15314:    
15315: =item *
15316: 
15317: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15318: All arguments are optional. Returns a hash of a roles, either for
15319: co-author/assistant author roles for a user's Construction Space
15320: (default), or if $context is 'userroles', roles for the user himself,
15321: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15322: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15323: For each key, value is set to colon-separated start and end times for
15324: the role.  If no username and domain are specified, will default to
15325: current user/domain. Types, roles, and roledoms are references to arrays
15326: of role statuses (active, future or previous), roles 
15327: (e.g., cc,in, st etc.) and domains of the roles which can be used
15328: to restrict the list of roles reported. If no array ref is 
15329: provided for types, will default to return only active roles.
15330: 
15331: =item *
15332: 
15333: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15334: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15335: 
15336: Additional optional arguments are: $type (if role checking is to be restricted 
15337: to certain user status types -- previous (expired roles), active (currently
15338: available roles) or future (roles available in the future), and
15339: $hideprivileged -- if true will not report course roles for users who
15340: have active Domain Coordinator role in course's domain or in additional
15341: domains (specified in 'Domains to check for privileged users' in course
15342: environment -- set via:  Course Settings -> Classlists and staff listing).
15343: 
15344: =item *
15345: 
15346: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15347: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15348: $possdomains and $possroles are optional array refs -- to domains to check and
15349: roles to check.  If $possdomains is not specified, a dump will be done of the
15350: users' roles.db to check for a dc or su role in any domain. This can be
15351: time consuming if &privileged is called repeatedly (e.g., when displaying a
15352: classlist), so in such cases, supplying a $possdomains array is preferred, as
15353: this then allows &privileged_by_domain() to be used, which caches the identity
15354: of privileged users, eliminating the need for repeated calls to &dump().
15355: 
15356: =item *
15357: 
15358: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15359: where the outer hash keys are domains specified in the $possdomains array ref,
15360: next inner hash keys are privileged roles specified in the $roles array ref,
15361: and the innermost hash contains key = value pairs for username:domain = end:start
15362: for active or future "privileged" users with that role in that domain. To avoid
15363: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15364: innerhash are cached using priv_$role and $dom as the identifiers.
15365: 
15366: =back
15367: 
15368: =head2 User Modification
15369: 
15370: =over 4
15371: 
15372: =item *
15373: 
15374: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15375: user for the level given by URL.  Optional start and end dates (leave empty
15376: string or zero for "no date")
15377: 
15378: =item *
15379: 
15380: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15381: change a users, password, possible return values are: ok,
15382: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15383: refused
15384: 
15385: =item *
15386: 
15387: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15388: 
15389: =item *
15390: 
15391: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15392:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15393: 
15394: will update user information (firstname,middlename,lastname,generation,
15395: permanentemail), and if forceid is true, student/employee ID also.
15396: A user's institutional affiliation(s) can also be updated.
15397: User information fields will not be overwritten with empty entries 
15398: unless the field is included in the $candelete array reference.
15399: This array is included when a single user is modified via "Manage Users",
15400: or when Autoupdate.pl is run by cron in a domain.
15401: 
15402: =item *
15403: 
15404: modifystudent
15405: 
15406: modify a student's enrollment and identification information.
15407: The course id is resolved based on the current user's environment.  
15408: This means the invoking user must be a course coordinator or otherwise
15409: associated with a course.
15410: 
15411: This call is essentially a wrapper for lonnet::modifyuser and
15412: lonnet::modify_student_enrollment
15413: 
15414: Inputs: 
15415: 
15416: =over 4
15417: 
15418: =item B<$udom> Student's loncapa domain
15419: 
15420: =item B<$uname> Student's loncapa login name
15421: 
15422: =item B<$uid> Student/Employee ID
15423: 
15424: =item B<$umode> Student's authentication mode
15425: 
15426: =item B<$upass> Student's password
15427: 
15428: =item B<$first> Student's first name
15429: 
15430: =item B<$middle> Student's middle name
15431: 
15432: =item B<$last> Student's last name
15433: 
15434: =item B<$gene> Student's generation
15435: 
15436: =item B<$usec> Student's section in course
15437: 
15438: =item B<$end> Unix time of the roles expiration
15439: 
15440: =item B<$start> Unix time of the roles start date
15441: 
15442: =item B<$forceid> If defined, allow $uid to be changed
15443: 
15444: =item B<$desiredhome> server to use as home server for student
15445: 
15446: =item B<$email> Student's permanent e-mail address
15447: 
15448: =item B<$type> Type of enrollment (auto or manual)
15449: 
15450: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15451: 
15452: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15453: 
15454: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15455: 
15456: =item B<$context> role change context (shown in User Management Logs display in a course)
15457: 
15458: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15459: 
15460: =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.
15461: 
15462: =back
15463: 
15464: =item *
15465: 
15466: modify_student_enrollment
15467: 
15468: Change a student's enrollment status in a class.  The environment variable
15469: 'role.request.course' must be defined for this function to proceed.
15470: 
15471: Inputs:
15472: 
15473: =over 4
15474: 
15475: =item $udom, student's domain
15476: 
15477: =item $uname, student's name
15478: 
15479: =item $uid, student's user id
15480: 
15481: =item $first, student's first name
15482: 
15483: =item $middle
15484: 
15485: =item $last
15486: 
15487: =item $gene
15488: 
15489: =item $usec
15490: 
15491: =item $end
15492: 
15493: =item $start
15494: 
15495: =item $type
15496: 
15497: =item $locktype
15498: 
15499: =item $cid
15500: 
15501: =item $selfenroll
15502: 
15503: =item $context
15504: 
15505: =item $credits, number of credits student will earn from this class
15506: 
15507: =item $instsec, institutional course section code for student
15508: 
15509: =back
15510: 
15511: 
15512: =item *
15513: 
15514: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15515: custom role; give a custom role to a user for the level given by URL.  Specify
15516: name and domain of role author, and role name
15517: 
15518: =item *
15519: 
15520: revokerole($udom,$uname,$url,$role) : revoke a role for url
15521: 
15522: =item *
15523: 
15524: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15525: 
15526: =back
15527: 
15528: =head2 Course Infomation
15529: 
15530: =over 4
15531: 
15532: =item *
15533: 
15534: coursedescription($courseid,$options) : returns a hash of information about the
15535: specified course id, including all environment settings for the
15536: course, the description of the course will be in the hash under the
15537: key 'description'
15538: 
15539: $options is an optional parameter that if supplied is a hash reference that controls
15540: what how this function works.  It has the following key/values:
15541: 
15542: =over 4
15543: 
15544: =item freshen_cache
15545: 
15546: If defined, and the environment cache for the course is valid, it is 
15547: returned in the returned hash.
15548: 
15549: =item one_time
15550: 
15551: If defined, the last cache time is set to _now_
15552: 
15553: =item user
15554: 
15555: If defined, the supplied username is used instead of the current user.
15556: 
15557: 
15558: =back
15559: 
15560: =item *
15561: 
15562: resdata($name,$domain,$type,@which) : request for current parameter
15563: setting for a specific $type, where $type is either 'course' or 'user',
15564: @what should be a list of parameters to ask about. This routine caches
15565: answers for 10 minutes.
15566: 
15567: =item *
15568: 
15569: get_courseresdata($courseid, $domain) : dump the entire course resource
15570: data base, returning a hash that is keyed by the resource name and has
15571: values that are the resource value.  I believe that the timestamps and
15572: versions are also returned.
15573: 
15574: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15575: supplemental content area. This routine caches the number of files for 
15576: 10 minutes.
15577: 
15578: =back
15579: 
15580: =head2 Course Modification
15581: 
15582: =over 4
15583: 
15584: =item *
15585: 
15586: writecoursepref($courseid,%prefs) : write preferences (environment
15587: database) for a course
15588: 
15589: =item *
15590: 
15591: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15592: 
15593: =item *
15594: 
15595: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15596: 
15597: =item *
15598: 
15599: is_course($courseid), is_course($cdom, $cnum)
15600: 
15601: Accepts either a combined $courseid (in the form of domain_courseid) or the
15602: two component version $cdom, $cnum. It checks if the specified course exists.
15603: 
15604: Returns:
15605:     undef if the course doesn't exist, otherwise
15606:     in scalar context the combined courseid.
15607:     in list context the two components of the course identifier, domain and 
15608:     courseid.    
15609: 
15610: =back
15611: 
15612: =head2 Bubblesheet Configuration
15613: 
15614: =over 4
15615: 
15616: =item *
15617: 
15618: get_scantron_config($which)
15619: 
15620: $which - the name of the configuration to parse from the file.
15621: 
15622: Parses and returns the bubblesheet configuration line selected as a
15623: hash of configuration file fields.
15624: 
15625: 
15626: Returns:
15627:     If the named configuration is not in the file, an empty
15628:     hash is returned.
15629: 
15630:     a hash with the fields
15631:       name         - internal name for the this configuration setup
15632:       description  - text to display to operator that describes this config
15633:       CODElocation - if 0 or the string 'none'
15634:                           - no CODE exists for this config
15635:                      if -1 || the string 'letter'
15636:                           - a CODE exists for this config and is
15637:                             a string of letters
15638:                      Unsupported value (but planned for future support)
15639:                           if a positive integer
15640:                                - The CODE exists as the first n items from
15641:                                  the question section of the form
15642:                           if the string 'number'
15643:                                - The CODE exists for this config and is
15644:                                  a string of numbers
15645:       CODEstart   - (only matter if a CODE exists) column in the line where
15646:                      the CODE starts
15647:       CODElength  - length of the CODE
15648:       IDstart     - column where the student/employee ID starts
15649:       IDlength    - length of the student/employee ID info
15650:       Qstart      - column where the information from the bubbled
15651:                     'questions' start
15652:       Qlength     - number of columns comprising a single bubble line from
15653:                     the sheet. (usually either 1 or 10)
15654:       Qon         - either a single character representing the character used
15655:                     to signal a bubble was chosen in the positional setup, or
15656:                     the string 'letter' if the letter of the chosen bubble is
15657:                     in the final, or 'number' if a number representing the
15658:                     chosen bubble is in the file (1->A 0->J)
15659:       Qoff        - the character used to represent that a bubble was
15660:                     left blank
15661:       PaperID     - if the scanning process generates a unique number for each
15662:                     sheet scanned the column that this ID number starts in
15663:       PaperIDlength - number of columns that comprise the unique ID number
15664:                       for the sheet of paper
15665:       FirstName   - column that the first name starts in
15666:       FirstNameLength - number of columns that the first name spans
15667:       LastName    - column that the last name starts in
15668:       LastNameLength - number of columns that the last name spans
15669:       BubblesPerRow - number of bubbles available in each row used to
15670:                       bubble an answer. (If not specified, 10 assumed).
15671: 
15672: 
15673: =item *
15674: 
15675: get_scantronformat_file($cdom)
15676: 
15677: $cdom - the course's domain (optional); if not supplied, uses
15678: domain for current $env{'request.course.id'}.
15679: 
15680: Returns an array containing lines from the scantron format file for
15681: the domain of the course.
15682: 
15683: If a url for a custom.tab file is listed in domain's configuration.db,
15684: lines are from this file.
15685: 
15686: Otherwise, if a default.tab has been published in RES space by the
15687: domainconfig user, lines are from this file.
15688: 
15689: Otherwise, fall back to getting lines from the legacy file on the
15690: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15691: 
15692: =back
15693: 
15694: =head2 Resource Subroutines
15695: 
15696: =over 4
15697: 
15698: =item *
15699: 
15700: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15701: 
15702: =item *
15703: 
15704: repcopy($filename) : subscribes to the requested file, and attempts to
15705: replicate from the owning library server, Might return
15706: 'unavailable', 'not_found', 'forbidden', 'ok', or
15707: 'bad_request', also attempts to grab the metadata for the
15708: resource. Expects the local filesystem pathname
15709: (/home/httpd/html/res/....)
15710: 
15711: =back
15712: 
15713: =head2 Resource Information
15714: 
15715: =over 4
15716: 
15717: =item *
15718: 
15719: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15720: and returns the value of a variety of different possible values,
15721: $varname should be a request string, and the other parameters can be
15722: used to specify who and what one is asking about. Ordinarily, $cid 
15723: does not need to be specified, as it is retrived from 
15724: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15725: within lonuserstate::loadmap() when initializing a course, before
15726: $env{'request.course.id'} has been set, so it needs to be provided
15727: in that one case.
15728: 
15729: Possible values for $varname are environment.lastname (or other item
15730: from the envirnment hash), user.name (or someother aspect about the
15731: user), resource.0.maxtries (or some other part and parameter of a
15732: resource)
15733: 
15734: =item *
15735: 
15736: directcondval($number) : get current value of a condition; reads from a state
15737: string
15738: 
15739: =item *
15740: 
15741: condval($condidx) : value of condition index based on state
15742: 
15743: =item *
15744: 
15745: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15746: resource's metadata, $what should be either a specific key, or either
15747: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15748: packages that this resource currently uses, the last 3 arguments are 
15749: only used internally for recursive metadata.
15750: 
15751: the toolsymb is only used where the uri is for an external tool (for which
15752: the uri as well as the symb are guaranteed to be unique).
15753: 
15754: this function automatically caches all requests except any made recursively
15755: to retrieve a list of metadata keys for an imported library file ($liburi is 
15756: defined).
15757: 
15758: =item *
15759: 
15760: metadata_query($query,$custom,$customshow) : make a metadata query against the
15761: network of library servers; returns file handle of where SQL and regex results
15762: will be stored for query
15763: 
15764: =item *
15765: 
15766: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15767: return symbolic list entry (all arguments optional). 
15768: 
15769: Args: filename is the filename (including path) for the file for which a symb 
15770: is required; donotrecurse, if true will prevent calls to allowed() being made 
15771: to check access status if more than one resource was found in the bighash 
15772: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15773: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15774: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15775: cause possible symbs to be checked to determine if they are subject to content
15776: blocking, if so they will not be included as possible symbs; possibles is a
15777: ref to a hash, which, as a side effect, will be populated with all possible 
15778: symbs (content blocking not tested).
15779:  
15780: returns the data handle
15781: 
15782: =item *
15783: 
15784: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15785: and is a possible symb for the URL in $thisfn, and if is an encrypted
15786: resource that the user accessed using /enc/ returns a 1 on success, 0
15787: on failure, user must be in a course, as it assumes the existence of
15788: the course initial hash, and uses $env('request.course.id'}.  The third
15789: arg is an optional reference to a scalar.  If this arg is passed in the 
15790: call to symbverify, it will be set to 1 if the symb has been set to be 
15791: encrypted; otherwise it will be null.  
15792: 
15793: =item *
15794: 
15795: symbclean($symb) : removes versions numbers from a symb, returns the
15796: cleaned symb
15797: 
15798: =item *
15799: 
15800: is_on_map($uri) : checks if the $uri is somewhere on the current
15801: course map, user must be in a course for it to work.
15802: 
15803: =item *
15804: 
15805: numval($salt) : return random seed value (addend for rndseed)
15806: 
15807: =item *
15808: 
15809: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15810: a random seed, all arguments are optional, if they aren't sent it uses the
15811: environment to derive them. Note: if symb isn't sent and it can't get one
15812: from &symbread it will use the current time as its return value
15813: 
15814: =item *
15815: 
15816: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15817: unfakeable, receipt
15818: 
15819: =item *
15820: 
15821: receipt() : API to ireceipt working off of env values; given out to users
15822: 
15823: =item *
15824: 
15825: countacc($url) : count the number of accesses to a given URL
15826: 
15827: =item *
15828: 
15829: 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
15830: 
15831: =item *
15832: 
15833: 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)
15834: 
15835: =item *
15836: 
15837: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15838: 
15839: =item *
15840: 
15841: devalidate($symb) : devalidate temporary spreadsheet calculations,
15842: forcing spreadsheet to reevaluate the resource scores next time.
15843: 
15844: =item * 
15845: 
15846: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15847: when viewing in course context.
15848: 
15849:  input: six args -- filename (decluttered), course number, course domain,
15850:                     url, symb (if registered) and group (if this is a 
15851:                     group item -- e.g., bulletin board, group page etc.).
15852: 
15853:  output: array of five scalars --
15854:          $cfile -- url for file editing if editable on current server
15855:          $home -- homeserver of resource (i.e., for author if published,
15856:                                           or course if uploaded.).
15857:          $switchserver --  1 if server switch will be needed.
15858:          $forceedit -- 1 if icon/link should be to go to edit mode 
15859:          $forceview -- 1 if icon/link should be to go to view mode
15860: 
15861: =item *
15862: 
15863: is_course_upload($file,$cnum,$cdom)
15864: 
15865: Used in course context to determine if current file was uploaded to 
15866: the course (i.e., would be found in /userfiles/docs on the course's 
15867: homeserver.
15868: 
15869:   input: 3 args -- filename (decluttered), course number and course domain.
15870:   output: boolean -- 1 if file was uploaded.
15871: 
15872: =back
15873: 
15874: =head2 Storing/Retreiving Data
15875: 
15876: =over 4
15877: 
15878: =item *
15879: 
15880: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15881: permanently for this url; hashref needs to be given and should be a \%hashname;
15882: the remaining args aren't required and if they aren't passed or are '' they will
15883: be derived from the env (with the exception of $laststore, which is an 
15884: optional arg used when a user's submission is stored in grading).
15885: $laststore is $version=$timestamp, where $version is the most recent version
15886: number retrieved for the corresponding $symb in the $namespace db file, and
15887: $timestamp is the timestamp for that transaction (UNIX time).
15888: $laststore is currently only passed when cstore() is called by 
15889: structuretags::finalize_storage().
15890: 
15891: =item *
15892: 
15893: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15894: but uses critical subroutine
15895: 
15896: =item *
15897: 
15898: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15899: all args are optional
15900: 
15901: =item *
15902: 
15903: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15904: dumps the complete (or key matching regexp) namespace into a hash
15905: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15906: normally &store()ed into
15907: 
15908: $range should be either an integer '100' (give me the first 100
15909:                                            matching records)
15910:               or be  two integers sperated by a - with no spaces
15911:                  '30-50' (give me the 30th through the 50th matching
15912:                           records)
15913: 
15914: 
15915: =item *
15916: 
15917: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15918: replaces a &store() version of data with a replacement set of data
15919: for a particular resource in a namespace passed in the $storehash hash 
15920: reference. If $tolog is true, the transaction is logged in the courselog
15921: with an action=PUTSTORE.
15922: 
15923: =item *
15924: 
15925: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15926: works very similar to store/cstore, but all data is stored in a
15927: temporary location and can be reset using tmpreset, $storehash should
15928: be a hash reference, returns nothing on success
15929: 
15930: =item *
15931: 
15932: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15933: similar to restore, but all data is stored in a temporary location and
15934: can be reset using tmpreset. Returns a hash of values on success,
15935: error string otherwise.
15936: 
15937: =item *
15938: 
15939: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15940: deltes all keys for $symb form the temporary storage hash.
15941: 
15942: =item *
15943: 
15944: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15945: reference filled in from namesp ($udom and $uname are optional)
15946: 
15947: =item *
15948: 
15949: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15950: namesp ($udom and $uname are optional)
15951: 
15952: =item *
15953: 
15954: dump($namespace,$udom,$uname,$regexp,$range) : 
15955: dumps the complete (or key matching regexp) namespace into a hash
15956: ($udom, $uname, $regexp, $range are optional)
15957: 
15958: $range should be either an integer '100' (give me the first 100
15959:                                            matching records)
15960:               or be  two integers sperated by a - with no spaces
15961:                  '30-50' (give me the 30th through the 50th matching
15962:                           records)
15963: =item *
15964: 
15965: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15966: $store can be a scalar, an array reference, or if the amount to be 
15967: incremented is > 1, a hash reference.
15968: 
15969: ($udom and $uname are optional)
15970: 
15971: =item *
15972: 
15973: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15974: ($udom and $uname are optional)
15975: 
15976: =item *
15977: 
15978: cput($namespace,$storehash,$udom,$uname) : critical put
15979: ($udom and $uname are optional)
15980: 
15981: =item *
15982: 
15983: newput($namespace,$storehash,$udom,$uname) :
15984: 
15985: Attempts to store the items in the $storehash, but only if they don't
15986: currently exist, if this succeeds you can be certain that you have 
15987: successfully created a new key value pair in the $namespace db.
15988: 
15989: 
15990: Args:
15991:  $namespace: name of database to store values to
15992:  $storehash: hashref to store to the db
15993:  $udom: (optional) domain of user containing the db
15994:  $uname: (optional) name of user caontaining the db
15995: 
15996: Returns:
15997:  'ok' -> succeeded in storing all keys of $storehash
15998:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15999:                         least <key> already existed in the db (other
16000:                         requested keys may also already exist)
16001:  'error: <msg>' -> unable to tie the DB or other error occurred
16002:  'con_lost' -> unable to contact request server
16003:  'refused' -> action was not allowed by remote machine
16004: 
16005: 
16006: =item *
16007: 
16008: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16009: reference filled in from namesp (encrypts the return communication)
16010: ($udom and $uname are optional)
16011: 
16012: =item *
16013: 
16014: log($udom,$name,$home,$message) : write to permanent log for user; use
16015: critical subroutine
16016: 
16017: =item *
16018: 
16019: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16020: array reference filled in from namespace found in domain level on either
16021: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16022: 
16023: =item *
16024: 
16025: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16026: domain level either on specified domain server ($uhome) or primary domain 
16027: server ($udom and $uhome are optional)
16028: 
16029: =item * 
16030: 
16031: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16032: for: authentication, language, quotas, timezone, date locale, and portal URL in
16033: the target domain.
16034: 
16035: May also include additional key => value pairs for the following groups:
16036: 
16037: =over
16038: 
16039: =item
16040: disk quotas (MB allocated by default to portfolios and authoring spaces).
16041: 
16042: =over
16043: 
16044: =item defaultquota, authorquota
16045: 
16046: =back
16047: 
16048: =item
16049: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16050: portfolio for users).
16051: 
16052: =over
16053: 
16054: =item
16055: aboutme, blog, webdav, portfolio
16056: 
16057: =back
16058: 
16059: =item
16060: requestcourses: ability to request courses, and how requests are processed.
16061: 
16062: =over
16063: 
16064: =item
16065: official, unofficial, community, textbook, placement
16066: 
16067: =back
16068: 
16069: =item
16070: inststatus: types of institutional affiliation, and order in which they are displayed.
16071: 
16072: =over
16073: 
16074: =item
16075: inststatustypes, inststatusorder, inststatusguest
16076: 
16077: =back
16078: 
16079: =item
16080: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16081: for course's uploaded content.
16082: 
16083: =over
16084: 
16085: =item
16086: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16087: communityquota, textbookquota, placementquota
16088: 
16089: =back
16090: 
16091: =item
16092: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16093: on your servers.
16094: 
16095: =over
16096: 
16097: =item 
16098: remotesessions, hostedsessions
16099: 
16100: =back
16101: 
16102: =back
16103: 
16104: In cases where a domain coordinator has never used the "Set Domain Configuration"
16105: utility to create a configuration.db file on a domain's primary library server 
16106: only the following domain defaults: auth_def, auth_arg_def, lang_def
16107: -- corresponding values are authentication type (internal, krb4, krb5,
16108: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16109: will be available. Values are retrieved from cache (if current), unless the
16110: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16111: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16112: 
16113: Typical usage:
16114: 
16115: %domdefaults = &get_domain_defaults($target_domain);
16116: 
16117: =back
16118: 
16119: =head2 Network Status Functions
16120: 
16121: =over 4
16122: 
16123: =item *
16124: 
16125: dirlist() : return directory list based on URI (first arg).
16126: 
16127: Inputs: 1 required, 5 optional.
16128: 
16129: =over
16130: 
16131: =item 
16132: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16133: 
16134: =item
16135: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16136: 
16137: =item
16138: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16139: 
16140: =item
16141: $getpropath - boolean: 1 if prepend path using &propath(). 
16142: 
16143: =item
16144: $getuserdir - boolean: 1 if prepend path for "userfiles".
16145: 
16146: =item 
16147: $alternateRoot - path to prepend in place of path from $uri.
16148: 
16149: =back
16150: 
16151: Returns: Array of up to two items.
16152: 
16153: =over
16154: 
16155: a reference to an array of files/subdirectories
16156: 
16157: =over
16158: 
16159: Each element in the array of files/subdirectories is a & separated list of
16160: item name and the result of running stat on the item.  If dirlist was requested
16161: for a file instead of a directory, the item name will be ''. For a directory 
16162: listing, if the item is a metadata file, the element will end &N&M 
16163: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16164: default copyright set (1).  
16165: 
16166: =back
16167: 
16168: a scalar containing error condition (if encountered).
16169: 
16170: =over
16171: 
16172: =item 
16173: no_host (no homeserver identified for $username:$domain).
16174: 
16175: =item 
16176: no_such_host (server contacted for listing not identified as valid host).
16177: 
16178: =item 
16179: con_lost (connection to remote server failed).
16180: 
16181: =item 
16182: refused (invalid $username:$domain received on lond side).
16183: 
16184: =item 
16185: no_such_dir (directory at specified path on lond side does not exist). 
16186: 
16187: =item 
16188: empty (directory at specified path on lond side is empty).
16189: 
16190: =over
16191: 
16192: This is currently not encountered because the &ls3, &ls2, 
16193: &ls (_handler) routines on the lond side do not filter out
16194: . and .. from a directory listing. 
16195: 
16196: =back
16197: 
16198: =back
16199: 
16200: =back
16201: 
16202: =item *
16203: 
16204: spareserver() : find server with least workload from spare.tab
16205: 
16206: 
16207: =item *
16208: 
16209: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16210: if there is no corresponding loncapa host.
16211: 
16212: =back
16213: 
16214: 
16215: =head2 Apache Request
16216: 
16217: =over 4
16218: 
16219: =item *
16220: 
16221: ssi($url,%hash) : server side include, does a complete request cycle on url to
16222: localhost, posts hash
16223: 
16224: =back
16225: 
16226: =head2 Data to String to Data
16227: 
16228: =over 4
16229: 
16230: =item *
16231: 
16232: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16233: and '&' separators, supports elements that are arrayrefs and hashrefs
16234: 
16235: =item *
16236: 
16237: hashref2str($hashref) : convert a hashref into a string complete with
16238: escaping and '=' and '&' separators, supports elements that are
16239: arrayrefs and hashrefs
16240: 
16241: =item *
16242: 
16243: arrayref2str($arrayref) : convert an arrayref into a string complete
16244: with escaping and '&' separators, supports elements that are arrayrefs
16245: and hashrefs
16246: 
16247: =item *
16248: 
16249: str2hash($string) : convert string to hash using unescaping and
16250: splitting on '=' and '&', supports elements that are arrayrefs and
16251: hashrefs
16252: 
16253: =item *
16254: 
16255: str2array($string) : convert string to hash using unescaping and
16256: splitting on '&', supports elements that are arrayrefs and hashrefs
16257: 
16258: =back
16259: 
16260: =head2 Logging Routines
16261: 
16262: 
16263: These routines allow one to make log messages in the lonnet.log and
16264: lonnet.perm logfiles.
16265: 
16266: =over 4
16267: 
16268: =item *
16269: 
16270: logtouch() : make sure the logfile, lonnet.log, exists
16271: 
16272: =item *
16273: 
16274: logthis() : append message to the normal lonnet.log file, it gets
16275: preiodically rolled over and deleted.
16276: 
16277: =item *
16278: 
16279: logperm() : append a permanent message to lonnet.perm.log, this log
16280: file never gets deleted by any automated portion of the system, only
16281: messages of critical importance should go in here.
16282: 
16283: 
16284: =back
16285: 
16286: =head2 General File Helper Routines
16287: 
16288: =over 4
16289: 
16290: =item *
16291: 
16292: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16293: (a) files in /uploaded
16294:   (i) If a local copy of the file exists - 
16295:       compares modification date of local copy with last-modified date for 
16296:       definitive version stored on home server for course. If local copy is 
16297:       stale, requests a new version from the home server and stores it. 
16298:       If the original has been removed from the home server, then local copy 
16299:       is unlinked.
16300:   (ii) If local copy does not exist -
16301:       requests the file from the home server and stores it. 
16302:   
16303:   If $caller is 'uploadrep':  
16304:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16305:     for request for files originally uploaded via DOCS. 
16306:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16307:   
16308:   Otherwise:
16309:      This indicates a call from the content generation phase of the request.
16310:      -  returns the entire contents of the file or -1.
16311:      
16312: (b) files in /res
16313:    - returns the entire contents of a file or -1; 
16314:    it properly subscribes to and replicates the file if neccessary.
16315: 
16316: 
16317: =item *
16318: 
16319: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16320:                   reference
16321: 
16322: returns either a stat() list of data about the file or an empty list
16323: if the file doesn't exist or couldn't find out about it (connection
16324: problems or user unknown)
16325: 
16326: =item *
16327: 
16328: filelocation($dir,$file) : returns file system location of a file
16329: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16330: directory that relative $file lookups are to looked in ($dir of /a/dir
16331: and a file of ../bob will become /a/bob)
16332: 
16333: =item *
16334: 
16335: hreflocation($dir,$file) : returns file system location or a URL; same as
16336: filelocation except for hrefs
16337: 
16338: =item *
16339: 
16340: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16341: also removes beginning /home/httpd/html unless /priv/ follows it.
16342: 
16343: =back
16344: 
16345: =head2 Usererfile file routines (/uploaded*)
16346: 
16347: =over 4
16348: 
16349: =item *
16350: 
16351: userfileupload(): main rotine for putting a file in a user or course's
16352:                   filespace, arguments are,
16353: 
16354:  formname - required - this is the name of the element in $env where the
16355:            filename, and the contents of the file to create/modifed exist
16356:            the filename is in $env{'form.'.$formname.'.filename'} and the
16357:            contents of the file is located in $env{'form.'.$formname}
16358:  context - if coursedoc, store the file in the course of the active role
16359:              of the current user; 
16360:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16361:            if 'canceloverwrite': delete file in tmp/overwrites directory
16362:  subdir - required - subdirectory to put the file in under ../userfiles/
16363:          if undefined, it will be placed in "unknown"
16364: 
16365:  (This routine calls clean_filename() to remove any dangerous
16366:  characters from the filename, and then calls finuserfileupload() to
16367:  complete the transaction)
16368: 
16369:  returns either the url of the uploaded file (/uploaded/....) if successful
16370:  and /adm/notfound.html if unsuccessful
16371: 
16372: =item *
16373: 
16374: clean_filename(): routine for cleaing a filename up for storage in
16375:                  userfile space, argument is:
16376: 
16377:  filename - proposed filename
16378: 
16379: returns: the new clean filename
16380: 
16381: =item *
16382: 
16383: finishuserfileupload(): routine that creates and sends the file to
16384: userspace, probably shouldn't be called directly
16385: 
16386:   docuname: username or courseid of destination for the file
16387:   docudom: domain of user/course of destination for the file
16388:   formname: same as for userfileupload()
16389:   fname: filename (including subdirectories) for the file
16390:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16391:           if hashref, and context is scantron, will convert csv format to standard format
16392:   allfiles: reference to hash used to store objects found by parser
16393:   codebase: reference to hash used for codebases of java objects found by parser
16394:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16395:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16396:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16397:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16398:   context: if 'overwrite', will move the uploaded file from its temporary location to
16399:             userfiles to facilitate overwriting a previously uploaded file with same name.
16400:   mimetype: reference to scalar to accommodate mime type determined
16401:             from File::MMagic if $parser = parse.
16402: 
16403:  returns either the url of the uploaded file (/uploaded/....) if successful
16404:  and /adm/notfound.html if unsuccessful (or an error message if context 
16405:  was 'overwrite').
16406:  
16407: 
16408: =item *
16409: 
16410: renameuserfile(): renames an existing userfile to a new name
16411: 
16412:   Args:
16413:    docuname: username or courseid of destination for the file
16414:    docudom: domain of user/course of destination for the file
16415:    old: current file name (including any subdirs under userfiles)
16416:    new: desired file name (including any subdirs under userfiles)
16417: 
16418: =item *
16419: 
16420: mkdiruserfile(): creates a directory is a userfiles dir
16421: 
16422:   Args:
16423:    docuname: username or courseid of destination for the file
16424:    docudom: domain of user/course of destination for the file
16425:    dir: dir to create (including any subdirs under userfiles)
16426: 
16427: =item *
16428: 
16429: removeuserfile(): removes a file that exists in userfiles
16430: 
16431:   Args:
16432:    docuname: username or courseid of destination for the file
16433:    docudom: domain of user/course of destination for the file
16434:    fname: filname to delete (including any subdirs under userfiles)
16435: 
16436: =item *
16437: 
16438: removeuploadedurl(): convience function for removeuserfile()
16439: 
16440:   Args:
16441:    url:  a full /uploaded/... url to delete
16442: 
16443: =item * 
16444: 
16445: get_portfile_permissions():
16446:   Args:
16447:     domain: domain of user or course contain the portfolio files
16448:     user: name of user or num of course contain the portfolio files
16449:   Returns:
16450:     hashref of a dump of the proper file_permissions.db
16451:    
16452: 
16453: =item * 
16454: 
16455: get_access_controls():
16456: 
16457: Args:
16458:   current_permissions: the hash ref returned from get_portfile_permissions()
16459:   group: (optional) the group you want the files associated with
16460:   file: (optional) the file you want access info on
16461: 
16462: Returns:
16463:     a hash (keys are file names) of hashes containing
16464:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16465:         values are XML containing access control settings (see below) 
16466: 
16467: Internal notes:
16468: 
16469:  access controls are stored in file_permissions.db as key=value pairs.
16470:     key -> path to file/file_name\0uniqueID:scope_end_start
16471:         where scope -> public,guest,course,group,domains or users.
16472:               end -> UNIX time for end of access (0 -> no end date)
16473:               start -> UNIX time for start of access
16474: 
16475:     value -> XML description of access control
16476:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16477:             <start></start>
16478:             <end></end>
16479: 
16480:             <password></password>  for scope type = guest
16481: 
16482:             <domain></domain>     for scope type = course or group
16483:             <number></number>
16484:             <roles id="">
16485:              <role></role>
16486:              <access></access>
16487:              <section></section>
16488:              <group></group>
16489:             </roles>
16490: 
16491:             <dom></dom>         for scope type = domains
16492: 
16493:             <users>             for scope type = users
16494:              <user>
16495:               <uname></uname>
16496:               <udom></udom>
16497:              </user>
16498:             </users>
16499:            </scope> 
16500:               
16501:  Access data is also aggregated for each file in an additional key=value pair:
16502:  key -> path to file/file_name\0accesscontrol 
16503:  value -> reference to hash
16504:           hash contains key = value pairs
16505:           where key = uniqueID:scope_end_start
16506:                 value = UNIX time record was last updated
16507: 
16508:           Used to improve speed of look-ups of access controls for each file.  
16509:  
16510:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16511: 
16512: =item *
16513: 
16514: modify_access_controls():
16515: 
16516: Modifies access controls for a portfolio file
16517: Args
16518: 1. file name
16519: 2. reference to hash of required changes,
16520: 3. domain
16521: 4. username
16522:   where domain,username are the domain of the portfolio owner 
16523:   (either a user or a course) 
16524: 
16525: Returns:
16526: 1. result of additions or updates ('ok' or 'error', with error message). 
16527: 2. result of deletions ('ok' or 'error', with error message).
16528: 3. reference to hash of any new or updated access controls.
16529: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16530:    key = integer (inbound ID)
16531:    value = uniqueID
16532: 
16533: =item *
16534: 
16535: get_timebased_id():
16536: 
16537: Attempts to get a unique timestamp-based suffix for use with items added to a 
16538: course via the Course Editor (e.g., folders, composite pages, 
16539: group bulletin boards).
16540: 
16541: Args: (first three required; six others optional)
16542: 
16543: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16544:    docssequence, or name of group
16545: 
16546: 2. keyid (alphanumeric): name of temporary locking key in hash,
16547:    e.g., num, boardids
16548: 
16549: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16550:    file will be named nohist_namespace.db
16551: 
16552: 4. cdom: domain of course; default is current course domain from %env
16553: 
16554: 5. cnum: course number; default is current course number from %env
16555: 
16556: 6. idtype: set to concat if an additional digit is to be appended to the 
16557:    unix timestamp to form the suffix, if the plain timestamp is already
16558:    in use.  Default is to not do this, but simply increment the unix 
16559:    timestamp by 1 until a unique key is obtained.
16560: 
16561: 7. who: holder of locking key; defaults to user:domain for user.
16562: 
16563: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16564:    retrying); default is 3.
16565: 
16566: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16567: 
16568: Returns:
16569: 
16570: 1. suffix obtained (numeric)
16571: 
16572: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16573: 
16574: 3. error: contains (localized) error message if an error occurred.
16575: 
16576: 
16577: =back
16578: 
16579: =head2 HTTP Helper Routines
16580: 
16581: =over 4
16582: 
16583: =item *
16584: 
16585: escape() : unpack non-word characters into CGI-compatible hex codes
16586: 
16587: =item *
16588: 
16589: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16590: 
16591: =back
16592: 
16593: =head1 PRIVATE SUBROUTINES
16594: 
16595: =head2 Underlying communication routines (Shouldn't call)
16596: 
16597: =over 4
16598: 
16599: =item *
16600: 
16601: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16602: 
16603: =item *
16604: 
16605: reply() : uses subreply to send a message to remote machine, logs all failures
16606: 
16607: =item *
16608: 
16609: critical() : passes a critical message to another server; if cannot
16610: get through then place message in connection buffer directory and
16611: returns con_delayed, if incapable of saving message, returns
16612: con_failed
16613: 
16614: =item *
16615: 
16616: reconlonc() : tries to reconnect lonc client processes.
16617: 
16618: =back
16619: 
16620: =head2 Resource Access Logging
16621: 
16622: =over 4
16623: 
16624: =item *
16625: 
16626: flushcourselogs() : flush (save) buffer logs and access logs
16627: 
16628: =item *
16629: 
16630: courselog($what) : save message for course in hash
16631: 
16632: =item *
16633: 
16634: courseacclog($what) : save message for course using &courselog().  Perform
16635: special processing for specific resource types (problems, exams, quizzes, etc).
16636: 
16637: =item *
16638: 
16639: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16640: as a PerlChildExitHandler
16641: 
16642: =back
16643: 
16644: =head2 Other
16645: 
16646: =over 4
16647: 
16648: =item *
16649: 
16650: symblist($mapname,%newhash) : update symbolic storage links
16651: 
16652: =back
16653: 
16654: =cut
16655: 

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