File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1445: download - view: text, annotated - select for diffs
Fri Apr 9 00:57:31 2021 UTC (3 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Fix typo in rev. 1.1444

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1445 2021/04/09 00:57:31 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: use LONCAPA::LWPReq;
  105: use LONCAPA::transliterate;
  106: 
  107: use File::Copy;
  108: 
  109: my $readit;
  110: my $max_connection_retries = 20;     # Or some such value.
  111: 
  112: require Exporter;
  113: 
  114: our @ISA = qw (Exporter);
  115: our @EXPORT = qw(%env);
  116: 
  117: 
  118: # ------------------------------------ Logging (parameters, docs, slots, roles)
  119: {
  120:     my $logid;
  121:     sub write_log {
  122: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  123:         if ($context eq 'course') {
  124:             if (($cnum eq '') || ($cdom eq '')) {
  125:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  126:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  127:             }
  128:         }
  129: 	$logid ++;
  130:         my $now = time();
  131: 	my $id=$now.'00000'.$$.'00000'.$logid;
  132:         my $ip = &get_requestor_ip();
  133:         my $logentry = { 
  134:                           $id => {
  135:                                    'exe_uname' => $env{'user.name'},
  136:                                    'exe_udom'  => $env{'user.domain'},
  137:                                    'exe_time'  => $now,
  138:                                    'exe_ip'    => $ip,
  139:                                    'delflag'   => $delflag,
  140:                                    'logentry'  => $storehash,
  141:                                    'uname'     => $uname,
  142:                                    'udom'      => $udom,
  143:                                   }
  144:                        };
  145: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  146:     }
  147: }
  148: 
  149: sub logtouch {
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     unless (-e "$execdir/logs/lonnet.log") {	
  152: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  153: 	close $fh;
  154:     }
  155:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  156:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  157: }
  158: 
  159: sub logthis {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  165: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  166: 	print $fh $logstring;
  167: 	close($fh);
  168:     }
  169:     return 1;
  170: }
  171: 
  172: sub logperm {
  173:     my $message=shift;
  174:     my $execdir=$perlvar{'lonDaemons'};
  175:     my $now=time;
  176:     my $local=localtime($now);
  177:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  178: 	print $fh "$now:$message:$local\n";
  179: 	close($fh);
  180:     }
  181:     return 1;
  182: }
  183: 
  184: sub create_connection {
  185:     my ($hostname,$lonid) = @_;
  186:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  187: 				     Type    => SOCK_STREAM,
  188: 				     Timeout => 10);
  189:     return 0 if (!$client);
  190:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  191:     my $result = <$client>;
  192:     chomp($result);
  193:     return 1 if ($result eq 'done');
  194:     return 0;
  195: }
  196: 
  197: sub get_server_timezone {
  198:     my ($cnum,$cdom) = @_;
  199:     my $home=&homeserver($cnum,$cdom);
  200:     if ($home ne 'no_host') {
  201:         my $cachetime = 24*3600;
  202:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  203:         if (defined($cached)) {
  204:             return $timezone;
  205:         } else {
  206:             my $timezone = &reply('servertimezone',$home);
  207:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  208:         }
  209:     }
  210: }
  211: 
  212: sub get_server_distarch {
  213:     my ($lonhost,$ignore_cache) = @_;
  214:     if (defined($lonhost)) {
  215:         if (!defined(&hostname($lonhost))) {
  216:             return;
  217:         }
  218:         my $cachetime = 12*3600;
  219:         if (!$ignore_cache) {
  220:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  221:             if (defined($cached)) {
  222:                 return $distarch;
  223:             }
  224:         }
  225:         my $rep = &reply('serverdistarch',$lonhost);
  226:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  227:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  228:                 $rep eq '') {
  229:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  230:         }
  231:     }
  232:     return;
  233: }
  234: 
  235: sub get_servercerts_info {
  236:     my ($lonhost,$hostname,$context) = @_;
  237:     return if ($lonhost eq '');
  238:     if ($hostname eq '') {
  239:         $hostname = &hostname($lonhost);
  240:     }
  241:     return if ($hostname eq '');
  242:     my ($rep,$uselocal);
  243:     if ($context eq 'install') {
  244:         $uselocal = 1;
  245:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  246:         $uselocal = 1;
  247:     }
  248:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  249:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  250:         if ($distro eq '') {
  251:             $uselocal = 0;
  252:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  253:             if ($1 < 6) {
  254:                 $uselocal = 0;
  255:             }
  256:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  257:             if ($1 < 12) {
  258:                 $uselocal = 0;
  259:             }
  260:         }
  261:     }
  262:     if ($uselocal) {
  263:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  264:     } else {
  265:         $rep=&reply('servercerts',$lonhost);
  266:     }
  267:     my ($result,%returnhash);
  268:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  269:         ($rep eq 'unknown_cmd')) {
  270:         $result = $rep;
  271:     } else {
  272:         $result = 'ok';
  273:         my @pairs=split(/\&/,$rep);
  274:         foreach my $item (@pairs) {
  275:             my ($key,$value)=split(/=/,$item,2);
  276:             my $what = &unescape($key);
  277:             $returnhash{$what}=&thaw_unescape($value);
  278:         }
  279:     }
  280:     return ($result,\%returnhash);
  281: }
  282: 
  283: sub get_server_loncaparev {
  284:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  285:     if (defined($lonhost)) {
  286:         if (!defined(&hostname($lonhost))) {
  287:             undef($lonhost);
  288:         }
  289:     }
  290:     if (!defined($lonhost)) {
  291:         if (defined(&domain($dom,'primary'))) {
  292:             $lonhost=&domain($dom,'primary');
  293:             if ($lonhost eq 'no_host') {
  294:                 undef($lonhost);
  295:             }
  296:         }
  297:     }
  298:     if (defined($lonhost)) {
  299:         my $cachetime = 12*3600;
  300:         if (!$ignore_cache) {
  301:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  302:             if (defined($cached)) {
  303:                 return $loncaparev;
  304:             }
  305:         }
  306:         my ($answer,$loncaparev);
  307:         my @ids=&current_machine_ids();
  308:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  309:             $answer = $perlvar{'lonVersion'};
  310:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  311:                 $loncaparev = $1;
  312:             }
  313:         } else {
  314:             $answer = &reply('serverloncaparev',$lonhost);
  315:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  316:                 if ($caller eq 'loncron') {
  317:                     my $hostname = &hostname($lonhost);
  318:                     my $protocol = $protocol{$lonhost};
  319:                     $protocol = 'http' if ($protocol ne 'https');
  320:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  321:                     my $request=new HTTP::Request('GET',$url);
  322:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  323:                     unless ($response->is_error()) {
  324:                         my $content = $response->content;
  325:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  326:                             $loncaparev = $1;
  327:                         }
  328:                     }
  329:                 } else {
  330:                     $loncaparev = $loncaparevs{$lonhost};
  331:                 }
  332:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  333:                 $loncaparev = $1;
  334:             }
  335:         }
  336:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  337:     }
  338: }
  339: 
  340: sub get_server_homeID {
  341:     my ($hostname,$ignore_cache,$caller) = @_;
  342:     unless ($ignore_cache) {
  343:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  344:         if (defined($cached)) {
  345:             return $serverhomeID;
  346:         }
  347:     }
  348:     my $cachetime = 12*3600;
  349:     my $serverhomeID;
  350:     if ($caller eq 'loncron') { 
  351:         my @machine_ids = &machine_ids($hostname);
  352:         foreach my $id (@machine_ids) {
  353:             my $response = &reply('serverhomeID',$id);
  354:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  355:                 $serverhomeID = $response;
  356:                 last;
  357:             }
  358:         }
  359:         if ($serverhomeID eq '') {
  360:             $serverhomeID = $machine_ids[-1];
  361:         }
  362:     } else {
  363:         $serverhomeID = $serverhomeIDs{$hostname};
  364:     }
  365:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  366: }
  367: 
  368: sub get_remote_globals {
  369:     my ($lonhost,$whathash,$ignore_cache) = @_;
  370:     my ($result,%returnhash,%whatneeded);
  371:     if (ref($whathash) eq 'HASH') {
  372:         foreach my $what (sort(keys(%{$whathash}))) {
  373:             my $hashid = $lonhost.'-'.$what;
  374:             my ($response,$cached);
  375:             unless ($ignore_cache) {
  376:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  377:             }
  378:             if (defined($cached)) {
  379:                 $returnhash{$what} = $response;
  380:             } else {
  381:                 $whatneeded{$what} = 1;
  382:             }
  383:         }
  384:         if (keys(%whatneeded) == 0) {
  385:             $result = 'ok';
  386:         } else {
  387:             my $requested = &freeze_escape(\%whatneeded);
  388:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  389:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  390:                 ($rep eq 'unknown_cmd')) {
  391:                 $result = $rep;
  392:             } else {
  393:                 $result = 'ok';
  394:                 my @pairs=split(/\&/,$rep);
  395:                 foreach my $item (@pairs) {
  396:                     my ($key,$value)=split(/=/,$item,2);
  397:                     my $what = &unescape($key);
  398:                     my $hashid = $lonhost.'-'.$what;
  399:                     $returnhash{$what}=&thaw_unescape($value);
  400:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  401:                 }
  402:             }
  403:         }
  404:     }
  405:     return ($result,\%returnhash);
  406: }
  407: 
  408: sub remote_devalidate_cache {
  409:     my ($lonhost,$cachekeys) = @_;
  410:     my $items;
  411:     return unless (ref($cachekeys) eq 'ARRAY');
  412:     my $cachestr = join('&',@{$cachekeys});
  413:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  414:     return $response;
  415: }
  416: 
  417: # -------------------------------------------------- Non-critical communication
  418: sub subreply {
  419:     my ($cmd,$server)=@_;
  420:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  421:     #
  422:     #  With loncnew process trimming, there's a timing hole between lonc server
  423:     #  process exit and the master server picking up the listen on the AF_UNIX
  424:     #  socket.  In that time interval, a lock file will exist:
  425: 
  426:     my $lockfile=$peerfile.".lock";
  427:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  428: 	sleep(0.1);
  429:     }
  430:     # At this point, either a loncnew parent is listening or an old lonc
  431:     # or loncnew child is listening so we can connect or everything's dead.
  432:     #
  433:     #   We'll give the connection a few tries before abandoning it.  If
  434:     #   connection is not possible, we'll con_lost back to the client.
  435:     #   
  436:     my $client;
  437:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  438: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  439: 				      Type    => SOCK_STREAM,
  440: 				      Timeout => 10);
  441: 	if ($client) {
  442: 	    last;		# Connected!
  443: 	} else {
  444: 	    &create_connection(&hostname($server),$server);
  445: 	}
  446:         sleep(0.1);	# Try again later if failed connection.
  447:     }
  448:     my $answer;
  449:     if ($client) {
  450: 	print $client "sethost:$server:$cmd\n";
  451: 	$answer=<$client>;
  452: 	if (!$answer) { $answer="con_lost"; }
  453: 	chomp($answer);
  454:     } else {
  455: 	$answer = 'con_lost';	# Failed connection.
  456:     }
  457:     return $answer;
  458: }
  459: 
  460: sub reply {
  461:     my ($cmd,$server)=@_;
  462:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  463:     my $answer=subreply($cmd,$server);
  464:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  465:         my $logged = $cmd;
  466:         if ($cmd =~ /^encrypt:([^:]+):/) {
  467:             my $subcmd = $1;
  468:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  469:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  470:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  471:                 (undef,undef,my @rest) = split(/:/,$cmd);
  472:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  473:                     splice(@rest,2,1,'Hidden');
  474:                 } elsif ($subcmd eq 'passwd') {
  475:                     splice(@rest,2,2,('Hidden','Hidden'));
  476:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  477:                          ($subcmd eq 'autoexportgrades')) {
  478:                     splice(@rest,3,1,'Hidden');
  479:                 }
  480:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  481:             }
  482:         }
  483:         &logthis("<font color=\"blue\">WARNING:".
  484:                  " $logged to $server returned $answer</font>");
  485:     }
  486:     return $answer;
  487: }
  488: 
  489: # ----------------------------------------------------------- Send USR1 to lonc
  490: 
  491: sub reconlonc {
  492:     my ($lonid) = @_;
  493:     if ($lonid) {
  494:         my $hostname = &hostname($lonid);
  495: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  496: 	if ($hostname && -e $peerfile) {
  497: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  498: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  499: 					     Type    => SOCK_STREAM,
  500: 					     Timeout => 10);
  501: 	    if ($client) {
  502: 		print $client ("reset_retries\n");
  503: 		my $answer=<$client>;
  504: 		#reset just this one.
  505: 	    }
  506: 	}
  507: 	return;
  508:     }
  509: 
  510:     &logthis("Trying to reconnect lonc");
  511:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  512:     if (open(my $fh,"<",$loncfile)) {
  513: 	my $loncpid=<$fh>;
  514:         chomp($loncpid);
  515:         if (kill 0 => $loncpid) {
  516: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  517:             kill USR1 => $loncpid;
  518:             sleep 1;
  519:         } else {
  520: 	    &logthis(
  521:                "<font color=\"blue\">WARNING:".
  522:                " lonc at pid $loncpid not responding, giving up</font>");
  523:         }
  524:     } else {
  525: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  526:     }
  527: }
  528: 
  529: # ------------------------------------------------------ Critical communication
  530: 
  531: sub critical {
  532:     my ($cmd,$server)=@_;
  533:     unless (&hostname($server)) {
  534:         &logthis("<font color=\"blue\">WARNING:".
  535:                " Critical message to unknown server ($server)</font>");
  536:         return 'no_such_host';
  537:     }
  538:     my $answer=reply($cmd,$server);
  539:     if ($answer eq 'con_lost') {
  540: 	&reconlonc($server);
  541: 	my $answer=reply($cmd,$server);
  542:         if ($answer eq 'con_lost') {
  543:             my $now=time;
  544:             my $middlename=$cmd;
  545:             $middlename=substr($middlename,0,16);
  546:             $middlename=~s/\W//g;
  547:             my $dfilename=
  548:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  549:             $dumpcount++;
  550:             {
  551: 		my $dfh;
  552: 		if (open($dfh,">",$dfilename)) {
  553: 		    print $dfh "$cmd\n"; 
  554: 		    close($dfh);
  555: 		}
  556:             }
  557:             sleep 1;
  558:             my $wcmd='';
  559:             {
  560: 		my $dfh;
  561: 		if (open($dfh,"<",$dfilename)) {
  562: 		    $wcmd=<$dfh>; 
  563: 		    close($dfh);
  564: 		}
  565:             }
  566:             chomp($wcmd);
  567:             if ($wcmd eq $cmd) {
  568: 		&logthis("<font color=\"blue\">WARNING: ".
  569:                          "Connection buffer $dfilename: $cmd</font>");
  570:                 &logperm("D:$server:$cmd");
  571: 	        return 'con_delayed';
  572:             } else {
  573:                 &logthis("<font color=\"red\">CRITICAL:"
  574:                         ." Critical connection failed: $server $cmd</font>");
  575:                 &logperm("F:$server:$cmd");
  576:                 return 'con_failed';
  577:             }
  578:         }
  579:     }
  580:     return $answer;
  581: }
  582: 
  583: # ------------------------------------------- check if return value is an error
  584: 
  585: sub error {
  586:     my ($result) = @_;
  587:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  588: 	if ($2 == 2) { return undef; }
  589: 	return $1;
  590:     }
  591:     return undef;
  592: }
  593: 
  594: sub convert_and_load_session_env {
  595:     my ($lonidsdir,$handle)=@_;
  596:     my @profile;
  597:     {
  598: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  599: 	if (!$opened) {
  600: 	    return 0;
  601: 	}
  602: 	flock($idf,LOCK_SH);
  603: 	@profile=<$idf>;
  604: 	close($idf);
  605:     }
  606:     my %temp_env;
  607:     foreach my $line (@profile) {
  608: 	if ($line !~ m/=/) {
  609: 	    return 0;
  610: 	}
  611: 	chomp($line);
  612: 	my ($envname,$envvalue)=split(/=/,$line,2);
  613: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  614:     }
  615:     unlink("$lonidsdir/$handle.id");
  616:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  617: 	    0640)) {
  618: 	%disk_env = %temp_env;
  619: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  620: 	untie(%disk_env);
  621:     }
  622:     return 1;
  623: }
  624: 
  625: # ------------------------------------------- Transfer profile into environment
  626: my $env_loaded;
  627: sub transfer_profile_to_env {
  628:     my ($lonidsdir,$handle,$force_transfer) = @_;
  629:     if (!$force_transfer && $env_loaded) { return; } 
  630: 
  631:     if (!defined($lonidsdir)) {
  632: 	$lonidsdir = $perlvar{'lonIDsDir'};
  633:     }
  634:     if (!defined($handle)) {
  635:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  636:     }
  637: 
  638:     my $convert;
  639:     {
  640:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  641: 	if (!$opened) {
  642: 	    return;
  643: 	}
  644: 	flock($idf,LOCK_SH);
  645: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  646: 		&GDBM_READER(),0640)) {
  647: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  648: 	    untie(%disk_env);
  649: 	} else {
  650: 	    $convert = 1;
  651: 	}
  652:     }
  653:     if ($convert) {
  654: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  655: 	    &logthis("Failed to load session, or convert session.");
  656: 	}
  657:     }
  658: 
  659:     my %remove;
  660:     while ( my $envname = each(%env) ) {
  661:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  662:             if ($time < time-300) {
  663:                 $remove{$key}++;
  664:             }
  665:         }
  666:     }
  667: 
  668:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  669:     $env_loaded=1;
  670:     foreach my $expired_key (keys(%remove)) {
  671:         &delenv($expired_key);
  672:     }
  673: }
  674: 
  675: # ---------------------------------------------------- Check for valid session 
  676: sub check_for_valid_session {
  677:     my ($r,$name,$userhashref,$domref) = @_;
  678:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  679:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  680:     if ($name eq 'lonDAV') {
  681:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  682:     } else {
  683:         $lonidsdir=$r->dir_config('lonIDsDir');
  684:         if ($name eq '') {
  685:             $name = 'lonID';
  686:         }
  687:     }
  688:     if ($name eq 'lonID') {
  689:         $secure = 'lonSID';
  690:         $linkname = 'lonLinkID';
  691:         $pubname = 'lonPubID';
  692:         if (exists($cookies{$secure})) {
  693:             $lonid=$cookies{$secure};
  694:         } elsif (exists($cookies{$name})) {
  695:             $lonid=$cookies{$name};
  696:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  697:             $lonid=$cookies{$linkname};
  698:         } elsif (exists($cookies{$pubname})) {
  699:             $lonid=$cookies{$pubname};
  700:         }
  701:     } else {
  702:         $lonid=$cookies{$name};
  703:     }
  704:     return undef if (!$lonid);
  705: 
  706:     my $handle=&LONCAPA::clean_handle($lonid->value);
  707:     if (-l "$lonidsdir/$handle.id") {
  708:         my $link = readlink("$lonidsdir/$handle.id");
  709:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  710:             $handle = $1;
  711:         }
  712:     }
  713:     if (!-e "$lonidsdir/$handle.id") {
  714:         if ((ref($domref)) && ($name eq 'lonID') && 
  715:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  716:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  717:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  718:                 $$domref = $possudom;
  719:             }
  720:         }
  721:         return undef;
  722:     }
  723: 
  724:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  725:     return undef if (!$opened);
  726: 
  727:     flock($idf,LOCK_SH);
  728:     my %disk_env;
  729:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  730: 	    &GDBM_READER(),0640)) {
  731: 	return undef;	
  732:     }
  733: 
  734:     if (!defined($disk_env{'user.name'})
  735: 	|| !defined($disk_env{'user.domain'})) {
  736:         untie(%disk_env);
  737: 	return undef;
  738:     }
  739: 
  740:     if (ref($userhashref) eq 'HASH') {
  741:         $userhashref->{'name'} = $disk_env{'user.name'};
  742:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  743:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  744:         if ($userhashref->{'lti'}) {
  745:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  746:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  747:         }
  748:     }
  749:     untie(%disk_env);
  750: 
  751:     return $handle;
  752: }
  753: 
  754: sub timed_flock {
  755:     my ($file,$lock_type) = @_;
  756:     my $failed=0;
  757:     eval {
  758: 	local $SIG{__DIE__}='DEFAULT';
  759: 	local $SIG{ALRM}=sub {
  760: 	    $failed=1;
  761: 	    die("failed lock");
  762: 	};
  763: 	alarm(13);
  764: 	flock($file,$lock_type);
  765: 	alarm(0);
  766:     };
  767:     if ($failed) {
  768: 	return undef;
  769:     } else {
  770: 	return 1;
  771:     }
  772: }
  773: 
  774: sub get_sessionfile_vars {
  775:     my ($handle,$lonidsdir,$storearr) = @_;
  776:     my %returnhash;
  777:     unless (ref($storearr) eq 'ARRAY') {
  778:         return %returnhash;
  779:     }
  780:     if (-l "$lonidsdir/$handle.id") {
  781:         my $link = readlink("$lonidsdir/$handle.id");
  782:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  783:             $handle = $1;
  784:         }
  785:     }
  786:     if ((-e "$lonidsdir/$handle.id") &&
  787:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  788:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  789:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  790:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  791:                 flock($idf,LOCK_SH);
  792:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  793:                         &GDBM_READER(),0640)) {
  794:                     foreach my $item (@{$storearr}) {
  795:                         $returnhash{$item} = $disk_env{$item};
  796:                     }
  797:                     untie(%disk_env);
  798:                 }
  799:             }
  800:         }
  801:     }
  802:     return %returnhash;
  803: }
  804: 
  805: # ---------------------------------------------------------- Append Environment
  806: 
  807: sub appenv {
  808:     my ($newenv,$roles) = @_;
  809:     if (ref($newenv) eq 'HASH') {
  810:         foreach my $key (keys(%{$newenv})) {
  811:             my $refused = 0;
  812: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  813:                 $refused = 1;
  814:                 if (ref($roles) eq 'ARRAY') {
  815:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  816:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  817:                         $refused = 0;
  818:                     }
  819:                 }
  820:             }
  821:             if ($refused) {
  822:                 &logthis("<font color=\"blue\">WARNING: ".
  823:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  824:                          .'</font>');
  825: 	        delete($newenv->{$key});
  826:             } else {
  827:                 $env{$key}=$newenv->{$key};
  828:             }
  829:         }
  830:         my $lonids = $perlvar{'lonIDsDir'};
  831:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  832:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  833:             if ($opened
  834: 	        && &timed_flock($env_file,LOCK_EX)
  835: 	        &&
  836: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  837: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  838: 	        while (my ($key,$value) = each(%{$newenv})) {
  839: 	            $disk_env{$key} = $value;
  840: 	        }
  841: 	        untie(%disk_env);
  842:             }
  843:         }
  844:     }
  845:     return 'ok';
  846: }
  847: # ----------------------------------------------------- Delete from Environment
  848: 
  849: sub delenv {
  850:     my ($delthis,$regexp,$roles) = @_;
  851:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  852:         my $refused = 1;
  853:         if (ref($roles) eq 'ARRAY') {
  854:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  855:             if (grep(/^\Q$role\E$/,@{$roles})) {
  856:                 $refused = 0;
  857:             }
  858:         }
  859:         if ($refused) {
  860:             &logthis("<font color=\"blue\">WARNING: ".
  861:                      "Attempt to delete from environment ".$delthis);
  862:             return 'error';
  863:         }
  864:     }
  865:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  866:     if ($opened
  867: 	&& &timed_flock($env_file,LOCK_EX)
  868: 	&&
  869: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  870: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  871: 	foreach my $key (keys(%disk_env)) {
  872: 	    if ($regexp) {
  873:                 if ($key=~/^$delthis/) {
  874:                     delete($env{$key});
  875:                     delete($disk_env{$key});
  876:                 } 
  877:             } else {
  878:                 if ($key=~/^\Q$delthis\E/) {
  879: 		    delete($env{$key});
  880: 		    delete($disk_env{$key});
  881: 	        }
  882:             }
  883: 	}
  884: 	untie(%disk_env);
  885:     }
  886:     return 'ok';
  887: }
  888: 
  889: sub get_env_multiple {
  890:     my ($name) = @_;
  891:     my @values;
  892:     if (defined($env{$name})) {
  893:         # exists is it an array
  894:         if (ref($env{$name})) {
  895:             @values=@{ $env{$name} };
  896:         } else {
  897:             $values[0]=$env{$name};
  898:         }
  899:     }
  900:     return(@values);
  901: }
  902: 
  903: # ------------------------------------------------------------------- Locking
  904: 
  905: sub set_lock {
  906:     my ($text)=@_;
  907:     $locknum++;
  908:     my $id=$$.'-'.$locknum;
  909:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  910:              'session.lock.'.$id => $text});
  911:     return $id;
  912: }
  913: 
  914: sub get_locks {
  915:     my $num=0;
  916:     my %texts=();
  917:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  918:        if ($lock=~/\w/) {
  919:           $num++;
  920:           $texts{$lock}=$env{'session.lock.'.$lock};
  921:        }
  922:    }
  923:    return ($num,%texts);
  924: }
  925: 
  926: sub remove_lock {
  927:     my ($id)=@_;
  928:     my $newlocks='';
  929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  930:        if (($lock=~/\w/) && ($lock ne $id)) {
  931:           $newlocks.=','.$lock;
  932:        }
  933:     }
  934:     &appenv({'session.locks' => $newlocks});
  935:     &delenv('session.lock.'.$id);
  936: }
  937: 
  938: sub remove_all_locks {
  939:     my $activelocks=$env{'session.locks'};
  940:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  941:        if ($lock=~/\w/) {
  942:           &remove_lock($lock);
  943:        }
  944:     }
  945: }
  946: 
  947: 
  948: # ------------------------------------------ Find out current server userload
  949: sub userload {
  950:     my $numusers=0;
  951:     {
  952: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  953: 	my $filename;
  954: 	my $curtime=time;
  955: 	while ($filename=readdir(LONIDS)) {
  956: 	    next if ($filename eq '.' || $filename eq '..');
  957: 	    next if ($filename =~ /publicuser_\d+\.id/);
  958:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  959: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  960: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  961: 	}
  962: 	closedir(LONIDS);
  963:     }
  964:     my $userloadpercent=0;
  965:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  966:     if ($maxuserload) {
  967: 	$userloadpercent=100*$numusers/$maxuserload;
  968:     }
  969:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  970:     return $userloadpercent;
  971: }
  972: 
  973: # ------------------------------ Find server with least workload from spare.tab
  974: 
  975: sub spareserver {
  976:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  977:     my $spare_server;
  978:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  979:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  980:                                                      :  $userloadpercent;
  981:     my ($uint_dom,$remotesessions);
  982:     if (($udom ne '') && (&domain($udom) ne '')) {
  983:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  984:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  985:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  986:         $remotesessions = $udomdefaults{'remotesessions'};
  987:     }
  988:     my $spareshash = &this_host_spares($udom);
  989:     if (ref($spareshash) eq 'HASH') {
  990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  992:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  993:                                              $try_server));
  994: 	        ($spare_server, $lowest_load) =
  995: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  996:             }
  997:         }
  998: 
  999:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1000: 
 1001:         if (!$found_server) {
 1002:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1003: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1004:                     next unless (&spare_can_host($udom,$uint_dom,
 1005:                                                  $remotesessions,$try_server));
 1006: 	            ($spare_server, $lowest_load) =
 1007: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1008:                 }
 1009: 	    }
 1010:         }
 1011:     }
 1012: 
 1013:     if (!$want_server_name) {
 1014:         if (defined($spare_server)) {
 1015:             my $hostname = &hostname($spare_server);
 1016:             if (defined($hostname)) {
 1017:                 my $protocol = 'http';
 1018:                 if ($protocol{$spare_server} eq 'https') {
 1019:                     $protocol = $protocol{$spare_server};
 1020:                 }
 1021: 	        $spare_server = $protocol.'://'.$hostname;
 1022:             }
 1023:         }
 1024:     }
 1025:     return $spare_server;
 1026: }
 1027: 
 1028: sub compare_server_load {
 1029:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1030: 
 1031:     if ($required) {
 1032:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1033:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1034:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1035:         if (($major eq '' && $minor eq '') ||
 1036:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1037:             return ($spare_server,$lowest_load);
 1038:         }
 1039:     }
 1040: 
 1041:     my $loadans     = &reply('load',    $try_server);
 1042:     my $userloadans = &reply('userload',$try_server);
 1043: 
 1044:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1045: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1046:     }
 1047: 
 1048:     my $load;
 1049:     if ($loadans =~ /\d/) {
 1050: 	if ($userloadans =~ /\d/) {
 1051: 	    #both are numbers, pick the bigger one
 1052: 	    $load = ($loadans > $userloadans) ? $loadans 
 1053: 		                              : $userloadans;
 1054: 	} else {
 1055: 	    $load = $loadans;
 1056: 	}
 1057:     } else {
 1058: 	$load = $userloadans;
 1059:     }
 1060: 
 1061:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1062: 	$spare_server = $try_server;
 1063: 	$lowest_load  = $load;
 1064:     }
 1065:     return ($spare_server,$lowest_load);
 1066: }
 1067: 
 1068: # --------------------------- ask offload servers if user already has a session
 1069: sub find_existing_session {
 1070:     my ($udom,$uname) = @_;
 1071:     my $spareshash = &this_host_spares($udom);
 1072:     if (ref($spareshash) eq 'HASH') {
 1073:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1074:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1075:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1076:             }
 1077:         }
 1078:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1079:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1080:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1081:             }
 1082:         }
 1083:     }
 1084:     return;
 1085: }
 1086: 
 1087: sub delusersession {
 1088:     my ($lonid,$udom,$uname) = @_;
 1089:     my $uprimary_id = &domain($udom,'primary');
 1090:     my $uintdom = &internet_dom($uprimary_id);
 1091:     my $intdom = &internet_dom($lonid);
 1092:     my $serverhomedom = &host_domain($lonid);
 1093:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1094:         return &reply(join(':','delusersession',
 1095:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1096:     }
 1097:     return;
 1098: }
 1099: 
 1100: # check if user's browser sent load balancer cookie and server still has session
 1101: # and is not overloaded.
 1102: sub check_for_balancer_cookie {
 1103:     my ($r,$update_mtime) = @_;
 1104:     my ($otherserver,$cookie);
 1105:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1106:     if (exists($cookies{'balanceID'})) {
 1107:         my $balid = $cookies{'balanceID'};
 1108:         $cookie=&LONCAPA::clean_handle($balid->value);
 1109:         my $balancedir=$r->dir_config('lonBalanceDir');
 1110:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1111:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1112:                 my ($possudom,$possuname) = ($1,$2);
 1113:                 my $has_session = 0;
 1114:                 if ((&domain($possudom) ne '') &&
 1115:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1116:                     my $try_server;
 1117:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1118:                     if ($opened) {
 1119:                         flock($idf,LOCK_SH);
 1120:                         while (my $line = <$idf>) {
 1121:                             chomp($line);
 1122:                             if (&hostname($line) ne '') {
 1123:                                 $try_server = $line;
 1124:                                 last;
 1125:                             }
 1126:                         }
 1127:                         close($idf);
 1128:                         if (($try_server) &&
 1129:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1130:                             my $lowest_load = 30000;
 1131:                             ($otherserver,$lowest_load) =
 1132:                                 &compare_server_load($try_server,undef,$lowest_load);
 1133:                             if ($otherserver ne '' && $lowest_load < 100) {
 1134:                                 $has_session = 1;
 1135:                             } else {
 1136:                                 undef($otherserver);
 1137:                             }
 1138:                         }
 1139:                     }
 1140:                 }
 1141:                 if ($has_session) {
 1142:                     if ($update_mtime) {
 1143:                         my $atime = my $mtime = time;
 1144:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1145:                     }
 1146:                 } else {
 1147:                     unlink("$balancedir/$cookie.id");
 1148:                 }
 1149:             }
 1150:         }
 1151:     }
 1152:     return ($otherserver,$cookie);
 1153: }
 1154: 
 1155: sub updatebalcookie {
 1156:     my ($cookie,$balancer,$lastentry)=@_;
 1157:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1158:         my ($udom,$uname) = ($1,$2);
 1159:         my $uprimary_id = &domain($udom,'primary');
 1160:         my $uintdom = &internet_dom($uprimary_id);
 1161:         my $intdom = &internet_dom($balancer);
 1162:         my $serverhomedom = &host_domain($balancer);
 1163:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1164:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1165:         }
 1166:     }
 1167:     return;
 1168: }
 1169: 
 1170: sub delbalcookie {
 1171:     my ($cookie,$balancer) =@_;
 1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1173:         my ($udom,$uname) = ($1,$2);
 1174:         my $uprimary_id = &domain($udom,'primary');
 1175:         my $uintdom = &internet_dom($uprimary_id);
 1176:         my $intdom = &internet_dom($balancer);
 1177:         my $serverhomedom = &host_domain($balancer);
 1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1179:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1180:         }
 1181:     }
 1182: }
 1183: 
 1184: # -------------------------------- ask if server already has a session for user
 1185: sub has_user_session {
 1186:     my ($lonid,$udom,$uname) = @_;
 1187:     my $result = &reply(join(':','userhassession',
 1188: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1189:     return 1 if ($result eq 'ok');
 1190: 
 1191:     return 0;
 1192: }
 1193: 
 1194: # --------- determine least loaded server in a user's domain which allows login
 1195: 
 1196: sub choose_server {
 1197:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1198:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1199:     my %servers = &get_servers($udom);
 1200:     my $lowest_load = 30000;
 1201:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1202:     if ($skiploadbal) {
 1203:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1204:         unless (defined($cached)) {
 1205:             my $cachetime = 60*60*24;
 1206:             my %domconfig =
 1207:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1208:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1209:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1210:                                            $cachetime);
 1211:             }
 1212:         }
 1213:     }
 1214:     foreach my $lonhost (keys(%servers)) {
 1215:         if ($skiploadbal) {
 1216:             if (ref($balancers) eq 'HASH') {
 1217:                 next if (exists($balancers->{$lonhost}));
 1218:             }
 1219:         }
 1220:         my $loginvia;
 1221:         if ($checkloginvia) {
 1222:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1223:             if ($loginvia) {
 1224:                 my ($server,$path) = split(/:/,$loginvia);
 1225:                 ($login_host, $lowest_load) =
 1226:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1227:                 if ($login_host eq $server) {
 1228:                     $portal_path = $path;
 1229:                     $isredirect = 1;
 1230:                 }
 1231:             } else {
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $lonhost) {
 1235:                     $portal_path = '';
 1236:                     $isredirect = ''; 
 1237:                 }
 1238:             }
 1239:         } else {
 1240:             ($login_host, $lowest_load) =
 1241:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1242:         }
 1243:     }
 1244:     if ($login_host ne '') {
 1245:         $hostname = &hostname($login_host);
 1246:     }
 1247:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1248: }
 1249: 
 1250: sub get_course_sessions {
 1251:     my ($cnum,$cdom,$lastactivity) = @_;
 1252:     my %servers = &internet_dom_servers($cdom);
 1253:     my %returnhash;
 1254:     foreach my $server (sort(keys(%servers))) {
 1255:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1256:         my @pairs=split(/\&/,$rep);
 1257:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1258:             foreach my $item (@pairs) {
 1259:                 my ($key,$value)=split(/=/,$item,2);
 1260:                 $key = &unescape($key);
 1261:                 next if ($key =~ /^error: 2 /);
 1262:                 if (exists($returnhash{$key})) {
 1263:                     next if ($value < $returnhash{$key});
 1264:                 }
 1265:                 $returnhash{$key}=$value;
 1266:             }
 1267:         }
 1268:     }
 1269:     return %returnhash;
 1270: }
 1271: 
 1272: # --------------------------------------------- Try to change a user's password
 1273: 
 1274: sub changepass {
 1275:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1276:     $currentpass = &escape($currentpass);
 1277:     $newpass     = &escape($newpass);
 1278:     my $lonhost = $perlvar{'lonHostID'};
 1279:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1280: 		       $server);
 1281:     if (! $answer) {
 1282: 	&logthis("No reply on password change request to $server ".
 1283: 		 "by $uname in domain $udom.");
 1284:     } elsif ($answer =~ "^ok") {
 1285:         &logthis("$uname in $udom successfully changed their password ".
 1286: 		 "on $server.");
 1287:     } elsif ($answer =~ "^pwchange_failure") {
 1288: 	&logthis("$uname in $udom was unable to change their password ".
 1289: 		 "on $server.  The action was blocked by either lcpasswd ".
 1290: 		 "or pwchange");
 1291:     } elsif ($answer =~ "^non_authorized") {
 1292:         &logthis("$uname in $udom did not get their password correct when ".
 1293: 		 "attempting to change it on $server.");
 1294:     } elsif ($answer =~ "^auth_mode_error") {
 1295:         &logthis("$uname in $udom attempted to change their password despite ".
 1296: 		 "not being locally or internally authenticated on $server.");
 1297:     } elsif ($answer =~ "^unknown_user") {
 1298:         &logthis("$uname in $udom attempted to change their password ".
 1299: 		 "on $server but were unable to because $server is not ".
 1300: 		 "their home server.");
 1301:     } elsif ($answer =~ "^refused") {
 1302: 	&logthis("$server refused to change $uname in $udom password because ".
 1303: 		 "it was sent an unencrypted request to change the password.");
 1304:     } elsif ($answer =~ "invalid_client") {
 1305:         &logthis("$server refused to change $uname in $udom password because ".
 1306:                  "it was a reset by e-mail originating from an invalid server.");
 1307:     } elsif ($answer =~ "^prioruse") {
 1308:        &logthis("$server refused to change $uname in $udom password because ".
 1309:                 "the password had been used before");
 1310:     }
 1311:     return $answer;
 1312: }
 1313: 
 1314: # ----------------------- Try to determine user's current authentication scheme
 1315: 
 1316: sub queryauthenticate {
 1317:     my ($uname,$udom)=@_;
 1318:     my $uhome=&homeserver($uname,$udom);
 1319:     if (!$uhome) {
 1320: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1321: 	return 'no_host';
 1322:     }
 1323:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1324:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1325: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1326:     }
 1327:     return $answer;
 1328: }
 1329: 
 1330: # --------- Try to authenticate user from domain's lib servers (first this one)
 1331: 
 1332: sub authenticate {
 1333:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1334:     $upass=&escape($upass);
 1335:     $uname= &LONCAPA::clean_username($uname);
 1336:     my $uhome=&homeserver($uname,$udom,1);
 1337:     my $newhome;
 1338:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1339: # Maybe the machine was offline and only re-appeared again recently?
 1340:         &reconlonc();
 1341: # One more
 1342: 	$uhome=&homeserver($uname,$udom,1);
 1343:         if (($uhome eq 'no_host') && $checkdefauth) {
 1344:             if (defined(&domain($udom,'primary'))) {
 1345:                 $newhome=&domain($udom,'primary');
 1346:             }
 1347:             if ($newhome ne '') {
 1348:                 $uhome = $newhome;
 1349:             }
 1350:         }
 1351: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1352: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1353: 	    return 'no_host';
 1354:         }
 1355:     }
 1356:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1357:     if ($answer eq 'authorized') {
 1358:         if ($newhome) {
 1359:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1360:             return 'no_account_on_host'; 
 1361:         } else {
 1362:             &logthis("User $uname at $udom authorized by $uhome");
 1363:             return $uhome;
 1364:         }
 1365:     }
 1366:     if ($answer eq 'non_authorized') {
 1367: 	&logthis("User $uname at $udom rejected by $uhome");
 1368: 	return 'no_host'; 
 1369:     }
 1370:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1371:     return 'no_host';
 1372: }
 1373: 
 1374: sub can_host_session {
 1375:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1376:     my $canhost = 1;
 1377:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1378:     if (ref($remotesessions) eq 'HASH') {
 1379:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1380:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1381:                 $canhost = 0;
 1382:             } else {
 1383:                 $canhost = 1;
 1384:             }
 1385:         }
 1386:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1388:                 $canhost = 1;
 1389:             } else {
 1390:                 $canhost = 0;
 1391:             }
 1392:         }
 1393:         if ($canhost) {
 1394:             if ($remotesessions->{'version'} ne '') {
 1395:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1396:                 if ($reqmajor ne '' && $reqminor ne '') {
 1397:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1398:                         my $major = $1;
 1399:                         my $minor = $2;
 1400:                         if (($major < $reqmajor ) ||
 1401:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1402:                             $canhost = 0;
 1403:                         }
 1404:                     } else {
 1405:                         $canhost = 0;
 1406:                     }
 1407:                 }
 1408:             }
 1409:         }
 1410:     }
 1411:     if ($canhost) {
 1412:         if (ref($hostedsessions) eq 'HASH') {
 1413:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1414:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1415:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1416:                 if (($uint_dom ne '') && 
 1417:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1418:                     $canhost = 0;
 1419:                 } else {
 1420:                     $canhost = 1;
 1421:                 }
 1422:             }
 1423:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1424:                 if (($uint_dom ne '') && 
 1425:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1426:                     $canhost = 1;
 1427:                 } else {
 1428:                     $canhost = 0;
 1429:                 }
 1430:             }
 1431:         }
 1432:     }
 1433:     return $canhost;
 1434: }
 1435: 
 1436: sub spare_can_host {
 1437:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1438:     my $canhost=1;
 1439:     my $try_server_hostname = &hostname($try_server);
 1440:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1441:     my $serverhomedom = &host_domain($serverhomeID);
 1442:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1443:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1444:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1445:             $canhost = 0;
 1446:         }
 1447:     }
 1448:     if ($canhost) {
 1449:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1450:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1451:                 unless (&shared_institution($udom,$try_server)) {
 1452:                     $canhost = 0;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     if (($canhost) && ($uint_dom)) {
 1458:         my @intdoms;
 1459:         my $internet_names = &get_internet_names($try_server);
 1460:         if (ref($internet_names) eq 'ARRAY') {
 1461:             @intdoms = @{$internet_names};
 1462:         }
 1463:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1464:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1465:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1466:                                          $remotesessions,
 1467:                                          $defdomdefaults{'hostedsessions'});
 1468:         }
 1469:     }
 1470:     return $canhost;
 1471: }
 1472: 
 1473: sub this_host_spares {
 1474:     my ($dom) = @_;
 1475:     my ($dom_in_use,$lonhost_in_use,$result);
 1476:     my @hosts = &current_machine_ids();
 1477:     foreach my $lonhost (@hosts) {
 1478:         if (&host_domain($lonhost) eq $dom) {
 1479:             $dom_in_use = $dom;
 1480:             $lonhost_in_use = $lonhost;
 1481:             last;
 1482:         }
 1483:     }
 1484:     if ($dom_in_use ne '') {
 1485:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1486:     }
 1487:     if (ref($result) ne 'HASH') {
 1488:         $lonhost_in_use = $perlvar{'lonHostID'};
 1489:         $dom_in_use = &host_domain($lonhost_in_use);
 1490:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1491:         if (ref($result) ne 'HASH') {
 1492:             $result = \%spareid;
 1493:         }
 1494:     }
 1495:     return $result;
 1496: }
 1497: 
 1498: sub spares_for_offload  {
 1499:     my ($dom_in_use,$lonhost_in_use) = @_;
 1500:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1501:     if (defined($cached)) {
 1502:         return $result;
 1503:     } else {
 1504:         my $cachetime = 60*60*24;
 1505:         my %domconfig =
 1506:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1507:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1508:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1509:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1510:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1511:                 }
 1512:             }
 1513:         }
 1514:     }
 1515:     return;
 1516: }
 1517: 
 1518: sub get_lonbalancer_config {
 1519:     my ($servers) = @_;
 1520:     my ($currbalancer,$currtargets);
 1521:     if (ref($servers) eq 'HASH') {
 1522:         foreach my $server (keys(%{$servers})) {
 1523:             my %what = (
 1524:                          spareid => 1,
 1525:                          perlvar => 1,
 1526:                        );
 1527:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1528:             if ($result eq 'ok') {
 1529:                 if (ref($returnhash) eq 'HASH') {
 1530:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1531:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1532:                             $currbalancer = $server;
 1533:                             $currtargets = {};
 1534:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1535:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1536:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1537:                                 }
 1538:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1539:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1540:                                 }
 1541:                             }
 1542:                             last;
 1543:                         }
 1544:                     }
 1545:                 }
 1546:             }
 1547:         }
 1548:     }
 1549:     return ($currbalancer,$currtargets);
 1550: }
 1551: 
 1552: sub check_loadbalancing {
 1553:     my ($uname,$udom,$caller) = @_;
 1554:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1555:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1556:     my $lonhost = $perlvar{'lonHostID'};
 1557:     my @hosts = &current_machine_ids();
 1558:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1559:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1560:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1561:     my $serverhomedom = &host_domain($lonhost);
 1562:     my $domneedscache;
 1563:     my $cachetime = 60*60*24;
 1564: 
 1565:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1566:         $dom_in_use = $udom;
 1567:         $homeintdom = 1;
 1568:     } else {
 1569:         $dom_in_use = $serverhomedom;
 1570:     }
 1571:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1572:     unless (defined($cached)) {
 1573:         my %domconfig =
 1574:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1575:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1577:         } else {
 1578:             $domneedscache = $dom_in_use;
 1579:         }
 1580:     }
 1581:     if (ref($result) eq 'HASH') {
 1582:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1583:             &check_balancer_result($result,@hosts);
 1584:         if ($is_balancer) {
 1585:             if (ref($currrules) eq 'HASH') {
 1586:                 if ($homeintdom) {
 1587:                     if ($uname ne '') {
 1588:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1589:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1590:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1591:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1592:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1593:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1594:                             }
 1595:                         }
 1596:                         if ($rule_in_effect eq '') {
 1597:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1598:                             if ($userenv{'inststatus'} ne '') {
 1599:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1600:                                 my ($othertitle,$usertypes,$types) =
 1601:                                     &Apache::loncommon::sorted_inst_types($udom);
 1602:                                 if (ref($types) eq 'ARRAY') {
 1603:                                     foreach my $type (@{$types}) {
 1604:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1605:                                             if (exists($currrules->{$type})) {
 1606:                                                 $rule_in_effect = $currrules->{$type};
 1607:                                             }
 1608:                                         }
 1609:                                     }
 1610:                                 }
 1611:                             } else {
 1612:                                 if (exists($currrules->{'default'})) {
 1613:                                     $rule_in_effect = $currrules->{'default'};
 1614:                                 }
 1615:                             }
 1616:                         }
 1617:                     } else {
 1618:                         if (exists($currrules->{'default'})) {
 1619:                             $rule_in_effect = $currrules->{'default'};
 1620:                         }
 1621:                     }
 1622:                 } else {
 1623:                     if ($currrules->{'_LC_external'} ne '') {
 1624:                         $rule_in_effect = $currrules->{'_LC_external'};
 1625:                     }
 1626:                 }
 1627:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1628:                                                        $uname,$udom);
 1629:             }
 1630:         }
 1631:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1632:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1633:         unless (defined($cached)) {
 1634:             my %domconfig =
 1635:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1636:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1637:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1638:             } else {
 1639:                 $domneedscache = $serverhomedom;
 1640:             }
 1641:         }
 1642:         if (ref($result) eq 'HASH') {
 1643:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1644:                 &check_balancer_result($result,@hosts);
 1645:             if ($is_balancer) {
 1646:                 if (ref($currrules) eq 'HASH') {
 1647:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1648:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1649:                     }
 1650:                 }
 1651:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1652:                                                        $uname,$udom);
 1653:             }
 1654:         } else {
 1655:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1656:                 $is_balancer = 1;
 1657:                 $offloadto = &this_host_spares($dom_in_use);
 1658:             }
 1659:             unless (defined($cached)) {
 1660:                 $domneedscache = $serverhomedom;
 1661:             }
 1662:         }
 1663:     } else {
 1664:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1665:             $is_balancer = 1;
 1666:             $offloadto = &this_host_spares($dom_in_use);
 1667:         }
 1668:         unless (defined($cached)) {
 1669:             $domneedscache = $serverhomedom;
 1670:         }
 1671:     }
 1672:     if ($domneedscache) {
 1673:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1674:     }
 1675:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1676:         my $lowest_load = 30000;
 1677:         if (ref($offloadto) eq 'HASH') {
 1678:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1679:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1680:                     ($otherserver,$lowest_load) =
 1681:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1682:                 }
 1683:             }
 1684:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1685: 
 1686:             if (!$found_server) {
 1687:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1688:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1689:                         ($otherserver,$lowest_load) =
 1690:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1691:                     }
 1692:                 }
 1693:             }
 1694:         } elsif (ref($offloadto) eq 'ARRAY') {
 1695:             if (@{$offloadto} == 1) {
 1696:                 $otherserver = $offloadto->[0];
 1697:             } elsif (@{$offloadto} > 1) {
 1698:                 foreach my $try_server (@{$offloadto}) {
 1699:                     ($otherserver,$lowest_load) =
 1700:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1701:                 }
 1702:             }
 1703:         }
 1704:         unless ($caller eq 'login') {
 1705:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1706:                 $is_balancer = 0;
 1707:                 if ($uname ne '' && $udom ne '') {
 1708:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1709:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1710:                                  'user.loadbalcheck.time' => time});
 1711:                     }
 1712:                 }
 1713:             }
 1714:         }
 1715:     }
 1716:     if (($is_balancer) && (!$homeintdom)) {
 1717:         undef($setcookie);
 1718:     }
 1719:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1720: }
 1721: 
 1722: sub check_balancer_result {
 1723:     my ($result,@hosts) = @_;
 1724:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1725:     if (ref($result) eq 'HASH') {
 1726:         if ($result->{'lonhost'} ne '') {
 1727:             my $currbalancer = $result->{'lonhost'};
 1728:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1729:                 $is_balancer = 1;
 1730:                 $currtargets = $result->{'targets'};
 1731:                 $currrules = $result->{'rules'};
 1732:             }
 1733:             $dom_balancers = $currbalancer;
 1734:         } else {
 1735:             if (keys(%{$result})) {
 1736:                 foreach my $key (keys(%{$result})) {
 1737:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1738:                         (ref($result->{$key}) eq 'HASH')) {
 1739:                         $is_balancer = 1;
 1740:                         $currrules = $result->{$key}{'rules'};
 1741:                         $currtargets = $result->{$key}{'targets'};
 1742:                         $setcookie = $result->{$key}{'cookie'};
 1743:                         last;
 1744:                     }
 1745:                 }
 1746:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1747:             }
 1748:         }
 1749:     }
 1750:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1751: }
 1752: 
 1753: sub get_loadbalancer_targets {
 1754:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1755:     my $offloadto;
 1756:     if ($rule_in_effect eq 'none') {
 1757:         return [$perlvar{'lonHostID'}];
 1758:     } elsif ($rule_in_effect eq '') {
 1759:         $offloadto = $currtargets;
 1760:     } else {
 1761:         if ($rule_in_effect eq 'homeserver') {
 1762:             my $homeserver = &homeserver($uname,$udom);
 1763:             if ($homeserver ne 'no_host') {
 1764:                 $offloadto = [$homeserver];
 1765:             }
 1766:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1767:             my %domconfig =
 1768:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1769:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1770:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1771:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1772:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1773:                     }
 1774:                 }
 1775:             } else {
 1776:                 my %servers = &internet_dom_servers($udom);
 1777:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1778:                 if (&hostname($remotebalancer) ne '') {
 1779:                     $offloadto = [$remotebalancer];
 1780:                 }
 1781:             }
 1782:         } elsif (&hostname($rule_in_effect) ne '') {
 1783:             $offloadto = [$rule_in_effect];
 1784:         }
 1785:     }
 1786:     return $offloadto;
 1787: }
 1788: 
 1789: sub internet_dom_servers {
 1790:     my ($dom) = @_;
 1791:     my (%uniqservers,%servers);
 1792:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1793:     my @machinedoms = &machine_domains($primaryserver);
 1794:     foreach my $mdom (@machinedoms) {
 1795:         my %currservers = %servers;
 1796:         my %server = &get_servers($mdom);
 1797:         %servers = (%currservers,%server);
 1798:     }
 1799:     my %by_hostname;
 1800:     foreach my $id (keys(%servers)) {
 1801:         push(@{$by_hostname{$servers{$id}}},$id);
 1802:     }
 1803:     foreach my $hostname (sort(keys(%by_hostname))) {
 1804:         if (@{$by_hostname{$hostname}} > 1) {
 1805:             my $match = 0;
 1806:             foreach my $id (@{$by_hostname{$hostname}}) {
 1807:                 if (&host_domain($id) eq $dom) {
 1808:                     $uniqservers{$id} = $hostname;
 1809:                     $match = 1;
 1810:                 }
 1811:             }
 1812:             unless ($match) {
 1813:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1814:             }
 1815:         } else {
 1816:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1817:         }
 1818:     }
 1819:     return %uniqservers;
 1820: }
 1821: 
 1822: sub trusted_domains {
 1823:     my ($cmdtype,$calldom) = @_;
 1824:     my ($trusted,$untrusted);
 1825:     if (&domain($calldom) eq '') {
 1826:         return ($trusted,$untrusted);
 1827:     }
 1828:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1829:         return ($trusted,$untrusted);
 1830:     }
 1831:     my $callprimary = &domain($calldom,'primary');
 1832:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1833:     if ($intcalldom eq '') {
 1834:         return ($trusted,$untrusted);
 1835:     }
 1836: 
 1837:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1838:     unless (defined($cached)) {
 1839:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1840:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1841:         $trustconfig = $domconfig{'trust'};
 1842:     }
 1843:     if (ref($trustconfig)) {
 1844:         my (%possexc,%possinc,@allexc,@allinc); 
 1845:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1846:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1847:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1848:             }
 1849:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1850:                 $possinc{$intcalldom} = 1;
 1851:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1852:             }
 1853:         }
 1854:         if (keys(%possexc)) {
 1855:             if (keys(%possinc)) {
 1856:                 foreach my $key (sort(keys(%possexc))) {
 1857:                     next if ($key eq $intcalldom);
 1858:                     unless ($possinc{$key}) {
 1859:                         push(@allexc,$key);
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 @allexc = sort(keys(%possexc));
 1864:             }
 1865:         }
 1866:         if (keys(%possinc)) {
 1867:             $possinc{$intcalldom} = 1;
 1868:             @allinc = sort(keys(%possinc));
 1869:         }
 1870:         if ((@allexc > 0) || (@allinc > 0)) {
 1871:             my %doms_by_intdom;
 1872:             my %allintdoms = &all_host_intdom();
 1873:             my %alldoms = &all_host_domain();
 1874:             foreach my $key (%allintdoms) {
 1875:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1876:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1877:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1878:                     }
 1879:                 } else {
 1880:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1881:                 }
 1882:             }
 1883:             foreach my $exc (@allexc) {
 1884:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1885:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1886:                 }
 1887:             }
 1888:             foreach my $inc (@allinc) {
 1889:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1890:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1891:                 }
 1892:             }
 1893:         }
 1894:     }
 1895:     return ($trusted,$untrusted);
 1896: }
 1897: 
 1898: sub will_trust {
 1899:     my ($cmdtype,$domain,$possdom) = @_;
 1900:     return 1 if ($domain eq $possdom);
 1901:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1902:     my $willtrust; 
 1903:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1904:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1905:             $willtrust = 1;
 1906:         }
 1907:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1908:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1909:             $willtrust = 1;
 1910:         }
 1911:     } else {
 1912:         $willtrust = 1;
 1913:     }
 1914:     return $willtrust;
 1915: }
 1916: 
 1917: # ---------------------- Find the homebase for a user from domain's lib servers
 1918: 
 1919: my %homecache;
 1920: sub homeserver {
 1921:     my ($uname,$udom,$ignoreBadCache)=@_;
 1922:     my $index="$uname:$udom";
 1923: 
 1924:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1925: 
 1926:     my %servers = &get_servers($udom,'library');
 1927:     foreach my $tryserver (keys(%servers)) {
 1928:         next if ($ignoreBadCache ne 'true' && 
 1929: 		 exists($badServerCache{$tryserver}));
 1930: 
 1931: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1932: 	if ($answer eq 'found') {
 1933: 	    delete($badServerCache{$tryserver}); 
 1934: 	    return $homecache{$index}=$tryserver;
 1935: 	} elsif ($answer eq 'no_host') {
 1936: 	    $badServerCache{$tryserver}=1;
 1937: 	}
 1938:     }    
 1939:     return 'no_host';
 1940: }
 1941: 
 1942: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1943: 
 1944: sub idget {
 1945:     my ($udom,$idsref,$namespace)=@_;
 1946:     my %returnhash=();
 1947:     my @ids=(); 
 1948:     if (ref($idsref) eq 'ARRAY') {
 1949:         @ids = @{$idsref};
 1950:     } else {
 1951:         return %returnhash; 
 1952:     }
 1953:     if ($namespace eq '') {
 1954:         $namespace = 'ids';
 1955:     }
 1956:     
 1957:     my %servers = &get_servers($udom,'library');
 1958:     foreach my $tryserver (keys(%servers)) {
 1959: 	my $idlist=join('&', map { &escape($_); } @ids);
 1960: 	if ($namespace eq 'ids') {
 1961: 	    $idlist=~tr/A-Z/a-z/;
 1962: 	}
 1963: 	my $reply;
 1964: 	if ($namespace eq 'ids') {
 1965: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1966: 	} else {
 1967: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1968: 	}
 1969: 	my @answer=();
 1970: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1971: 	    @answer=split(/\&/,$reply);
 1972: 	}                    ;
 1973: 	my $i;
 1974: 	for ($i=0;$i<=$#ids;$i++) {
 1975: 	    if ($answer[$i]) {
 1976: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1977: 	    }
 1978: 	}
 1979:     }
 1980:     return %returnhash;
 1981: }
 1982: 
 1983: # ------------------------------------- Find the IDs behind a list of usernames
 1984: 
 1985: sub idrget {
 1986:     my ($udom,@unames)=@_;
 1987:     my %returnhash=();
 1988:     foreach my $uname (@unames) {
 1989:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1990:     }
 1991:     return %returnhash;
 1992: }
 1993: 
 1994: # Store away a list of names and associated student/employee IDs or clicker IDs
 1995: 
 1996: sub idput {
 1997:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1998:     my %servers=();
 1999:     my %ids=();
 2000:     my %byid = ();
 2001:     if (ref($idsref) eq 'HASH') {
 2002:         %ids=%{$idsref};
 2003:     }
 2004:     if ($namespace eq '') {
 2005:         $namespace = 'ids'; 
 2006:     }
 2007:     foreach my $uname (keys(%ids)) {
 2008: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2009:         if ($uhom eq '') {
 2010:             $uhom=&homeserver($uname,$udom);
 2011:         }
 2012:         if ($uhom ne 'no_host') {
 2013:             my $esc_unam=&escape($uname);
 2014:             if ($namespace eq 'ids') {
 2015:                 my $id=&escape($ids{$uname});
 2016:                 $id=~tr/A-Z/a-z/;
 2017:                 my $esc_unam=&escape($uname);
 2018:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2019:             } else {
 2020:                 my @currids = split(/,/,$ids{$uname});
 2021:                 foreach my $id (@currids) {
 2022:                     $byid{$uhom}{$id} .= $uname.',';
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027:     if ($namespace eq 'clickers') {
 2028:         foreach my $server (keys(%byid)) {
 2029:             if (ref($byid{$server}) eq 'HASH') {
 2030:                 foreach my $id (keys(%{$byid{$server}})) {
 2031:                     $byid{$server} =~ s/,$//;
 2032:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2033:                 }
 2034:             }
 2035:         }
 2036:     }
 2037:     foreach my $server (keys(%servers)) {
 2038:         $servers{$server} =~ s/\&$//;
 2039:         if ($namespace eq 'ids') {     
 2040:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2041:         } else {
 2042:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2043:         }
 2044:     }
 2045: }
 2046: 
 2047: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2048: 
 2049: sub iddel {
 2050:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2051:     my %result=();
 2052:     my %ids=();
 2053:     my %byid = ();
 2054:     if (ref($idshashref) eq 'HASH') {
 2055:         %ids=%{$idshashref};
 2056:     } else {
 2057:         return %result;
 2058:     }
 2059:     if ($namespace eq '') {
 2060:         $namespace = 'ids';
 2061:     }
 2062:     my %servers=();
 2063:     while (my ($id,$unamestr) = each(%ids)) {
 2064:         if ($namespace eq 'ids') {
 2065:             my $uhom = $uhome;
 2066:             if ($uhom eq '') { 
 2067:                 $uhom=&homeserver($unamestr,$udom);
 2068:             }
 2069:             if ($uhom ne 'no_host') {
 2070:                 $servers{$uhom}.='&'.&escape($id);
 2071:             }
 2072:          } else {
 2073:             my @curritems = split(/,/,$ids{$id});
 2074:             foreach my $uname (@curritems) {
 2075:                 my $uhom = $uhome;
 2076:                 if ($uhom eq '') {
 2077:                     $uhom=&homeserver($uname,$udom);
 2078:                 }
 2079:                 if ($uhom ne 'no_host') { 
 2080:                     $byid{$uhom}{$id} .= $uname.',';
 2081:                 }
 2082:             }
 2083:         }
 2084:     }
 2085:     if ($namespace eq 'clickers') {
 2086:         foreach my $server (keys(%byid)) {
 2087:             if (ref($byid{$server}) eq 'HASH') {
 2088:                 foreach my $id (keys(%{$byid{$server}})) {
 2089:                     $byid{$server}{$id} =~ s/,$//;
 2090:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2091:                 }
 2092:             }
 2093:         }
 2094:     }
 2095:     foreach my $server (keys(%servers)) {
 2096:         $servers{$server} =~ s/\&$//;
 2097:         if ($namespace eq 'ids') {
 2098:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2099:         } elsif ($namespace eq 'clickers') {
 2100:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2101:         }
 2102:     }
 2103:     return %result;
 2104: }
 2105: 
 2106: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2107: 
 2108: sub updateclickers {
 2109:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2110:     my %clickers;
 2111:     if (ref($idshashref) eq 'HASH') {
 2112:         %clickers=%{$idshashref};
 2113:     } else {
 2114:         return;
 2115:     }
 2116:     my $items='';
 2117:     foreach my $item (keys(%clickers)) {
 2118:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2119:     }
 2120:     $items=~s/\&$//;
 2121:     my $request = "updateclickers:$udom:$action:$items";
 2122:     if ($critical) {
 2123:         return &critical($request,$uhome);
 2124:     } else {
 2125:         return &reply($request,$uhome);
 2126:     }
 2127: }
 2128: 
 2129: # ------------------------------dump from db file owned by domainconfig user
 2130: sub dump_dom {
 2131:     my ($namespace, $udom, $regexp) = @_;
 2132: 
 2133:     $udom ||= $env{'user.domain'};
 2134: 
 2135:     return () unless $udom;
 2136: 
 2137:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2138: }
 2139: 
 2140: # ------------------------------------------ get items from domain db files   
 2141: 
 2142: sub get_dom {
 2143:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2144:     return if ($udom eq 'public');
 2145:     my $items='';
 2146:     foreach my $item (@$storearr) {
 2147:         $items.=&escape($item).'&';
 2148:     }
 2149:     $items=~s/\&$//;
 2150:     if (!$udom) {
 2151:         $udom=$env{'user.domain'};
 2152:         return if ($udom eq 'public');
 2153:         if (defined(&domain($udom,'primary'))) {
 2154:             $uhome=&domain($udom,'primary');
 2155:         } else {
 2156:             undef($uhome);
 2157:         }
 2158:     } else {
 2159:         if (!$uhome) {
 2160:             if (defined(&domain($udom,'primary'))) {
 2161:                 $uhome=&domain($udom,'primary');
 2162:             }
 2163:         }
 2164:     }
 2165:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2166:         my $rep;
 2167:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2168:             # domain information is hosted on this machine
 2169:             my $cmd = 'getdom';
 2170:             if ($namespace =~ /^enc/) {
 2171:                 $cmd = 'egetdom';
 2172:             }
 2173:             $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
 2174:         } else {
 2175:             if ($namespace =~ /^enc/) {
 2176:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2177:             } else {
 2178:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2179:             }
 2180:         }
 2181:         my %returnhash;
 2182:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2183:             return %returnhash;
 2184:         }
 2185:         my @pairs=split(/\&/,$rep);
 2186:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2187:             return @pairs;
 2188:         }
 2189:         my $i=0;
 2190:         foreach my $item (@$storearr) {
 2191:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2192:             $i++;
 2193:         }
 2194:         return %returnhash;
 2195:     } else {
 2196:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2197:     }
 2198: }
 2199: 
 2200: # -------------------------------------------- put items in domain db files 
 2201: 
 2202: sub put_dom {
 2203:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2204:     if (!$udom) {
 2205:         $udom=$env{'user.domain'};
 2206:         if (defined(&domain($udom,'primary'))) {
 2207:             $uhome=&domain($udom,'primary');
 2208:         } else {
 2209:             undef($uhome);
 2210:         }
 2211:     } else {
 2212:         if (!$uhome) {
 2213:             if (defined(&domain($udom,'primary'))) {
 2214:                 $uhome=&domain($udom,'primary');
 2215:             }
 2216:         }
 2217:     } 
 2218:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2219:         my $items='';
 2220:         foreach my $item (keys(%$storehash)) {
 2221:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2222:         }
 2223:         $items=~s/\&$//;
 2224:         if ($namespace =~ /^enc/) {
 2225:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2226:         } else {
 2227:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2228:         }
 2229:     } else {
 2230:         &logthis("put_dom failed - no homeserver and/or domain");
 2231:     }
 2232: }
 2233: 
 2234: # --------------------- newput for items in db file owned by domainconfig user
 2235: sub newput_dom {
 2236:     my ($namespace,$storehash,$udom) = @_;
 2237:     my $result;
 2238:     if (!$udom) {
 2239:         $udom=$env{'user.domain'};
 2240:     }
 2241:     if ($udom) {
 2242:         my $uname = &get_domainconfiguser($udom);
 2243:         $result = &newput($namespace,$storehash,$udom,$uname);
 2244:     }
 2245:     return $result;
 2246: }
 2247: 
 2248: # --------------------- delete for items in db file owned by domainconfig user
 2249: sub del_dom {
 2250:     my ($namespace,$storearr,$udom)=@_;
 2251:     if (ref($storearr) eq 'ARRAY') {
 2252:         if (!$udom) {
 2253:             $udom=$env{'user.domain'};
 2254:         }
 2255:         if ($udom) {
 2256:             my $uname = &get_domainconfiguser($udom); 
 2257:             return &del($namespace,$storearr,$udom,$uname);
 2258:         }
 2259:     }
 2260: }
 2261: 
 2262: # ----------------------------------construct domainconfig user for a domain 
 2263: sub get_domainconfiguser {
 2264:     my ($udom) = @_;
 2265:     return $udom.'-domainconfig';
 2266: }
 2267: 
 2268: sub retrieve_inst_usertypes {
 2269:     my ($udom) = @_;
 2270:     my (%returnhash,@order);
 2271:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2272:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2273:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2274:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2275:     } else {
 2276:         if (defined(&domain($udom,'primary'))) {
 2277:             my $uhome=&domain($udom,'primary');
 2278:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2279:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2280:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2281:                 return (\%returnhash,\@order);
 2282:             }
 2283:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2284:             my @pairs=split(/\&/,$hashitems);
 2285:             foreach my $item (@pairs) {
 2286:                 my ($key,$value)=split(/=/,$item,2);
 2287:                 $key = &unescape($key);
 2288:                 next if ($key =~ /^error: 2 /);
 2289:                 $returnhash{$key}=&thaw_unescape($value);
 2290:             }
 2291:             my @esc_order = split(/\&/,$orderitems);
 2292:             foreach my $item (@esc_order) {
 2293:                 push(@order,&unescape($item));
 2294:             }
 2295:         } else {
 2296:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2297:         }
 2298:         return (\%returnhash,\@order);
 2299:     }
 2300: }
 2301: 
 2302: sub is_domainimage {
 2303:     my ($url) = @_;
 2304:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2305:         if (&domain($1) ne '') {
 2306:             return '1';
 2307:         }
 2308:     }
 2309:     return;
 2310: }
 2311: 
 2312: sub inst_directory_query {
 2313:     my ($srch) = @_;
 2314:     my $udom = $srch->{'srchdomain'};
 2315:     my %results;
 2316:     my $homeserver = &domain($udom,'primary');
 2317:     my $outcome;
 2318:     if ($homeserver ne '') {
 2319:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2320:             if ($srch->{'srchby'} eq 'email') {
 2321:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2322:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2323:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2324:                     (($major == 2) && ($minor < 12))) {
 2325:                     return;
 2326:                 }
 2327:             }
 2328:         }
 2329: 	my $queryid=&reply("querysend:instdirsearch:".
 2330: 			   &escape($srch->{'srchby'}).':'.
 2331: 			   &escape($srch->{'srchterm'}).':'.
 2332: 			   &escape($srch->{'srchtype'}),$homeserver);
 2333: 	my $host=&hostname($homeserver);
 2334: 	if ($queryid !~/^\Q$host\E\_/) {
 2335: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2336: 	    return;
 2337: 	}
 2338: 	my $response = &get_query_reply($queryid);
 2339: 	my $maxtries = 5;
 2340: 	my $tries = 1;
 2341: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2342: 	    $response = &get_query_reply($queryid);
 2343: 	    $tries ++;
 2344: 	}
 2345: 
 2346:         if (!&error($response) && $response ne 'refused') {
 2347:             if ($response eq 'unavailable') {
 2348:                 $outcome = $response;
 2349:             } else {
 2350:                 $outcome = 'ok';
 2351:                 my @matches = split(/\n/,$response);
 2352:                 foreach my $match (@matches) {
 2353:                     my ($key,$value) = split(/=/,$match);
 2354:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2355:                 }
 2356:             }
 2357:         }
 2358:     }
 2359:     return ($outcome,%results);
 2360: }
 2361: 
 2362: sub usersearch {
 2363:     my ($srch) = @_;
 2364:     my $dom = $srch->{'srchdomain'};
 2365:     my %results;
 2366:     my %libserv = &all_library();
 2367:     my $query = 'usersearch';
 2368:     foreach my $tryserver (keys(%libserv)) {
 2369:         if (&host_domain($tryserver) eq $dom) {
 2370:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2371:                 if ($srch->{'srchby'} eq 'email') {
 2372:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2373:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2374:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2375:                              (($major == 2) && ($minor < 12)));
 2376:                 }
 2377:             }
 2378:             my $host=&hostname($tryserver);
 2379:             my $queryid=
 2380:                 &reply("querysend:".&escape($query).':'.
 2381:                        &escape($srch->{'srchby'}).':'.
 2382:                        &escape($srch->{'srchtype'}).':'.
 2383:                        &escape($srch->{'srchterm'}),$tryserver);
 2384:             if ($queryid !~/^\Q$host\E\_/) {
 2385:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2386:                 next;
 2387:             }
 2388:             my $reply = &get_query_reply($queryid);
 2389:             my $maxtries = 1;
 2390:             my $tries = 1;
 2391:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2392:                 $reply = &get_query_reply($queryid);
 2393:                 $tries ++;
 2394:             }
 2395:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2396:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2397:             } else {
 2398:                 my @matches;
 2399:                 if ($reply =~ /\n/) {
 2400:                     @matches = split(/\n/,$reply);
 2401:                 } else {
 2402:                     @matches = split(/\&/,$reply);
 2403:                 }
 2404:                 foreach my $match (@matches) {
 2405:                     my ($uname,$udom,%userhash);
 2406:                     foreach my $entry (split(/:/,$match)) {
 2407:                         my ($key,$value) =
 2408:                             map {&unescape($_);} split(/=/,$entry);
 2409:                         $userhash{$key} = $value;
 2410:                         if ($key eq 'username') {
 2411:                             $uname = $value;
 2412:                         } elsif ($key eq 'domain') {
 2413:                             $udom = $value;
 2414:                         }
 2415:                     }
 2416:                     $results{$uname.':'.$udom} = \%userhash;
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     return %results;
 2422: }
 2423: 
 2424: sub get_instuser {
 2425:     my ($udom,$uname,$id) = @_;
 2426:     my $homeserver = &domain($udom,'primary');
 2427:     my ($outcome,%results);
 2428:     if ($homeserver ne '') {
 2429:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2430:                            &escape($id).':'.&escape($udom),$homeserver);
 2431:         my $host=&hostname($homeserver);
 2432:         if ($queryid !~/^\Q$host\E\_/) {
 2433:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2434:             return;
 2435:         }
 2436:         my $response = &get_query_reply($queryid);
 2437:         my $maxtries = 5;
 2438:         my $tries = 1;
 2439:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2440:             $response = &get_query_reply($queryid);
 2441:             $tries ++;
 2442:         }
 2443:         if (!&error($response) && $response ne 'refused') {
 2444:             if ($response eq 'unavailable') {
 2445:                 $outcome = $response;
 2446:             } else {
 2447:                 $outcome = 'ok';
 2448:                 my @matches = split(/\n/,$response);
 2449:                 foreach my $match (@matches) {
 2450:                     my ($key,$value) = split(/=/,$match);
 2451:                     $results{&unescape($key)} = &thaw_unescape($value);
 2452:                 }
 2453:             }
 2454:         }
 2455:     }
 2456:     my %userinfo;
 2457:     if (ref($results{$uname}) eq 'HASH') {
 2458:         %userinfo = %{$results{$uname}};
 2459:     } 
 2460:     return ($outcome,%userinfo);
 2461: }
 2462: 
 2463: sub get_multiple_instusers {
 2464:     my ($udom,$users,$caller) = @_;
 2465:     my ($outcome,$results);
 2466:     if (ref($users) eq 'HASH') {
 2467:         my $count = keys(%{$users}); 
 2468:         my $requested = &freeze_escape($users);
 2469:         my $homeserver = &domain($udom,'primary');
 2470:         if ($homeserver ne '') {
 2471:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2472:             my $host=&hostname($homeserver);
 2473:             if ($queryid !~/^\Q$host\E\_/) {
 2474:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2475:                          ' for host: '.$homeserver.'in domain '.$udom);
 2476:                 return ($outcome,$results);
 2477:             }
 2478:             my $response = &get_query_reply($queryid);
 2479:             my $maxtries = 5;
 2480:             if ($count > 100) {
 2481:                 $maxtries = 1+int($count/20);
 2482:             }
 2483:             my $tries = 1;
 2484:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2485:                 $response = &get_query_reply($queryid);
 2486:                 $tries ++;
 2487:             }
 2488:             if ($response eq '') {
 2489:                 $results = {};
 2490:                 foreach my $key (keys(%{$users})) {
 2491:                     my ($uname,$id);
 2492:                     if ($caller eq 'id') {
 2493:                         $id = $key;
 2494:                     } else {
 2495:                         $uname = $key;
 2496:                     }
 2497:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2498:                     $outcome = $resp;
 2499:                     if ($resp eq 'ok') {
 2500:                         %{$results} = (%{$results}, %info);
 2501:                     } else {
 2502:                         last;
 2503:                     }
 2504:                 }
 2505:             } elsif(!&error($response) && ($response ne 'refused')) {
 2506:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2507:                     $outcome = $response;
 2508:                 } else {
 2509:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2510:                     if ($outcome eq 'ok') {
 2511:                         $results = &thaw_unescape($userdata); 
 2512:                     }
 2513:                 }
 2514:             }
 2515:         }
 2516:     }
 2517:     return ($outcome,$results);
 2518: }
 2519: 
 2520: sub inst_rulecheck {
 2521:     my ($udom,$uname,$id,$item,$rules) = @_;
 2522:     my %returnhash;
 2523:     if ($udom ne '') {
 2524:         if (ref($rules) eq 'ARRAY') {
 2525:             @{$rules} = map {&escape($_);} (@{$rules});
 2526:             my $rulestr = join(':',@{$rules});
 2527:             my $homeserver=&domain($udom,'primary');
 2528:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2529:                 my $response;
 2530:                 if ($item eq 'username') {                
 2531:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2532:                                               ':'.&escape($uname).':'.$rulestr,
 2533:                                               $homeserver));
 2534:                 } elsif ($item eq 'id') {
 2535:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2536:                                               ':'.&escape($id).':'.$rulestr,
 2537:                                               $homeserver));
 2538:                 } elsif ($item eq 'selfcreate') {
 2539:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2540:                                                &escape($udom).':'.&escape($uname).
 2541:                                               ':'.$rulestr,$homeserver));
 2542:                 }
 2543:                 if ($response ne 'refused') {
 2544:                     my @pairs=split(/\&/,$response);
 2545:                     foreach my $item (@pairs) {
 2546:                         my ($key,$value)=split(/=/,$item,2);
 2547:                         $key = &unescape($key);
 2548:                         next if ($key =~ /^error: 2 /);
 2549:                         $returnhash{$key}=&thaw_unescape($value);
 2550:                     }
 2551:                 }
 2552:             }
 2553:         }
 2554:     }
 2555:     return %returnhash;
 2556: }
 2557: 
 2558: sub inst_userrules {
 2559:     my ($udom,$check) = @_;
 2560:     my (%ruleshash,@ruleorder);
 2561:     if ($udom ne '') {
 2562:         my $homeserver=&domain($udom,'primary');
 2563:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2564:             my $response;
 2565:             if ($check eq 'id') {
 2566:                 $response=&reply('instidrules:'.&escape($udom),
 2567:                                  $homeserver);
 2568:             } elsif ($check eq 'email') {
 2569:                 $response=&reply('instemailrules:'.&escape($udom),
 2570:                                  $homeserver);
 2571:             } else {
 2572:                 $response=&reply('instuserrules:'.&escape($udom),
 2573:                                  $homeserver);
 2574:             }
 2575:             if (($response ne 'refused') && ($response ne 'error') && 
 2576:                 ($response ne 'unknown_cmd') && 
 2577:                 ($response ne 'no_such_host')) {
 2578:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2579:                 my @pairs=split(/\&/,$hashitems);
 2580:                 foreach my $item (@pairs) {
 2581:                     my ($key,$value)=split(/=/,$item,2);
 2582:                     $key = &unescape($key);
 2583:                     next if ($key =~ /^error: 2 /);
 2584:                     $ruleshash{$key}=&thaw_unescape($value);
 2585:                 }
 2586:                 my @esc_order = split(/\&/,$orderitems);
 2587:                 foreach my $item (@esc_order) {
 2588:                     push(@ruleorder,&unescape($item));
 2589:                 }
 2590:             }
 2591:         }
 2592:     }
 2593:     return (\%ruleshash,\@ruleorder);
 2594: }
 2595: 
 2596: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2597: 
 2598: sub get_domain_defaults {
 2599:     my ($domain,$ignore_cache) = @_;
 2600:     return if (($domain eq '') || ($domain eq 'public'));
 2601:     my $cachetime = 60*60*24;
 2602:     unless ($ignore_cache) {
 2603:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2604:         if (defined($cached)) {
 2605:             if (ref($result) eq 'HASH') {
 2606:                 return %{$result};
 2607:             }
 2608:         }
 2609:     }
 2610:     my %domdefaults;
 2611:     my %domconfig =
 2612:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2613:                                   'requestcourses','inststatus',
 2614:                                   'coursedefaults','usersessions',
 2615:                                   'requestauthor','selfenrollment',
 2616:                                   'coursecategories','ssl','autoenroll',
 2617:                                   'trust','helpsettings','wafproxy'],$domain);
 2618:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2619:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2620:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2621:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2622:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2623:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2624:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2625:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2626:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2627:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2628:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2629:     } else {
 2630:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2631:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2632:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2633:     }
 2634:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2635:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2636:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2637:         } else {
 2638:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2639:         }
 2640:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2641:         foreach my $item (@usertools) {
 2642:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2643:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2644:             }
 2645:         }
 2646:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2647:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2648:         }
 2649:     }
 2650:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2651:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2652:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2653:         }
 2654:     }
 2655:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2656:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2657:     }
 2658:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2659:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2660:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2661:         }
 2662:     }
 2663:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2664:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2665:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2666:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2667:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2668:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2669:         }
 2670:         foreach my $type (@coursetypes) {
 2671:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2672:                 unless ($type eq 'community') {
 2673:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2674:                 }
 2675:             }
 2676:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2677:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2678:             }
 2679:             if ($domdefaults{'postsubmit'} eq 'on') {
 2680:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2681:                     $domdefaults{$type.'postsubtimeout'} = 
 2682:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2683:                 }
 2684:             }
 2685:         }
 2686:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2687:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2688:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2689:                 if (@clonecodes) {
 2690:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2691:                 }
 2692:             }
 2693:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2694:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2695:         }
 2696:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2697:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2698:         } 
 2699:     }
 2700:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2701:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2702:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2703:         }
 2704:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2705:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2706:         }
 2707:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2708:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2709:         }
 2710:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2711:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2712:         }
 2713:     }
 2714:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2715:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2716:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2717:                             'approval','limit');
 2718:             foreach my $type (@coursetypes) {
 2719:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2720:                     my @mgrdc = ();
 2721:                     foreach my $item (@settings) {
 2722:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2723:                             push(@mgrdc,$item);
 2724:                         }
 2725:                     }
 2726:                     if (@mgrdc) {
 2727:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2728:                     }
 2729:                 }
 2730:             }
 2731:         }
 2732:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2733:             foreach my $type (@coursetypes) {
 2734:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2735:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2736:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2737:                     }
 2738:                 }
 2739:             }
 2740:         }
 2741:     }
 2742:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2743:         $domdefaults{'catauth'} = 'std';
 2744:         $domdefaults{'catunauth'} = 'std';
 2745:         if ($domconfig{'coursecategories'}{'auth'}) {
 2746:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2747:         }
 2748:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2749:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2750:         }
 2751:     }
 2752:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2753:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2754:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2755:         }
 2756:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2757:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2758:         }
 2759:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2760:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2761:         }
 2762:     }
 2763:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2764:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2765:         foreach my $prefix (@prefixes) {
 2766:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2767:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2768:             }
 2769:         }
 2770:     }
 2771:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2772:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2773:     }
 2774:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2775:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2776:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2777:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2778:         }
 2779:     }
 2780:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2781:         foreach my $item ('ipheader','trusted','vpnint','vpnext') {
 2782:             if ($domconfig{'wafproxy'}{$item}) {
 2783:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2784:             }
 2785:         }
 2786:     } 
 2787:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2788:     return %domdefaults;
 2789: }
 2790: 
 2791: sub get_dom_cats {
 2792:     my ($dom) = @_;
 2793:     return unless (&domain($dom));
 2794:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2795:     unless (defined($cached)) {
 2796:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2797:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2798:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2799:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2800:             } else {
 2801:                 $cats = {};
 2802:             }
 2803:         } else {
 2804:             $cats = {};
 2805:         }
 2806:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2807:     }
 2808:     return $cats;
 2809: }
 2810: 
 2811: sub get_dom_instcats {
 2812:     my ($dom) = @_;
 2813:     return unless (&domain($dom));
 2814:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2815:     unless (defined($cached)) {
 2816:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2817:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2818:         if ($totcodes > 0) {
 2819:             my $caller = 'global';
 2820:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2821:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2822:                 $instcats = {
 2823:                                 codes => \%codes,
 2824:                                 codetitles => \@codetitles,
 2825:                                 cat_titles => \%cat_titles,
 2826:                                 cat_order => \%cat_order,
 2827:                             };
 2828:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2829:             }
 2830:         }
 2831:     }
 2832:     return $instcats;
 2833: }
 2834: 
 2835: sub retrieve_instcodes {
 2836:     my ($coursecodes,$dom) = @_;
 2837:     my $totcodes;
 2838:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2839:     foreach my $course (keys(%courses)) {
 2840:         if (ref($courses{$course}) eq 'HASH') {
 2841:             if ($courses{$course}{'inst_code'} ne '') {
 2842:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2843:                 $totcodes ++;
 2844:             }
 2845:         }
 2846:     }
 2847:     return $totcodes;
 2848: }
 2849: 
 2850: sub course_portal_url {
 2851:     my ($cnum,$cdom) = @_;
 2852:     my $chome = &homeserver($cnum,$cdom);
 2853:     my $hostname = &hostname($chome);
 2854:     my $protocol = $protocol{$chome};
 2855:     $protocol = 'http' if ($protocol ne 'https');
 2856:     my %domdefaults = &get_domain_defaults($cdom);
 2857:     my $firsturl;
 2858:     if ($domdefaults{'portal_def'}) {
 2859:         $firsturl = $domdefaults{'portal_def'};
 2860:     } else {
 2861:         $firsturl = $protocol.'://'.$hostname;
 2862:     }
 2863:     return $firsturl;
 2864: }
 2865: 
 2866: # --------------------------------------------- Get domain config for passwords
 2867: 
 2868: sub get_passwdconf {
 2869:     my ($dom) = @_;
 2870:     my (%passwdconf,$gotconf,$lookup);
 2871:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2872:     if (defined($cached)) {
 2873:         if (ref($result) eq 'HASH') {
 2874:             %passwdconf = %{$result};
 2875:             $gotconf = 1;
 2876:         }
 2877:     }
 2878:     unless ($gotconf) {
 2879:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2880:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2881:             %passwdconf = %{$domconfig{'passwords'}};
 2882:         }
 2883:         my $cachetime = 24*60*60;
 2884:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2885:     }
 2886:     return %passwdconf;
 2887: }
 2888: 
 2889: # --------------------------------------------------- Assign a key to a student
 2890: 
 2891: sub assign_access_key {
 2892: #
 2893: # a valid key looks like uname:udom#comments
 2894: # comments are being appended
 2895: #
 2896:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2897:     $kdom=
 2898:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2899:     $knum=
 2900:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2901:     $cdom=
 2902:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2903:     $cnum=
 2904:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2905:     $udom=$env{'user.name'} unless (defined($udom));
 2906:     $uname=$env{'user.domain'} unless (defined($uname));
 2907:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2908:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2909:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2910:                                                   # assigned to this person
 2911:                                                   # - this should not happen,
 2912:                                                   # unless something went wrong
 2913:                                                   # the first time around
 2914: # ready to assign
 2915:         $logentry=$1.'; '.$logentry;
 2916:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2917:                                                  $kdom,$knum) eq 'ok') {
 2918: # key now belongs to user
 2919: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2920:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2921:                 &appenv({'environment.'.$envkey => $ckey});
 2922:                 return 'ok';
 2923:             } else {
 2924:                 return 
 2925:   'error: Count not permanently assign key, will need to be re-entered later.';
 2926: 	    }
 2927:         } else {
 2928:             return 'error: Could not assign key, try again later.';
 2929:         }
 2930:     } elsif (!$existing{$ckey}) {
 2931: # the key does not exist
 2932: 	return 'error: The key does not exist';
 2933:     } else {
 2934: # the key is somebody else's
 2935: 	return 'error: The key is already in use';
 2936:     }
 2937: }
 2938: 
 2939: # ------------------------------------------ put an additional comment on a key
 2940: 
 2941: sub comment_access_key {
 2942: #
 2943: # a valid key looks like uname:udom#comments
 2944: # comments are being appended
 2945: #
 2946:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2947:     $cdom=
 2948:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2949:     $cnum=
 2950:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2951:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2952:     if ($existing{$ckey}) {
 2953:         $existing{$ckey}.='; '.$logentry;
 2954: # ready to assign
 2955:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2956:                                                  $cdom,$cnum) eq 'ok') {
 2957: 	    return 'ok';
 2958:         } else {
 2959: 	    return 'error: Count not store comment.';
 2960:         }
 2961:     } else {
 2962: # the key does not exist
 2963: 	return 'error: The key does not exist';
 2964:     }
 2965: }
 2966: 
 2967: # ------------------------------------------------------ Generate a set of keys
 2968: 
 2969: sub generate_access_keys {
 2970:     my ($number,$cdom,$cnum,$logentry)=@_;
 2971:     $cdom=
 2972:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2973:     $cnum=
 2974:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2975:     unless (&allowed('mky',$cdom)) { return 0; }
 2976:     unless (($cdom) && ($cnum)) { return 0; }
 2977:     if ($number>10000) { return 0; }
 2978:     sleep(2); # make sure don't get same seed twice
 2979:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2980:     my $total=0;
 2981:     for (my $i=1;$i<=$number;$i++) {
 2982:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2983:                   sprintf("%lx",int(100000*rand)).'-'.
 2984:                   sprintf("%lx",int(100000*rand));
 2985:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2986:        $newkey=~s/0/h/g; # and also 0 and O
 2987:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2988:        if ($existing{$newkey}) {
 2989:            $i--;
 2990:        } else {
 2991: 	  if (&put('accesskeys',
 2992:               { $newkey => '# generated '.localtime().
 2993:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2994:                            '; '.$logentry },
 2995: 		   $cdom,$cnum) eq 'ok') {
 2996:               $total++;
 2997: 	  }
 2998:        }
 2999:     }
 3000:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3001:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3002:     return $total;
 3003: }
 3004: 
 3005: # ------------------------------------------------------- Validate an accesskey
 3006: 
 3007: sub validate_access_key {
 3008:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3009:     $cdom=
 3010:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3011:     $cnum=
 3012:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3013:     $udom=$env{'user.domain'} unless (defined($udom));
 3014:     $uname=$env{'user.name'} unless (defined($uname));
 3015:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3016:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3017: }
 3018: 
 3019: # ------------------------------------- Find the section of student in a course
 3020: sub devalidate_getsection_cache {
 3021:     my ($udom,$unam,$courseid)=@_;
 3022:     my $hashid="$udom:$unam:$courseid";
 3023:     &devalidate_cache_new('getsection',$hashid);
 3024: }
 3025: 
 3026: sub courseid_to_courseurl {
 3027:     my ($courseid) = @_;
 3028:     #already url style courseid
 3029:     return $courseid if ($courseid =~ m{^/});
 3030: 
 3031:     if (exists($env{'course.'.$courseid.'.num'})) {
 3032: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3033: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3034: 	return "/$cdom/$cnum";
 3035:     }
 3036: 
 3037:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3038:     if (exists($courseinfo{'num'})) {
 3039: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3040:     }
 3041: 
 3042:     return undef;
 3043: }
 3044: 
 3045: sub getsection {
 3046:     my ($udom,$unam,$courseid)=@_;
 3047:     my $cachetime=1800;
 3048: 
 3049:     my $hashid="$udom:$unam:$courseid";
 3050:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3051:     if (defined($cached)) { return $result; }
 3052: 
 3053:     my %Pending; 
 3054:     my %Expired;
 3055:     #
 3056:     # Each role can either have not started yet (pending), be active, 
 3057:     #    or have expired.
 3058:     #
 3059:     # If there is an active role, we are done.
 3060:     #
 3061:     # If there is more than one role which has not started yet, 
 3062:     #     choose the one which will start sooner
 3063:     # If there is one role which has not started yet, return it.
 3064:     #
 3065:     # If there is more than one expired role, choose the one which ended last.
 3066:     # If there is a role which has expired, return it.
 3067:     #
 3068:     $courseid = &courseid_to_courseurl($courseid);
 3069:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3070:     foreach my $key (keys(%roleshash)) {
 3071:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3072:         my $section=$1;
 3073:         if ($key eq $courseid.'_st') { $section=''; }
 3074:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3075:         my $now=time;
 3076:         if (defined($end) && $end && ($now > $end)) {
 3077:             $Expired{$end}=$section;
 3078:             next;
 3079:         }
 3080:         if (defined($start) && $start && ($now < $start)) {
 3081:             $Pending{$start}=$section;
 3082:             next;
 3083:         }
 3084:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3085:     }
 3086:     #
 3087:     # Presumedly there will be few matching roles from the above
 3088:     # loop and the sorting time will be negligible.
 3089:     if (scalar(keys(%Pending))) {
 3090:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3091:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3092:     } 
 3093:     if (scalar(keys(%Expired))) {
 3094:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3095:         my $time = pop(@sorted);
 3096:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3097:     }
 3098:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3099: }
 3100: 
 3101: sub save_cache {
 3102:     &purge_remembered();
 3103:     #&Apache::loncommon::validate_page();
 3104:     undef(%env);
 3105:     undef($env_loaded);
 3106: }
 3107: 
 3108: my $to_remember=-1;
 3109: my %remembered;
 3110: my %accessed;
 3111: my $kicks=0;
 3112: my $hits=0;
 3113: sub make_key {
 3114:     my ($name,$id) = @_;
 3115:     if (length($id) > 65 
 3116: 	&& length(&escape($id)) > 200) {
 3117: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3118:     }
 3119:     return &escape($name.':'.$id);
 3120: }
 3121: 
 3122: sub devalidate_cache_new {
 3123:     my ($name,$id,$debug) = @_;
 3124:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3125:     my $remembered_id=$name.':'.$id;
 3126:     $id=&make_key($name,$id);
 3127:     $memcache->delete($id);
 3128:     delete($remembered{$remembered_id});
 3129:     delete($accessed{$remembered_id});
 3130: }
 3131: 
 3132: sub is_cached_new {
 3133:     my ($name,$id,$debug) = @_;
 3134:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3135:     if (exists($remembered{$remembered_id})) {
 3136: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3137: 	$accessed{$remembered_id}=[&gettimeofday()];
 3138: 	$hits++;
 3139: 	return ($remembered{$remembered_id},1);
 3140:     }
 3141:     $id=&make_key($name,$id);
 3142:     my $value = $memcache->get($id);
 3143:     if (!(defined($value))) {
 3144: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3145: 	return (undef,undef);
 3146:     }
 3147:     if ($value eq '__undef__') {
 3148: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3149: 	$value=undef;
 3150:     }
 3151:     &make_room($remembered_id,$value,$debug);
 3152:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3153:     return ($value,1);
 3154: }
 3155: 
 3156: sub do_cache_new {
 3157:     my ($name,$id,$value,$time,$debug) = @_;
 3158:     my $remembered_id=$name.':'.$id;
 3159:     $id=&make_key($name,$id);
 3160:     my $setvalue=$value;
 3161:     if (!defined($setvalue)) {
 3162: 	$setvalue='__undef__';
 3163:     }
 3164:     if (!defined($time) ) {
 3165: 	$time=600;
 3166:     }
 3167:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3168:     my $result = $memcache->set($id,$setvalue,$time);
 3169:     if (! $result) {
 3170: 	&logthis("caching of id -> $id  failed");
 3171: 	$memcache->disconnect_all();
 3172:     }
 3173:     # need to make a copy of $value
 3174:     &make_room($remembered_id,$value,$debug);
 3175:     return $value;
 3176: }
 3177: 
 3178: sub make_room {
 3179:     my ($remembered_id,$value,$debug)=@_;
 3180: 
 3181:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3182:                                     : $value;
 3183:     if ($to_remember<0) { return; }
 3184:     $accessed{$remembered_id}=[&gettimeofday()];
 3185:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3186:     my $to_kick;
 3187:     my $max_time=0;
 3188:     foreach my $other (keys(%accessed)) {
 3189: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3190: 	    $to_kick=$other;
 3191: 	    $max_time=&tv_interval($accessed{$other});
 3192: 	}
 3193:     }
 3194:     delete($remembered{$to_kick});
 3195:     delete($accessed{$to_kick});
 3196:     $kicks++;
 3197:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3198:     return;
 3199: }
 3200: 
 3201: sub purge_remembered {
 3202:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3203:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3204:     undef(%remembered);
 3205:     undef(%accessed);
 3206: }
 3207: # ------------------------------------- Read an entry from a user's environment
 3208: 
 3209: sub userenvironment {
 3210:     my ($udom,$unam,@what)=@_;
 3211:     my $items;
 3212:     foreach my $item (@what) {
 3213:         $items.=&escape($item).'&';
 3214:     }
 3215:     $items=~s/\&$//;
 3216:     my %returnhash=();
 3217:     my $uhome = &homeserver($unam,$udom);
 3218:     unless ($uhome eq 'no_host') {
 3219:         my @answer=split(/\&/, 
 3220:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3221:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3222:             return %returnhash;
 3223:         }
 3224:         my $i;
 3225:         for ($i=0;$i<=$#what;$i++) {
 3226: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3227:         }
 3228:     }
 3229:     return %returnhash;
 3230: }
 3231: 
 3232: # ---------------------------------------------------------- Get a studentphoto
 3233: sub studentphoto {
 3234:     my ($udom,$unam,$ext) = @_;
 3235:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3236:     if (defined($env{'request.course.id'})) {
 3237:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3238:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3239:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3240:             } else {
 3241:                 my ($result,$perm_reqd)=
 3242: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3243:                 if ($result eq 'ok') {
 3244:                     if (!($perm_reqd eq 'yes')) {
 3245:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3246:                     }
 3247:                 }
 3248:             }
 3249:         }
 3250:     } else {
 3251:         my ($result,$perm_reqd) = 
 3252: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3253:         if ($result eq 'ok') {
 3254:             if (!($perm_reqd eq 'yes')) {
 3255:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3256:             }
 3257:         }
 3258:     }
 3259:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3260: }
 3261: 
 3262: sub retrievestudentphoto {
 3263:     my ($udom,$unam,$ext,$type) = @_;
 3264:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3265:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3266:     if ($ret eq 'ok') {
 3267:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3268:         if ($type eq 'thumbnail') {
 3269:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3270:         }
 3271:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3272:         return $tokenurl;
 3273:     } else {
 3274:         if ($type eq 'thumbnail') {
 3275:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3276:         } else { 
 3277:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3278:         }
 3279:     }
 3280: }
 3281: 
 3282: # -------------------------------------------------------------------- New chat
 3283: 
 3284: sub chatsend {
 3285:     my ($newentry,$anon,$group)=@_;
 3286:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3287:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3288:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3289:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3290: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3291: 		   &escape($newentry)).':'.$group,$chome);
 3292: }
 3293: 
 3294: # ------------------------------------------ Find current version of a resource
 3295: 
 3296: sub getversion {
 3297:     my $fname=&clutter(shift);
 3298:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3299:     return &currentversion(&filelocation('',$fname));
 3300: }
 3301: 
 3302: sub currentversion {
 3303:     my $fname=shift;
 3304:     my $author=$fname;
 3305:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3306:     my ($udom,$uname)=split(/\//,$author);
 3307:     my $home=&homeserver($uname,$udom);
 3308:     if ($home eq 'no_host') { 
 3309:         return -1; 
 3310:     }
 3311:     my $answer=&reply("currentversion:$fname",$home);
 3312:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3313: 	return -1;
 3314:     }
 3315:     return $answer;
 3316: }
 3317: 
 3318: #
 3319: # Return special version number of resource if set by override, empty otherwise
 3320: #
 3321: sub usedversion {
 3322:     my $fname=shift;
 3323:     unless ($fname) { $fname=$env{'request.uri'}; }
 3324:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3325:     if ($urlversion) { return $urlversion; }
 3326:     return '';
 3327: }
 3328: 
 3329: # ----------------------------- Subscribe to a resource, return URL if possible
 3330: 
 3331: sub subscribe {
 3332:     my $fname=shift;
 3333:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3334:     $fname=~s/[\n\r]//g;
 3335:     my $author=$fname;
 3336:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3337:     my ($udom,$uname)=split(/\//,$author);
 3338:     my $home=homeserver($uname,$udom);
 3339:     if ($home eq 'no_host') {
 3340:         return 'not_found';
 3341:     }
 3342:     my $answer=reply("sub:$fname",$home);
 3343:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3344: 	$answer.=' by '.$home;
 3345:     }
 3346:     return $answer;
 3347: }
 3348:     
 3349: # -------------------------------------------------------------- Replicate file
 3350: 
 3351: sub repcopy {
 3352:     my $filename=shift;
 3353:     $filename=~s/\/+/\//g;
 3354:     my $londocroot = $perlvar{'lonDocRoot'};
 3355:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3356:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3357:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3358: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3359: 	return &repcopy_userfile($filename);
 3360:     }
 3361:     $filename=~s/[\n\r]//g;
 3362:     my $transname="$filename.in.transfer";
 3363: # FIXME: this should flock
 3364:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3365:     my $remoteurl=subscribe($filename);
 3366:     if ($remoteurl =~ /^con_lost by/) {
 3367: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3368:            return 'unavailable';
 3369:     } elsif ($remoteurl eq 'not_found') {
 3370: 	   #&logthis("Subscribe returned not_found: $filename");
 3371: 	   return 'not_found';
 3372:     } elsif ($remoteurl =~ /^rejected by/) {
 3373: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3374:            return 'forbidden';
 3375:     } elsif ($remoteurl eq 'directory') {
 3376:            return 'ok';
 3377:     } else {
 3378:         my $author=$filename;
 3379:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3380:         my ($udom,$uname)=split(/\//,$author);
 3381:         my $home=homeserver($uname,$udom);
 3382:         unless ($home eq $perlvar{'lonHostID'}) {
 3383:            my @parts=split(/\//,$filename);
 3384:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3385:            if ($path ne "$londocroot/res") {
 3386:                &logthis("Malconfiguration for replication: $filename");
 3387: 	       return 'bad_request';
 3388:            }
 3389:            my $count;
 3390:            for ($count=5;$count<$#parts;$count++) {
 3391:                $path.="/$parts[$count]";
 3392:                if ((-e $path)!=1) {
 3393: 		   mkdir($path,0777);
 3394:                }
 3395:            }
 3396:            my $request=new HTTP::Request('GET',"$remoteurl");
 3397:            my $response;
 3398:            if ($remoteurl =~ m{/raw/}) {
 3399:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3400:            } else {
 3401:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3402:            }
 3403:            if ($response->is_error()) {
 3404: 	       unlink($transname);
 3405:                my $message=$response->status_line;
 3406:                &logthis("<font color=\"blue\">WARNING:"
 3407:                        ." LWP get: $message: $filename</font>");
 3408:                return 'unavailable';
 3409:            } else {
 3410: 	       if ($remoteurl!~/\.meta$/) {
 3411:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3412:                   my $mresponse;
 3413:                   if ($remoteurl =~ m{/raw/}) {
 3414:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3415:                   } else {
 3416:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3417:                   }
 3418:                   if ($mresponse->is_error()) {
 3419: 		      unlink($filename.'.meta');
 3420:                       &logthis(
 3421:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3422:                   }
 3423: 	       }
 3424:                rename($transname,$filename);
 3425:                return 'ok';
 3426:            }
 3427:        }
 3428:     }
 3429: }
 3430: 
 3431: # ------------------------------------------------- Unsubscribe from a resource
 3432: 
 3433: sub unsubscribe {
 3434:     my ($fname) = @_;
 3435:     my $answer;
 3436:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3437:     $fname=~s/[\n\r]//g;
 3438:     my $author=$fname;
 3439:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3440:     my ($udom,$uname)=split(/\//,$author);
 3441:     my $home=homeserver($uname,$udom);
 3442:     if ($home eq 'no_host') {
 3443:         $answer = 'no_host';
 3444:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3445:         $answer = 'home';
 3446:     } else {
 3447:         my $defdom = $perlvar{'lonDefDomain'};
 3448:         if (&will_trust('content',$defdom,$udom)) {
 3449:             $answer = reply("unsub:$fname",$home);
 3450:         } else {
 3451:             $answer = 'untrusted';
 3452:         }
 3453:     }
 3454:     return $answer;
 3455: }
 3456: 
 3457: # ------------------------------------------------ Get server side include body
 3458: sub ssi_body {
 3459:     my ($filelink,%form)=@_;
 3460:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3461:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3462:     }
 3463:     my $output='';
 3464:     my $response;
 3465:     if ($filelink=~/^https?\:/) {
 3466:        ($output,$response)=&externalssi($filelink);
 3467:     } else {
 3468:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3469:        $filelink .= 'inhibitmenu=yes';
 3470:        ($output,$response)=&ssi($filelink,%form);
 3471:     }
 3472:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3473:     $output=~s/^.*?\<body[^\>]*\>//si;
 3474:     $output=~s/\<\/body\s*\>.*?$//si;
 3475:     if (wantarray) {
 3476:         return ($output, $response);
 3477:     } else {
 3478:         return $output;
 3479:     }
 3480: }
 3481: 
 3482: # --------------------------------------------------------- Server Side Include
 3483: 
 3484: sub absolute_url {
 3485:     my ($host_name) = @_;
 3486:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3487:     if ($host_name eq '') {
 3488: 	$host_name = $ENV{'SERVER_NAME'};
 3489:     }
 3490:     return $protocol.$host_name;
 3491: }
 3492: 
 3493: #
 3494: #   Server side include.
 3495: # Parameters:
 3496: #  fn     Possibly encrypted resource name/id.
 3497: #  form   Hash that describes how the rendering should be done
 3498: #         and other things.
 3499: # Returns:
 3500: #   Scalar context: The content of the response.
 3501: #   Array context:  2 element list of the content and the full response object.
 3502: #     
 3503: sub ssi {
 3504: 
 3505:     my ($fn,%form)=@_;
 3506:     my $request;
 3507: 
 3508:     $form{'no_update_last_known'}=1;
 3509:     &Apache::lonenc::check_encrypt(\$fn);
 3510:     if (%form) {
 3511:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3512:       $request->content(join('&',map { 
 3513:             my $name = escape($_);
 3514:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3515:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3516:             : &escape($form{$_}) );    
 3517:         } keys(%form)));
 3518:     } else {
 3519:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3520:     }
 3521: 
 3522:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3523:     my $lonhost = $perlvar{'lonHostID'};
 3524:     my $islocal;
 3525:     if (($env{'request.course.id'}) &&
 3526:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3527:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3528:         ($form{'grade_symb'} ne '') &&
 3529:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3530:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3531:         $islocal = 1;
 3532:     }
 3533:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3534:                                                 '','','',$islocal);
 3535: 
 3536:     if (wantarray) {
 3537: 	return ($response->content, $response);
 3538:     } else {
 3539: 	return $response->content;
 3540:     }
 3541: }
 3542: 
 3543: sub externalssi {
 3544:     my ($url)=@_;
 3545:     my $request=new HTTP::Request('GET',$url);
 3546:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3547:     if (wantarray) {
 3548:         return ($response->content, $response);
 3549:     } else {
 3550:         return $response->content;
 3551:     }
 3552: }
 3553: 
 3554: 
 3555: # If the local copy of a replicated resource is outdated, trigger a  
 3556: # connection from the homeserver to flush the delayed queue. If no update 
 3557: # happens, remove local copies of outdated resource (and corresponding
 3558: # metadata file).
 3559: 
 3560: sub remove_stale_resfile {
 3561:     my ($url) = @_;
 3562:     my $removed;
 3563:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3564:         my $audom = $1;
 3565:         my $auname = $2;
 3566:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3567:             my $homeserver = &homeserver($auname,$audom);
 3568:             unless (($homeserver eq 'no_host') ||
 3569:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3570:                 my $fname = &filelocation('',$url);
 3571:                 if (-e $fname) {
 3572:                     my $hostname = &hostname($homeserver);
 3573:                     if ($hostname) {
 3574:                         my $protocol = $protocol{$homeserver};
 3575:                         $protocol = 'http' if ($protocol ne 'https');
 3576:                         my $uri = &declutter($url);
 3577:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3578:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3579:                         if ($response->is_success()) {
 3580:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3581:                             my $locmodtime = (stat($fname))[9];
 3582:                             if ($locmodtime < $remmodtime) {
 3583:                                 my $stale;
 3584:                                 my $answer = &reply('pong',$homeserver);
 3585:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3586:                                     sleep(0.2);
 3587:                                     $locmodtime = (stat($fname))[9];
 3588:                                     if ($locmodtime < $remmodtime) {
 3589:                                         my $posstransfer = $fname.'.in.transfer';
 3590:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3591:                                             $removed = 1;
 3592:                                         } else {
 3593:                                             $stale = 1;
 3594:                                         }
 3595:                                     } else {
 3596:                                         $removed = 1;
 3597:                                     }
 3598:                                 } else {
 3599:                                     $stale = 1;
 3600:                                 }
 3601:                                 if ($stale) {
 3602:                                     if (unlink($fname)) {
 3603:                                         if ($uri!~/\.meta$/) {
 3604:                                             if (-e $fname.'.meta') {
 3605:                                                 unlink($fname.'.meta');
 3606:                                             }
 3607:                                         }
 3608:                                         my $unsubresult = &unsubscribe($fname);
 3609:                                         unless ($unsubresult eq 'ok') {
 3610:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3611:                                         }
 3612:                                         $removed = 1;
 3613:                                     }
 3614:                                 }
 3615:                             }
 3616:                         }
 3617:                     }
 3618:                 }
 3619:             }
 3620:         }
 3621:     }
 3622:     return $removed;
 3623: }
 3624: 
 3625: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3626: 
 3627: sub allowuploaded {
 3628:     my ($srcurl,$url)=@_;
 3629:     $url=&clutter(&declutter($url));
 3630:     my $dir=$url;
 3631:     $dir=~s/\/[^\/]+$//;
 3632:     my %httpref=();
 3633:     my $httpurl=&hreflocation('',$url);
 3634:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3635:     &Apache::lonnet::appenv(\%httpref);
 3636: }
 3637: 
 3638: #
 3639: # Determine if the current user should be able to edit a particular resource,
 3640: # when viewing in course context.
 3641: # (a) When viewing resource used to determine if "Edit" item is included in 
 3642: #     Functions.
 3643: # (b) When displaying folder contents in course editor, used to determine if
 3644: #     "Edit" link will be displayed alongside resource.
 3645: #
 3646: #  input: six args -- filename (decluttered), course number, course domain,
 3647: #                   url, symb (if registered) and group (if this is a group
 3648: #                   item -- e.g., bulletin board, group page etc.).
 3649: #  output: array of five scalars -- 
 3650: #          $cfile -- url for file editing if editable on current server
 3651: #          $home -- homeserver of resource (i.e., for author if published,
 3652: #                                           or course if uploaded.).
 3653: #          $switchserver --  1 if server switch will be needed.
 3654: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3655: #          $forceview -- 1 if icon/link should be to go to view mode
 3656: #
 3657: 
 3658: sub can_edit_resource {
 3659:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3660:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3661: #
 3662: # For aboutme pages user can only edit his/her own.
 3663: #
 3664:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3665:         my ($sdom,$sname) = ($1,$2);
 3666:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3667:             $home = $env{'user.home'};
 3668:             $cfile = $resurl;
 3669:             if ($env{'form.forceedit'}) {
 3670:                 $forceview = 1;
 3671:             } else {
 3672:                 $forceedit = 1;
 3673:             }
 3674:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3675:         } else {
 3676:             return;
 3677:         }
 3678:     }
 3679: 
 3680:     if ($env{'request.course.id'}) {
 3681:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3682:         if ($group ne '') {
 3683: # if this is a group homepage or group bulletin board, check group privs
 3684:             my $allowed = 0;
 3685:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3686:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3687:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3688:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3689:                     $allowed = 1;
 3690:                 }
 3691:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3692:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3693:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3694:                     $allowed = 1;
 3695:                 }
 3696:             }
 3697:             if ($allowed) {
 3698:                 $home=&homeserver($cnum,$cdom);
 3699:                 if ($env{'form.forceedit'}) {
 3700:                     $forceview = 1;
 3701:                 } else {
 3702:                     $forceedit = 1;
 3703:                 }
 3704:                 $cfile = $resurl;
 3705:             } else {
 3706:                 return;
 3707:             }
 3708:         } else {
 3709:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3710:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3711:                     return;
 3712:                 }
 3713:             } elsif (!$crsedit) {
 3714: #
 3715: # No edit allowed where CC has switched to student role.
 3716: #
 3717:                 return;
 3718:             }
 3719:         }
 3720:     }
 3721: 
 3722:     if ($file ne '') {
 3723:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3724:             if (&is_course_upload($file,$cnum,$cdom)) {
 3725:                 $uploaded = 1;
 3726:                 $incourse = 1;
 3727:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3728:                     $cfile = &hreflocation('',$file);
 3729:                     if ($env{'form.forceedit'}) {
 3730:                         $forceview = 1;
 3731:                     } else {
 3732:                         $forceedit = 1;
 3733:                     }
 3734:                 }
 3735:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3736:                 $incourse = 1;
 3737:                 if ($env{'form.forceedit'}) {
 3738:                     $forceview = 1;
 3739:                 } else {
 3740:                     $forceedit = 1;
 3741:                 }
 3742:                 $cfile = $resurl;
 3743:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3744:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3745:                     $incourse = 1;
 3746:                     if ($env{'form.forceedit'}) {
 3747:                         $forceview = 1;
 3748:                     } else {
 3749:                         $forceedit = 1;
 3750:                     }
 3751:                     $cfile = $resurl;
 3752:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3753:                     $incourse = 1;
 3754:                     $cfile = $resurl.'/smpedit';
 3755:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3756:                     $incourse = 1;
 3757:                     if ($env{'form.forceedit'}) {
 3758:                         $forceview = 1;
 3759:                     } else {
 3760:                         $forceedit = 1;
 3761:                     }
 3762:                     $cfile = $resurl;
 3763:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3764:                     my ($map,$id,$res) = &decode_symb($symb);
 3765:                     if ($map =~ /\.page$/) {
 3766:                         $incourse = 1;
 3767:                         if ($env{'form.forceedit'}) {
 3768:                             $forceview = 1;
 3769:                             $cfile = $map;
 3770:                         } else {
 3771:                             $forceedit = 1;
 3772:                             $cfile =  '/adm/wrapper'.$resurl;
 3773:                         }
 3774:                     }
 3775:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3776:                     $incourse = 1;
 3777:                     if ($env{'form.forceedit'}) {
 3778:                         $forceview = 1;
 3779:                     } else {
 3780:                         $forceedit = 1;
 3781:                     }
 3782:                     $cfile = $resurl;
 3783:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3784:                     $incourse = 1;
 3785:                     if ($env{'form.forceedit'}) {
 3786:                         $forceview = 1;
 3787:                     } else {
 3788:                         $forceedit = 1;
 3789:                     }
 3790:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3791:                 }
 3792:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3793:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3794:                 if (&is_on_map($template)) { 
 3795:                     $incourse = 1;
 3796:                     $forceview = 1;
 3797:                     $cfile = $template;
 3798:                 }
 3799:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3800:                 $incourse = 1;
 3801:                 if ($env{'form.forceedit'}) {
 3802:                     $forceview = 1;
 3803:                 } else {
 3804:                     $forceedit = 1;
 3805:                 }
 3806:                 $cfile = $resurl;
 3807:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3808:                 $incourse = 1;
 3809:                 if ($env{'form.forceedit'}) {
 3810:                     $forceview = 1;
 3811:                 } else {
 3812:                     $forceedit = 1;
 3813:                 }
 3814:                 $cfile = $resurl;
 3815:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3816:                 $incourse = 1;
 3817:                 $forceview = 1;
 3818:                 if ($symb) {
 3819:                     my ($map,$id,$res)=&decode_symb($symb);
 3820:                     $env{'request.symb'} = $symb;
 3821:                     $cfile = &clutter($res);
 3822:                 } else {
 3823:                     $cfile = $env{'form.suppurl'};
 3824:                     my $escfile = &unescape($cfile);
 3825:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3826:                         $cfile = '/adm/wrapper'.$escfile;
 3827:                     } else {
 3828:                         $escfile =~ s{^http://}{};
 3829:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3830:                     }
 3831:                 }
 3832:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3833:                 if ($env{'form.forceedit'}) {
 3834:                     $forceview = 1;
 3835:                 } else {
 3836:                     $forceedit = 1;
 3837:                 }
 3838:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3839:             }
 3840:         }
 3841:         if ($uploaded || $incourse) {
 3842:             $home=&homeserver($cnum,$cdom);
 3843:         } elsif ($file !~ m{/$}) {
 3844:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3845:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3846:             # Check that the user has permission to edit this resource
 3847:             my $setpriv = 1;
 3848:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3849:             if (defined($cfudom)) {
 3850:                 $home=&homeserver($cfuname,$cfudom);
 3851:                 $cfile=$file;
 3852:             }
 3853:         }
 3854:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3855:             (($home ne '') && ($home ne 'no_host'))) {
 3856:             my @ids=&current_machine_ids();
 3857:             unless (grep(/^\Q$home\E$/,@ids)) {
 3858:                 $switchserver=1;
 3859:             }
 3860:         }
 3861:     }
 3862:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3863: }
 3864: 
 3865: sub is_course_upload {
 3866:     my ($file,$cnum,$cdom) = @_;
 3867:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3868:     $uploadpath =~ s{^\/}{};
 3869:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3870:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3871:         return 1;
 3872:     }
 3873:     return;
 3874: }
 3875: 
 3876: sub in_course {
 3877:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3878:     if ($hideprivileged) {
 3879:         my $skipuser;
 3880:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3881:         my @possdoms = ($cdom);  
 3882:         if ($coursehash{'checkforpriv'}) { 
 3883:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3884:         }
 3885:         if (&privileged($uname,$udom,\@possdoms)) {
 3886:             $skipuser = 1;
 3887:             if ($coursehash{'nothideprivileged'}) {
 3888:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3889:                     my $user;
 3890:                     if ($item =~ /:/) {
 3891:                         $user = $item;
 3892:                     } else {
 3893:                         $user = join(':',split(/[\@]/,$item));
 3894:                     }
 3895:                     if ($user eq $uname.':'.$udom) {
 3896:                         undef($skipuser);
 3897:                         last;
 3898:                     }
 3899:                 }
 3900:             }
 3901:             if ($skipuser) {
 3902:                 return 0;
 3903:             }
 3904:         }
 3905:     }
 3906:     $type ||= 'any';
 3907:     if (!defined($cdom) || !defined($cnum)) {
 3908:         my $cid  = $env{'request.course.id'};
 3909:         $cdom = $env{'course.'.$cid.'.domain'};
 3910:         $cnum = $env{'course.'.$cid.'.num'};
 3911:     }
 3912:     my $typesref;
 3913:     if (($type eq 'any') || ($type eq 'all')) {
 3914:         $typesref = ['active','previous','future'];
 3915:     } elsif ($type eq 'previous' || $type eq 'future') {
 3916:         $typesref = [$type];
 3917:     }
 3918:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3919:                               $typesref,undef,[$cdom]);
 3920:     my ($tmp) = keys(%roles);
 3921:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3922:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3923:     if (@course_roles > 0) {
 3924:         return 1;
 3925:     }
 3926:     return 0;
 3927: }
 3928: 
 3929: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3930: # input: action, courseID, current domain, intended
 3931: #        path to file, source of file, instruction to parse file for objects,
 3932: #        ref to hash for embedded objects,
 3933: #        ref to hash for codebase of java objects.
 3934: #        reference to scalar to accommodate mime type determined
 3935: #          from File::MMagic if $parser = parse.
 3936: #
 3937: # output: url to file (if action was uploaddoc), 
 3938: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3939: #
 3940: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3941: # course.
 3942: #
 3943: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3944: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3945: #          course's home server.
 3946: #
 3947: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3948: #          be copied from $source (current location) to 
 3949: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3950: #         and will then be copied to
 3951: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3952: #         course's home server.
 3953: #
 3954: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3955: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3956: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3957: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3958: #         in course's home server.
 3959: #
 3960: 
 3961: sub process_coursefile {
 3962:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3963:         $mimetype)=@_;
 3964:     my $fetchresult;
 3965:     my $home=&homeserver($docuname,$docudom);
 3966:     if ($action eq 'propagate') {
 3967:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3968: 			     $home);
 3969:     } else {
 3970:         my $fpath = '';
 3971:         my $fname = $file;
 3972:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3973:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3974:         my $filepath = &build_filepath($fpath);
 3975:         if ($action eq 'copy') {
 3976:             if ($source eq '') {
 3977:                 $fetchresult = 'no source file';
 3978:                 return $fetchresult;
 3979:             } else {
 3980:                 my $destination = $filepath.'/'.$fname;
 3981:                 rename($source,$destination);
 3982:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3983:                                  $home);
 3984:             }
 3985:         } elsif ($action eq 'uploaddoc') {
 3986:             open(my $fh,'>',$filepath.'/'.$fname);
 3987:             print $fh $env{'form.'.$source};
 3988:             close($fh);
 3989:             if ($parser eq 'parse') {
 3990:                 my $mm = new File::MMagic;
 3991:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3992:                 if ($type eq 'text/html') {
 3993:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3994:                     unless ($parse_result eq 'ok') {
 3995:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3996:                     }
 3997:                 }
 3998:                 if (ref($mimetype)) {
 3999:                     $$mimetype = $type;
 4000:                 } 
 4001:             }
 4002:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4003:                                  $home);
 4004:             if ($fetchresult eq 'ok') {
 4005:                 return '/uploaded/'.$fpath.'/'.$fname;
 4006:             } else {
 4007:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4008:                         ' to host '.$home.': '.$fetchresult);
 4009:                 return '/adm/notfound.html';
 4010:             }
 4011:         }
 4012:     }
 4013:     unless ( $fetchresult eq 'ok') {
 4014:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4015:              ' to host '.$home.': '.$fetchresult);
 4016:     }
 4017:     return $fetchresult;
 4018: }
 4019: 
 4020: sub build_filepath {
 4021:     my ($fpath) = @_;
 4022:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4023:     unless ($fpath eq '') {
 4024:         my @parts=split('/',$fpath);
 4025:         foreach my $part (@parts) {
 4026:             $filepath.= '/'.$part;
 4027:             if ((-e $filepath)!=1) {
 4028:                 mkdir($filepath,0777);
 4029:             }
 4030:         }
 4031:     }
 4032:     return $filepath;
 4033: }
 4034: 
 4035: sub store_edited_file {
 4036:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4037:     my $file = $primary_url;
 4038:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4039:     my $fpath = '';
 4040:     my $fname = $file;
 4041:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4042:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4043:     my $filepath = &build_filepath($fpath);
 4044:     open(my $fh,'>',$filepath.'/'.$fname);
 4045:     print $fh $content;
 4046:     close($fh);
 4047:     my $home=&homeserver($docuname,$docudom);
 4048:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4049: 			  $home);
 4050:     if ($$fetchresult eq 'ok') {
 4051:         return '/uploaded/'.$fpath.'/'.$fname;
 4052:     } else {
 4053:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4054: 		 ' to host '.$home.': '.$$fetchresult);
 4055:         return '/adm/notfound.html';
 4056:     }
 4057: }
 4058: 
 4059: sub clean_filename {
 4060:     my ($fname,$args)=@_;
 4061: # Replace Windows backslashes by forward slashes
 4062:     $fname=~s/\\/\//g;
 4063:     if (!$args->{'keep_path'}) {
 4064:         # Get rid of everything but the actual filename
 4065: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4066:     }
 4067: # Replace spaces by underscores
 4068:     $fname=~s/\s+/\_/g;
 4069: # Transliterate non-ascii text to ascii
 4070:     my $lang = &Apache::lonlocal::current_language();
 4071:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4072: # Replace all other weird characters by nothing
 4073:     $fname=~s{[^/\w\.\-]}{}g;
 4074: # Replace all .\d. sequences with _\d. so they no longer look like version
 4075: # numbers
 4076:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4077: # Replace three or more adjacent underscores with one for consistency 
 4078: # with loncfile::filename_check() so complete url can be extracted by
 4079: # lonnet::decode_symb()
 4080:     $fname=~s/_{3,}/_/g;
 4081:     return $fname;
 4082: }
 4083: 
 4084: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4085: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4086: # image with the same aspect ratio as the original, but with dimensions which do 
 4087: # not exceed $resizewidth and $resizeheight.
 4088:  
 4089: sub resizeImage {
 4090:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4091:     my $ima = Image::Magick->new;
 4092:     my $resized;
 4093:     if (-e $img_path) {
 4094:         $ima->Read($img_path);
 4095:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4096:             my $width = $ima->Get('width');
 4097:             my $height = $ima->Get('height');
 4098:             if ($width > $resizewidth) {
 4099: 	        my $factor = $width/$resizewidth;
 4100:                 my $newheight = $height/$factor;
 4101:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4102:                 $resized = 1;
 4103:             }
 4104:         }
 4105:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4106:             my $width = $ima->Get('width');
 4107:             my $height = $ima->Get('height');
 4108:             if ($height > $resizeheight) {
 4109:                 my $factor = $height/$resizeheight;
 4110:                 my $newwidth = $width/$factor;
 4111:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4112:                 $resized = 1;
 4113:             }
 4114:         }
 4115:         if ($resized) {
 4116:             $ima->Write($img_path);
 4117:         }
 4118:     }
 4119:     return;
 4120: }
 4121: 
 4122: # --------------- Take an uploaded file and put it into the userfiles directory
 4123: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4124: #                    the desired filename is in $env{"form.$formname.filename"}
 4125: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4126: #                                    canceloverwrite, scantron or ''.
 4127: #                   if 'coursedoc': upload to the current course
 4128: #                   if 'existingfile': write file to tmp/overwrites directory 
 4129: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4130: #                   $context is passed as argument to &finishuserfileupload
 4131: #        $subdir - directory in userfile to store the file into
 4132: #        $parser - instruction to parse file for objects ($parser = parse) or
 4133: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4134: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4135: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4136: #        $allfiles - reference to hash for embedded objects
 4137: #        $codebase - reference to hash for codebase of java objects
 4138: #        $desuname - username for permanent storage of uploaded file
 4139: #        $dsetudom - domain for permanaent storage of uploaded file
 4140: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4141: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4142: #        $resizewidth - width (pixels) to which to resize uploaded image
 4143: #        $resizeheight - height (pixels) to which to resize uploaded image
 4144: #        $mimetype - reference to scalar to accommodate mime type determined
 4145: #                    from File::MMagic.
 4146: # 
 4147: # output: url of file in userspace, or error: <message> 
 4148: #             or /adm/notfound.html if failure to upload occurse
 4149: 
 4150: sub userfileupload {
 4151:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4152:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4153:     if (!defined($subdir)) { $subdir='unknown'; }
 4154:     my $fname=$env{'form.'.$formname.'.filename'};
 4155:     $fname=&clean_filename($fname);
 4156:     # See if there is anything left
 4157:     unless ($fname) { return 'error: no uploaded file'; }
 4158:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4159:     if ($fname =~ /^\./) {
 4160:         my ($s,$usec) = &gettimeofday();
 4161:         while (length($usec) < 6) {
 4162:             $usec = '0'.$usec;
 4163:         }
 4164:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4165:     }
 4166:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4167:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4168:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4169:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4170:         my $now = time;
 4171:         my $filepath;
 4172:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4173:              $filepath = 'tmp/helprequests/'.$now;
 4174:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4175:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4176:                          '_'.$env{'user.domain'}.'/pending';
 4177:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4178:             my ($docuname,$docudom);
 4179:             if ($destudom =~ /^$match_domain$/) {
 4180:                 $docudom = $destudom;
 4181:             } else {
 4182:                 $docudom = $env{'user.domain'};
 4183:             }
 4184:             if ($destuname =~ /^$match_username$/) {
 4185:                 $docuname = $destuname;
 4186:             } else {
 4187:                 $docuname = $env{'user.name'};
 4188:             }
 4189:             if (exists($env{'form.group'})) {
 4190:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4191:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4192:             }
 4193:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4194:             if ($context eq 'canceloverwrite') {
 4195:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4196:                 if (-e  $tempfile) {
 4197:                     my @info = stat($tempfile);
 4198:                     if ($info[9] eq $env{'form.timestamp'}) {
 4199:                         unlink($tempfile);
 4200:                     }
 4201:                 }
 4202:                 return;
 4203:             }
 4204:         }
 4205:         # Create the directory if not present
 4206:         my @parts=split(/\//,$filepath);
 4207:         my $fullpath = $perlvar{'lonDaemons'};
 4208:         for (my $i=0;$i<@parts;$i++) {
 4209:             $fullpath .= '/'.$parts[$i];
 4210:             if ((-e $fullpath)!=1) {
 4211:                 mkdir($fullpath,0777);
 4212:             }
 4213:         }
 4214:         open(my $fh,'>',$fullpath.'/'.$fname);
 4215:         print $fh $env{'form.'.$formname};
 4216:         close($fh);
 4217:         if ($context eq 'existingfile') {
 4218:             my @info = stat($fullpath.'/'.$fname);
 4219:             return ($fullpath.'/'.$fname,$info[9]);
 4220:         } else {
 4221:             return $fullpath.'/'.$fname;
 4222:         }
 4223:     }
 4224:     if ($subdir eq 'scantron') {
 4225:         $fname = 'scantron_orig_'.$fname;
 4226:     } else {
 4227:         $fname="$subdir/$fname";
 4228:     }
 4229:     if ($context eq 'coursedoc') {
 4230: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4231: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4232:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4233:             return &finishuserfileupload($docuname,$docudom,
 4234: 					 $formname,$fname,$parser,$allfiles,
 4235: 					 $codebase,$thumbwidth,$thumbheight,
 4236:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4237:         } else {
 4238:             if ($env{'form.folder'}) {
 4239:                 $fname=$env{'form.folder'}.'/'.$fname;
 4240:             }
 4241:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4242: 				       $fname,$formname,$parser,
 4243: 				       $allfiles,$codebase,$mimetype);
 4244:         }
 4245:     } elsif (defined($destuname)) {
 4246:         my $docuname=$destuname;
 4247:         my $docudom=$destudom;
 4248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4249: 				     $parser,$allfiles,$codebase,
 4250:                                      $thumbwidth,$thumbheight,
 4251:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4252:     } else {
 4253:         my $docuname=$env{'user.name'};
 4254:         my $docudom=$env{'user.domain'};
 4255:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4256:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4257:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4258:         }
 4259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4260: 				     $parser,$allfiles,$codebase,
 4261:                                      $thumbwidth,$thumbheight,
 4262:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4263:     }
 4264: }
 4265: 
 4266: sub finishuserfileupload {
 4267:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4268:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4269:     my $path=$docudom.'/'.$docuname.'/';
 4270:     my $filepath=$perlvar{'lonDocRoot'};
 4271:   
 4272:     my ($fnamepath,$file,$fetchthumb);
 4273:     $file=$fname;
 4274:     if ($fname=~m|/|) {
 4275:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4276: 	$path.=$fnamepath.'/';
 4277:     }
 4278:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4279:     my $count;
 4280:     for ($count=4;$count<=$#parts;$count++) {
 4281:         $filepath.="/$parts[$count]";
 4282:         if ((-e $filepath)!=1) {
 4283: 	    mkdir($filepath,0777);
 4284:         }
 4285:     }
 4286: 
 4287: # Save the file
 4288:     {
 4289: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4290: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4291: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4292: 	    return '/adm/notfound.html';
 4293: 	}
 4294:         if ($context eq 'overwrite') {
 4295:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4296:             my $target = $filepath.'/'.$file;
 4297:             if (-e $source) {
 4298:                 my @info = stat($source);
 4299:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4300:                     unless (&File::Copy::move($source,$target)) {
 4301:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4302:                         return "Moving from $source failed";
 4303:                     }
 4304:                 } else {
 4305:                     return "Temporary file: $source had unexpected date/time for last modification";
 4306:                 }
 4307:             } else {
 4308:                 return "Temporary file: $source missing";
 4309:             }
 4310:         } elsif (!print FH ($env{'form.'.$formname})) {
 4311: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4312: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4313: 	    return '/adm/notfound.html';
 4314: 	}
 4315: 	close(FH);
 4316:         if ($resizewidth && $resizeheight) {
 4317:             my $mm = new File::MMagic;
 4318:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4319:             if ($mime_type =~ m{^image/}) {
 4320: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4321:             }  
 4322: 	}
 4323:     }
 4324:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4325:         if (ref($mimetype)) {
 4326:             if ($$mimetype eq '') {
 4327:                 my $mm = new File::MMagic;
 4328:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4329:                 $$mimetype = $type;
 4330:             }
 4331:         }
 4332:     }
 4333:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4334:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4335:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4336:                                                        $allfiles,$codebase);
 4337:             unless ($parse_result eq 'ok') {
 4338:                 &logthis('Failed to parse '.$filepath.$file.
 4339: 	   	         ' for embedded media: '.$parse_result); 
 4340:             }
 4341:         }
 4342:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4343:         my $format = $env{'form.scantron_format'};
 4344:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4345:     }
 4346:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4347:         my $input = $filepath.'/'.$file;
 4348:         my $output = $filepath.'/'.'tn-'.$file;
 4349:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4350:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4351:         system({$args[0]} @args);
 4352:         if (-e $filepath.'/'.'tn-'.$file) {
 4353:             $fetchthumb  = 1; 
 4354:         }
 4355:     }
 4356:  
 4357: # Notify homeserver to grep it
 4358: #
 4359:     my $docuhome=&homeserver($docuname,$docudom);	
 4360:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4361:     if ($fetchresult eq 'ok') {
 4362:         if ($fetchthumb) {
 4363:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4364:             if ($thumbresult ne 'ok') {
 4365:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4366:                          $docuhome.': '.$thumbresult);
 4367:             }
 4368:         }
 4369: #
 4370: # Return the URL to it
 4371:         return '/uploaded/'.$path.$file;
 4372:     } else {
 4373:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4374: 		 ': '.$fetchresult);
 4375:         return '/adm/notfound.html';
 4376:     }
 4377: }
 4378: 
 4379: sub extract_embedded_items {
 4380:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4381:     my @state = ();
 4382:     my (%lastids,%related,%shockwave,%flashvars);
 4383:     my %javafiles = (
 4384:                       codebase => '',
 4385:                       code => '',
 4386:                       archive => ''
 4387:                     );
 4388:     my %mediafiles = (
 4389:                       src => '',
 4390:                       movie => '',
 4391:                      );
 4392:     my $p;
 4393:     if ($content) {
 4394:         $p = HTML::LCParser->new($content);
 4395:     } else {
 4396:         $p = HTML::LCParser->new($fullpath);
 4397:     }
 4398:     while (my $t=$p->get_token()) {
 4399: 	if ($t->[0] eq 'S') {
 4400: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4401: 	    push(@state, $tagname);
 4402:             if (lc($tagname) eq 'allow') {
 4403:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4404:             }
 4405: 	    if (lc($tagname) eq 'img') {
 4406: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4407: 	    }
 4408: 	    if (lc($tagname) eq 'a') {
 4409:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4410:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4411:                 }
 4412: 	    }
 4413:             if (lc($tagname) eq 'script') {
 4414:                 my $src;
 4415:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4416:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4417:                 } else {
 4418:                     if ($attr->{'src'} ne '') {
 4419:                         $src = $attr->{'src'};
 4420:                         &add_filetype($allfiles,$src,'src');
 4421:                     }
 4422:                 }
 4423:                 my $text = $p->get_trimmed_text();
 4424:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4425:                     my @swfargs = split(/,/,$1);
 4426:                     foreach my $item (@swfargs) {
 4427:                         $item =~ s/["']//g;
 4428:                         $item =~ s/^\s+//;
 4429:                         $item =~ s/\s+$//;
 4430:                     }
 4431:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4432:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4433:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4434:                         } else {
 4435:                             $related{$swfargs[0]} = [$swfargs[2]];
 4436:                         }
 4437:                     }
 4438:                 }
 4439:             }
 4440:             if (lc($tagname) eq 'link') {
 4441:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4442:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4443:                 }
 4444:             }
 4445: 	    if (lc($tagname) eq 'object' ||
 4446: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4447: 		foreach my $item (keys(%javafiles)) {
 4448: 		    $javafiles{$item} = '';
 4449: 		}
 4450:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4451:                     $lastids{lc($tagname)} = $attr->{'id'};
 4452:                 }
 4453: 	    }
 4454: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4455: 		my $name = lc($attr->{'name'});
 4456: 		foreach my $item (keys(%javafiles)) {
 4457: 		    if ($name eq $item) {
 4458: 			$javafiles{$item} = $attr->{'value'};
 4459: 			last;
 4460: 		    }
 4461: 		}
 4462:                 my $pathfrom;
 4463: 		foreach my $item (keys(%mediafiles)) {
 4464: 		    if ($name eq $item) {
 4465:                         $pathfrom = $attr->{'value'};
 4466:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4467: 			&add_filetype($allfiles,$pathfrom,$name);
 4468: 			last;
 4469: 		    }
 4470: 		}
 4471:                 if ($name eq 'flashvars') {
 4472:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4473:                 }
 4474:                 if ($pathfrom ne '') {
 4475:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4476:                                          $pathfrom);
 4477:                 }
 4478: 	    }
 4479: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4480: 		foreach my $item (keys(%javafiles)) {
 4481: 		    if ($attr->{$item}) {
 4482: 			$javafiles{$item} = $attr->{$item};
 4483: 			last;
 4484: 		    }
 4485: 		}
 4486: 		foreach my $item (keys(%mediafiles)) {
 4487: 		    if ($attr->{$item}) {
 4488: 			&add_filetype($allfiles,$attr->{$item},$item);
 4489: 			last;
 4490: 		    }
 4491: 		}
 4492:                 if (lc($tagname) eq 'embed') {
 4493:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4494:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4495:                                              $attr->{'src'});
 4496:                     }
 4497:                 }
 4498: 	    }
 4499:             if (lc($tagname) eq 'iframe') {
 4500:                 my $src = $attr->{'src'} ;
 4501:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4502:                     &add_filetype($allfiles,$src,'src');
 4503:                 } elsif ($src =~ m{^/}) {
 4504:                     if ($env{'request.course.id'}) {
 4505:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4506:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4507:                         my $url = &hreflocation('',$fullpath);
 4508:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4509:                             my $relpath = $1;
 4510:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4511:                                 &add_filetype($allfiles,$1,'src');
 4512:                             }
 4513:                         }
 4514:                     }
 4515:                 }
 4516:             }
 4517:             if ($t->[4] =~ m{/>$}) {
 4518:                 pop(@state);
 4519:             }
 4520: 	} elsif ($t->[0] eq 'E') {
 4521: 	    my ($tagname) = ($t->[1]);
 4522: 	    if ($javafiles{'codebase'} ne '') {
 4523: 		$javafiles{'codebase'} .= '/';
 4524: 	    }  
 4525: 	    if (lc($tagname) eq 'applet' ||
 4526: 		lc($tagname) eq 'object' ||
 4527: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4528: 		) {
 4529: 		foreach my $item (keys(%javafiles)) {
 4530: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4531: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4532: 			&add_filetype($allfiles,$file,$item);
 4533: 		    }
 4534: 		}
 4535: 	    } 
 4536: 	    pop @state;
 4537: 	}
 4538:     }
 4539:     foreach my $id (sort(keys(%flashvars))) {
 4540:         if ($shockwave{$id} ne '') {
 4541:             my @pairs = split(/\&/,$flashvars{$id});
 4542:             foreach my $pair (@pairs) {
 4543:                 my ($key,$value) = split(/\=/,$pair);
 4544:                 if ($key eq 'thumb') {
 4545:                     &add_filetype($allfiles,$value,$key);
 4546:                 } elsif ($key eq 'content') {
 4547:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4548:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4549:                     if ($ext ne '') {
 4550:                         &add_filetype($allfiles,$path.$value,$ext);
 4551:                     }
 4552:                 }
 4553:             }
 4554:         }
 4555:     }
 4556:     return 'ok';
 4557: }
 4558: 
 4559: sub add_filetype {
 4560:     my ($allfiles,$file,$type)=@_;
 4561:     if (exists($allfiles->{$file})) {
 4562: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4563: 	    push(@{$allfiles->{$file}}, &escape($type));
 4564: 	}
 4565:     } else {
 4566: 	@{$allfiles->{$file}} = (&escape($type));
 4567:     }
 4568: }
 4569: 
 4570: sub embedded_dependency {
 4571:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4572:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4573:         if (($identifier ne '') &&
 4574:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4575:             ($pathfrom ne '')) {
 4576:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4577:             foreach my $dep (@{$related->{$identifier}}) {
 4578:                 &add_filetype($allfiles,$path.$dep,'object');
 4579:             }
 4580:         }
 4581:     }
 4582:     return;
 4583: }
 4584: 
 4585: sub bubblesheet_converter {
 4586:     my ($cdom,$fullpath,$config,$format) = @_;
 4587:     if ((&domain($cdom) ne '') &&
 4588:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4589:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4590:         my (%csvcols,%csvoptions);
 4591:         if (ref($config->{'fields'}) eq 'HASH') {  
 4592:             %csvcols = %{$config->{'fields'}};
 4593:         }
 4594:         if (ref($config->{'options'}) eq 'HASH') {
 4595:             %csvoptions = %{$config->{'options'}};
 4596:         }
 4597:         my %csvbynum = reverse(%csvcols);
 4598:         my %scantronconf = &get_scantron_config($format,$cdom);
 4599:         if (keys(%scantronconf)) {
 4600:             my %bynum = (
 4601:                           $scantronconf{CODEstart} => 'CODEstart',
 4602:                           $scantronconf{IDstart}   => 'IDstart',
 4603:                           $scantronconf{PaperID}   => 'PaperID',
 4604:                           $scantronconf{FirstName} => 'FirstName',
 4605:                           $scantronconf{LastName}  => 'LastName',
 4606:                           $scantronconf{Qstart}    => 'Qstart',
 4607:                         );
 4608:             my @ordered;
 4609:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4610:                 push(@ordered,$bynum{$item});
 4611:             }
 4612:             my %mapstart = (
 4613:                               CODEstart => 'CODE',
 4614:                               IDstart   => 'ID',
 4615:                               PaperID   => 'PaperID',
 4616:                               FirstName => 'FirstName',
 4617:                               LastName  => 'LastName',
 4618:                               Qstart    => 'FirstQuestion',
 4619:                            );
 4620:             my %maplength = (
 4621:                               CODEstart => 'CODElength',
 4622:                               IDstart   => 'IDlength',
 4623:                               PaperID   => 'PaperIDlength',
 4624:                               FirstName => 'FirstNamelength',
 4625:                               LastName  => 'LastNamelength',
 4626:             );
 4627:             if (open(my $fh,'<',$fullpath)) {
 4628:                 my $output;
 4629:                 my %lettdig = &letter_to_digits();
 4630:                 my %diglett = reverse(%lettdig);
 4631:                 my $numletts = scalar(keys(%lettdig));
 4632:                 my $num = 0;
 4633:                 while (my $line=<$fh>) {
 4634:                     $num ++;
 4635:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4636:                     $line =~ s{[\r\n]+$}{};
 4637:                     my %found;
 4638:                     my @values = split(/,/,$line);
 4639:                     my ($qstart,$record);
 4640:                     for (my $i=0; $i<@values; $i++) {
 4641:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4642:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4643:                             if ($values[$i] eq '') {
 4644:                                 $values[$i] = $scantronconf{'Qoff'};
 4645:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4646:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4647:                                     $values[$i] = $lettdig{uc($values[$i])};
 4648:                                 }
 4649:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4650:                                 if ($values[$i] =~ /^[0-9]$/) {
 4651:                                     $values[$i] = $diglett{$values[$i]};
 4652:                                 }
 4653:                             } else {
 4654:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4655:                                     my $digit;
 4656:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4657:                                         $digit = $lettdig{uc($values[$i])}-1;
 4658:                                         if ($values[$i] eq 'J') {
 4659:                                             $digit += $numletts;
 4660:                                         }
 4661:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4662:                                         $digit = $values[$i]-1;
 4663:                                         if ($values[$i] eq '0') {
 4664:                                             $digit += $numletts;
 4665:                                         }
 4666:                                     }
 4667:                                     my $qval='';
 4668:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4669:                                         if ($j == $digit) {
 4670:                                             $qval .= $scantronconf{'Qon'};
 4671:                                         } else {
 4672:                                             $qval .= $scantronconf{'Qoff'};
 4673:                                         }
 4674:                                     }
 4675:                                     $values[$i] = $qval;
 4676:                                 }
 4677:                             }
 4678:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4679:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4680:                             }
 4681:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4682:                             if ($numblank > 0) {
 4683:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4684:                             }
 4685:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4686:                                 $qstart = $i;
 4687:                                 $found{$csvbynum{$i}} = $values[$i];
 4688:                             } else {
 4689:                                 $found{'FirstQuestion'} .= $values[$i];
 4690:                             }
 4691:                         } elsif (exists($csvbynum{$i})) {
 4692:                             if ($csvoptions{'rem'}) {
 4693:                                 $values[$i] =~ s/^\s+//;
 4694:                             }
 4695:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4696:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4697:                                     $values[$i] = '0'.$values[$i];
 4698:                                 }
 4699:                             }
 4700:                             $found{$csvbynum{$i}} = $values[$i];
 4701:                         }
 4702:                     }
 4703:                     foreach my $item (@ordered) {
 4704:                         my $currlength = 1+length($record);
 4705:                         my $numspaces = $scantronconf{$item} - $currlength;
 4706:                         if ($numspaces > 0) {
 4707:                             $record .= (' ' x $numspaces);
 4708:                         }
 4709:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4710:                             unless ($item eq 'Qstart') {
 4711:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4712:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4713:                                 }
 4714:                             }
 4715:                             $record .= $found{$mapstart{$item}};
 4716:                         }
 4717:                     }
 4718:                     $output .= "$record\n";
 4719:                 }
 4720:                 close($fh);
 4721:                 if ($output) {
 4722:                     if (open(my $fh,'>',$fullpath)) {
 4723:                         print $fh $output;
 4724:                         close($fh);
 4725:                     }
 4726:                 }
 4727:             }
 4728:         }
 4729:         return;
 4730:     }
 4731: }
 4732: 
 4733: sub letter_to_digits {
 4734:     my %lettdig = (
 4735:                     A => 1,
 4736:                     B => 2,
 4737:                     C => 3,
 4738:                     D => 4,
 4739:                     E => 5,
 4740:                     F => 6,
 4741:                     G => 7,
 4742:                     H => 8,
 4743:                     I => 9,
 4744:                     J => 0,
 4745:                   );
 4746:     return %lettdig;
 4747: }
 4748: 
 4749: sub get_scantron_config {
 4750:     my ($which,$cdom) = @_;
 4751:     my @lines = &get_scantronformat_file($cdom);
 4752:     my %config;
 4753:     #FIXME probably should move to XML it has already gotten a bit much now
 4754:     foreach my $line (@lines) {
 4755:         my ($name,$descrip)=split(/:/,$line);
 4756:         if ($name ne $which ) { next; }
 4757:         chomp($line);
 4758:         my @config=split(/:/,$line);
 4759:         $config{'name'}=$config[0];
 4760:         $config{'description'}=$config[1];
 4761:         $config{'CODElocation'}=$config[2];
 4762:         $config{'CODEstart'}=$config[3];
 4763:         $config{'CODElength'}=$config[4];
 4764:         $config{'IDstart'}=$config[5];
 4765:         $config{'IDlength'}=$config[6];
 4766:         $config{'Qstart'}=$config[7];
 4767:         $config{'Qlength'}=$config[8];
 4768:         $config{'Qoff'}=$config[9];
 4769:         $config{'Qon'}=$config[10];
 4770:         $config{'PaperID'}=$config[11];
 4771:         $config{'PaperIDlength'}=$config[12];
 4772:         $config{'FirstName'}=$config[13];
 4773:         $config{'FirstNamelength'}=$config[14];
 4774:         $config{'LastName'}=$config[15];
 4775:         $config{'LastNamelength'}=$config[16];
 4776:         $config{'BubblesPerRow'}=$config[17];
 4777:         last;
 4778:     }
 4779:     return %config;
 4780: }
 4781: 
 4782: sub get_scantronformat_file {
 4783:     my ($cdom) = @_;
 4784:     if ($cdom eq '') {
 4785:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4786:     }
 4787:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4788:     my $gottab = 0;
 4789:     my @lines;
 4790:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4791:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4792:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4793:             if ($formatfile ne '-1') {
 4794:                 @lines = split("\n",$formatfile,-1);
 4795:                 $gottab = 1;
 4796:             }
 4797:         }
 4798:     }
 4799:     if (!$gottab) {
 4800:         my $confname = $cdom.'-domainconfig';
 4801:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4802:         my $formatfile = &getfile($default);
 4803:         if ($formatfile ne '-1') {
 4804:             @lines = split("\n",$formatfile,-1);
 4805:             $gottab = 1;
 4806:         }
 4807:     }
 4808:     if (!$gottab) {
 4809:         my @domains = &current_machine_domains();
 4810:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4811:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4812:                 @lines = <$fh>;
 4813:                 close($fh);
 4814:             }
 4815:         } else {
 4816:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4817:                 @lines = <$fh>;
 4818:                 close($fh);
 4819:             }
 4820:         }
 4821:     }
 4822:     return @lines;
 4823: }
 4824: 
 4825: sub removeuploadedurl {
 4826:     my ($url)=@_;	
 4827:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4828:     return &removeuserfile($uname,$udom,$fname);
 4829: }
 4830: 
 4831: sub removeuserfile {
 4832:     my ($docuname,$docudom,$fname)=@_;
 4833:     my $home=&homeserver($docuname,$docudom);    
 4834:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4835:     if ($result eq 'ok') {	
 4836:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4837:             my $metafile = $fname.'.meta';
 4838:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4839: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4840:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4841:             my $sqlresult = 
 4842:                 &update_portfolio_table($docuname,$docudom,$file,
 4843:                                         'portfolio_metadata',$group,
 4844:                                         'delete');
 4845:         }
 4846:     }
 4847:     return $result;
 4848: }
 4849: 
 4850: sub mkdiruserfile {
 4851:     my ($docuname,$docudom,$dir)=@_;
 4852:     my $home=&homeserver($docuname,$docudom);
 4853:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4854: }
 4855: 
 4856: sub renameuserfile {
 4857:     my ($docuname,$docudom,$old,$new)=@_;
 4858:     my $home=&homeserver($docuname,$docudom);
 4859:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4860:                         &escape("$old").':'.&escape("$new"),$home);
 4861:     if ($result eq 'ok') {
 4862:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4863:             my $oldmeta = $old.'.meta';
 4864:             my $newmeta = $new.'.meta';
 4865:             my $metaresult = 
 4866:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4867: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4868:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4869:             my $sqlresult = 
 4870:                 &update_portfolio_table($docuname,$docudom,$file,
 4871:                                         'portfolio_metadata',$group,
 4872:                                         'delete');
 4873:         }
 4874:     }
 4875:     return $result;
 4876: }
 4877: 
 4878: # ------------------------------------------------------------------------- Log
 4879: 
 4880: sub log {
 4881:     my ($dom,$nam,$hom,$what)=@_;
 4882:     return critical("log:$dom:$nam:$what",$hom);
 4883: }
 4884: 
 4885: # ------------------------------------------------------------------ Course Log
 4886: #
 4887: # This routine flushes several buffers of non-mission-critical nature
 4888: #
 4889: 
 4890: sub flushcourselogs {
 4891:     &logthis('Flushing log buffers');
 4892: #
 4893: # course logs
 4894: # This is a log of all transactions in a course, which can be used
 4895: # for data mining purposes
 4896: #
 4897: # It also collects the courseid database, which lists last transaction
 4898: # times and course titles for all courseids
 4899: #
 4900:     my %courseidbuffer=();
 4901:     foreach my $crsid (keys(%courselogs)) {
 4902:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4903: 		          &escape($courselogs{$crsid}),
 4904: 		          $coursehombuf{$crsid}) eq 'ok') {
 4905: 	    delete $courselogs{$crsid};
 4906:         } else {
 4907:             &logthis('Failed to flush log buffer for '.$crsid);
 4908:             if (length($courselogs{$crsid})>40000) {
 4909:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4910:                         " exceeded maximum size, deleting.</font>");
 4911:                delete $courselogs{$crsid};
 4912:             }
 4913:         }
 4914:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4915:             'description' => $coursedescrbuf{$crsid},
 4916:             'inst_code'    => $courseinstcodebuf{$crsid},
 4917:             'type'        => $coursetypebuf{$crsid},
 4918:             'owner'       => $courseownerbuf{$crsid},
 4919:         };
 4920:     }
 4921: #
 4922: # Write course id database (reverse lookup) to homeserver of courses 
 4923: # Is used in pickcourse
 4924: #
 4925:     foreach my $crs_home (keys(%courseidbuffer)) {
 4926:         my $response = &courseidput(&host_domain($crs_home),
 4927:                                     $courseidbuffer{$crs_home},
 4928:                                     $crs_home,'timeonly');
 4929:     }
 4930: #
 4931: # File accesses
 4932: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4933: #
 4934:     foreach my $entry (keys(%accesshash)) {
 4935:         if ($entry =~ /___count$/) {
 4936:             my ($dom,$name);
 4937:             ($dom,$name,undef)=
 4938: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4939:             if (! defined($dom) || $dom eq '' || 
 4940:                 ! defined($name) || $name eq '') {
 4941:                 my $cid = $env{'request.course.id'};
 4942:                 $dom  = $env{'request.'.$cid.'.domain'};
 4943:                 $name = $env{'request.'.$cid.'.num'};
 4944:             }
 4945:             my $value = $accesshash{$entry};
 4946:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4947:             my %temphash=($url => $value);
 4948:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4949:             if ($result eq 'ok') {
 4950:                 delete $accesshash{$entry};
 4951:             }
 4952:         } else {
 4953:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4954:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4955:             my %temphash=($entry => $accesshash{$entry});
 4956:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4957:                 delete $accesshash{$entry};
 4958:             }
 4959:         }
 4960:     }
 4961: #
 4962: # Roles
 4963: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4964: #
 4965:     foreach my $entry (keys(%userrolehash)) {
 4966:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4967: 	    split(/\:/,$entry);
 4968:         if (&Apache::lonnet::put('nohist_userroles',
 4969:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4970:                 $rudom,$runame) eq 'ok') {
 4971: 	    delete $userrolehash{$entry};
 4972:         }
 4973:     }
 4974: #
 4975: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4976: #
 4977:     my %domrolebuffer = ();
 4978:     foreach my $entry (keys(%domainrolehash)) {
 4979:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4980:         if ($domrolebuffer{$rudom}) {
 4981:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4982:                       '='.&escape($domainrolehash{$entry});
 4983:         } else {
 4984:             $domrolebuffer{$rudom}.=&escape($entry).
 4985:                       '='.&escape($domainrolehash{$entry});
 4986:         }
 4987:         delete $domainrolehash{$entry};
 4988:     }
 4989:     foreach my $dom (keys(%domrolebuffer)) {
 4990: 	my %servers;
 4991: 	if (defined(&domain($dom,'primary'))) {
 4992: 	    my $primary=&domain($dom,'primary');
 4993: 	    my $hostname=&hostname($primary);
 4994: 	    $servers{$primary} = $hostname;
 4995: 	} else { 
 4996: 	    %servers = &get_servers($dom,'library');
 4997: 	}
 4998: 	foreach my $tryserver (keys(%servers)) {
 4999: 	    if (&reply('domroleput:'.$dom.':'.
 5000: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5001: 		last;
 5002: 	    } else {  
 5003: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5004: 	    }
 5005:         }
 5006:     }
 5007:     $dumpcount++;
 5008: }
 5009: 
 5010: sub courselog {
 5011:     my $what=shift;
 5012:     $what=time.':'.$what;
 5013:     unless ($env{'request.course.id'}) { return ''; }
 5014:     $coursedombuf{$env{'request.course.id'}}=
 5015:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5016:     $coursenumbuf{$env{'request.course.id'}}=
 5017:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5018:     $coursehombuf{$env{'request.course.id'}}=
 5019:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5020:     $coursedescrbuf{$env{'request.course.id'}}=
 5021:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5022:     $courseinstcodebuf{$env{'request.course.id'}}=
 5023:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5024:     $courseownerbuf{$env{'request.course.id'}}=
 5025:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5026:     $coursetypebuf{$env{'request.course.id'}}=
 5027:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5028:     if (defined $courselogs{$env{'request.course.id'}}) {
 5029: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5030:     } else {
 5031: 	$courselogs{$env{'request.course.id'}}.=$what;
 5032:     }
 5033:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5034: 	&flushcourselogs();
 5035:     }
 5036: }
 5037: 
 5038: sub courseacclog {
 5039:     my $fnsymb=shift;
 5040:     unless ($env{'request.course.id'}) { return ''; }
 5041:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5042:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5043:         $what.=':POST';
 5044:         # FIXME: Probably ought to escape things....
 5045: 	foreach my $key (keys(%env)) {
 5046:             if ($key=~/^form\.(.*)/) {
 5047:                 my $formitem = $1;
 5048:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5049:                     $what.=':'.$formitem.'='.$env{$key};
 5050:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5051:                     if ($formitem eq 'proctorpassword') {
 5052:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5053:                     } else {
 5054:                         $what.=':'.$formitem.'='.$env{$key};
 5055:                     }
 5056:                 }
 5057:             }
 5058:         }
 5059:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5060:         # FIXME: We should not be depending on a form parameter that someone
 5061:         # editing lonsearchcat.pm might change in the future.
 5062:         if ($env{'form.phase'} eq 'course_search') {
 5063:             $what.= ':POST';
 5064:             # FIXME: Probably ought to escape things....
 5065:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5066:                                  'crsdiscuss') {
 5067:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5068:             }
 5069:         }
 5070:     }
 5071:     &courselog($what);
 5072: }
 5073: 
 5074: sub countacc {
 5075:     my $url=&declutter(shift);
 5076:     return if (! defined($url) || $url eq '');
 5077:     unless ($env{'request.course.id'}) { return ''; }
 5078: #
 5079: # Mark that this url was used in this course
 5080: #
 5081:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5082: #
 5083: # Increase the access count for this resource in this child process
 5084: #
 5085:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5086:     $accesshash{$key}++;
 5087: }
 5088: 
 5089: sub linklog {
 5090:     my ($from,$to)=@_;
 5091:     $from=&declutter($from);
 5092:     $to=&declutter($to);
 5093:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5094:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5095: }
 5096: 
 5097: sub statslog {
 5098:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5099:     if ($users<2) { return; }
 5100:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5101:             'course'       => $env{'request.course.id'},
 5102:             'sections'     => '"all"',
 5103:             'num_students' => $users,
 5104:             'part'         => $part,
 5105:             'symb'         => $symb,
 5106:             'mean_tries'   => $av_attempts,
 5107:             'deg_of_diff'  => $degdiff});
 5108:     foreach my $key (keys(%dynstore)) {
 5109:         $accesshash{$key}=$dynstore{$key};
 5110:     }
 5111: }
 5112:   
 5113: sub userrolelog {
 5114:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5115:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5116:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5117:        $userrolehash
 5118:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5119:                     =$tend.':'.$tstart;
 5120:     }
 5121:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5122:        $userrolehash
 5123:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5124:                     =$tend.':'.$tstart;
 5125:     }
 5126:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5127:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5128:        $domainrolehash
 5129:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5130:                     = $tend.':'.$tstart;
 5131:     }
 5132: }
 5133: 
 5134: sub courserolelog {
 5135:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5136:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5137:         my $cdom = $1;
 5138:         my $cnum = $2;
 5139:         my $sec = $3;
 5140:         my $namespace = 'rolelog';
 5141:         my %storehash = (
 5142:                            role    => $trole,
 5143:                            start   => $tstart,
 5144:                            end     => $tend,
 5145:                            selfenroll => $selfenroll,
 5146:                            context    => $context,
 5147:                         );
 5148:         if ($trole eq 'gr') {
 5149:             $namespace = 'groupslog';
 5150:             $storehash{'group'} = $sec;
 5151:         } else {
 5152:             $storehash{'section'} = $sec;
 5153:         }
 5154:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5155:                    $domain,$cnum,$cdom);
 5156:         if (($trole ne 'st') || ($sec ne '')) {
 5157:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5158:         }
 5159:     }
 5160:     return;
 5161: }
 5162: 
 5163: sub domainrolelog {
 5164:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5165:     if ($area =~ m{^/($match_domain)/$}) {
 5166:         my $cdom = $1;
 5167:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5168:         my $namespace = 'rolelog';
 5169:         my %storehash = (
 5170:                            role    => $trole,
 5171:                            start   => $tstart,
 5172:                            end     => $tend,
 5173:                            context => $context,
 5174:                         );
 5175:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5176:                    $domain,$domconfiguser,$cdom);
 5177:     }
 5178:     return;
 5179: 
 5180: }
 5181: 
 5182: sub coauthorrolelog {
 5183:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5184:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5185:         my $audom = $1;
 5186:         my $auname = $2;
 5187:         my $namespace = 'rolelog';
 5188:         my %storehash = (
 5189:                            role    => $trole,
 5190:                            start   => $tstart,
 5191:                            end     => $tend,
 5192:                            context => $context,
 5193:                         );
 5194:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5195:                    $domain,$auname,$audom);
 5196:     }
 5197:     return;
 5198: }
 5199: 
 5200: sub get_course_adv_roles {
 5201:     my ($cid,$codes) = @_;
 5202:     $cid=$env{'request.course.id'} unless (defined($cid));
 5203:     my %coursehash=&coursedescription($cid);
 5204:     my $crstype = &Apache::loncommon::course_type($cid);
 5205:     my %nothide=();
 5206:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5207:         if ($user !~ /:/) {
 5208: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5209:         } else {
 5210:             $nothide{$user}=1;
 5211:         }
 5212:     }
 5213:     my @possdoms = ($coursehash{'domain'});
 5214:     if ($coursehash{'checkforpriv'}) {
 5215:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5216:     }
 5217:     my %returnhash=();
 5218:     my %dumphash=
 5219:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5220:     my $now=time;
 5221:     my %privileged;
 5222:     foreach my $entry (keys(%dumphash)) {
 5223: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5224:         if (($tstart) && ($tstart<0)) { next; }
 5225:         if (($tend) && ($tend<$now)) { next; }
 5226:         if (($tstart) && ($now<$tstart)) { next; }
 5227:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5228: 	if ($username eq '' || $domain eq '') { next; }
 5229:         if ((&privileged($username,$domain,\@possdoms)) &&
 5230:             (!$nothide{$username.':'.$domain})) { next; }
 5231: 	if ($role eq 'cr') { next; }
 5232:         if ($codes) {
 5233:             if ($section) { $role .= ':'.$section; }
 5234:             if ($returnhash{$role}) {
 5235:                 $returnhash{$role}.=','.$username.':'.$domain;
 5236:             } else {
 5237:                 $returnhash{$role}=$username.':'.$domain;
 5238:             }
 5239:         } else {
 5240:             my $key=&plaintext($role,$crstype);
 5241:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5242:             if ($returnhash{$key}) {
 5243: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5244:             } else {
 5245:                 $returnhash{$key}=$username.':'.$domain;
 5246:             }
 5247:         }
 5248:     }
 5249:     return %returnhash;
 5250: }
 5251: 
 5252: sub get_my_roles {
 5253:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5254:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5255:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5256:     my (%dumphash,%nothide);
 5257:     if ($context eq 'userroles') {
 5258:         %dumphash = &dump('roles',$udom,$uname);
 5259:     } else {
 5260:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5261:         if ($hidepriv) {
 5262:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5263:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5264:                 if ($user !~ /:/) {
 5265:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5266:                 } else {
 5267:                     $nothide{$user} = 1;
 5268:                 }
 5269:             }
 5270:         }
 5271:     }
 5272:     my %returnhash=();
 5273:     my $now=time;
 5274:     my %privileged;
 5275:     foreach my $entry (keys(%dumphash)) {
 5276:         my ($role,$tend,$tstart);
 5277:         if ($context eq 'userroles') {
 5278:             next if ($entry =~ /^rolesdef/);
 5279: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5280:         } else {
 5281:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5282:         }
 5283:         if (($tstart) && ($tstart<0)) { next; }
 5284:         my $status = 'active';
 5285:         if (($tend) && ($tend<=$now)) {
 5286:             $status = 'previous';
 5287:         } 
 5288:         if (($tstart) && ($now<$tstart)) {
 5289:             $status = 'future';
 5290:         }
 5291:         if (ref($types) eq 'ARRAY') {
 5292:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5293:                 next;
 5294:             } 
 5295:         } else {
 5296:             if ($status ne 'active') {
 5297:                 next;
 5298:             }
 5299:         }
 5300:         my ($rolecode,$username,$domain,$section,$area);
 5301:         if ($context eq 'userroles') {
 5302:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5303:             (undef,$domain,$username,$section) = split(/\//,$area);
 5304:         } else {
 5305:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5306:         }
 5307:         if (ref($roledoms) eq 'ARRAY') {
 5308:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5309:                 next;
 5310:             }
 5311:         }
 5312:         if (ref($roles) eq 'ARRAY') {
 5313:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5314:                 if ($role =~ /^cr\//) {
 5315:                     if (!grep(/^cr$/,@{$roles})) {
 5316:                         next;
 5317:                     }
 5318:                 } elsif ($role =~ /^gr\//) {
 5319:                     if (!grep(/^gr$/,@{$roles})) {
 5320:                         next;
 5321:                     }
 5322:                 } else {
 5323:                     next;
 5324:                 }
 5325:             }
 5326:         }
 5327:         if ($hidepriv) {
 5328:             my @privroles = ('dc','su');
 5329:             if ($context eq 'userroles') {
 5330:                 next if (grep(/^\Q$role\E$/,@privroles));
 5331:             } else {
 5332:                 my $possdoms = [$domain];
 5333:                 if (ref($roledoms) eq 'ARRAY') {
 5334:                    push(@{$possdoms},@{$roledoms}); 
 5335:                 }
 5336:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5337:                     if (!$nothide{$username.':'.$domain}) {
 5338:                         next;
 5339:                     }
 5340:                 }
 5341:             }
 5342:         }
 5343:         if ($withsec) {
 5344:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5345:                 $tstart.':'.$tend;
 5346:         } else {
 5347:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5348:         }
 5349:     }
 5350:     return %returnhash;
 5351: }
 5352: 
 5353: sub get_all_adhocroles {
 5354:     my ($dom) = @_;
 5355:     my @roles_by_num = ();
 5356:     my %domdefaults = &get_domain_defaults($dom);
 5357:     my (%description,%access_in_dom,%access_info);
 5358:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5359:         my $count = 0;
 5360:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5361:         my %ordered;
 5362:         foreach my $role (sort(keys(%domcurrent))) {
 5363:             my ($order,$desc,$access_in_dom);
 5364:             if (ref($domcurrent{$role}) eq 'HASH') {
 5365:                 $order = $domcurrent{$role}{'order'};
 5366:                 $desc = $domcurrent{$role}{'desc'};
 5367:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5368:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5369:             }
 5370:             if ($order eq '') {
 5371:                 $order = $count;
 5372:             }
 5373:             $ordered{$order} = $role;
 5374:             if ($desc ne '') {
 5375:                 $description{$role} = $desc;
 5376:             } else {
 5377:                 $description{$role}= $role;
 5378:             }
 5379:             $count++;
 5380:         }
 5381:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5382:             push(@roles_by_num,$ordered{$item});
 5383:         }
 5384:     }
 5385:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5386: }
 5387: 
 5388: sub get_my_adhocroles {
 5389:     my ($cid,$checkreg) = @_;
 5390:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5391:     if ($env{'request.course.id'} eq $cid) {
 5392:         $cdom = $env{'course.'.$cid.'.domain'};
 5393:         $cnum = $env{'course.'.$cid.'.num'};
 5394:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5395:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5396:         $cdom = $1;
 5397:         $cnum = $2;
 5398:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5399:                                      $cdom,$cnum);
 5400:     }
 5401:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5402:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5403:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5404:         if ($rosterhash{$user} ne '') {
 5405:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5406:             return ([],{}) if ($type eq 'auto');
 5407:         }
 5408:     }
 5409:     if (($cdom ne '') && ($cnum ne ''))  {
 5410:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5411:             my $then=$env{'user.login.time'};
 5412:             my $update=$env{'user.update.time'};
 5413:             if (!$update) {
 5414:                 $update = $then;
 5415:             }
 5416:             my @liveroles;
 5417:             foreach my $role ('dh','da') {
 5418:                 if ($env{"user.role.$role./$cdom/"}) {
 5419:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5420:                     my $limit = $update;
 5421:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5422:                         $limit = $then;
 5423:                     }
 5424:                     my $activerole = 1;
 5425:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5426:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5427:                     if ($activerole) {
 5428:                         push(@liveroles,$role);
 5429:                     }
 5430:                 }
 5431:             }
 5432:             if (@liveroles) {
 5433:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5434:                     my ($accessref,$accessinfo,%access_in_dom);
 5435:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5436:                     if (ref($roles_by_num) eq 'ARRAY') {
 5437:                         if (@{$roles_by_num}) {
 5438:                             my %settings;
 5439:                             if ($env{'request.course.id'} eq $cid) {
 5440:                                 foreach my $envkey (keys(%env)) {
 5441:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5442:                                         $settings{$1} = $env{$envkey};
 5443:                                     }
 5444:                                 }
 5445:                             } else {
 5446:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5447:                             }
 5448:                             my %setincrs;
 5449:                             if ($settings{'internal.adhocaccess'}) {
 5450:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5451:                             }
 5452:                             my @statuses;
 5453:                             if ($env{'environment.inststatus'}) {
 5454:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5455:                             }
 5456:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5457:                             if (ref($accessref) eq 'HASH') {
 5458:                                 %access_in_dom = %{$accessref};
 5459:                             }
 5460:                             foreach my $role (@{$roles_by_num}) {
 5461:                                 my ($curraccess,@okstatus,@personnel);
 5462:                                 if ($setincrs{$role}) {
 5463:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5464:                                     if ($curraccess eq 'status') {
 5465:                                         @okstatus = split(/\&/,$rest);
 5466:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5467:                                         @personnel = split(/\&/,$rest);
 5468:                                     }
 5469:                                 } else {
 5470:                                     $curraccess = $access_in_dom{$role};
 5471:                                     if (ref($accessinfo) eq 'HASH') {
 5472:                                         if ($curraccess eq 'status') {
 5473:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5474:                                                 @okstatus = @{$accessinfo->{$role}};
 5475:                                             }
 5476:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5477:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5478:                                                 @personnel = @{$accessinfo->{$role}};
 5479:                                             }
 5480:                                         }
 5481:                                     }
 5482:                                 }
 5483:                                 if ($curraccess eq 'none') {
 5484:                                     next;
 5485:                                 } elsif ($curraccess eq 'all') {
 5486:                                     push(@possroles,$role);
 5487:                                 } elsif ($curraccess eq 'dh') {
 5488:                                     if (grep(/^dh$/,@liveroles)) {
 5489:                                         push(@possroles,$role);
 5490:                                     } else {
 5491:                                         next;
 5492:                                     }
 5493:                                 } elsif ($curraccess eq 'da') {
 5494:                                     if (grep(/^da$/,@liveroles)) {
 5495:                                         push(@possroles,$role);
 5496:                                     } else {
 5497:                                         next;
 5498:                                     }
 5499:                                 } elsif ($curraccess eq 'status') {
 5500:                                     if (@okstatus) {
 5501:                                         if (!@statuses) {
 5502:                                             if (grep(/^default$/,@okstatus)) {
 5503:                                                 push(@possroles,$role);
 5504:                                             }
 5505:                                         } else {
 5506:                                             foreach my $status (@okstatus) {
 5507:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5508:                                                     push(@possroles,$role);
 5509:                                                     last;
 5510:                                                 }
 5511:                                             }
 5512:                                         }
 5513:                                     }
 5514:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5515:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5516:                                         if ($curraccess eq 'exc') {
 5517:                                             push(@possroles,$role);
 5518:                                         }
 5519:                                     } elsif ($curraccess eq 'inc') {
 5520:                                         push(@possroles,$role);
 5521:                                     }
 5522:                                 }
 5523:                             }
 5524:                         }
 5525:                     }
 5526:                 }
 5527:             }
 5528:         }
 5529:     }
 5530:     unless (ref($description) eq 'HASH') {
 5531:         if (ref($roles_by_num) eq 'ARRAY') {
 5532:             my %desc;
 5533:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5534:             $description = \%desc;
 5535:         } else {
 5536:             $description = {};
 5537:         }
 5538:     }
 5539:     return (\@possroles,$description);
 5540: }
 5541: 
 5542: # ----------------------------------------------------- Frontpage Announcements
 5543: #
 5544: #
 5545: 
 5546: sub postannounce {
 5547:     my ($server,$text)=@_;
 5548:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5549:     unless ($text=~/\w/) { $text=''; }
 5550:     return &reply('setannounce:'.&escape($text),$server);
 5551: }
 5552: 
 5553: sub getannounce {
 5554: 
 5555:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5556: 	my $announcement='';
 5557: 	while (my $line = <$fh>) { $announcement .= $line; }
 5558: 	close($fh);
 5559: 	if ($announcement=~/\w/) { 
 5560: 	    return 
 5561:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5562:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5563: 	} else {
 5564: 	    return '';
 5565: 	}
 5566:     } else {
 5567: 	return '';
 5568:     }
 5569: }
 5570: 
 5571: # ---------------------------------------------------------- Course ID routines
 5572: # Deal with domain's nohist_courseid.db files
 5573: #
 5574: 
 5575: sub courseidput {
 5576:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5577:     return unless (ref($storehash) eq 'HASH');
 5578:     my $outcome;
 5579:     if ($caller eq 'timeonly') {
 5580:         my $cids = '';
 5581:         foreach my $item (keys(%$storehash)) {
 5582:             $cids.=&escape($item).'&';
 5583:         }
 5584:         $cids=~s/\&$//;
 5585:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5586:                           $coursehome);       
 5587:     } else {
 5588:         my $items = '';
 5589:         foreach my $item (keys(%$storehash)) {
 5590:             $items.= &escape($item).'='.
 5591:                      &freeze_escape($$storehash{$item}).'&';
 5592:         }
 5593:         $items=~s/\&$//;
 5594:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5595:                           $coursehome);
 5596:     }
 5597:     if ($outcome eq 'unknown_cmd') {
 5598:         my $what;
 5599:         foreach my $cid (keys(%$storehash)) {
 5600:             $what .= &escape($cid).'=';
 5601:             foreach my $item ('description','inst_code','owner','type') {
 5602:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5603:             }
 5604:             $what =~ s/\:$/&/;
 5605:         }
 5606:         $what =~ s/\&$//;  
 5607:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5608:     } else {
 5609:         return $outcome;
 5610:     }
 5611: }
 5612: 
 5613: sub courseiddump {
 5614:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5615:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5616:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5617:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5618:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5619:     my $as_hash = 1;
 5620:     my %returnhash;
 5621:     if (!$domfilter) { $domfilter=''; }
 5622:     my %libserv = &all_library();
 5623:     foreach my $tryserver (keys(%libserv)) {
 5624:         if ( (  $hostidflag == 1 
 5625: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5626: 	     || (!defined($hostidflag)) ) {
 5627: 
 5628: 	    if (($domfilter eq '') ||
 5629: 		(&host_domain($tryserver) eq $domfilter)) {
 5630:                 my $rep;
 5631:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5632:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5633:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5634:                                 &escape($descfilter), &escape($instcodefilter), 
 5635:                                 &escape($ownerfilter), &escape($coursefilter),
 5636:                                 &escape($typefilter), &escape($regexp_ok), 
 5637:                                 $as_hash, &escape($selfenrollonly), 
 5638:                                 &escape($catfilter), $showhidden, $caller, 
 5639:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5640:                                 &escape($createdbefore), &escape($createdafter), 
 5641:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5642:                                 $reqcrsdom,&escape($reqinstcode))));
 5643:                 } else {
 5644:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5645:                              $sincefilter.':'.&escape($descfilter).':'.
 5646:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5647:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5648:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5649:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5650:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5651:                              &escape($cc_clone).':'.$cloneonly.':'.
 5652:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5653:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5654:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5655:                 }
 5656:                      
 5657:                 my @pairs=split(/\&/,$rep);
 5658:                 foreach my $item (@pairs) {
 5659:                     my ($key,$value)=split(/\=/,$item,2);
 5660:                     $key = &unescape($key);
 5661:                     next if ($key =~ /^error: 2 /);
 5662:                     my $result = &thaw_unescape($value);
 5663:                     if (ref($result) eq 'HASH') {
 5664:                         $returnhash{$key}=$result;
 5665:                     } else {
 5666:                         my @responses = split(/:/,$value);
 5667:                         my @items = ('description','inst_code','owner','type');
 5668:                         for (my $i=0; $i<@responses; $i++) {
 5669:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5670:                         }
 5671:                     }
 5672:                 }
 5673:             }
 5674:         }
 5675:     }
 5676:     return %returnhash;
 5677: }
 5678: 
 5679: sub courselastaccess {
 5680:     my ($cdom,$cnum,$hostidref) = @_;
 5681:     my %returnhash;
 5682:     if ($cdom && $cnum) {
 5683:         my $chome = &homeserver($cnum,$cdom);
 5684:         if ($chome ne 'no_host') {
 5685:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5686:             &extract_lastaccess(\%returnhash,$rep);
 5687:         }
 5688:     } else {
 5689:         if (!$cdom) { $cdom=''; }
 5690:         my %libserv = &all_library();
 5691:         foreach my $tryserver (keys(%libserv)) {
 5692:             if (ref($hostidref) eq 'ARRAY') {
 5693:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5694:             } 
 5695:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5696:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5697:                 &extract_lastaccess(\%returnhash,$rep);
 5698:             }
 5699:         }
 5700:     }
 5701:     return %returnhash;
 5702: }
 5703: 
 5704: sub extract_lastaccess {
 5705:     my ($returnhash,$rep) = @_;
 5706:     if (ref($returnhash) eq 'HASH') {
 5707:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5708:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5709:                  $rep eq '') {
 5710:             my @pairs=split(/\&/,$rep);
 5711:             foreach my $item (@pairs) {
 5712:                 my ($key,$value)=split(/\=/,$item,2);
 5713:                 $key = &unescape($key);
 5714:                 next if ($key =~ /^error: 2 /);
 5715:                 $returnhash->{$key} = &thaw_unescape($value);
 5716:             }
 5717:         }
 5718:     }
 5719:     return;
 5720: }
 5721: 
 5722: # ---------------------------------------------------------- DC e-mail
 5723: 
 5724: sub dcmailput {
 5725:     my ($domain,$msgid,$message,$server)=@_;
 5726:     my $status = &Apache::lonnet::critical(
 5727:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5728:        &escape($message),$server);
 5729:     return $status;
 5730: }
 5731: 
 5732: sub dcmaildump {
 5733:     my ($dom,$startdate,$enddate,$senders) = @_;
 5734:     my %returnhash=();
 5735: 
 5736:     if (defined(&domain($dom,'primary'))) {
 5737:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5738:                                                          &escape($enddate).':';
 5739: 	my @esc_senders=map { &escape($_)} @$senders;
 5740: 	$cmd.=&escape(join('&',@esc_senders));
 5741: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5742:             my ($key,$value) = split(/\=/,$line,2);
 5743:             if (($key) && ($value)) {
 5744:                 $returnhash{&unescape($key)} = &unescape($value);
 5745:             }
 5746:         }
 5747:     }
 5748:     return %returnhash;
 5749: }
 5750: # ---------------------------------------------------------- Domain roles
 5751: 
 5752: sub get_domain_roles {
 5753:     my ($dom,$roles,$startdate,$enddate)=@_;
 5754:     if ((!defined($startdate)) || ($startdate eq '')) {
 5755:         $startdate = '.';
 5756:     }
 5757:     if ((!defined($enddate)) || ($enddate eq '')) {
 5758:         $enddate = '.';
 5759:     }
 5760:     my $rolelist;
 5761:     if (ref($roles) eq 'ARRAY') {
 5762:         $rolelist = join('&',@{$roles});
 5763:     }
 5764:     my %personnel = ();
 5765: 
 5766:     my %servers = &get_servers($dom,'library');
 5767:     foreach my $tryserver (keys(%servers)) {
 5768: 	%{$personnel{$tryserver}}=();
 5769: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5770: 					    &escape($startdate).':'.
 5771: 					    &escape($enddate).':'.
 5772: 					    &escape($rolelist), $tryserver))) {
 5773: 	    my ($key,$value) = split(/\=/,$line,2);
 5774: 	    if (($key) && ($value)) {
 5775: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5776: 	    }
 5777: 	}
 5778:     }
 5779:     return %personnel;
 5780: }
 5781: 
 5782: sub get_active_domroles {
 5783:     my ($dom,$roles) = @_;
 5784:     return () unless (ref($roles) eq 'ARRAY');
 5785:     my $now = time;
 5786:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5787:     my %domroles;
 5788:     foreach my $server (keys(%dompersonnel)) {
 5789:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5790:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5791:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5792:         }
 5793:     }
 5794:     return %domroles;
 5795: }
 5796: 
 5797: # ----------------------------------------------------------- Interval timing 
 5798: 
 5799: {
 5800: # Caches needed for speedup of navmaps
 5801: # We don't want to cache this for very long at all (5 seconds at most)
 5802: # 
 5803: # The user for whom we cache
 5804: my $cachedkey='';
 5805: # The cached times for this user
 5806: my %cachedtimes=();
 5807: # When this was last done
 5808: my $cachedtime='';
 5809: 
 5810: sub load_all_first_access {
 5811:     my ($uname,$udom,$ignorecache)=@_;
 5812:     if (($cachedkey eq $uname.':'.$udom) &&
 5813:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5814:         (!$ignorecache)) {
 5815:         return;
 5816:     }
 5817:     $cachedtime=time;
 5818:     $cachedkey=$uname.':'.$udom;
 5819:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5820: }
 5821: 
 5822: sub get_first_access {
 5823:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5824:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5825:     if ($argsymb) { $symb=$argsymb; }
 5826:     my ($map,$id,$res)=&decode_symb($symb);
 5827:     if ($argmap) { $map = $argmap; }
 5828:     if ($type eq 'course') {
 5829: 	$res='course';
 5830:     } elsif ($type eq 'map') {
 5831: 	$res=&symbread($map);
 5832:     } else {
 5833: 	$res=$symb;
 5834:     }
 5835:     &load_all_first_access($uname,$udom,$ignorecache);
 5836:     return $cachedtimes{"$courseid\0$res"};
 5837: }
 5838: 
 5839: sub set_first_access {
 5840:     my ($type,$interval)=@_;
 5841:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5842:     my ($map,$id,$res)=&decode_symb($symb);
 5843:     if ($type eq 'course') {
 5844: 	$res='course';
 5845:     } elsif ($type eq 'map') {
 5846: 	$res=&symbread($map);
 5847:     } else {
 5848: 	$res=$symb;
 5849:     }
 5850:     $cachedkey='';
 5851:     my $firstaccess=&get_first_access($type,$symb,$map);
 5852:     if ($firstaccess) {
 5853:         &logthis("First access time already set ($firstaccess) when attempting ".
 5854:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5855:                  "in $courseid");
 5856:         return 'already_set';
 5857:     } else {
 5858:         my $start = time;
 5859: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5860:                           $udom,$uname);
 5861:         if ($putres eq 'ok') {
 5862:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5863:                  $udom,$uname); 
 5864:             &appenv(
 5865:                      {
 5866:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5867:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5868:                      }
 5869:                   );
 5870:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5871:                 $cachedtimes{"$courseid\0$res"} = $start;
 5872:             }
 5873:         } elsif ($putres ne 'refused') {
 5874:             &logthis("Result: $putres when attempting to set first access time ".
 5875:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5876:         }
 5877:         return $putres;
 5878:     }
 5879:     return 'already_set';
 5880: }
 5881: }
 5882: 
 5883: # --------------------------------------------- Set Expire Date for Spreadsheet
 5884: 
 5885: sub expirespread {
 5886:     my ($uname,$udom,$stype,$usymb)=@_;
 5887:     my $cid=$env{'request.course.id'}; 
 5888:     if ($cid) {
 5889:        my $now=time;
 5890:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5891:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5892:                             $env{'course.'.$cid.'.num'}.
 5893: 	        	    ':nohist_expirationdates:'.
 5894:                             &escape($key).'='.$now,
 5895:                             $env{'course.'.$cid.'.home'})
 5896:     }
 5897:     return 'ok';
 5898: }
 5899: 
 5900: # ----------------------------------------------------- Devalidate Spreadsheets
 5901: 
 5902: sub devalidate {
 5903:     my ($symb,$uname,$udom)=@_;
 5904:     my $cid=$env{'request.course.id'}; 
 5905:     if ($cid) {
 5906:         # delete the stored spreadsheets for
 5907:         # - the student level sheet of this user in course's homespace
 5908:         # - the assessment level sheet for this resource 
 5909:         #   for this user in user's homespace
 5910: 	# - current conditional state info
 5911: 	my $key=$uname.':'.$udom.':';
 5912:         my $status=
 5913: 	    &del('nohist_calculatedsheets',
 5914: 		 [$key.'studentcalc:'],
 5915: 		 $env{'course.'.$cid.'.domain'},
 5916: 		 $env{'course.'.$cid.'.num'})
 5917: 		.' '.
 5918: 	    &del('nohist_calculatedsheets_'.$cid,
 5919: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5920:         unless ($status eq 'ok ok') {
 5921:            &logthis('Could not devalidate spreadsheet '.
 5922:                     $uname.' at '.$udom.' for '.
 5923: 		    $symb.': '.$status);
 5924:         }
 5925: 	&delenv('user.state.'.$cid);
 5926:     }
 5927: }
 5928: 
 5929: sub get_scalar {
 5930:     my ($string,$end) = @_;
 5931:     my $value;
 5932:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5933: 	$value = $1;
 5934:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5935: 	$value = $1;
 5936:     }
 5937:     return &unescape($value);
 5938: }
 5939: 
 5940: sub array2str {
 5941:   my (@array) = @_;
 5942:   my $result=&arrayref2str(\@array);
 5943:   $result=~s/^__ARRAY_REF__//;
 5944:   $result=~s/__END_ARRAY_REF__$//;
 5945:   return $result;
 5946: }
 5947: 
 5948: sub arrayref2str {
 5949:   my ($arrayref) = @_;
 5950:   my $result='__ARRAY_REF__';
 5951:   foreach my $elem (@$arrayref) {
 5952:     if(ref($elem) eq 'ARRAY') {
 5953:       $result.=&arrayref2str($elem).'&';
 5954:     } elsif(ref($elem) eq 'HASH') {
 5955:       $result.=&hashref2str($elem).'&';
 5956:     } elsif(ref($elem)) {
 5957:       #print("Got a ref of ".(ref($elem))." skipping.");
 5958:     } else {
 5959:       $result.=&escape($elem).'&';
 5960:     }
 5961:   }
 5962:   $result=~s/\&$//;
 5963:   $result .= '__END_ARRAY_REF__';
 5964:   return $result;
 5965: }
 5966: 
 5967: sub hash2str {
 5968:   my (%hash) = @_;
 5969:   my $result=&hashref2str(\%hash);
 5970:   $result=~s/^__HASH_REF__//;
 5971:   $result=~s/__END_HASH_REF__$//;
 5972:   return $result;
 5973: }
 5974: 
 5975: sub hashref2str {
 5976:   my ($hashref)=@_;
 5977:   my $result='__HASH_REF__';
 5978:   foreach my $key (sort(keys(%$hashref))) {
 5979:     if (ref($key) eq 'ARRAY') {
 5980:       $result.=&arrayref2str($key).'=';
 5981:     } elsif (ref($key) eq 'HASH') {
 5982:       $result.=&hashref2str($key).'=';
 5983:     } elsif (ref($key)) {
 5984:       $result.='=';
 5985:       #print("Got a ref of ".(ref($key))." skipping.");
 5986:     } else {
 5987: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5988:     }
 5989: 
 5990:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5991:       $result.=&arrayref2str($hashref->{$key}).'&';
 5992:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5993:       $result.=&hashref2str($hashref->{$key}).'&';
 5994:     } elsif(ref($hashref->{$key})) {
 5995:        $result.='&';
 5996:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5997:     } else {
 5998:       $result.=&escape($hashref->{$key}).'&';
 5999:     }
 6000:   }
 6001:   $result=~s/\&$//;
 6002:   $result .= '__END_HASH_REF__';
 6003:   return $result;
 6004: }
 6005: 
 6006: sub str2hash {
 6007:     my ($string)=@_;
 6008:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6009:     return %$hash;
 6010: }
 6011: 
 6012: sub str2hashref {
 6013:   my ($string) = @_;
 6014: 
 6015:   my %hash;
 6016: 
 6017:   if($string !~ /^__HASH_REF__/) {
 6018:       if (! ($string eq '' || !defined($string))) {
 6019: 	  $hash{'error'}='Not hash reference';
 6020:       }
 6021:       return (\%hash, $string);
 6022:   }
 6023: 
 6024:   $string =~ s/^__HASH_REF__//;
 6025: 
 6026:   while($string !~ /^__END_HASH_REF__/) {
 6027:       #key
 6028:       my $key='';
 6029:       if($string =~ /^__HASH_REF__/) {
 6030:           ($key, $string)=&str2hashref($string);
 6031:           if(defined($key->{'error'})) {
 6032:               $hash{'error'}='Bad data';
 6033:               return (\%hash, $string);
 6034:           }
 6035:       } elsif($string =~ /^__ARRAY_REF__/) {
 6036:           ($key, $string)=&str2arrayref($string);
 6037:           if($key->[0] eq 'Array reference error') {
 6038:               $hash{'error'}='Bad data';
 6039:               return (\%hash, $string);
 6040:           }
 6041:       } else {
 6042:           $string =~ s/^(.*?)=//;
 6043: 	  $key=&unescape($1);
 6044:       }
 6045:       $string =~ s/^=//;
 6046: 
 6047:       #value
 6048:       my $value='';
 6049:       if($string =~ /^__HASH_REF__/) {
 6050:           ($value, $string)=&str2hashref($string);
 6051:           if(defined($value->{'error'})) {
 6052:               $hash{'error'}='Bad data';
 6053:               return (\%hash, $string);
 6054:           }
 6055:       } elsif($string =~ /^__ARRAY_REF__/) {
 6056:           ($value, $string)=&str2arrayref($string);
 6057:           if($value->[0] eq 'Array reference error') {
 6058:               $hash{'error'}='Bad data';
 6059:               return (\%hash, $string);
 6060:           }
 6061:       } else {
 6062: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6063:       }
 6064:       $string =~ s/^&//;
 6065: 
 6066:       $hash{$key}=$value;
 6067:   }
 6068: 
 6069:   $string =~ s/^__END_HASH_REF__//;
 6070: 
 6071:   return (\%hash, $string);
 6072: }
 6073: 
 6074: sub str2array {
 6075:     my ($string)=@_;
 6076:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6077:     return @$array;
 6078: }
 6079: 
 6080: sub str2arrayref {
 6081:   my ($string) = @_;
 6082:   my @array;
 6083: 
 6084:   if($string !~ /^__ARRAY_REF__/) {
 6085:       if (! ($string eq '' || !defined($string))) {
 6086: 	  $array[0]='Array reference error';
 6087:       }
 6088:       return (\@array, $string);
 6089:   }
 6090: 
 6091:   $string =~ s/^__ARRAY_REF__//;
 6092: 
 6093:   while($string !~ /^__END_ARRAY_REF__/) {
 6094:       my $value='';
 6095:       if($string =~ /^__HASH_REF__/) {
 6096:           ($value, $string)=&str2hashref($string);
 6097:           if(defined($value->{'error'})) {
 6098:               $array[0] ='Array reference error';
 6099:               return (\@array, $string);
 6100:           }
 6101:       } elsif($string =~ /^__ARRAY_REF__/) {
 6102:           ($value, $string)=&str2arrayref($string);
 6103:           if($value->[0] eq 'Array reference error') {
 6104:               $array[0] ='Array reference error';
 6105:               return (\@array, $string);
 6106:           }
 6107:       } else {
 6108: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6109:       }
 6110:       $string =~ s/^&//;
 6111: 
 6112:       push(@array, $value);
 6113:   }
 6114: 
 6115:   $string =~ s/^__END_ARRAY_REF__//;
 6116: 
 6117:   return (\@array, $string);
 6118: }
 6119: 
 6120: # -------------------------------------------------------------------Temp Store
 6121: 
 6122: sub tmpreset {
 6123:   my ($symb,$namespace,$domain,$stuname) = @_;
 6124:   if (!$symb) {
 6125:     $symb=&symbread();
 6126:     if (!$symb) { $symb= $env{'request.url'}; }
 6127:   }
 6128:   $symb=escape($symb);
 6129: 
 6130:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6131:   $namespace=~s/\//\_/g;
 6132:   $namespace=~s/\W//g;
 6133: 
 6134:   if (!$domain) { $domain=$env{'user.domain'}; }
 6135:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6136:   if ($domain eq 'public' && $stuname eq 'public') {
 6137:       $stuname=&get_requestor_ip();
 6138:   }
 6139:   my $path=LONCAPA::tempdir();
 6140:   my %hash;
 6141:   if (tie(%hash,'GDBM_File',
 6142: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6143: 	  &GDBM_WRCREAT(),0640)) {
 6144:     foreach my $key (keys(%hash)) {
 6145:       if ($key=~ /:$symb/) {
 6146: 	delete($hash{$key});
 6147:       }
 6148:     }
 6149:   }
 6150: }
 6151: 
 6152: sub tmpstore {
 6153:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6154: 
 6155:   if (!$symb) {
 6156:     $symb=&symbread();
 6157:     if (!$symb) { $symb= $env{'request.url'}; }
 6158:   }
 6159:   $symb=escape($symb);
 6160: 
 6161:   if (!$namespace) {
 6162:     # I don't think we would ever want to store this for a course.
 6163:     # it seems this will only be used if we don't have a course.
 6164:     #$namespace=$env{'request.course.id'};
 6165:     #if (!$namespace) {
 6166:       $namespace=$env{'request.state'};
 6167:     #}
 6168:   }
 6169:   $namespace=~s/\//\_/g;
 6170:   $namespace=~s/\W//g;
 6171:   if (!$domain) { $domain=$env{'user.domain'}; }
 6172:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6173:   if ($domain eq 'public' && $stuname eq 'public') {
 6174:       $stuname=&get_requestor_ip();
 6175:   }
 6176:   my $now=time;
 6177:   my %hash;
 6178:   my $path=LONCAPA::tempdir();
 6179:   if (tie(%hash,'GDBM_File',
 6180: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6181: 	  &GDBM_WRCREAT(),0640)) {
 6182:     $hash{"version:$symb"}++;
 6183:     my $version=$hash{"version:$symb"};
 6184:     my $allkeys=''; 
 6185:     foreach my $key (keys(%$storehash)) {
 6186:       $allkeys.=$key.':';
 6187:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6188:     }
 6189:     $hash{"$version:$symb:timestamp"}=$now;
 6190:     $allkeys.='timestamp';
 6191:     $hash{"$version:keys:$symb"}=$allkeys;
 6192:     if (untie(%hash)) {
 6193:       return 'ok';
 6194:     } else {
 6195:       return "error:$!";
 6196:     }
 6197:   } else {
 6198:     return "error:$!";
 6199:   }
 6200: }
 6201: 
 6202: # -----------------------------------------------------------------Temp Restore
 6203: 
 6204: sub tmprestore {
 6205:   my ($symb,$namespace,$domain,$stuname) = @_;
 6206: 
 6207:   if (!$symb) {
 6208:     $symb=&symbread();
 6209:     if (!$symb) { $symb= $env{'request.url'}; }
 6210:   }
 6211:   $symb=escape($symb);
 6212: 
 6213:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6214: 
 6215:   if (!$domain) { $domain=$env{'user.domain'}; }
 6216:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6217:   if ($domain eq 'public' && $stuname eq 'public') {
 6218:       $stuname=&get_requestor_ip();
 6219:   }
 6220:   my %returnhash;
 6221:   $namespace=~s/\//\_/g;
 6222:   $namespace=~s/\W//g;
 6223:   my %hash;
 6224:   my $path=LONCAPA::tempdir();
 6225:   if (tie(%hash,'GDBM_File',
 6226: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6227: 	  &GDBM_READER(),0640)) {
 6228:     my $version=$hash{"version:$symb"};
 6229:     $returnhash{'version'}=$version;
 6230:     my $scope;
 6231:     for ($scope=1;$scope<=$version;$scope++) {
 6232:       my $vkeys=$hash{"$scope:keys:$symb"};
 6233:       my @keys=split(/:/,$vkeys);
 6234:       my $key;
 6235:       $returnhash{"$scope:keys"}=$vkeys;
 6236:       foreach $key (@keys) {
 6237: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6238: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6239:       }
 6240:     }
 6241:     if (!(untie(%hash))) {
 6242:       return "error:$!";
 6243:     }
 6244:   } else {
 6245:     return "error:$!";
 6246:   }
 6247:   return %returnhash;
 6248: }
 6249: 
 6250: # ----------------------------------------------------------------------- Store
 6251: 
 6252: sub store {
 6253:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6254:     my $home='';
 6255: 
 6256:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6257: 
 6258:     $symb=&symbclean($symb);
 6259:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6260: 
 6261:     if (!$domain) { $domain=$env{'user.domain'}; }
 6262:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6263: 
 6264:     &devalidate($symb,$stuname,$domain);
 6265: 
 6266:     $symb=escape($symb);
 6267:     if (!$namespace) { 
 6268:        unless ($namespace=$env{'request.course.id'}) { 
 6269:           return ''; 
 6270:        } 
 6271:     }
 6272:     if (!$home) { $home=$env{'user.home'}; }
 6273: 
 6274:     $$storehash{'ip'}=&get_requestor_ip();
 6275:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6276: 
 6277:     my $namevalue='';
 6278:     foreach my $key (keys(%$storehash)) {
 6279:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6280:     }
 6281:     $namevalue=~s/\&$//;
 6282:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6283:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6284: }
 6285: 
 6286: # -------------------------------------------------------------- Critical Store
 6287: 
 6288: sub cstore {
 6289:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6290:     my $home='';
 6291: 
 6292:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6293: 
 6294:     $symb=&symbclean($symb);
 6295:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6296: 
 6297:     if (!$domain) { $domain=$env{'user.domain'}; }
 6298:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6299: 
 6300:     &devalidate($symb,$stuname,$domain);
 6301: 
 6302:     $symb=escape($symb);
 6303:     if (!$namespace) { 
 6304:        unless ($namespace=$env{'request.course.id'}) { 
 6305:           return ''; 
 6306:        } 
 6307:     }
 6308:     if (!$home) { $home=$env{'user.home'}; }
 6309: 
 6310:     $$storehash{'ip'}=&get_requestor_ip();
 6311:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6312: 
 6313:     my $namevalue='';
 6314:     foreach my $key (keys(%$storehash)) {
 6315:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6316:     }
 6317:     $namevalue=~s/\&$//;
 6318:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6319:     return critical
 6320:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6321: }
 6322: 
 6323: # --------------------------------------------------------------------- Restore
 6324: 
 6325: sub restore {
 6326:     my ($symb,$namespace,$domain,$stuname) = @_;
 6327:     my $home='';
 6328: 
 6329:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6330: 
 6331:     if (!$symb) {
 6332:         return if ($namespace eq 'courserequests');
 6333:         unless ($symb=escape(&symbread())) { return ''; }
 6334:     } else {
 6335:         unless ($namespace eq 'courserequests') {
 6336:             $symb=&escape(&symbclean($symb));
 6337:         }
 6338:     }
 6339:     if (!$namespace) { 
 6340:        unless ($namespace=$env{'request.course.id'}) { 
 6341:           return ''; 
 6342:        } 
 6343:     }
 6344:     if (!$domain) { $domain=$env{'user.domain'}; }
 6345:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6346:     if (!$home) { $home=$env{'user.home'}; }
 6347:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6348: 
 6349:     my %returnhash=();
 6350:     foreach my $line (split(/\&/,$answer)) {
 6351: 	my ($name,$value)=split(/\=/,$line);
 6352:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6353:     }
 6354:     my $version;
 6355:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6356:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6357:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6358:        }
 6359:     }
 6360:     return %returnhash;
 6361: }
 6362: 
 6363: # ---------------------------------------------------------- Course Description
 6364: #
 6365: #  
 6366: 
 6367: sub coursedescription {
 6368:     my ($courseid,$args)=@_;
 6369:     $courseid=~s/^\///;
 6370:     $courseid=~s/\_/\//g;
 6371:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6372:     my $chome=&homeserver($cnum,$cdomain);
 6373:     my $normalid=$cdomain.'_'.$cnum;
 6374:     # need to always cache even if we get errors otherwise we keep 
 6375:     # trying and trying and trying to get the course description.
 6376:     my %envhash=();
 6377:     my %returnhash=();
 6378:     
 6379:     my $expiretime=600;
 6380:     if ($env{'request.course.id'} eq $normalid) {
 6381: 	$expiretime=120;
 6382:     }
 6383: 
 6384:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6385:     if (!$args->{'freshen_cache'}
 6386: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6387: 	foreach my $key (keys(%env)) {
 6388: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6389: 	    my ($setting) = $1;
 6390: 	    $returnhash{$setting} = $env{$key};
 6391: 	}
 6392: 	return %returnhash;
 6393:     }
 6394: 
 6395:     # get the data again
 6396: 
 6397:     if (!$args->{'one_time'}) {
 6398: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6399:     }
 6400: 
 6401:     if ($chome ne 'no_host') {
 6402:        %returnhash=&dump('environment',$cdomain,$cnum);
 6403:        if (!exists($returnhash{'con_lost'})) {
 6404: 	   my $username = $env{'user.name'}; # Defult username
 6405: 	   if(defined $args->{'user'}) {
 6406: 	       $username = $args->{'user'};
 6407: 	   }
 6408:            $returnhash{'home'}= $chome;
 6409: 	   $returnhash{'domain'} = $cdomain;
 6410: 	   $returnhash{'num'} = $cnum;
 6411:            if (!defined($returnhash{'type'})) {
 6412:                $returnhash{'type'} = 'Course';
 6413:            }
 6414:            while (my ($name,$value) = each %returnhash) {
 6415:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6416:            }
 6417:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6418:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6419: 	       $username.'_'.$cdomain.'_'.$cnum;
 6420:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6421:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6422:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6423:        }
 6424:     }
 6425:     if (!$args->{'one_time'}) {
 6426: 	&appenv(\%envhash);
 6427:     }
 6428:     return %returnhash;
 6429: }
 6430: 
 6431: sub update_released_required {
 6432:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6433:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6434:         $cid = $env{'request.course.id'};
 6435:         $cdom = $env{'course.'.$cid.'.domain'};
 6436:         $cnum = $env{'course.'.$cid.'.num'};
 6437:         $chome = $env{'course.'.$cid.'.home'};
 6438:     }
 6439:     if ($needsrelease) {
 6440:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6441:         my $needsupdate;
 6442:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6443:             $needsupdate = 1;
 6444:         } else {
 6445:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6446:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6447:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6448:                 $needsupdate = 1;
 6449:             }
 6450:         }
 6451:         if ($needsupdate) {
 6452:             my %needshash = (
 6453:                              'internal.releaserequired' => $needsrelease,
 6454:                             );
 6455:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6456:             if ($putresult eq 'ok') {
 6457:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6458:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6459:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6460:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6461:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6462:                 }
 6463:             }
 6464:         }
 6465:     }
 6466:     return;
 6467: }
 6468: 
 6469: # -------------------------------------------------See if a user is privileged
 6470: 
 6471: sub privileged {
 6472:     my ($username,$domain,$possdomains,$possroles)=@_;
 6473:     my $now = time;
 6474:     my $roles;
 6475:     if (ref($possroles) eq 'ARRAY') {
 6476:         $roles = $possroles; 
 6477:     } else {
 6478:         $roles = ['dc','su'];
 6479:     }
 6480:     if (ref($possdomains) eq 'ARRAY') {
 6481:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6482:         foreach my $dom (@{$possdomains}) {
 6483:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6484:                 (ref($privileged{$dom}) eq 'HASH')) {
 6485:                 foreach my $role (@{$roles}) {
 6486:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6487:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6488:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6489:                             return 1 unless (($end && $end < $now) ||
 6490:                                              ($start && $start > $now));
 6491:                         }
 6492:                     }
 6493:                 }
 6494:             }
 6495:         }
 6496:     } else {
 6497:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6498:         my $now = time;
 6499: 
 6500:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6501:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6502:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6503:                 return 1 unless ($tend && $tend < $now) 
 6504:                         or ($tstart && $tstart > $now);
 6505:             }
 6506:         }
 6507:     }
 6508:     return 0;
 6509: }
 6510: 
 6511: sub privileged_by_domain {
 6512:     my ($domains,$roles) = @_;
 6513:     my %privileged = ();
 6514:     my $cachetime = 60*60*24;
 6515:     my $now = time;
 6516:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6517:         return %privileged;
 6518:     }
 6519:     foreach my $dom (@{$domains}) {
 6520:         next if (ref($privileged{$dom}) eq 'HASH');
 6521:         my $needroles;
 6522:         foreach my $role (@{$roles}) {
 6523:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6524:             if (defined($cached)) {
 6525:                 if (ref($result) eq 'HASH') {
 6526:                     $privileged{$dom}{$role} = $result;
 6527:                 }
 6528:             } else {
 6529:                 $needroles = 1;
 6530:             }
 6531:         }
 6532:         if ($needroles) {
 6533:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6534:             $privileged{$dom} = {};
 6535:             foreach my $server (keys(%dompersonnel)) {
 6536:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6537:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6538:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6539:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6540:                         next if ($end && $end < $now);
 6541:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6542:                             $dompersonnel{$server}{$item};
 6543:                     }
 6544:                 }
 6545:             }
 6546:             if (ref($privileged{$dom}) eq 'HASH') {
 6547:                 foreach my $role (@{$roles}) {
 6548:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6549:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6550:                     } else {
 6551:                         my %hash = ();
 6552:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6553:                     }
 6554:                 }
 6555:             }
 6556:         }
 6557:     }
 6558:     return %privileged;
 6559: }
 6560: 
 6561: # -------------------------------------------------------- Get user privileges
 6562: 
 6563: sub rolesinit {
 6564:     my ($domain, $username) = @_;
 6565:     my %userroles = ('user.login.time' => time);
 6566:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6567: 
 6568:     # firstaccess and timerinterval are related to timed maps/resources. 
 6569:     # also, blocking can be triggered by an activating timer
 6570:     # it's saved in the user's %env.
 6571:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6572:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6573:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6574:         %timerintchk, %timerintenv);
 6575: 
 6576:     foreach my $key (keys(%firstaccess)) {
 6577:         my ($cid, $rest) = split(/\0/, $key);
 6578:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6579:     }
 6580: 
 6581:     foreach my $key (keys(%timerinterval)) {
 6582:         my ($cid,$rest) = split(/\0/,$key);
 6583:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6584:     }
 6585: 
 6586:     my %allroles=();
 6587:     my %allgroups=();
 6588: 
 6589:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6590:         my $role = $rolesdump{$area};
 6591:         $area =~ s/\_\w\w$//;
 6592: 
 6593:         my ($trole, $tend, $tstart, $group_privs);
 6594: 
 6595:         if ($role =~ /^cr/) {
 6596:         # Custom role, defined by a user 
 6597:         # e.g., user.role.cr/msu/smith/mynewrole
 6598:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6599:                 $trole = $1;
 6600:                 ($tend, $tstart) = split('_', $2);
 6601:             } else {
 6602:                 $trole = $role;
 6603:             }
 6604:         } elsif ($role =~ m|^gr/|) {
 6605:         # Role of member in a group, defined within a course/community
 6606:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6607:             ($trole, $tend, $tstart) = split(/_/, $role);
 6608:             next if $tstart eq '-1';
 6609:             ($trole, $group_privs) = split(/\//, $trole);
 6610:             $group_privs = &unescape($group_privs);
 6611:         } else {
 6612:         # Just a normal role, defined in roles.tab
 6613:             ($trole, $tend, $tstart) = split(/_/,$role);
 6614:         }
 6615: 
 6616:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6617:                  $username);
 6618:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6619: 
 6620:         # role expired or not available yet?
 6621:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6622:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6623: 
 6624:         next if $area eq '' or $trole eq '';
 6625: 
 6626:         my $spec = "$trole.$area";
 6627:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6628: 
 6629:         if ($trole =~ /^cr\//) {
 6630:         # Custom role, defined by a user
 6631:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6632:         } elsif ($trole eq 'gr') {
 6633:         # Role of a member in a group, defined within a course/community
 6634:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6635:             next;
 6636:         } else {
 6637:         # Normal role, defined in roles.tab
 6638:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6639:         }
 6640: 
 6641:         my $cid = $tdomain.'_'.$trest;
 6642:         unless ($firstaccchk{$cid}) {
 6643:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6644:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6645:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6646:                         $coursetimerstarts{$cid}{$item}; 
 6647:                 }
 6648:             }
 6649:             $firstaccchk{$cid} = 1;
 6650:         }
 6651:         unless ($timerintchk{$cid}) {
 6652:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6653:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6654:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6655:                        $coursetimerintervals{$cid}{$item};
 6656:                 }
 6657:             }
 6658:             $timerintchk{$cid} = 1;
 6659:         }
 6660:     }
 6661: 
 6662:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6663:                                                           \%allroles, \%allgroups);
 6664:     $env{'user.adv'} = $userroles{'user.adv'};
 6665:     $env{'user.rar'} = $userroles{'user.rar'};
 6666: 
 6667:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6668: }
 6669: 
 6670: sub set_arearole {
 6671:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6672:     unless ($nolog) {
 6673: # log the associated role with the area
 6674:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6675:     }
 6676:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6677: }
 6678: 
 6679: sub custom_roleprivs {
 6680:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6681:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6682:     my $homsvr = &homeserver($rauthor,$rdomain);
 6683:     if (&hostname($homsvr) ne '') {
 6684:         my ($rdummy,$roledef)=
 6685:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6686:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6687:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6688:             if (defined($syspriv)) {
 6689:                 if ($trest =~ /^$match_community$/) {
 6690:                     $syspriv =~ s/bre\&S//; 
 6691:                 }
 6692:                 $$allroles{'cm./'}.=':'.$syspriv;
 6693:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6694:             }
 6695:             if ($tdomain ne '') {
 6696:                 if (defined($dompriv)) {
 6697:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6698:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6699:                 }
 6700:                 if (($trest ne '') && (defined($coursepriv))) {
 6701:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6702:                         my $rolename = $1;
 6703:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6704:                     }
 6705:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6706:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6707:                 }
 6708:             }
 6709:         }
 6710:     }
 6711: }
 6712: 
 6713: sub course_adhocrole_privs {
 6714:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6715:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6716:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6717:         my (%currprivs,%storeprivs);
 6718:         foreach my $item (split(/:/,$coursepriv)) {
 6719:             my ($priv,$restrict) = split(/\&/,$item);
 6720:             $currprivs{$priv} = $restrict;
 6721:         }
 6722:         my (%possadd,%possremove,%full);
 6723:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6724:             my ($priv,$restrict)=split(/\&/,$item);
 6725:             $full{$priv} = $restrict;
 6726:         }
 6727:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6728:              next if ($item eq '');
 6729:              my ($rule,$rest) = split(/=/,$item);
 6730:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6731:              foreach my $priv (split(/:/,$rest)) {
 6732:                  if ($priv ne '') {
 6733:                      if ($rule eq 'off') {
 6734:                          $possremove{$priv} = 1;
 6735:                      } else {
 6736:                          $possadd{$priv} = 1;
 6737:                      }
 6738:                  }
 6739:              }
 6740:          }
 6741:          foreach my $priv (sort(keys(%full))) {
 6742:              if (exists($currprivs{$priv})) {
 6743:                  unless (exists($possremove{$priv})) {
 6744:                      $storeprivs{$priv} = $currprivs{$priv};
 6745:                  }
 6746:              } elsif (exists($possadd{$priv})) {
 6747:                  $storeprivs{$priv} = $full{$priv};
 6748:              }
 6749:          }
 6750:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6751:      }
 6752:      return $coursepriv;
 6753: }
 6754: 
 6755: sub group_roleprivs {
 6756:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6757:     my $access = 1;
 6758:     my $now = time;
 6759:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6760:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6761:     if ($access) {
 6762:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6763:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6764:     }
 6765: }
 6766: 
 6767: sub standard_roleprivs {
 6768:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6769:     if (defined($pr{$trole.':s'})) {
 6770:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6771:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6772:     }
 6773:     if ($tdomain ne '') {
 6774:         if (defined($pr{$trole.':d'})) {
 6775:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6776:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6777:         }
 6778:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6779:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6780:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6781:         }
 6782:     }
 6783: }
 6784: 
 6785: sub set_userprivs {
 6786:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6787:     my $author=0;
 6788:     my $adv=0;
 6789:     my $rar=0;
 6790:     my %grouproles = ();
 6791:     if (keys(%{$allgroups}) > 0) {
 6792:         my @groupkeys; 
 6793:         foreach my $role (keys(%{$allroles})) {
 6794:             push(@groupkeys,$role);
 6795:         }
 6796:         if (ref($groups_roles) eq 'HASH') {
 6797:             foreach my $key (keys(%{$groups_roles})) {
 6798:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6799:                     push(@groupkeys,$key);
 6800:                 }
 6801:             }
 6802:         }
 6803:         if (@groupkeys > 0) {
 6804:             foreach my $role (@groupkeys) {
 6805:                 my ($trole,$area,$sec,$extendedarea);
 6806:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6807:                     $trole = $1;
 6808:                     $area = $2;
 6809:                     $sec = $3;
 6810:                     $extendedarea = $area.$sec;
 6811:                     if (exists($$allgroups{$area})) {
 6812:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6813:                             my $spec = $trole.'.'.$extendedarea;
 6814:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6815:                                                 $$allgroups{$area}{$group};
 6816:                         }
 6817:                     }
 6818:                 }
 6819:             }
 6820:         }
 6821:     }
 6822:     foreach my $group (keys(%grouproles)) {
 6823:         $$allroles{$group} = $grouproles{$group};
 6824:     }
 6825:     foreach my $role (keys(%{$allroles})) {
 6826:         my %thesepriv;
 6827:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6828:         foreach my $item (split(/:/,$$allroles{$role})) {
 6829:             if ($item ne '') {
 6830:                 my ($privilege,$restrictions)=split(/&/,$item);
 6831:                 if ($restrictions eq '') {
 6832:                     $thesepriv{$privilege}='F';
 6833:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6834:                     $thesepriv{$privilege}.=$restrictions;
 6835:                 }
 6836:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6837:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6838:             }
 6839:         }
 6840:         my $thesestr='';
 6841:         foreach my $priv (sort(keys(%thesepriv))) {
 6842: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6843: 	}
 6844:         $userroles->{'user.priv.'.$role} = $thesestr;
 6845:     }
 6846:     return ($author,$adv,$rar);
 6847: }
 6848: 
 6849: sub role_status {
 6850:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6851:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6852:         my ($one,$two) = split(m{\./},$rolekey,2);
 6853:         (undef,undef,$$role) = split(/\./,$one,3);
 6854:         unless (!defined($$role) || $$role eq '') {
 6855:             $$where = '/'.$two;
 6856:             $$trolecode=$$role.'.'.$$where;
 6857:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6858:             $$tstatus='is';
 6859:             if ($$tstart && $$tstart>$update) {
 6860:                 $$tstatus='future';
 6861:                 if ($$tstart<$now) {
 6862:                     if ($$tstart && $$tstart>$refresh) {
 6863:                         if (($$where ne '') && ($$role ne '')) {
 6864:                             my (%allroles,%allgroups,$group_privs,
 6865:                                 %groups_roles,@rolecodes);
 6866:                             my %userroles = (
 6867:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6868:                             );
 6869:                             @rolecodes = ('cm'); 
 6870:                             my $spec=$$role.'.'.$$where;
 6871:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6872:                             if ($$role =~ /^cr\//) {
 6873:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6874:                                 push(@rolecodes,'cr');
 6875:                             } elsif ($$role eq 'gr') {
 6876:                                 push(@rolecodes,$$role);
 6877:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6878:                                                     $env{'user.name'});
 6879:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6880:                                 (undef,my $group_privs) = split(/\//,$trole);
 6881:                                 $group_privs = &unescape($group_privs);
 6882:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6883:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6884:                                 &get_groups_roles($tdomain,$trest,
 6885:                                                   \%course_roles,\@rolecodes,
 6886:                                                   \%groups_roles);
 6887:                             } else {
 6888:                                 push(@rolecodes,$$role);
 6889:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6890:                             }
 6891:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6892:                                                                    \%groups_roles);
 6893:                             &appenv(\%userroles,\@rolecodes);
 6894:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6895:                         }
 6896:                     }
 6897:                     $$tstatus = 'is';
 6898:                 }
 6899:             }
 6900:             if ($$tend) {
 6901:                 if ($$tend<$update) {
 6902:                     $$tstatus='expired';
 6903:                 } elsif ($$tend<$now) {
 6904:                     $$tstatus='will_not';
 6905:                 }
 6906:             }
 6907:         }
 6908:     }
 6909: }
 6910: 
 6911: sub get_groups_roles {
 6912:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6913:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6914:                   (ref($rolecodes) eq 'ARRAY') && 
 6915:                   (ref($groups_roles) eq 'HASH')); 
 6916:     if (keys(%{$cdom_courseroles}) > 0) {
 6917:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6918:         if ($cdom ne '' && $cnum ne '') {
 6919:             foreach my $key (keys(%{$cdom_courseroles})) {
 6920:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6921:                     my $crsrole = $1;
 6922:                     my $crssec = $2;
 6923:                     if ($crsrole =~ /^cr/) {
 6924:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6925:                             push(@{$rolecodes},'cr');
 6926:                         }
 6927:                     } else {
 6928:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6929:                             push(@{$rolecodes},$crsrole);
 6930:                         }
 6931:                     }
 6932:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6933:                     if ($crssec ne '') {
 6934:                         $rolekey .= "/$crssec";
 6935:                     }
 6936:                     $rolekey .= './';
 6937:                     $groups_roles->{$rolekey} = $rolecodes;
 6938:                 }
 6939:             }
 6940:         }
 6941:     }
 6942:     return;
 6943: }
 6944: 
 6945: sub delete_env_groupprivs {
 6946:     my ($where,$courseroles,$possroles) = @_;
 6947:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6948:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6949:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6950:         %{$courseroles->{$udom}} =
 6951:             &get_my_roles('','','userroles',['active'],
 6952:                           $possroles,[$udom],1);
 6953:     }
 6954:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6955:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6956:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6957:             my $area = '/'.$cdom.'/'.$cnum;
 6958:             my $privkey = "user.priv.$crsrole.$area";
 6959:             if ($crssec ne '') {
 6960:                 $privkey .= '/'.$crssec;
 6961:             }
 6962:             $privkey .= ".$area/$group";
 6963:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6964:         }
 6965:     }
 6966:     return;
 6967: }
 6968: 
 6969: sub check_adhoc_privs {
 6970:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6971:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6972:     if ($sec) {
 6973:         $cckey .= '/'.$sec;
 6974:     } 
 6975:     my $setprivs;
 6976:     if ($env{$cckey}) {
 6977:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6978:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6979:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6980:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6981:             $setprivs = 1;
 6982:         }
 6983:     } else {
 6984:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6985:         $setprivs = 1;
 6986:     }
 6987:     return $setprivs;
 6988: }
 6989: 
 6990: sub set_adhoc_privileges {
 6991: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6992:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6993:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6994:     if ($sec ne '') {
 6995:         $area .= '/'.$sec;
 6996:     }
 6997:     my $spec = $role.'.'.$area;
 6998:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6999:                                   $env{'user.name'},1);
 7000:     my %rolehash = ();
 7001:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7002:         my $rolename = $1;
 7003:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7004:         my %domdef = &get_domain_defaults($dcdom);
 7005:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7006:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7007:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7008:             }
 7009:         }
 7010:     } else {
 7011:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7012:     }
 7013:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7014:     &appenv(\%userroles,[$role,'cm']);
 7015:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7016:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7017:             ($caller eq 'tiny')) {
 7018:         &appenv( {'request.role'        => $spec,
 7019:                   'request.role.domain' => $dcdom,
 7020:                   'request.course.sec'  => $sec,
 7021:                  }
 7022:                );
 7023:         my $tadv=0;
 7024:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7025:         &appenv({'request.role.adv'    => $tadv});
 7026:     }
 7027: }
 7028: 
 7029: # --------------------------------------------------------------- get interface
 7030: 
 7031: sub get {
 7032:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7033:    my $items='';
 7034:    foreach my $item (@$storearr) {
 7035:        $items.=&escape($item).'&';
 7036:    }
 7037:    $items=~s/\&$//;
 7038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7039:    if (!$uname) { $uname=$env{'user.name'}; }
 7040:    my $uhome=&homeserver($uname,$udomain);
 7041: 
 7042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7043:    my @pairs=split(/\&/,$rep);
 7044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7045:      return @pairs;
 7046:    }
 7047:    my %returnhash=();
 7048:    my $i=0;
 7049:    foreach my $item (@$storearr) {
 7050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7051:       $i++;
 7052:    }
 7053:    return %returnhash;
 7054: }
 7055: 
 7056: # --------------------------------------------------------------- del interface
 7057: 
 7058: sub del {
 7059:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7060:    my $items='';
 7061:    foreach my $item (@$storearr) {
 7062:        $items.=&escape($item).'&';
 7063:    }
 7064: 
 7065:    $items=~s/\&$//;
 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7067:    if (!$uname) { $uname=$env{'user.name'}; }
 7068:    my $uhome=&homeserver($uname,$udomain);
 7069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7070: }
 7071: 
 7072: # -------------------------------------------------------------- dump interface
 7073: 
 7074: sub unserialize {
 7075:     my ($rep, $escapedkeys) = @_;
 7076: 
 7077:     return {} if $rep =~ /^error/;
 7078: 
 7079:     my %returnhash=();
 7080: 	foreach my $item (split(/\&/,$rep)) {
 7081: 	    my ($key, $value) = split(/=/, $item, 2);
 7082: 	    $key = unescape($key) unless $escapedkeys;
 7083: 	    next if $key =~ /^error: 2 /;
 7084: 	    $returnhash{$key} = &thaw_unescape($value);
 7085: 	}
 7086:     #return %returnhash;
 7087:     return \%returnhash;
 7088: }        
 7089: 
 7090: # see Lond::dump_with_regexp
 7091: # if $escapedkeys hash keys won't get unescaped.
 7092: sub dump {
 7093:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7094:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7095:     if (!$uname) { $uname=$env{'user.name'}; }
 7096:     my $uhome=&homeserver($uname,$udomain);
 7097: 
 7098:     if ($regexp) {
 7099:         $regexp=&escape($regexp);
 7100:     } else {
 7101:         $regexp='.';
 7102:     }
 7103:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7104:         # user is hosted on this machine
 7105:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7106:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7107:         return %{unserialize($reply, $escapedkeys)};
 7108:     }
 7109:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7110:     my @pairs=split(/\&/,$rep);
 7111:     my %returnhash=();
 7112:     if (!($rep =~ /^error/ )) {
 7113: 	foreach my $item (@pairs) {
 7114: 	    my ($key,$value)=split(/=/,$item,2);
 7115:         $key = unescape($key) unless $escapedkeys;
 7116:         #$key = &unescape($key);
 7117: 	    next if ($key =~ /^error: 2 /);
 7118: 	    $returnhash{$key}=&thaw_unescape($value);
 7119: 	}
 7120:     }
 7121:     return %returnhash;
 7122: }
 7123: 
 7124: 
 7125: # --------------------------------------------------------- dumpstore interface
 7126: 
 7127: sub dumpstore {
 7128:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7129:    # same as dump but keys must be escaped. They may contain colon separated
 7130:    # lists of values that may themself contain colons (e.g. symbs).
 7131:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7132: }
 7133: 
 7134: # -------------------------------------------------------------- keys interface
 7135: 
 7136: sub getkeys {
 7137:    my ($namespace,$udomain,$uname)=@_;
 7138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7139:    if (!$uname) { $uname=$env{'user.name'}; }
 7140:    my $uhome=&homeserver($uname,$udomain);
 7141:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7142:    my @keyarray=();
 7143:    foreach my $key (split(/\&/,$rep)) {
 7144:       next if ($key =~ /^error: 2 /);
 7145:       push(@keyarray,&unescape($key));
 7146:    }
 7147:    return @keyarray;
 7148: }
 7149: 
 7150: # --------------------------------------------------------------- currentdump
 7151: sub currentdump {
 7152:    my ($courseid,$sdom,$sname)=@_;
 7153:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7154:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7155:    $sname    = $env{'user.name'}         if (! defined($sname));
 7156:    my $uhome = &homeserver($sname,$sdom);
 7157:    my $rep;
 7158: 
 7159:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7160:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7161:                    $courseid)));
 7162:    } else {
 7163:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7164:    }
 7165: 
 7166:    return if ($rep =~ /^(error:|no_such_host)/);
 7167:    #
 7168:    my %returnhash=();
 7169:    #
 7170:    if ($rep eq 'unknown_cmd') {
 7171:        # an old lond will not know currentdump
 7172:        # Do a dump and make it look like a currentdump
 7173:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7174:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7175:        my %hash = @tmp;
 7176:        @tmp=();
 7177:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7178:    } else {
 7179:        my @pairs=split(/\&/,$rep);
 7180:        foreach my $pair (@pairs) {
 7181:            my ($key,$value)=split(/=/,$pair,2);
 7182:            my ($symb,$param) = split(/:/,$key);
 7183:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7184:                                                         &thaw_unescape($value);
 7185:        }
 7186:    }
 7187:    return %returnhash;
 7188: }
 7189: 
 7190: sub convert_dump_to_currentdump{
 7191:     my %hash = %{shift()};
 7192:     my %returnhash;
 7193:     # Code ripped from lond, essentially.  The only difference
 7194:     # here is the unescaping done by lonnet::dump().  Conceivably
 7195:     # we might run in to problems with parameter names =~ /^v\./
 7196:     while (my ($key,$value) = each(%hash)) {
 7197:         my ($v,$symb,$param) = split(/:/,$key);
 7198: 	$symb  = &unescape($symb);
 7199: 	$param = &unescape($param);
 7200:         next if ($v eq 'version' || $symb eq 'keys');
 7201:         next if (exists($returnhash{$symb}) &&
 7202:                  exists($returnhash{$symb}->{$param}) &&
 7203:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7204:         $returnhash{$symb}->{$param}=$value;
 7205:         $returnhash{$symb}->{'v.'.$param}=$v;
 7206:     }
 7207:     #
 7208:     # Remove all of the keys in the hashes which keep track of
 7209:     # the version of the parameter.
 7210:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7211:         # use a foreach because we are going to delete from the hash.
 7212:         foreach my $key (keys(%$param_hash)) {
 7213:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7214:         }
 7215:     }
 7216:     return \%returnhash;
 7217: }
 7218: 
 7219: # ------------------------------------------------------ critical inc interface
 7220: 
 7221: sub cinc {
 7222:     return &inc(@_,'critical');
 7223: }
 7224: 
 7225: # --------------------------------------------------------------- inc interface
 7226: 
 7227: sub inc {
 7228:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7229:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7230:     if (!$uname) { $uname=$env{'user.name'}; }
 7231:     my $uhome=&homeserver($uname,$udomain);
 7232:     my $items='';
 7233:     if (! ref($store)) {
 7234:         # got a single value, so use that instead
 7235:         $items = &escape($store).'=&';
 7236:     } elsif (ref($store) eq 'SCALAR') {
 7237:         $items = &escape($$store).'=&';        
 7238:     } elsif (ref($store) eq 'ARRAY') {
 7239:         $items = join('=&',map {&escape($_);} @{$store});
 7240:     } elsif (ref($store) eq 'HASH') {
 7241:         while (my($key,$value) = each(%{$store})) {
 7242:             $items.= &escape($key).'='.&escape($value).'&';
 7243:         }
 7244:     }
 7245:     $items=~s/\&$//;
 7246:     if ($critical) {
 7247: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7248:     } else {
 7249: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7250:     }
 7251: }
 7252: 
 7253: # --------------------------------------------------------------- put interface
 7254: 
 7255: sub put {
 7256:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7257:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7258:    if (!$uname) { $uname=$env{'user.name'}; }
 7259:    my $uhome=&homeserver($uname,$udomain);
 7260:    my $items='';
 7261:    foreach my $item (keys(%$storehash)) {
 7262:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7263:    }
 7264:    $items=~s/\&$//;
 7265:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7266: }
 7267: 
 7268: # ------------------------------------------------------------ newput interface
 7269: 
 7270: sub newput {
 7271:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7273:    if (!$uname) { $uname=$env{'user.name'}; }
 7274:    my $uhome=&homeserver($uname,$udomain);
 7275:    my $items='';
 7276:    foreach my $key (keys(%$storehash)) {
 7277:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7278:    }
 7279:    $items=~s/\&$//;
 7280:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7281: }
 7282: 
 7283: # ---------------------------------------------------------  putstore interface
 7284: 
 7285: sub putstore {
 7286:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7288:    if (!$uname) { $uname=$env{'user.name'}; }
 7289:    my $uhome=&homeserver($uname,$udomain);
 7290:    my $items='';
 7291:    foreach my $key (keys(%$storehash)) {
 7292:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7293:    }
 7294:    $items=~s/\&$//;
 7295:    my $esc_symb=&escape($symb);
 7296:    my $esc_v=&escape($version);
 7297:    my $reply =
 7298:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7299: 	      $uhome);
 7300:    if (($tolog) && ($reply eq 'ok')) {
 7301:        my $namevalue='';
 7302:        foreach my $key (keys(%{$storehash})) {
 7303:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7304:        }
 7305:        my $ip = &get_requestor_ip();
 7306:        $namevalue .= 'ip='.&escape($ip).
 7307:                      '&host='.&escape($perlvar{'lonHostID'}).
 7308:                      '&version='.$esc_v.
 7309:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7310:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7311:    }
 7312:    if ($reply eq 'unknown_cmd') {
 7313:        # gfall back to way things use to be done
 7314:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7315: 			    $uname);
 7316:    }
 7317:    return $reply;
 7318: }
 7319: 
 7320: sub old_putstore {
 7321:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7322:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7323:     if (!$uname) { $uname=$env{'user.name'}; }
 7324:     my $uhome=&homeserver($uname,$udomain);
 7325:     my %newstorehash;
 7326:     foreach my $item (keys(%$storehash)) {
 7327: 	my $key = $version.':'.&escape($symb).':'.$item;
 7328: 	$newstorehash{$key} = $storehash->{$item};
 7329:     }
 7330:     my $items='';
 7331:     my %allitems = ();
 7332:     foreach my $item (keys(%newstorehash)) {
 7333: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7334: 	    my $key = $1.':keys:'.$2;
 7335: 	    $allitems{$key} .= $3.':';
 7336: 	}
 7337: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7338:     }
 7339:     foreach my $item (keys(%allitems)) {
 7340: 	$allitems{$item} =~ s/\:$//;
 7341: 	$items.= $item.'='.$allitems{$item}.'&';
 7342:     }
 7343:     $items=~s/\&$//;
 7344:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7345: }
 7346: 
 7347: # ------------------------------------------------------ critical put interface
 7348: 
 7349: sub cput {
 7350:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7351:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7352:    if (!$uname) { $uname=$env{'user.name'}; }
 7353:    my $uhome=&homeserver($uname,$udomain);
 7354:    my $items='';
 7355:    foreach my $item (keys(%$storehash)) {
 7356:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7357:    }
 7358:    $items=~s/\&$//;
 7359:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7360: }
 7361: 
 7362: # -------------------------------------------------------------- eget interface
 7363: 
 7364: sub eget {
 7365:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7366:    my $items='';
 7367:    foreach my $item (@$storearr) {
 7368:        $items.=&escape($item).'&';
 7369:    }
 7370:    $items=~s/\&$//;
 7371:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7372:    if (!$uname) { $uname=$env{'user.name'}; }
 7373:    my $uhome=&homeserver($uname,$udomain);
 7374:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7375:    my @pairs=split(/\&/,$rep);
 7376:    my %returnhash=();
 7377:    my $i=0;
 7378:    foreach my $item (@$storearr) {
 7379:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7380:       $i++;
 7381:    }
 7382:    return %returnhash;
 7383: }
 7384: 
 7385: # ------------------------------------------------------------ tmpput interface
 7386: sub tmpput {
 7387:     my ($storehash,$server,$context)=@_;
 7388:     my $items='';
 7389:     foreach my $item (keys(%$storehash)) {
 7390: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7391:     }
 7392:     $items=~s/\&$//;
 7393:     if (defined($context)) {
 7394:         $items .= ':'.&escape($context);
 7395:     }
 7396:     return &reply("tmpput:$items",$server);
 7397: }
 7398: 
 7399: # ------------------------------------------------------------ tmpget interface
 7400: sub tmpget {
 7401:     my ($token,$server)=@_;
 7402:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7403:     my $rep=&reply("tmpget:$token",$server);
 7404:     my %returnhash;
 7405:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7406:         return %returnhash;
 7407:     }
 7408:     foreach my $item (split(/\&/,$rep)) {
 7409: 	my ($key,$value)=split(/=/,$item);
 7410: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7411:     }
 7412:     return %returnhash;
 7413: }
 7414: 
 7415: # ------------------------------------------------------------ tmpdel interface
 7416: sub tmpdel {
 7417:     my ($token,$server)=@_;
 7418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7419:     return &reply("tmpdel:$token",$server);
 7420: }
 7421: 
 7422: # ------------------------------------------------------------ get_timebased_id 
 7423: 
 7424: sub get_timebased_id {
 7425:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7426:         $maxtries) = @_;
 7427:     my ($newid,$error,$dellock);
 7428:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7429:         return ('','ok','invalid call to get suffix');
 7430:     }
 7431: 
 7432: # set defaults for any optional args for which values were not supplied
 7433:     if ($who eq '') {
 7434:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7435:     }
 7436:     if (!$locktries) {
 7437:         $locktries = 3;
 7438:     }
 7439:     if (!$maxtries) {
 7440:         $maxtries = 10;
 7441:     }
 7442:     
 7443:     if (($cdom eq '') || ($cnum eq '')) {
 7444:         if ($env{'request.course.id'}) {
 7445:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7446:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7447:         }
 7448:         if (($cdom eq '') || ($cnum eq '')) {
 7449:             return ('','ok','call to get suffix not in course context');
 7450:         }
 7451:     }
 7452: 
 7453: # construct locking item
 7454:     my $lockhash = {
 7455:                       $prefix."\0".'locked_'.$keyid => $who,
 7456:                    };
 7457:     my $tries = 0;
 7458: 
 7459: # attempt to get lock on nohist_$namespace file
 7460:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7461:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7462:         $tries ++;
 7463:         sleep 1;
 7464:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7465:     }
 7466: 
 7467: # attempt to get unique identifier, based on current timestamp
 7468:     if ($gotlock eq 'ok') {
 7469:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7470:         my $id = time;
 7471:         $newid = $id;
 7472:         if ($idtype eq 'addcode') {
 7473:             $newid .= &sixnum_code();
 7474:         }
 7475:         my $idtries = 0;
 7476:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7477:             if ($idtype eq 'concat') {
 7478:                 $newid = $id.$idtries;
 7479:             } elsif ($idtype eq 'addcode') {
 7480:                 $newid = $newid.&sixnum_code();
 7481:             } else {
 7482:                 $newid ++;
 7483:             }
 7484:             $idtries ++;
 7485:         }
 7486:         if (!exists($inuse{$prefix."\0".$newid})) {
 7487:             my %new_item =  (
 7488:                               $prefix."\0".$newid => $who,
 7489:                             );
 7490:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7491:                                                  $cdom,$cnum);
 7492:             if ($putresult ne 'ok') {
 7493:                 undef($newid);
 7494:                 $error = 'error saving new item: '.$putresult;
 7495:             }
 7496:         } else {
 7497:              undef($newid);
 7498:              $error = ('error: no unique suffix available for the new item ');
 7499:         }
 7500: #  remove lock
 7501:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7502:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7503:     } else {
 7504:         $error = "error: could not obtain lockfile\n";
 7505:         $dellock = 'ok';
 7506:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7507:             $dellock = 'nolock';
 7508:         }
 7509:     }
 7510:     return ($newid,$dellock,$error);
 7511: }
 7512: 
 7513: sub sixnum_code {
 7514:     my $code;
 7515:     for (0..6) {
 7516:         $code .= int( rand(9) );
 7517:     }
 7518:     return $code;
 7519: }
 7520: 
 7521: # -------------------------------------------------- portfolio access checking
 7522: 
 7523: sub portfolio_access {
 7524:     my ($requrl,$clientip) = @_;
 7525:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7526:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7527:     if ($result) {
 7528:         my %setters;
 7529:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7530:             my ($startblock,$endblock) =
 7531:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7532:             if ($startblock && $endblock) {
 7533:                 return 'B';
 7534:             }
 7535:         } else {
 7536:             my ($startblock,$endblock) =
 7537:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7538:             if ($startblock && $endblock) {
 7539:                 return 'B';
 7540:             }
 7541:         }
 7542:     }
 7543:     if ($result eq 'ok') {
 7544:        return 'F';
 7545:     } elsif ($result =~ /^[^:]+:guest_/) {
 7546:        return 'A';
 7547:     }
 7548:     return '';
 7549: }
 7550: 
 7551: sub get_portfolio_access {
 7552:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7553: 
 7554:     if (!ref($access_hash)) {
 7555: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7556: 	my %access_controls = &get_access_controls($current_perms,$group,
 7557: 						   $file_name);
 7558: 	$access_hash = $access_controls{$file_name};
 7559:     }
 7560: 
 7561:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7562:     my $now = time;
 7563:     if (ref($access_hash) eq 'HASH') {
 7564:         foreach my $key (keys(%{$access_hash})) {
 7565:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7566:             if ($start > $now) {
 7567:                 next;
 7568:             }
 7569:             if ($end && $end<$now) {
 7570:                 next;
 7571:             }
 7572:             if ($scope eq 'public') {
 7573:                 $public = $key;
 7574:                 last;
 7575:             } elsif ($scope eq 'guest') {
 7576:                 $guest = $key;
 7577:             } elsif ($scope eq 'domains') {
 7578:                 push(@domains,$key);
 7579:             } elsif ($scope eq 'users') {
 7580:                 push(@users,$key);
 7581:             } elsif ($scope eq 'course') {
 7582:                 push(@courses,$key);
 7583:             } elsif ($scope eq 'group') {
 7584:                 push(@groups,$key);
 7585:             } elsif ($scope eq 'ip') {
 7586:                 push(@ips,$key);
 7587:             }
 7588:         }
 7589:         if ($public) {
 7590:             return 'ok';
 7591:         } elsif (@ips > 0) {
 7592:             my $allowed;
 7593:             foreach my $ipkey (@ips) {
 7594:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7595:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7596:                         $allowed = 1;
 7597:                         last; 
 7598:                     }
 7599:                 }
 7600:             }
 7601:             if ($allowed) {
 7602:                 return 'ok';
 7603:             }
 7604:         }
 7605:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7606:             if ($guest) {
 7607:                 return $guest;
 7608:             }
 7609:         } else {
 7610:             if (@domains > 0) {
 7611:                 foreach my $domkey (@domains) {
 7612:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7613:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7614:                             return 'ok';
 7615:                         }
 7616:                     }
 7617:                 }
 7618:             }
 7619:             if (@users > 0) {
 7620:                 foreach my $userkey (@users) {
 7621:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7622:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7623:                             if (ref($item) eq 'HASH') {
 7624:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7625:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7626:                                     return 'ok';
 7627:                                 }
 7628:                             }
 7629:                         }
 7630:                     } 
 7631:                 }
 7632:             }
 7633:             my %roleshash;
 7634:             my @courses_and_groups = @courses;
 7635:             push(@courses_and_groups,@groups); 
 7636:             if (@courses_and_groups > 0) {
 7637:                 my (%allgroups,%allroles); 
 7638:                 my ($start,$end,$role,$sec,$group);
 7639:                 foreach my $envkey (%env) {
 7640:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7641:                         my $cid = $2.'_'.$3; 
 7642:                         if ($1 eq 'gr') {
 7643:                             $group = $4;
 7644:                             $allgroups{$cid}{$group} = $env{$envkey};
 7645:                         } else {
 7646:                             if ($4 eq '') {
 7647:                                 $sec = 'none';
 7648:                             } else {
 7649:                                 $sec = $4;
 7650:                             }
 7651:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7652:                         }
 7653:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7654:                         my $cid = $2.'_'.$3;
 7655:                         if ($4 eq '') {
 7656:                             $sec = 'none';
 7657:                         } else {
 7658:                             $sec = $4;
 7659:                         }
 7660:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7661:                     }
 7662:                 }
 7663:                 if (keys(%allroles) == 0) {
 7664:                     return;
 7665:                 }
 7666:                 foreach my $key (@courses_and_groups) {
 7667:                     my %content = %{$$access_hash{$key}};
 7668:                     my $cnum = $content{'number'};
 7669:                     my $cdom = $content{'domain'};
 7670:                     my $cid = $cdom.'_'.$cnum;
 7671:                     if (!exists($allroles{$cid})) {
 7672:                         next;
 7673:                     }    
 7674:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7675:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7676:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7677:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7678:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7679:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7680:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7681:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7682:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7683:                                         if (grep/^all$/,@sections) {
 7684:                                             return 'ok';
 7685:                                         } else {
 7686:                                             if (grep/^$sec$/,@sections) {
 7687:                                                 return 'ok';
 7688:                                             }
 7689:                                         }
 7690:                                     }
 7691:                                 }
 7692:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7693:                                     if (grep/^none$/,@groups) {
 7694:                                         return 'ok';
 7695:                                     }
 7696:                                 } else {
 7697:                                     if (grep/^all$/,@groups) {
 7698:                                         return 'ok';
 7699:                                     } 
 7700:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7701:                                         if (grep/^$group$/,@groups) {
 7702:                                             return 'ok';
 7703:                                         }
 7704:                                     }
 7705:                                 } 
 7706:                             }
 7707:                         }
 7708:                     }
 7709:                 }
 7710:             }
 7711:             if ($guest) {
 7712:                 return $guest;
 7713:             }
 7714:         }
 7715:     }
 7716:     return;
 7717: }
 7718: 
 7719: sub course_group_datechecker {
 7720:     my ($dates,$now,$status) = @_;
 7721:     my ($start,$end) = split(/\./,$dates);
 7722:     if (!$start && !$end) {
 7723:         return 'ok';
 7724:     }
 7725:     if (grep/^active$/,@{$status}) {
 7726:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7727:             return 'ok';
 7728:         }
 7729:     }
 7730:     if (grep/^previous$/,@{$status}) {
 7731:         if ($end > $now ) {
 7732:             return 'ok';
 7733:         }
 7734:     }
 7735:     if (grep/^future$/,@{$status}) {
 7736:         if ($start > $now) {
 7737:             return 'ok';
 7738:         }
 7739:     }
 7740:     return; 
 7741: }
 7742: 
 7743: sub parse_portfolio_url {
 7744:     my ($url) = @_;
 7745: 
 7746:     my ($type,$udom,$unum,$group,$file_name);
 7747:     
 7748:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7749: 	$type = 1;
 7750:         $udom = $1;
 7751:         $unum = $2;
 7752:         $file_name = $3;
 7753:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7754: 	$type = 2;
 7755:         $udom = $1;
 7756:         $unum = $2;
 7757:         $group = $3;
 7758:         $file_name = $3.'/'.$4;
 7759:     }
 7760:     if (wantarray) {
 7761: 	return ($type,$udom,$unum,$file_name,$group);
 7762:     }
 7763:     return $type;
 7764: }
 7765: 
 7766: sub is_portfolio_url {
 7767:     my ($url) = @_;
 7768:     return scalar(&parse_portfolio_url($url));
 7769: }
 7770: 
 7771: sub is_portfolio_file {
 7772:     my ($file) = @_;
 7773:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7774:         return 1;
 7775:     }
 7776:     return;
 7777: }
 7778: 
 7779: sub usertools_access {
 7780:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7781:     my ($access,%tools);
 7782:     if ($context eq '') {
 7783:         $context = 'tools';
 7784:     }
 7785:     if ($context eq 'requestcourses') {
 7786:         %tools = (
 7787:                       official   => 1,
 7788:                       unofficial => 1,
 7789:                       community  => 1,
 7790:                       textbook   => 1,
 7791:                       placement  => 1,
 7792:                       lti        => 1,
 7793:                  );
 7794:     } elsif ($context eq 'requestauthor') {
 7795:         %tools = (
 7796:                       requestauthor => 1,
 7797:                  );
 7798:     } else {
 7799:         %tools = (
 7800:                       aboutme   => 1,
 7801:                       blog      => 1,
 7802:                       webdav    => 1,
 7803:                       portfolio => 1,
 7804:                  );
 7805:     }
 7806:     return if (!defined($tools{$tool}));
 7807: 
 7808:     if (($udom eq '') || ($uname eq '')) {
 7809:         $udom = $env{'user.domain'};
 7810:         $uname = $env{'user.name'};
 7811:     }
 7812: 
 7813:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7814:         if ($action ne 'reload') {
 7815:             if ($context eq 'requestcourses') {
 7816:                 return $env{'environment.canrequest.'.$tool};
 7817:             } elsif ($context eq 'requestauthor') {
 7818:                 return $env{'environment.canrequest.author'};
 7819:             } else {
 7820:                 return $env{'environment.availabletools.'.$tool};
 7821:             }
 7822:         }
 7823:     }
 7824: 
 7825:     my ($toolstatus,$inststatus,$envkey);
 7826:     if ($context eq 'requestauthor') {
 7827:         $envkey = $context; 
 7828:     } else {
 7829:         $envkey = $context.'.'.$tool;
 7830:     }
 7831: 
 7832:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7833:          ($action ne 'reload')) {
 7834:         $toolstatus = $env{'environment.'.$envkey};
 7835:         $inststatus = $env{'environment.inststatus'};
 7836:     } else {
 7837:         if (ref($userenvref) eq 'HASH') {
 7838:             $toolstatus = $userenvref->{$envkey};
 7839:             $inststatus = $userenvref->{'inststatus'};
 7840:         } else {
 7841:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7842:             $toolstatus = $userenv{$envkey};
 7843:             $inststatus = $userenv{'inststatus'};
 7844:         }
 7845:     }
 7846: 
 7847:     if ($toolstatus ne '') {
 7848:         if ($toolstatus) {
 7849:             $access = 1;
 7850:         } else {
 7851:             $access = 0;
 7852:         }
 7853:         return $access;
 7854:     }
 7855: 
 7856:     my ($is_adv,%domdef);
 7857:     if (ref($is_advref) eq 'HASH') {
 7858:         $is_adv = $is_advref->{'is_adv'};
 7859:     } else {
 7860:         $is_adv = &is_advanced_user($udom,$uname);
 7861:     }
 7862:     if (ref($domdefref) eq 'HASH') {
 7863:         %domdef = %{$domdefref};
 7864:     } else {
 7865:         %domdef = &get_domain_defaults($udom);
 7866:     }
 7867:     if (ref($domdef{$tool}) eq 'HASH') {
 7868:         if ($is_adv) {
 7869:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7870:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7871:                     $access = 1;
 7872:                 } else {
 7873:                     $access = 0;
 7874:                 }
 7875:                 return $access;
 7876:             }
 7877:         }
 7878:         if ($inststatus ne '') {
 7879:             my ($hasaccess,$hasnoaccess);
 7880:             foreach my $affiliation (split(/:/,$inststatus)) {
 7881:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7882:                     if ($domdef{$tool}{$affiliation}) {
 7883:                         $hasaccess = 1;
 7884:                     } else {
 7885:                         $hasnoaccess = 1;
 7886:                     }
 7887:                 }
 7888:             }
 7889:             if ($hasaccess || $hasnoaccess) {
 7890:                 if ($hasaccess) {
 7891:                     $access = 1;
 7892:                 } elsif ($hasnoaccess) {
 7893:                     $access = 0; 
 7894:                 }
 7895:                 return $access;
 7896:             }
 7897:         } else {
 7898:             if ($domdef{$tool}{'default'} ne '') {
 7899:                 if ($domdef{$tool}{'default'}) {
 7900:                     $access = 1;
 7901:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7902:                     $access = 0;
 7903:                 }
 7904:                 return $access;
 7905:             }
 7906:         }
 7907:     } else {
 7908:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7909:             $access = 1;
 7910:         } else {
 7911:             $access = 0;
 7912:         }
 7913:         return $access;
 7914:     }
 7915: }
 7916: 
 7917: sub is_course_owner {
 7918:     my ($cdom,$cnum,$udom,$uname) = @_;
 7919:     if (($udom eq '') || ($uname eq '')) {
 7920:         $udom = $env{'user.domain'};
 7921:         $uname = $env{'user.name'};
 7922:     }
 7923:     unless (($udom eq '') || ($uname eq '')) {
 7924:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7925:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7926:                 return 1;
 7927:             } else {
 7928:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7929:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7930:                     return 1;
 7931:                 }
 7932:             }
 7933:         }
 7934:     }
 7935:     return;
 7936: }
 7937: 
 7938: sub is_advanced_user {
 7939:     my ($udom,$uname) = @_;
 7940:     if ($udom ne '' && $uname ne '') {
 7941:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7942:             if (wantarray) {
 7943:                 return ($env{'user.adv'},$env{'user.author'});
 7944:             } else {
 7945:                 return $env{'user.adv'};
 7946:             }
 7947:         }
 7948:     }
 7949:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7950:     my %allroles;
 7951:     my ($is_adv,$is_author);
 7952:     foreach my $role (keys(%roleshash)) {
 7953:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7954:         my $area = '/'.$tdomain.'/'.$trest;
 7955:         if ($sec ne '') {
 7956:             $area .= '/'.$sec;
 7957:         }
 7958:         if (($area ne '') && ($trole ne '')) {
 7959:             my $spec=$trole.'.'.$area;
 7960:             if ($trole =~ /^cr\//) {
 7961:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7962:             } elsif ($trole ne 'gr') {
 7963:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7964:             }
 7965:             if ($trole eq 'au') {
 7966:                 $is_author = 1;
 7967:             }
 7968:         }
 7969:     }
 7970:     foreach my $role (keys(%allroles)) {
 7971:         last if ($is_adv);
 7972:         foreach my $item (split(/:/,$allroles{$role})) {
 7973:             if ($item ne '') {
 7974:                 my ($privilege,$restrictions)=split(/&/,$item);
 7975:                 if ($privilege eq 'adv') {
 7976:                     $is_adv = 1;
 7977:                     last;
 7978:                 }
 7979:             }
 7980:         }
 7981:     }
 7982:     if (wantarray) {
 7983:         return ($is_adv,$is_author);
 7984:     }
 7985:     return $is_adv;
 7986: }
 7987: 
 7988: sub check_can_request {
 7989:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7990:     my $canreq = 0;
 7991:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7992:         $uname = $env{'user.name'};
 7993:         $udom = $env{'user.domain'};
 7994:     }
 7995:     my ($types,$typename) = &Apache::loncommon::course_types();
 7996:     my @options = ('approval','validate','autolimit');
 7997:     my $optregex = join('|',@options);
 7998:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7999:         foreach my $type (@{$types}) {
 8000:             if (&usertools_access($uname,$udom,$type,undef,
 8001:                                   'requestcourses')) {
 8002:                 $canreq ++;
 8003:                 if (ref($request_domains) eq 'HASH') {
 8004:                     push(@{$request_domains->{$type}},$udom);
 8005:                 }
 8006:                 if ($dom eq $udom) {
 8007:                     $can_request->{$type} = 1;
 8008:                 }
 8009:             }
 8010:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8011:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8012:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8013:                 if (@curr > 0) {
 8014:                     foreach my $item (@curr) {
 8015:                         if (ref($request_domains) eq 'HASH') {
 8016:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8017:                             if ($otherdom ne '') {
 8018:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8019:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8020:                                         push(@{$request_domains->{$type}},$otherdom);
 8021:                                     }
 8022:                                 } else {
 8023:                                     push(@{$request_domains->{$type}},$otherdom);
 8024:                                 }
 8025:                             }
 8026:                         }
 8027:                     }
 8028:                     unless ($dom eq $env{'user.domain'}) {
 8029:                         $canreq ++;
 8030:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8031:                             $can_request->{$type} = 1;
 8032:                         }
 8033:                     }
 8034:                 }
 8035:             }
 8036:         }
 8037:     }
 8038:     return $canreq;
 8039: }
 8040: 
 8041: # ---------------------------------------------- Custom access rule evaluation
 8042: 
 8043: sub customaccess {
 8044:     my ($priv,$uri)=@_;
 8045:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8046:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8047:     $udom = &LONCAPA::clean_domain($udom);
 8048:     $ucrs = &LONCAPA::clean_username($ucrs);
 8049:     my $access=0;
 8050:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8051: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8052: 	if ($type eq 'user') {
 8053: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8054: 		my ($tdom,$tuname)=split(m{/},$scope);
 8055: 		if ($tdom) {
 8056: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8057: 		}
 8058: 		if ($tuname) {
 8059: 		    if ($tuname ne $env{'user.name'}) { next; }
 8060: 		}
 8061: 		$access=($effect eq 'allow');
 8062: 		last;
 8063: 	    }
 8064: 	} else {
 8065: 	    if ($role) {
 8066: 		if ($role ne $urole) { next; }
 8067: 	    }
 8068: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8069: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8070: 		if ($tdom) {
 8071: 		    if ($tdom ne $udom) { next; }
 8072: 		}
 8073: 		if ($tcrs) {
 8074: 		    if ($tcrs ne $ucrs) { next; }
 8075: 		}
 8076: 		if ($tsec) {
 8077: 		    if ($tsec ne $usec) { next; }
 8078: 		}
 8079: 		$access=($effect eq 'allow');
 8080: 		last;
 8081: 	    }
 8082: 	    if ($realm eq '' && $role eq '') {
 8083: 		$access=($effect eq 'allow');
 8084: 	    }
 8085: 	}
 8086:     }
 8087:     return $access;
 8088: }
 8089: 
 8090: # ------------------------------------------------- Check for a user privilege
 8091: 
 8092: sub allowed {
 8093:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 8094:     my $ver_orguri=$uri;
 8095:     $uri=&deversion($uri);
 8096:     my $orguri=$uri;
 8097:     $uri=&declutter($uri);
 8098: 
 8099:     if ($priv eq 'evb') {
 8100: # Evade communication block restrictions for specified role in a course
 8101:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8102:             return $1;
 8103:         } else {
 8104:             return;
 8105:         }
 8106:     }
 8107: 
 8108:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8109: # Free bre access to adm and meta resources
 8110:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8111: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8112: 	&& ($priv eq 'bre')) {
 8113: 	return 'F';
 8114:     }
 8115: 
 8116: # Free bre access to user's own portfolio contents
 8117:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8118:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8119: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8120:         my %setters;
 8121:         my ($startblock,$endblock) = 
 8122:             &Apache::loncommon::blockcheck(\%setters,'port');
 8123:         if ($startblock && $endblock) {
 8124:             return 'B';
 8125:         } else {
 8126:             return 'F';
 8127:         }
 8128:     }
 8129: 
 8130: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8131:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8132:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8133:         if (exists($env{'request.course.id'})) {
 8134:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8135:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8136:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8137:                 my $courseprivid=$env{'request.course.id'};
 8138:                 $courseprivid=~s/\_/\//;
 8139:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8140:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8141:                     return $1; 
 8142:                 } else {
 8143:                     if ($env{'request.course.sec'}) {
 8144:                         $courseprivid.='/'.$env{'request.course.sec'};
 8145:                     }
 8146:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8147:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8148:                         return $2;
 8149:                     }
 8150:                 }
 8151:             }
 8152:         }
 8153:     }
 8154: 
 8155: # Free bre to public access
 8156: 
 8157:     if ($priv eq 'bre') {
 8158:         my $copyright;
 8159:         unless ($uri =~ /ext\.tool/) {
 8160:             $copyright=&metadata($uri,'copyright');
 8161:         }
 8162: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8163:            return 'F'; 
 8164:         }
 8165:         if ($copyright eq 'priv') {
 8166:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8167: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8168: 		return '';
 8169:             }
 8170:         }
 8171:         if ($copyright eq 'domain') {
 8172:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8173: 	    unless (($env{'user.domain'} eq $1) ||
 8174:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8175: 		return '';
 8176:             }
 8177:         }
 8178:         if ($env{'request.role'}=~ /li\.\//) {
 8179:             # Library role, so allow browsing of resources in this domain.
 8180:             return 'F';
 8181:         }
 8182:         if ($copyright eq 'custom') {
 8183: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8184:         }
 8185:     }
 8186:     # Domain coordinator is trying to create a course
 8187:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8188:         # uri is the requested domain in this case.
 8189:         # comparison to 'request.role.domain' shows if the user has selected
 8190:         # a role of dc for the domain in question.
 8191:         return 'F' if ($uri eq $env{'request.role.domain'});
 8192:     }
 8193: 
 8194:     my $thisallowed='';
 8195:     my $statecond=0;
 8196:     my $courseprivid='';
 8197: 
 8198:     my $ownaccess;
 8199:     # Community Coordinator or Assistant Co-author browsing resource space.
 8200:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8201:         if ($uri eq '') {
 8202:             $ownaccess = 1;
 8203:         } else {
 8204:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8205:                 my $udom = $env{'user.domain'};
 8206:                 my $uname = $env{'user.name'};
 8207:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8208:                     $ownaccess = 1;
 8209:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8210:                     unless ($uri =~ m{\.\./}) {
 8211:                         $ownaccess = 1;
 8212:                     }
 8213:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8214:                     my $now = time;
 8215:                     if ($uri =~ m{^([^/]+)/?$}) {
 8216:                         my $adom = $1;
 8217:                         foreach my $key (keys(%env)) {
 8218:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8219:                                 my ($start,$end) = split('.',$env{$key});
 8220:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8221:                                     $ownaccess = 1;
 8222:                                     last;
 8223:                                 }
 8224:                             }
 8225:                         }
 8226:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8227:                         my $adom = $1;
 8228:                         my $aname = $2;
 8229:                         foreach my $role ('ca','aa') { 
 8230:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8231:                                 my ($start,$end) =
 8232:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8233:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8234:                                     $ownaccess = 1;
 8235:                                     last;
 8236:                                 }
 8237:                             }
 8238:                         }
 8239:                     }
 8240:                 }
 8241:             }
 8242:         }
 8243:     }
 8244: 
 8245: # Course
 8246: 
 8247:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8248:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8249:             $thisallowed.=$1;
 8250:         }
 8251:     }
 8252: 
 8253: # Domain
 8254: 
 8255:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8256:        =~/\Q$priv\E\&([^\:]*)/) {
 8257:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8258:             $thisallowed.=$1;
 8259:         }
 8260:     }
 8261: 
 8262: # User who is not author or co-author might still be able to edit
 8263: # resource of an author in the domain (e.g., if Domain Coordinator).
 8264:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8265:         (&allowed('mdc',$env{'request.course.id'}))) {
 8266:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8267:             $thisallowed.=$1;
 8268:         }
 8269:     }
 8270: 
 8271: # Course: uri itself is a course
 8272:     my $courseuri=$uri;
 8273:     $courseuri=~s/\_(\d)/\/$1/;
 8274:     $courseuri=~s/^([^\/])/\/$1/;
 8275: 
 8276:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8277:        =~/\Q$priv\E\&([^\:]*)/) {
 8278:         if ($priv eq 'mip') {
 8279:             my $rem = $1;
 8280:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8281:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8282:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8283:                 if ($cdom ne '') {
 8284:                     my %passwdconf = &get_passwdconf($cdom);
 8285:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8286:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8287:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8288:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8289:                                 unless (@inststatuses) {
 8290:                                     @inststatuses = ('default');
 8291:                                 }
 8292:                                 foreach my $status (@inststatuses) {
 8293:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8294:                                         $thisallowed.=$rem;
 8295:                                     }
 8296:                                 }
 8297:                             }
 8298:                         }
 8299:                     }
 8300:                 }
 8301:             }
 8302:         } else {
 8303:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8304:                 $thisallowed.=$1;
 8305:             }
 8306:         }
 8307:     }
 8308: 
 8309: # URI is an uploaded document for this course, default permissions don't matter
 8310: # not allowing 'edit' access (editupload) to uploaded course docs
 8311:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8312: 	$thisallowed='';
 8313:         my ($match)=&is_on_map($uri);
 8314:         if ($match) {
 8315:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8316:                   =~/\Q$priv\E\&([^\:]*)/) {
 8317:                 my $value = $1;
 8318:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8319:                 if ($deeplinkblock) {
 8320:                     $thisallowed='D';
 8321:                 } elsif ($noblockcheck) {
 8322:                     $thisallowed.=$value;
 8323:                 } else {
 8324:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8325:                     if (@blockers > 0) {
 8326:                         $thisallowed = 'B';
 8327:                     } else {
 8328:                         $thisallowed.=$value;
 8329:                     }
 8330:                 }
 8331:             }
 8332:         } else {
 8333:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8334:             if ($refuri) {
 8335:                 if ($refuri =~ m|^/adm/|) {
 8336:                     $thisallowed='F';
 8337:                 } else {
 8338:                     $refuri=&declutter($refuri);
 8339:                     my ($match) = &is_on_map($refuri);
 8340:                     if ($match) {
 8341:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8342:                         if ($deeplinkblock) {
 8343:                             $thisallowed='D';
 8344:                         } elsif ($noblockcheck) {
 8345:                             $thisallowed='F';
 8346:                         } else {
 8347:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8348:                             if (@blockers > 0) {
 8349:                                 $thisallowed = 'B';
 8350:                             } else {
 8351:                                 $thisallowed='F';
 8352:                             }
 8353:                         }
 8354:                     }
 8355:                 }
 8356:             }
 8357:         }
 8358:     }
 8359: 
 8360:     if ($priv eq 'bre'
 8361: 	&& $thisallowed ne 'F' 
 8362: 	&& $thisallowed ne '2'
 8363: 	&& &is_portfolio_url($uri)) {
 8364: 	$thisallowed = &portfolio_access($uri,$clientip);
 8365:     }
 8366: 
 8367: # Full access at system, domain or course-wide level? Exit.
 8368:     if ($thisallowed=~/F/) {
 8369: 	return 'F';
 8370:     }
 8371: 
 8372: # If this is generating or modifying users, exit with special codes
 8373: 
 8374:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8375: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8376: 	    my ($audom,$auname)=split('/',$uri);
 8377: # no author name given, so this just checks on the general right to make a co-author in this domain
 8378: 	    unless ($auname) { return $thisallowed; }
 8379: # an author name is given, so we are about to actually make a co-author for a certain account
 8380: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8381: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8382: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8383: 	}
 8384: 	return $thisallowed;
 8385:     }
 8386: #
 8387: # Gathered so far: system, domain and course wide privileges
 8388: #
 8389: # Course: See if uri or referer is an individual resource that is part of 
 8390: # the course
 8391: 
 8392:     if ($env{'request.course.id'}) {
 8393: 
 8394: # If this is modifying password (internal auth) domains must match for user and user's role.
 8395: 
 8396:         if ($priv eq 'mip') {
 8397:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8398:                 return $thisallowed;
 8399:             } else {
 8400:                 return '';
 8401:             }
 8402:         }
 8403: 
 8404:        $courseprivid=$env{'request.course.id'};
 8405:        if ($env{'request.course.sec'}) {
 8406:           $courseprivid.='/'.$env{'request.course.sec'};
 8407:        }
 8408:        $courseprivid=~s/\_/\//;
 8409:        my $checkreferer=1;
 8410:        my ($match,$cond)=&is_on_map($uri);
 8411:        if ($match) {
 8412:            $statecond=$cond;
 8413:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8414:                =~/\Q$priv\E\&([^\:]*)/) {
 8415:                my $value = $1;
 8416:                if ($priv eq 'bre') {
 8417:                    if ($noblockcheck) {
 8418:                        $thisallowed.=$value;
 8419:                    } else {
 8420:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8421:                        if (@blockers > 0) {
 8422:                            $thisallowed = 'B';
 8423:                        } else {
 8424:                            $thisallowed.=$value;
 8425:                        }
 8426:                    }
 8427:                } else {
 8428:                    $thisallowed.=$value;
 8429:                }
 8430:                $checkreferer=0;
 8431:            }
 8432:        }
 8433: 
 8434:        if ($checkreferer) {
 8435: 	  my $refuri=$env{'httpref.'.$orguri};
 8436:             unless ($refuri) {
 8437:                 foreach my $key (keys(%env)) {
 8438: 		    if ($key=~/^httpref\..*\*/) {
 8439: 			my $pattern=$key;
 8440:                         $pattern=~s/^httpref\.\/res\///;
 8441:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8442:                         $pattern=~s/\//\\\//g;
 8443:                         if ($orguri=~/$pattern/) {
 8444: 			    $refuri=$env{$key};
 8445:                         }
 8446:                     }
 8447:                 }
 8448:             }
 8449: 
 8450:          if ($refuri) { 
 8451: 	  $refuri=&declutter($refuri);
 8452:           my ($match,$cond)=&is_on_map($refuri);
 8453:             if ($match) {
 8454:               my $refstatecond=$cond;
 8455:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8456:                   =~/\Q$priv\E\&([^\:]*)/) {
 8457:                   my $value = $1;
 8458:                   if ($priv eq 'bre') {
 8459:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8460:                       if ($deeplinkblock) {
 8461:                           $thisallowed = 'D';
 8462:                       } elsif ($noblockcheck) {
 8463:                           $thisallowed.=$value;
 8464:                       } else {
 8465:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8466:                           if (@blockers > 0) {
 8467:                               $thisallowed = 'B';
 8468:                           } else {
 8469:                               $thisallowed.=$value;
 8470:                           }
 8471:                       }
 8472:                   } else {
 8473:                       $thisallowed.=$value;
 8474:                   }
 8475:                   $uri=$refuri;
 8476:                   $statecond=$refstatecond;
 8477:               }
 8478:           }
 8479:         }
 8480:        }
 8481:    }
 8482: 
 8483: #
 8484: # Gathered now: all privileges that could apply, and condition number
 8485: # 
 8486: #
 8487: # Full or no access?
 8488: #
 8489: 
 8490:     if ($thisallowed=~/F/) {
 8491: 	return 'F';
 8492:     }
 8493: 
 8494:     unless ($thisallowed) {
 8495:         return '';
 8496:     }
 8497: 
 8498: # Restrictions exist, deal with them
 8499: #
 8500: #   C:according to course preferences
 8501: #   R:according to resource settings
 8502: #   L:unless locked
 8503: #   X:according to user session state
 8504: #
 8505: 
 8506: # Possibly locked functionality, check all courses
 8507: # Locks might take effect only after 10 minutes cache expiration for other
 8508: # courses, and 2 minutes for current course
 8509: 
 8510:     my $envkey;
 8511:     if ($thisallowed=~/L/) {
 8512:         foreach $envkey (keys(%env)) {
 8513:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8514:                my $courseid=$2;
 8515:                my $roleid=$1.'.'.$2;
 8516:                $courseid=~s/^\///;
 8517:                my $expiretime=600;
 8518:                if ($env{'request.role'} eq $roleid) {
 8519: 		  $expiretime=120;
 8520:                }
 8521: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8522:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8523:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8524: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8525:                }
 8526:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8527:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8528: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8529:                        &log($env{'user.domain'},$env{'user.name'},
 8530:                             $env{'user.home'},
 8531:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8532:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8533:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8534: 		       return '';
 8535:                    }
 8536:                }
 8537:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8538:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8539: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8540:                        &log($env{'user.domain'},$env{'user.name'},
 8541:                             $env{'user.home'},
 8542:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8543:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8544:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8545: 		       return '';
 8546:                    }
 8547:                }
 8548: 	   }
 8549:        }
 8550:     }
 8551: 
 8552: #
 8553: # Rest of the restrictions depend on selected course
 8554: #
 8555: 
 8556:     unless ($env{'request.course.id'}) {
 8557: 	if ($thisallowed eq 'A') {
 8558: 	    return 'A';
 8559:         } elsif ($thisallowed eq 'B') {
 8560:             return 'B';
 8561: 	} else {
 8562: 	    return '1';
 8563: 	}
 8564:     }
 8565: 
 8566: #
 8567: # Now user is definitely in a course
 8568: #
 8569: 
 8570: 
 8571: # Course preferences
 8572: 
 8573:    if ($thisallowed=~/C/) {
 8574:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8575:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8576:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8577: 	   =~/\Q$rolecode\E/) {
 8578: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8579: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8580: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8581: 			$env{'request.course.id'});
 8582: 	   }
 8583:            return '';
 8584:        }
 8585: 
 8586:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8587: 	   =~/\Q$unamedom\E/) {
 8588: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8589: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8590: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8591: 			$env{'request.course.id'});
 8592: 	   }
 8593:            return '';
 8594:        }
 8595:    }
 8596: 
 8597: # Resource preferences
 8598: 
 8599:    if ($thisallowed=~/R/) {
 8600:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8601:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8602: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8605: 	   }
 8606: 	   return '';
 8607:        }
 8608:    }
 8609: 
 8610: # Restricted by state or randomout?
 8611: 
 8612:    if ($thisallowed=~/X/) {
 8613:       if ($env{'acc.randomout'}) {
 8614: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8615:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8616:             return ''; 
 8617:          }
 8618:       }
 8619:       if (&condval($statecond)) {
 8620: 	 return '2';
 8621:       } else {
 8622:          return '';
 8623:       }
 8624:    }
 8625: 
 8626:     if ($thisallowed eq 'A') {
 8627: 	return 'A';
 8628:     } elsif ($thisallowed eq 'B') {
 8629:         return 'B';
 8630:     } elsif ($thisallowed eq 'D') {
 8631:         return 'D';
 8632:     }
 8633:    return 'F';
 8634: }
 8635: 
 8636: # ------------------------------------------- Check construction space access
 8637: 
 8638: sub constructaccess {
 8639:     my ($url,$setpriv)=@_;
 8640: 
 8641: # We do not allow editing of previous versions of files
 8642:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8643: 
 8644: # Get username and domain from URL
 8645:     my ($ownername,$ownerdomain,$ownerhome);
 8646: 
 8647:     ($ownerdomain,$ownername) =
 8648:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8649: 
 8650: # The URL does not really point to any authorspace, forget it
 8651:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8652: 
 8653: # Now we need to see if the user has access to the authorspace of
 8654: # $ownername at $ownerdomain
 8655: 
 8656:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8657: # Real author for this?
 8658:        $ownerhome = $env{'user.home'};
 8659:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8660:           return ($ownername,$ownerdomain,$ownerhome);
 8661:        }
 8662:     } else {
 8663: # Co-author for this?
 8664:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8665:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8666:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8667:             return ($ownername,$ownerdomain,$ownerhome);
 8668:         }
 8669:         if ($env{'request.course.id'}) {
 8670:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8671:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8672:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8673:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8674:                     return ($ownername,$ownerdomain,$ownerhome);
 8675:                 }
 8676:             }
 8677:         }
 8678:     }
 8679: 
 8680: # We don't have any access right now. If we are not possibly going to do anything about this,
 8681: # we might as well leave
 8682:    unless ($setpriv) { return ''; }
 8683: 
 8684: # Backdoor access?
 8685:     my $allowed=&allowed('eco',$ownerdomain);
 8686: # Nope
 8687:     unless ($allowed) { return ''; }
 8688: # Looks like we may have access, but could be locked by the owner of the construction space
 8689:     if ($allowed eq 'U') {
 8690:         my %blocked=&get('environment',['domcoord.author'],
 8691:                          $ownerdomain,$ownername);
 8692: # Is blocked by owner
 8693:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8694:     }
 8695:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8696: # Grant temporary access
 8697:         my $then=$env{'user.login.time'};
 8698:         my $update=$env{'user.update.time'};
 8699:         if (!$update) { $update = $then; }
 8700:         my $refresh=$env{'user.refresh.time'};
 8701:         if (!$refresh) { $refresh = $update; }
 8702:         my $now = time;
 8703:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8704:                            $now,'ca','constructaccess');
 8705:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8706:         return($ownername,$ownerdomain,$ownerhome);
 8707:     }
 8708: # No business here
 8709:     return '';
 8710: }
 8711: 
 8712: # ----------------------------------------------------------- Content Blocking
 8713: 
 8714: {
 8715: # Caches for faster Course Contents display where content blocking
 8716: # is in operation (i.e., interval param set) for timed quiz.
 8717: #
 8718: # User for whom data are being temporarily cached.
 8719: my $cacheduser='';
 8720: # Course for which data are being temporarily cached.
 8721: my $cachedcid='';
 8722: # Cached blockers for this user (a hash of blocking items). 
 8723: my %cachedblockers=();
 8724: # When the data were last cached.
 8725: my $cachedlast='';
 8726: 
 8727: sub load_all_blockers {
 8728:     my ($uname,$udom)=@_;
 8729:     if (($uname ne '') && ($udom ne '')) { 
 8730:         if (($cacheduser eq $uname.':'.$udom) &&
 8731:             ($cachedcid eq $env{'request.course.id'}) &&
 8732:             (abs($cachedlast-time)<5)) {
 8733:             return;
 8734:         }
 8735:     }
 8736:     $cachedlast=time;
 8737:     $cacheduser=$uname.':'.$udom;
 8738:     $cachedcid=$env{'request.course.id'};
 8739:     %cachedblockers = &get_commblock_resources();
 8740:     return;
 8741: }
 8742: 
 8743: sub get_comm_blocks {
 8744:     my ($cdom,$cnum) = @_;
 8745:     if ($cdom eq '' || $cnum eq '') {
 8746:         return unless ($env{'request.course.id'});
 8747:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8748:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8749:     }
 8750:     my %commblocks;
 8751:     my $hashid=$cdom.'_'.$cnum;
 8752:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8753:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8754:         %commblocks = %{$blocksref};
 8755:     } else {
 8756:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8757:         my $cachetime = 600;
 8758:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8759:     }
 8760:     return %commblocks;
 8761: }
 8762: 
 8763: sub get_commblock_resources {
 8764:     my ($blocks) = @_;
 8765:     my %blockers = ();
 8766:     return %blockers unless ($env{'request.course.id'});
 8767:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8768:     my %commblocks;
 8769:     if (ref($blocks) eq 'HASH') {
 8770:         %commblocks = %{$blocks};
 8771:     } else {
 8772:         %commblocks = &get_comm_blocks();
 8773:     }
 8774:     return %blockers unless (keys(%commblocks) > 0); 
 8775:     my $navmap = Apache::lonnavmaps::navmap->new();
 8776:     return %blockers unless (ref($navmap));
 8777:     my $now = time;
 8778:     foreach my $block (keys(%commblocks)) {
 8779:         if ($block =~ /^(\d+)____(\d+)$/) {
 8780:             my ($start,$end) = ($1,$2);
 8781:             if ($start <= $now && $end >= $now) {
 8782:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8783:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8784:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8785:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8786:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8787:                             }
 8788:                         }
 8789:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8790:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8791:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8792:                             }
 8793:                         }
 8794:                     }
 8795:                 }
 8796:             }
 8797:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8798:             my $item = $1;
 8799:             my @to_test;
 8800:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8801:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8802:                     my @interval;
 8803:                     my $type = 'map';
 8804:                     if ($item eq 'course') {
 8805:                         $type = 'course';
 8806:                         @interval=&EXT("resource.0.interval");
 8807:                     } else {
 8808:                         if ($item =~ /___\d+___/) {
 8809:                             $type = 'resource';
 8810:                             @interval=&EXT("resource.0.interval",$item);
 8811:                             if (ref($navmap)) {                        
 8812:                                 my $res = $navmap->getBySymb($item); 
 8813:                                 push(@to_test,$res);
 8814:                             }
 8815:                         } else {
 8816:                             my $mapsymb = &symbread($item,1);
 8817:                             if ($mapsymb) {
 8818:                                 if (ref($navmap)) {
 8819:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8820:                                     if (ref($mapres)) {
 8821:                                         my $first = $mapres->map_start();
 8822:                                         my $finish = $mapres->map_finish();
 8823:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8824:                                         if (ref($it)) {
 8825:                                             my $res;
 8826:                                             while ($res = $it->next(undef,1)) {
 8827:                                                 next unless (ref($res));
 8828:                                                 my $symb = $res->symb();
 8829:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8830:                                                 @interval=&EXT("resource.0.interval",$symb);
 8831:                                                 if ($interval[1] eq 'map') {
 8832:                                                     if ($res->answerable()) {
 8833:                                                         push(@to_test,$res);
 8834:                                                         last;
 8835:                                                     }
 8836:                                                 }
 8837:                                             }
 8838:                                         }
 8839:                                     }
 8840:                                 }
 8841:                             }
 8842:                         }
 8843:                     }
 8844:                     if ($interval[0] =~ /^(\d+)/) {
 8845:                         my $timelimit = $1; 
 8846:                         my $first_access;
 8847:                         if ($type eq 'resource') {
 8848:                             $first_access=&get_first_access($interval[1],$item);
 8849:                         } elsif ($type eq 'map') {
 8850:                             $first_access=&get_first_access($interval[1],undef,$item);
 8851:                         } else {
 8852:                             $first_access=&get_first_access($interval[1]);
 8853:                         }
 8854:                         if ($first_access) {
 8855:                             my $timesup = $first_access+$timelimit;
 8856:                             if ($timesup > $now) {
 8857:                                 my $activeblock;
 8858:                                 foreach my $res (@to_test) {
 8859:                                     if ($res->answerable()) {
 8860:                                         $activeblock = 1;
 8861:                                         last;
 8862:                                     }
 8863:                                 }
 8864:                                 if ($activeblock) {
 8865:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8866:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8867:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8868:                                          }
 8869:                                     }
 8870:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8871:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8872:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8873:                                         }
 8874:                                     }
 8875:                                 }
 8876:                             }
 8877:                         }
 8878:                     }
 8879:                 }
 8880:             }
 8881:         }
 8882:     }
 8883:     return %blockers;
 8884: }
 8885: 
 8886: sub has_comm_blocking {
 8887:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8888:     my @blockers;
 8889:     return unless ($env{'request.course.id'});
 8890:     return unless ($priv eq 'bre');
 8891:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8892:     return if ($env{'request.state'} eq 'construct');
 8893:     my %blockinfo;
 8894:     if (ref($blocks) eq 'HASH') {
 8895:         %blockinfo = &get_commblock_resources($blocks);
 8896:     } else {
 8897:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8898:         %blockinfo = %cachedblockers;
 8899:     }
 8900:     return unless (keys(%blockinfo) > 0);
 8901:     my (%possibles,@symbs);
 8902:     if (!$symb) {
 8903:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8904:     }
 8905:     if ($symb) {
 8906:         @symbs = ($symb);
 8907:     } elsif (keys(%possibles)) { 
 8908:         @symbs = keys(%possibles);
 8909:     }
 8910:     my $noblock;
 8911:     foreach my $symb (@symbs) {
 8912:         last if ($noblock);
 8913:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8914:         foreach my $block (keys(%blockinfo)) {
 8915:             if ($block =~ /^firstaccess____(.+)$/) {
 8916:                 my $item = $1;
 8917:                 unless ($blocked) {
 8918:                     if (($item eq $map) || ($item eq $symb)) {
 8919:                         $noblock = 1;
 8920:                         last;
 8921:                     }
 8922:                 }
 8923:             }
 8924:             if (ref($blockinfo{$block}) eq 'HASH') {
 8925:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8926:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8927:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8928:                             push(@blockers,$block);
 8929:                         }
 8930:                     }
 8931:                 }
 8932:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8933:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8934:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8935:                             push(@blockers,$block);
 8936:                         }
 8937:                     }
 8938:                 }
 8939:             }
 8940:         }
 8941:     }
 8942:     unless ($noblock) { 
 8943:         return @blockers;
 8944:     }
 8945:     return;
 8946: }
 8947: }
 8948: 
 8949: sub deeplink_check {
 8950:     my ($priv,$symb,$uri) = @_;
 8951:     return unless ($env{'request.course.id'});
 8952:     return unless ($priv eq 'bre');
 8953:     return if ($env{'request.state'} eq 'construct');
 8954:     return if ($env{'request.role.adv'});
 8955:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8956:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8957:     my (%possibles,@symbs);
 8958:     if (!$symb) {
 8959:         $symb = &symbread($uri,1,1,1,\%possibles);
 8960:     }
 8961:     if ($symb) {
 8962:         @symbs = ($symb);
 8963:     } elsif (keys(%possibles)) {
 8964:         @symbs = keys(%possibles);
 8965:     }
 8966: 
 8967:     my ($login,$switchrole,$allow);
 8968:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8969:         my $key = $1;
 8970:         my $tinyurl;
 8971:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8972:         if (defined($cached)) {
 8973:              $tinyurl = $result;
 8974:         } else {
 8975:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8976:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8977:              if ($currtiny{$key} ne '') {
 8978:                  $tinyurl = $currtiny{$key};
 8979:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8980:              }
 8981:         }
 8982:         if ($tinyurl ne '') {
 8983:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8984:             if ($cnumreq eq $cnum) {
 8985:                 $login = $posslogin;
 8986:             } else {
 8987:                 $switchrole = 1;
 8988:             }
 8989:         }
 8990:     }
 8991:     foreach my $symb (@symbs) {
 8992:         last if ($allow);
 8993:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8994:         if ($deeplink eq '') {
 8995:             $allow = 1;
 8996:         } else {
 8997:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8998:             if ($access eq 'any') {
 8999:                 $allow = 1;
 9000:             } elsif ($login) {
 9001:                 if ($access eq 'only') {
 9002:                     if ($scope eq 'res') {
 9003:                         if ($symb eq $login) {
 9004:                             $allow = 1;
 9005:                         }
 9006:                     } elsif ($scope eq 'map') {
 9007: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 9008:                     } elsif ($scope eq 'rec') {
 9009: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 9010:                     }
 9011:                 } else {
 9012:                     my ($acctype,$item) = split(/:/,$access);
 9013:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 9014:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 9015:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9016:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 9017:                                 $allow = 1;
 9018:                             }
 9019:                         }
 9020:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9021:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9022:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9023:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 9024:                                 $allow = 1;
 9025:                             }
 9026:                         }
 9027:                     }
 9028:                 }
 9029:             }
 9030:         }
 9031:     }
 9032:     return if ($allow);
 9033:     return 1;
 9034: }
 9035: 
 9036: # -------------------------------- Deversion and split uri into path an filename   
 9037: 
 9038: #
 9039: #   Removes the version from a URI and
 9040: #   splits it in to its filename and path to the filename.
 9041: #   Seems like File::Basename could have done this more clearly.
 9042: #   Parameters:
 9043: #      $uri   - input URI
 9044: #   Returns:
 9045: #     Two element list consisting of 
 9046: #     $pathname  - the URI up to and excluding the trailing /
 9047: #     $filename  - The part of the URI following the last /
 9048: #  NOTE:
 9049: #    Another realization of this is simply:
 9050: #    use File::Basename;
 9051: #    ...
 9052: #    $uri = shift;
 9053: #    $filename = basename($uri);
 9054: #    $path     = dirname($uri);
 9055: #    return ($filename, $path);
 9056: #
 9057: #     The implementation below is probably faster however.
 9058: #
 9059: sub split_uri_for_cond {
 9060:     my $uri=&deversion(&declutter(shift));
 9061:     my @uriparts=split(/\//,$uri);
 9062:     my $filename=pop(@uriparts);
 9063:     my $pathname=join('/',@uriparts);
 9064:     return ($pathname,$filename);
 9065: }
 9066: # --------------------------------------------------- Is a resource on the map?
 9067: 
 9068: sub is_on_map {
 9069:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9070:     #Trying to find the conditional for the file
 9071:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9072: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9073:     if ($match) {
 9074: 	return (1,$1);
 9075:     } else {
 9076: 	return (0,0);
 9077:     }
 9078: }
 9079: 
 9080: # --------------------------------------------------------- Get symb from alias
 9081: 
 9082: sub get_symb_from_alias {
 9083:     my $symb=shift;
 9084:     my ($map,$resid,$url)=&decode_symb($symb);
 9085: # Already is a symb
 9086:     if ($url) { return $symb; }
 9087: # Must be an alias
 9088:     my $aliassymb='';
 9089:     my %bighash;
 9090:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9091:                             &GDBM_READER(),0640)) {
 9092:         my $rid=$bighash{'mapalias_'.$symb};
 9093: 	if ($rid) {
 9094: 	    my ($mapid,$resid)=split(/\./,$rid);
 9095: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9096: 				    $resid,$bighash{'src_'.$rid});
 9097: 	}
 9098:         untie %bighash;
 9099:     }
 9100:     return $aliassymb;
 9101: }
 9102: 
 9103: # ----------------------------------------------------------------- Define Role
 9104: 
 9105: sub definerole {
 9106:   if (allowed('mcr','/')) {
 9107:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9108:     foreach my $role (split(':',$sysrole)) {
 9109: 	my ($crole,$cqual)=split(/\&/,$role);
 9110:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9111:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9112: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9113:                return "refused:s:$crole&$cqual"; 
 9114:             }
 9115:         }
 9116:     }
 9117:     foreach my $role (split(':',$domrole)) {
 9118: 	my ($crole,$cqual)=split(/\&/,$role);
 9119:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9120:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9121: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9122:                return "refused:d:$crole&$cqual"; 
 9123:             }
 9124:         }
 9125:     }
 9126:     foreach my $role (split(':',$courole)) {
 9127: 	my ($crole,$cqual)=split(/\&/,$role);
 9128:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9129:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9130: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9131:                return "refused:c:$crole&$cqual"; 
 9132:             }
 9133:         }
 9134:     }
 9135:     my $uhome;
 9136:     if (($uname ne '') && ($udom ne '')) {
 9137:         $uhome = &homeserver($uname,$udom);
 9138:         return $uhome if ($uhome eq 'no_host');
 9139:     } else {
 9140:         $uname = $env{'user.name'};
 9141:         $udom = $env{'user.domain'};
 9142:         $uhome = $env{'user.home'};
 9143:     }
 9144:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9145:                 "$udom:$uname:rolesdef_$rolename=".
 9146:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9147:     return reply($command,$uhome);
 9148:   } else {
 9149:     return 'refused';
 9150:   }
 9151: }
 9152: 
 9153: # ---------------- Make a metadata query against the network of library servers
 9154: 
 9155: sub metadata_query {
 9156:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9157:     my %rhash;
 9158:     my %libserv = &all_library();
 9159:     my @server_list = (defined($server_array) ? @$server_array
 9160:                                               : keys(%libserv) );
 9161:     for my $server (@server_list) {
 9162:         my $domains = ''; 
 9163:         if (ref($domains_hash) eq 'HASH') {
 9164:             $domains = $domains_hash->{$server}; 
 9165:         }
 9166: 	unless ($custom or $customshow) {
 9167: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9168: 	    $rhash{$server}=$reply;
 9169: 	}
 9170: 	else {
 9171: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9172: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9173: 			     $server);
 9174: 	    $rhash{$server}=$reply;
 9175: 	}
 9176:     }
 9177:     return \%rhash;
 9178: }
 9179: 
 9180: # ----------------------------------------- Send log queries and wait for reply
 9181: 
 9182: sub log_query {
 9183:     my ($uname,$udom,$query,%filters)=@_;
 9184:     my $uhome=&homeserver($uname,$udom);
 9185:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9186:     my $uhost=&hostname($uhome);
 9187:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9188:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9189:                        $uhome);
 9190:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9191:     return get_query_reply($queryid);
 9192: }
 9193: 
 9194: # -------------------------- Update MySQL table for portfolio file
 9195: 
 9196: sub update_portfolio_table {
 9197:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9198:     if ($group ne '') {
 9199:         $file_name =~s /^\Q$group\E//;
 9200:     }
 9201:     my $homeserver = &homeserver($uname,$udom);
 9202:     my $queryid=
 9203:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9204:                ':'.&escape($file_name).':'.$action,$homeserver);
 9205:     my $reply = &get_query_reply($queryid);
 9206:     return $reply;
 9207: }
 9208: 
 9209: # -------------------------- Update MySQL allusers table
 9210: 
 9211: sub update_allusers_table {
 9212:     my ($uname,$udom,$names) = @_;
 9213:     my $homeserver = &homeserver($uname,$udom);
 9214:     my $queryid=
 9215:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9216:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9217:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9218:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9219:                'generation='.&escape($names->{'generation'}).'%%'.
 9220:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9221:                'id='.&escape($names->{'id'}),$homeserver);
 9222:     return;
 9223: }
 9224: 
 9225: # ------- Request retrieval of institutional classlists for course(s)
 9226: 
 9227: sub fetch_enrollment_query {
 9228:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9229:     my ($homeserver,$sleep,$loopmax);
 9230:     my $maxtries = 1;
 9231:     if ($context eq 'automated') {
 9232:         $homeserver = $perlvar{'lonHostID'};
 9233:         $sleep = 2;
 9234:         $loopmax = 100;
 9235:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9236:     } else {
 9237:         $homeserver = &homeserver($cnum,$dom);
 9238:     }
 9239:     my $host=&hostname($homeserver);
 9240:     my $cmd = '';
 9241:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9242:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9243:     }
 9244:     $cmd =~ s/%%$//;
 9245:     $cmd = &escape($cmd);
 9246:     my $query = 'fetchenrollment';
 9247:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9248:     unless ($queryid=~/^\Q$host\E\_/) { 
 9249:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9250:         return 'error: '.$queryid;
 9251:     }
 9252:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9253:     my $tries = 1;
 9254:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9255:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9256:         $tries ++;
 9257:     }
 9258:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9259:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9260:     } else {
 9261:         my @responses = split(/:/,$reply);
 9262:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9263:             foreach my $line (@responses) {
 9264:                 my ($key,$value) = split(/=/,$line,2);
 9265:                 $$replyref{$key} = $value;
 9266:             }
 9267:         } else {
 9268:             my $pathname = LONCAPA::tempdir();
 9269:             foreach my $line (@responses) {
 9270:                 my ($key,$value) = split(/=/,$line);
 9271:                 $$replyref{$key} = $value;
 9272:                 if ($value > 0) {
 9273:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9274:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9275:                         my $destname = $pathname.'/'.$filename;
 9276:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9277:                         if ($xml_classlist =~ /^error/) {
 9278:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9279:                         } else {
 9280:                             if ( open(FILE,">",$destname) ) {
 9281:                                 print FILE &unescape($xml_classlist);
 9282:                                 close(FILE);
 9283:                             } else {
 9284:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9285:                             }
 9286:                         }
 9287:                     }
 9288:                 }
 9289:             }
 9290:         }
 9291:         return 'ok';
 9292:     }
 9293:     return 'error';
 9294: }
 9295: 
 9296: sub get_query_reply {
 9297:     my ($queryid,$sleep,$loopmax) = @_;;
 9298:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9299:         $sleep = 0.2;
 9300:     }
 9301:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9302:         $loopmax = 100;
 9303:     }
 9304:     my $replyfile=LONCAPA::tempdir().$queryid;
 9305:     my $reply='';
 9306:     for (1..$loopmax) {
 9307: 	sleep($sleep);
 9308:         if (-e $replyfile.'.end') {
 9309: 	    if (open(my $fh,"<",$replyfile)) {
 9310: 		$reply = join('',<$fh>);
 9311: 		close($fh);
 9312: 	   } else { return 'error: reply_file_error'; }
 9313:            return &unescape($reply);
 9314: 	}
 9315:     }
 9316:     return 'timeout:'.$queryid;
 9317: }
 9318: 
 9319: sub courselog_query {
 9320: #
 9321: # possible filters:
 9322: # url: url or symb
 9323: # username
 9324: # domain
 9325: # action: view, submit, grade
 9326: # start: timestamp
 9327: # end: timestamp
 9328: #
 9329:     my (%filters)=@_;
 9330:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9331:     if ($filters{'url'}) {
 9332: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9333:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9334:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9335:     }
 9336:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9337:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9338:     return &log_query($cname,$cdom,'courselog',%filters);
 9339: }
 9340: 
 9341: sub userlog_query {
 9342: #
 9343: # possible filters:
 9344: # action: log check role
 9345: # start: timestamp
 9346: # end: timestamp
 9347: #
 9348:     my ($uname,$udom,%filters)=@_;
 9349:     return &log_query($uname,$udom,'userlog',%filters);
 9350: }
 9351: 
 9352: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9353: 
 9354: sub auto_run {
 9355:     my ($cnum,$cdom) = @_;
 9356:     my $response = 0;
 9357:     my $settings;
 9358:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9359:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9360:         $settings = $domconfig{'autoenroll'};
 9361:         if ($settings->{'run'} eq '1') {
 9362:             $response = 1;
 9363:         }
 9364:     } else {
 9365:         my $homeserver;
 9366:         if (&is_course($cdom,$cnum)) {
 9367:             $homeserver = &homeserver($cnum,$cdom);
 9368:         } else {
 9369:             $homeserver = &domain($cdom,'primary');
 9370:         }
 9371:         if ($homeserver ne 'no_host') {
 9372:             $response = &reply('autorun:'.$cdom,$homeserver);
 9373:         }
 9374:     }
 9375:     return $response;
 9376: }
 9377: 
 9378: sub auto_get_sections {
 9379:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9380:     my $homeserver;
 9381:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9382:         $homeserver = &homeserver($cnum,$cdom);
 9383:     }
 9384:     if (!defined($homeserver)) { 
 9385:         if ($cdom =~ /^$match_domain$/) {
 9386:             $homeserver = &domain($cdom,'primary');
 9387:         }
 9388:     }
 9389:     my @secs;
 9390:     if (defined($homeserver)) {
 9391:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9392:         unless ($response eq 'refused') {
 9393:             @secs = split(/:/,$response);
 9394:         }
 9395:     }
 9396:     return @secs;
 9397: }
 9398: 
 9399: sub auto_new_course {
 9400:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9401:     my $homeserver = &homeserver($cnum,$cdom);
 9402:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9403:     return $response;
 9404: }
 9405: 
 9406: sub auto_validate_courseID {
 9407:     my ($cnum,$cdom,$inst_course_id) = @_;
 9408:     my $homeserver = &homeserver($cnum,$cdom);
 9409:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9410:     return $response;
 9411: }
 9412: 
 9413: sub auto_validate_instcode {
 9414:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9415:     my ($homeserver,$response);
 9416:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9417:         $homeserver = &homeserver($cnum,$cdom);
 9418:     }
 9419:     if (!defined($homeserver)) {
 9420:         if ($cdom =~ /^$match_domain$/) {
 9421:             $homeserver = &domain($cdom,'primary');
 9422:         }
 9423:     }
 9424:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9425:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9426:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9427:     return ($outcome,$description,$defaultcredits);
 9428: }
 9429: 
 9430: sub auto_validate_inst_crosslist {
 9431:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9432:     my ($homeserver,$response);
 9433:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9434:         $homeserver = &homeserver($cnum,$cdom);
 9435:     }
 9436:     if (!defined($homeserver)) {
 9437:         if ($cdom =~ /^$match_domain$/) {
 9438:             $homeserver = &domain($cdom,'primary');
 9439:         }
 9440:     }
 9441:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9442:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9443:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9444:                          &escape($coowner),$homeserver);
 9445:     }
 9446:     return $response;
 9447: }
 9448: 
 9449: sub auto_create_password {
 9450:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9451:     my ($homeserver,$response);
 9452:     my $create_passwd = 0;
 9453:     my $authchk = '';
 9454:     if ($udom =~ /^$match_domain$/) {
 9455:         $homeserver = &domain($udom,'primary');
 9456:     }
 9457:     if ($homeserver eq '') {
 9458:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9459:             $homeserver = &homeserver($cnum,$cdom);
 9460:         }
 9461:     }
 9462:     if ($homeserver eq '') {
 9463:         $authchk = 'nodomain';
 9464:     } else {
 9465:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9466:         if ($response eq 'refused') {
 9467:             $authchk = 'refused';
 9468:         } else {
 9469:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9470:         }
 9471:     }
 9472:     return ($authparam,$create_passwd,$authchk);
 9473: }
 9474: 
 9475: sub auto_photo_permission {
 9476:     my ($cnum,$cdom,$students) = @_;
 9477:     my $homeserver = &homeserver($cnum,$cdom);
 9478:     my ($outcome,$perm_reqd,$conditions) = 
 9479: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9480:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9481: 	return (undef,undef);
 9482:     }
 9483:     return ($outcome,$perm_reqd,$conditions);
 9484: }
 9485: 
 9486: sub auto_checkphotos {
 9487:     my ($uname,$udom,$pid) = @_;
 9488:     my $homeserver = &homeserver($uname,$udom);
 9489:     my ($result,$resulttype);
 9490:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9491: 				   &escape($uname).':'.&escape($pid),
 9492: 				   $homeserver));
 9493:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9494: 	return (undef,undef);
 9495:     }
 9496:     if ($outcome) {
 9497:         ($result,$resulttype) = split(/:/,$outcome);
 9498:     } 
 9499:     return ($result,$resulttype);
 9500: }
 9501: 
 9502: sub auto_photochoice {
 9503:     my ($cnum,$cdom) = @_;
 9504:     my $homeserver = &homeserver($cnum,$cdom);
 9505:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9506: 						       &escape($cdom),
 9507: 						       $homeserver)));
 9508:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9509: 	return (undef,undef);
 9510:     }
 9511:     return ($update,$comment);
 9512: }
 9513: 
 9514: sub auto_photoupdate {
 9515:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9516:     my $homeserver = &homeserver($cnum,$dom);
 9517:     my $host=&hostname($homeserver);
 9518:     my $cmd = '';
 9519:     my $maxtries = 1;
 9520:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9521:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9522:     }
 9523:     $cmd =~ s/%%$//;
 9524:     $cmd = &escape($cmd);
 9525:     my $query = 'institutionalphotos';
 9526:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9527:     unless ($queryid=~/^\Q$host\E\_/) {
 9528:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9529:         return 'error: '.$queryid;
 9530:     }
 9531:     my $reply = &get_query_reply($queryid);
 9532:     my $tries = 1;
 9533:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9534:         $reply = &get_query_reply($queryid);
 9535:         $tries ++;
 9536:     }
 9537:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9538:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9539:     } else {
 9540:         my @responses = split(/:/,$reply);
 9541:         my $outcome = shift(@responses); 
 9542:         foreach my $item (@responses) {
 9543:             my ($key,$value) = split(/=/,$item);
 9544:             $$photo{$key} = $value;
 9545:         }
 9546:         return $outcome;
 9547:     }
 9548:     return 'error';
 9549: }
 9550: 
 9551: sub auto_instcode_format {
 9552:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9553: 	$cat_order) = @_;
 9554:     my $courses = '';
 9555:     my @homeservers;
 9556:     if ($caller eq 'global') {
 9557: 	my %servers = &get_servers($codedom,'library');
 9558: 	foreach my $tryserver (keys(%servers)) {
 9559: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9560: 		push(@homeservers,$tryserver);
 9561: 	    }
 9562:         }
 9563:     } elsif ($caller eq 'requests') {
 9564:         if ($codedom =~ /^$match_domain$/) {
 9565:             my $chome = &domain($codedom,'primary');
 9566:             unless ($chome eq 'no_host') {
 9567:                 push(@homeservers,$chome);
 9568:             }
 9569:         }
 9570:     } else {
 9571:         push(@homeservers,&homeserver($caller,$codedom));
 9572:     }
 9573:     foreach my $code (keys(%{$instcodes})) {
 9574:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9575:     }
 9576:     chop($courses);
 9577:     my $ok_response = 0;
 9578:     my $response;
 9579:     while (@homeservers > 0 && $ok_response == 0) {
 9580:         my $server = shift(@homeservers); 
 9581:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9582:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9583:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9584: 		split(/:/,$response);
 9585:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9586:             push(@{$codetitles},&str2array($codetitles_str));
 9587:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9588:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9589:             $ok_response = 1;
 9590:         }
 9591:     }
 9592:     if ($ok_response) {
 9593:         return 'ok';
 9594:     } else {
 9595:         return $response;
 9596:     }
 9597: }
 9598: 
 9599: sub auto_instcode_defaults {
 9600:     my ($domain,$returnhash,$code_order) = @_;
 9601:     my @homeservers;
 9602: 
 9603:     my %servers = &get_servers($domain,'library');
 9604:     foreach my $tryserver (keys(%servers)) {
 9605: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9606: 	    push(@homeservers,$tryserver);
 9607: 	}
 9608:     }
 9609: 
 9610:     my $response;
 9611:     foreach my $server (@homeservers) {
 9612:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9613:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9614: 	
 9615: 	foreach my $pair (split(/\&/,$response)) {
 9616: 	    my ($name,$value)=split(/\=/,$pair);
 9617: 	    if ($name eq 'code_order') {
 9618: 		@{$code_order} = split(/\&/,&unescape($value));
 9619: 	    } else {
 9620: 		$returnhash->{&unescape($name)}=&unescape($value);
 9621: 	    }
 9622: 	}
 9623: 	return 'ok';
 9624:     }
 9625: 
 9626:     return $response;
 9627: }
 9628: 
 9629: sub auto_possible_instcodes {
 9630:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9631:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9632:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9633:         return;
 9634:     }
 9635:     my (@homeservers,$uhome);
 9636:     if (defined(&domain($domain,'primary'))) {
 9637:         $uhome=&domain($domain,'primary');
 9638:         push(@homeservers,&domain($domain,'primary'));
 9639:     } else {
 9640:         my %servers = &get_servers($domain,'library');
 9641:         foreach my $tryserver (keys(%servers)) {
 9642:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9643:                 push(@homeservers,$tryserver);
 9644:             }
 9645:         }
 9646:     }
 9647:     my $response;
 9648:     foreach my $server (@homeservers) {
 9649:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9650:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9651:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9652:             split(':',$response);
 9653:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9654:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9655:         foreach my $item (split('&',$cat_title)) {   
 9656:             my ($name,$value)=split('=',$item);
 9657:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9658:         }
 9659:         foreach my $item (split('&',$cat_order)) {
 9660:             my ($name,$value)=split('=',$item);
 9661:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9662:         }
 9663:         return 'ok';
 9664:     }
 9665:     return $response;
 9666: }
 9667: 
 9668: sub auto_courserequest_checks {
 9669:     my ($dom) = @_;
 9670:     my ($homeserver,%validations);
 9671:     if ($dom =~ /^$match_domain$/) {
 9672:         $homeserver = &domain($dom,'primary');
 9673:     }
 9674:     unless ($homeserver eq 'no_host') {
 9675:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9676:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9677:             my @items = split(/&/,$response);
 9678:             foreach my $item (@items) {
 9679:                 my ($key,$value) = split('=',$item);
 9680:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9681:             }
 9682:         }
 9683:     }
 9684:     return %validations; 
 9685: }
 9686: 
 9687: sub auto_courserequest_validation {
 9688:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9689:     my ($homeserver,$response);
 9690:     if ($dom =~ /^$match_domain$/) {
 9691:         $homeserver = &domain($dom,'primary');
 9692:     }
 9693:     unless ($homeserver eq 'no_host') {
 9694:         my $customdata;
 9695:         if (ref($custominfo) eq 'HASH') {
 9696:             $customdata = &freeze_escape($custominfo);
 9697:         }
 9698:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9699:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9700:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9701:                                     $customdata,$homeserver));
 9702:     }
 9703:     return $response;
 9704: }
 9705: 
 9706: sub auto_validate_class_sec {
 9707:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9708:     my $homeserver = &homeserver($cnum,$cdom);
 9709:     my $ownerlist;
 9710:     if (ref($owners) eq 'ARRAY') {
 9711:         $ownerlist = join(',',@{$owners});
 9712:     } else {
 9713:         $ownerlist = $owners;
 9714:     }
 9715:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9716:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9717:     return $response;
 9718: }
 9719: 
 9720: sub auto_validate_instclasses {
 9721:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9722:     my ($homeserver,%validations);
 9723:     $homeserver = &homeserver($cnum,$cdom);
 9724:     unless ($homeserver eq 'no_host') {
 9725:         my $ownerlist;
 9726:         if (ref($owners) eq 'ARRAY') {
 9727:             $ownerlist = join(',',@{$owners});
 9728:         } else {
 9729:             $ownerlist = $owners;
 9730:         }
 9731:         if (ref($classesref) eq 'HASH') {
 9732:             my $classes = &freeze_escape($classesref);
 9733:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9734:                                 ':'.$cdom.':'.$classes,$homeserver);
 9735:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9736:                 my @items = split(/&/,$response);
 9737:                 foreach my $item (@items) {
 9738:                     my ($key,$value) = split('=',$item);
 9739:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9740:                 }
 9741:             }
 9742:         }
 9743:     }
 9744:     return %validations;
 9745: }
 9746: 
 9747: sub auto_crsreq_update {
 9748:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9749:         $code,$accessstart,$accessend,$inbound) = @_;
 9750:     my ($homeserver,%crsreqresponse);
 9751:     if ($cdom =~ /^$match_domain$/) {
 9752:         $homeserver = &domain($cdom,'primary');
 9753:     }
 9754:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9755:         my $info;
 9756:         if (ref($inbound) eq 'HASH') {
 9757:             $info = &freeze_escape($inbound);
 9758:         }
 9759:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9760:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9761:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9762:                             &escape($title).':'.&escape($code).':'.
 9763:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9764:                             $homeserver);
 9765:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9766:             my @items = split(/&/,$response);
 9767:             foreach my $item (@items) {
 9768:                 my ($key,$value) = split('=',$item);
 9769:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9770:             }
 9771:         }
 9772:     }
 9773:     return \%crsreqresponse;
 9774: }
 9775: 
 9776: sub auto_export_grades {
 9777:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9778:     my ($homeserver,%exportresponse);
 9779:     if ($cdom =~ /^$match_domain$/) {
 9780:         $homeserver = &domain($cdom,'primary');
 9781:     }
 9782:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9783:         my $info;
 9784:         if (ref($inforef) eq 'HASH') {
 9785:             $info = &freeze_escape($inforef);
 9786:         }
 9787:         if (ref($gradesref) eq 'HASH') {
 9788:             my $grades = &freeze_escape($gradesref);
 9789:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9790:                                 $info.':'.$grades,$homeserver);
 9791:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9792:                 my @items = split(/&/,$response);
 9793:                 foreach my $item (@items) {
 9794:                     my ($key,$value) = split('=',$item);
 9795:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9796:                 }
 9797:             }
 9798:         }
 9799:     }
 9800:     return \%exportresponse;
 9801: }
 9802: 
 9803: sub check_instcode_cloning {
 9804:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9805:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9806:         return;
 9807:     }
 9808:     my $canclone;
 9809:     if (@{$code_order} > 0) {
 9810:         my $instcoderegexp ='^';
 9811:         my @clonecodes = split(/\&/,$cloner);
 9812:         foreach my $item (@{$code_order}) {
 9813:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9814:                 foreach my $pair (@clonecodes) {
 9815:                     my ($key,$val) = split(/\=/,$pair,2);
 9816:                     $val = &unescape($val);
 9817:                     if ($key eq $item) {
 9818:                         $instcoderegexp .= '('.$val.')';
 9819:                         last;
 9820:                     }
 9821:                 }
 9822:             } else {
 9823:                 $instcoderegexp .= $codedefaults->{$item};
 9824:             }
 9825:         }
 9826:         $instcoderegexp .= '$';
 9827:         my (@from,@to);
 9828:         eval {
 9829:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9830:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9831:         };
 9832:         if ((@from > 0) && (@to > 0)) {
 9833:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9834:             if (!@diffs) {
 9835:                 $canclone = 1;
 9836:             }
 9837:         }
 9838:     }
 9839:     return $canclone;
 9840: }
 9841: 
 9842: sub default_instcode_cloning {
 9843:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9844:     my (%codedefaults,@code_order,$canclone);
 9845:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9846:         %codedefaults = %{$codedefaultsref};
 9847:         @code_order = @{$codeorderref};
 9848:     } elsif ($clonedom) {
 9849:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9850:     }
 9851:     if (($domdefclone) && (@code_order)) {
 9852:         my @clonecodes = split(/\+/,$domdefclone);
 9853:         my $instcoderegexp ='^';
 9854:         foreach my $item (@code_order) {
 9855:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9856:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9857:             } else {
 9858:                 $instcoderegexp .= $codedefaults{$item};
 9859:             }
 9860:         }
 9861:         $instcoderegexp .= '$';
 9862:         my (@from,@to);
 9863:         eval {
 9864:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9865:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9866:         };
 9867:         if ((@from > 0) && (@to > 0)) {
 9868:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9869:             if (!@diffs) {
 9870:                 $canclone = 1;
 9871:             }
 9872:         }
 9873:     }
 9874:     return $canclone;
 9875: }
 9876: 
 9877: # ------------------------------------------------------- Course Group routines
 9878: 
 9879: sub get_coursegroups {
 9880:     my ($cdom,$cnum,$group,$namespace) = @_;
 9881:     return(&dump($namespace,$cdom,$cnum,$group));
 9882: }
 9883: 
 9884: sub modify_coursegroup {
 9885:     my ($cdom,$cnum,$groupsettings) = @_;
 9886:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9887: }
 9888: 
 9889: sub toggle_coursegroup_status {
 9890:     my ($cdom,$cnum,$group,$action) = @_;
 9891:     my ($from_namespace,$to_namespace);
 9892:     if ($action eq 'delete') {
 9893:         $from_namespace = 'coursegroups';
 9894:         $to_namespace = 'deleted_groups';
 9895:     } else {
 9896:         $from_namespace = 'deleted_groups';
 9897:         $to_namespace = 'coursegroups';
 9898:     }
 9899:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9900:     if (my $tmp = &error(%curr_group)) {
 9901:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9902:         return ('read error',$tmp);
 9903:     } else {
 9904:         my %savedsettings = %curr_group; 
 9905:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9906:         my $deloutcome;
 9907:         if ($result eq 'ok') {
 9908:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9909:         } else {
 9910:             return ('write error',$result);
 9911:         }
 9912:         if ($deloutcome eq 'ok') {
 9913:             return 'ok';
 9914:         } else {
 9915:             return ('delete error',$deloutcome);
 9916:         }
 9917:     }
 9918: }
 9919: 
 9920: sub modify_group_roles {
 9921:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9922:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9923:     my $role = 'gr/'.&escape($userprivs);
 9924:     my ($uname,$udom) = split(/:/,$user);
 9925:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9926:     if ($result eq 'ok') {
 9927:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9928:     }
 9929:     return $result;
 9930: }
 9931: 
 9932: sub modify_coursegroup_membership {
 9933:     my ($cdom,$cnum,$membership) = @_;
 9934:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9935:     return $result;
 9936: }
 9937: 
 9938: sub get_active_groups {
 9939:     my ($udom,$uname,$cdom,$cnum) = @_;
 9940:     my $now = time;
 9941:     my %groups = ();
 9942:     foreach my $key (keys(%env)) {
 9943:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9944:             my ($start,$end) = split(/\./,$env{$key});
 9945:             if (($end!=0) && ($end<$now)) { next; }
 9946:             if (($start!=0) && ($start>$now)) { next; }
 9947:             if ($1 eq $cdom && $2 eq $cnum) {
 9948:                 $groups{$3} = $env{$key} ;
 9949:             }
 9950:         }
 9951:     }
 9952:     return %groups;
 9953: }
 9954: 
 9955: sub get_group_membership {
 9956:     my ($cdom,$cnum,$group) = @_;
 9957:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9958: }
 9959: 
 9960: sub get_users_groups {
 9961:     my ($udom,$uname,$courseid) = @_;
 9962:     my @usersgroups;
 9963:     my $cachetime=1800;
 9964: 
 9965:     my $hashid="$udom:$uname:$courseid";
 9966:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9967:     if (defined($cached)) {
 9968:         @usersgroups = split(/:/,$grouplist);
 9969:     } else {  
 9970:         $grouplist = '';
 9971:         my $courseurl = &courseid_to_courseurl($courseid);
 9972:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9973:         my $access_end = $env{'course.'.$courseid.
 9974:                               '.default_enrollment_end_date'};
 9975:         my $now = time;
 9976:         foreach my $key (keys(%roleshash)) {
 9977:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9978:                 my $group = $1;
 9979:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9980:                     my $start = $2;
 9981:                     my $end = $1;
 9982:                     if ($start == -1) { next; } # deleted from group
 9983:                     if (($start!=0) && ($start>$now)) { next; }
 9984:                     if (($end!=0) && ($end<$now)) {
 9985:                         if ($access_end && $access_end < $now) {
 9986:                             if ($access_end - $end < 86400) {
 9987:                                 push(@usersgroups,$group);
 9988:                             }
 9989:                         }
 9990:                         next;
 9991:                     }
 9992:                     push(@usersgroups,$group);
 9993:                 }
 9994:             }
 9995:         }
 9996:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9997:         $grouplist = join(':',@usersgroups);
 9998:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9999:     }
10000:     return @usersgroups;
10001: }
10002: 
10003: sub devalidate_getgroups_cache {
10004:     my ($udom,$uname,$cdom,$cnum)=@_;
10005:     my $courseid = $cdom.'_'.$cnum;
10006: 
10007:     my $hashid="$udom:$uname:$courseid";
10008:     &devalidate_cache_new('getgroups',$hashid);
10009: }
10010: 
10011: # ------------------------------------------------------------------ Plain Text
10012: 
10013: sub plaintext {
10014:     my ($short,$type,$cid,$forcedefault) = @_;
10015:     if ($short =~ m{^cr/}) {
10016: 	return (split('/',$short))[-1];
10017:     }
10018:     if (!defined($cid)) {
10019:         $cid = $env{'request.course.id'};
10020:     }
10021:     my %rolenames = (
10022:                       Course    => 'std',
10023:                       Community => 'alt1',
10024:                       Placement => 'std',
10025:                     );
10026:     if ($cid ne '') {
10027:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10028:             unless ($forcedefault) {
10029:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10030:                 &Apache::lonlocal::mt_escape(\$roletext);
10031:                 return &Apache::lonlocal::mt($roletext);
10032:             }
10033:         }
10034:     }
10035:     if ((defined($type)) && (defined($rolenames{$type})) &&
10036:         (defined($rolenames{$type})) && 
10037:         (defined($prp{$short}{$rolenames{$type}}))) {
10038:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10039:     } elsif ($cid ne '') {
10040:         my $crstype = $env{'course.'.$cid.'.type'};
10041:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10042:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10043:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10044:         }
10045:     }
10046:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10047: }
10048: 
10049: # ----------------------------------------------------------------- Assign Role
10050: 
10051: sub assignrole {
10052:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10053:         $context)=@_;
10054:     my $mrole;
10055:     if ($role =~ /^cr\//) {
10056:         my $cwosec=$url;
10057:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10058: 	unless (&allowed('ccr',$cwosec)) {
10059:            my $refused = 1;
10060:            if ($context eq 'requestcourses') {
10061:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10062:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10063:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10064:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10065:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10066:                            if ($crsenv{'internal.courseowner'} eq
10067:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10068:                                $refused = '';
10069:                            }
10070:                        }
10071:                    }
10072:                }
10073:            }
10074:            if ($refused) {
10075:                &logthis('Refused custom assignrole: '.
10076:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10077:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10078:                return 'refused';
10079:            }
10080:         }
10081:         $mrole='cr';
10082:     } elsif ($role =~ /^gr\//) {
10083:         my $cwogrp=$url;
10084:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10085:         unless (&allowed('mdg',$cwogrp)) {
10086:             &logthis('Refused group assignrole: '.
10087:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10088:                     $env{'user.name'}.' at '.$env{'user.domain'});
10089:             return 'refused';
10090:         }
10091:         $mrole='gr';
10092:     } else {
10093:         my $cwosec=$url;
10094:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10095:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10096:             my $refused;
10097:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10098:                 if (!(&allowed('c'.$role,$url))) {
10099:                     $refused = 1;
10100:                 }
10101:             } else {
10102:                 $refused = 1;
10103:             }
10104:             if ($refused) {
10105:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10106:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10107:                     my %crsenv;
10108:                     if ($role eq 'cc' || $role eq 'co') {
10109:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10110:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10111:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10112:                                 if ($crsenv{'internal.courseowner'} eq 
10113:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10114:                                     $refused = '';
10115:                                 }
10116:                             }
10117:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10118:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10119:                                 if ($crsenv{'internal.courseowner'} eq 
10120:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10121:                                     $refused = '';
10122:                                 }
10123:                             }
10124:                         }
10125:                     }
10126:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10127:                     if ($role eq 'st') {
10128:                         $refused = '';
10129:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10130:                         $refused = '';
10131:                     }
10132:                 } elsif ($context eq 'requestcourses') {
10133:                     my @possroles = ('st','ta','ep','in','cc','co');
10134:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10135:                         my $wrongcc;
10136:                         if ($cnum =~ /^$match_community$/) {
10137:                             $wrongcc = 1 if ($role eq 'cc');
10138:                         } else {
10139:                             $wrongcc = 1 if ($role eq 'co');
10140:                         }
10141:                         unless ($wrongcc) {
10142:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10143:                             if ($crsenv{'internal.courseowner'} eq 
10144:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10145:                                 $refused = '';
10146:                             }
10147:                         }
10148:                     }
10149:                 } elsif ($context eq 'requestauthor') {
10150:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10151:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10152:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10153:                             $refused = '';
10154:                         } else {
10155:                             my %domdefaults = &get_domain_defaults($udom);
10156:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10157:                                 my $checkbystatus;
10158:                                 if ($env{'user.adv'}) { 
10159:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10160:                                     if ($disposition eq 'automatic') {
10161:                                         $refused = '';
10162:                                     } elsif ($disposition eq '') {
10163:                                         $checkbystatus = 1;
10164:                                     } 
10165:                                 } else {
10166:                                     $checkbystatus = 1;
10167:                                 }
10168:                                 if ($checkbystatus) {
10169:                                     if ($env{'environment.inststatus'}) {
10170:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10171:                                         foreach my $type (@inststatuses) {
10172:                                             if (($type ne '') &&
10173:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10174:                                                 $refused = '';
10175:                                             }
10176:                                         }
10177:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10178:                                         $refused = '';
10179:                                     }
10180:                                 }
10181:                             }
10182:                         }
10183:                     }
10184:                 }
10185:                 if ($refused) {
10186:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10187:                              ' '.$role.' '.$end.' '.$start.' by '.
10188: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10189:                     return 'refused';
10190:                 }
10191:             }
10192:         } elsif ($role eq 'au') {
10193:             if ($url ne '/'.$udom.'/') {
10194:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10195:                          ' to assign author role for '.$uname.':'.$udom.
10196:                          ' in domain: '.$url.' refused (wrong domain).');
10197:                 return 'refused';
10198:             }
10199:         }
10200:         $mrole=$role;
10201:     }
10202:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10203:                 "$udom:$uname:$url".'_'."$mrole=$role";
10204:     if ($end) { $command.='_'.$end; }
10205:     if ($start) {
10206: 	if ($end) { 
10207:            $command.='_'.$start; 
10208:         } else {
10209:            $command.='_0_'.$start;
10210:         }
10211:     }
10212:     my $origstart = $start;
10213:     my $origend = $end;
10214:     my $delflag;
10215: # actually delete
10216:     if ($deleteflag) {
10217: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10218: # modify command to delete the role
10219:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10220:                 "$udom:$uname:$url".'_'."$mrole";
10221: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10222: # set start and finish to negative values for userrolelog
10223:            $start=-1;
10224:            $end=-1;
10225:            $delflag = 1;
10226:         }
10227:     }
10228: # send command
10229:     my $answer=&reply($command,&homeserver($uname,$udom));
10230: # log new user role if status is ok
10231:     if ($answer eq 'ok') {
10232: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10233:         if (($role eq 'cc') || ($role eq 'in') ||
10234:             ($role eq 'ep') || ($role eq 'ad') ||
10235:             ($role eq 'ta') || ($role eq 'st') ||
10236:             ($role=~/^cr/) || ($role eq 'gr') ||
10237:             ($role eq 'co')) {
10238: # for course roles, perform group memberships changes triggered by role change.
10239:             unless ($role =~ /^gr/) {
10240:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10241:                                                  $origstart,$selfenroll,$context);
10242:             }
10243:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10244:                            $selfenroll,$context);
10245:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10246:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10247:                  ($role eq 'da')) {
10248:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10249:                            $context);
10250:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10251:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10252:                              $context); 
10253:         }
10254:         if ($role eq 'cc') {
10255:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10256:         }
10257:     }
10258:     return $answer;
10259: }
10260: 
10261: sub autoupdate_coowners {
10262:     my ($url,$end,$start,$uname,$udom) = @_;
10263:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10264:     if (($cdom ne '') && ($cnum ne '')) {
10265:         my $now = time;
10266:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10267:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10268:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10269:             my $instcode = $coursehash{'internal.coursecode'};
10270:             my $xlists = $coursehash{'internal.crosslistings'};
10271:             if ($instcode ne '') {
10272:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10273:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10274:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10275:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10276:                         unless ($result eq 'valid') {
10277:                             if ($xlists ne '') {
10278:                                 foreach my $xlist (split(',',$xlists)) {
10279:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10280:                                     $result =
10281:                                         &Apache::lonnet::auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10282:                                                                                       $inst_crosslist,$uname.':'.$udom);
10283:                                         last if ($result eq 'valid');
10284:                                     }
10285:                                 }
10286:                             }
10287:                         }
10288:                         if ($result eq 'valid') {
10289:                             if ($coursehash{'internal.co-owners'}) {
10290:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10291:                                     push(@newcoowners,$coowner);
10292:                                 }
10293:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10294:                                     push(@newcoowners,$uname.':'.$udom);
10295:                                 }
10296:                                 @newcoowners = sort(@newcoowners);
10297:                             } else {
10298:                                 push(@newcoowners,$uname.':'.$udom);
10299:                             }
10300:                         } elsif ($coursehash{'internal.co-owners'}) {
10301:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10302:                                 unless ($coowner eq $uname.':'.$udom) {
10303:                                     push(@newcoowners,$coowner);
10304:                                 }
10305:                             }
10306:                             unless (@newcoowners > 0) {
10307:                                 $delcoowners = 1;
10308:                                 $coowners = '';
10309:                             }
10310:                         }
10311:                         if (@newcoowners || $delcoowners) {
10312:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10313:                                             $delcoowners,@newcoowners);
10314:                         }
10315:                     }
10316:                 }
10317:             }
10318:         }
10319:     }
10320: }
10321: 
10322: sub store_coowners {
10323:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10324:     my $cid = $cdom.'_'.$cnum;
10325:     my ($coowners,$delresult,$putresult);
10326:     if (@newcoowners) {
10327:         $coowners = join(',',@newcoowners);
10328:         my %coownershash = (
10329:                             'internal.co-owners' => $coowners,
10330:                            );
10331:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10332:         if ($putresult eq 'ok') {
10333:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10334:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10335:             }
10336:         }
10337:     }
10338:     if ($delcoowners) {
10339:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10340:         if ($delresult eq 'ok') {
10341:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10342:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10343:             }
10344:         }
10345:     }
10346:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10347:         my %crsinfo =
10348:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10349:         if (ref($crsinfo{$cid}) eq 'HASH') {
10350:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10351:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10352:         }
10353:     }
10354: }
10355: 
10356: # -------------------------------------------------- Modify user authentication
10357: # Overrides without validation
10358: 
10359: sub modifyuserauth {
10360:     my ($udom,$uname,$umode,$upass)=@_;
10361:     my $uhome=&homeserver($uname,$udom);
10362:     my $allowed;
10363:     if (&allowed('mau',$udom)) {
10364:         $allowed = 1;
10365:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10366:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10367:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10368:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10369:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10370:         if (($cdom ne '') && ($cnum ne '')) {
10371:             my $is_owner = &is_course_owner($cdom,$cnum);
10372:             if ($is_owner) {
10373:                 $allowed = 1;
10374:             }
10375:         }
10376:     }
10377:     unless ($allowed) { return 'refused'; }
10378:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10379:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10380:              ' in domain '.$env{'request.role.domain'});  
10381:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10382: 		     &escape($upass),$uhome);
10383:     my $ip = &get_requestor_ip();
10384:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10385:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10386:          '(Remote '.$ip.'): '.$reply);
10387:     &log($udom,,$uname,$uhome,
10388:         'Authentication changed by '.$env{'user.domain'}.', '.
10389:                                      $env{'user.name'}.', '.$umode.
10390:          '(Remote '.$ip.'): '.$reply);
10391:     unless ($reply eq 'ok') {
10392:         &logthis('Authentication mode error: '.$reply);
10393: 	return 'error: '.$reply;
10394:     }   
10395:     return 'ok';
10396: }
10397: 
10398: # --------------------------------------------------------------- Modify a user
10399: 
10400: sub modifyuser {
10401:     my ($udom,    $uname, $uid,
10402:         $umode,   $upass, $first,
10403:         $middle,  $last,  $gene,
10404:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10405:     $udom= &LONCAPA::clean_domain($udom);
10406:     $uname=&LONCAPA::clean_username($uname);
10407:     my $showcandelete = 'none';
10408:     if (ref($candelete) eq 'ARRAY') {
10409:         if (@{$candelete} > 0) {
10410:             $showcandelete = join(', ',@{$candelete});
10411:         }
10412:     }
10413:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10414:              $umode.', '.$first.', '.$middle.', '.
10415: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10416:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10417:                                      ' desiredhome not specified'). 
10418:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10419:              ' in domain '.$env{'request.role.domain'});
10420:     my $uhome=&homeserver($uname,$udom,'true');
10421:     my $newuser;
10422:     if ($uhome eq 'no_host') {
10423:         $newuser = 1;
10424:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10425:                 ($umode eq 'lti')) {
10426:             return 'error: more information needed to create new user';
10427:         }
10428:     }
10429: # ----------------------------------------------------------------- Create User
10430:     if (($uhome eq 'no_host') && 
10431: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10432:         my $unhome='';
10433:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10434:             $unhome = $desiredhome;
10435: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10436: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10437:         } else { # load balancing routine for determining $unhome
10438:             my $loadm=10000000;
10439: 	    my %servers = &get_servers($udom,'library');
10440: 	    foreach my $tryserver (keys(%servers)) {
10441: 		my $answer=reply('load',$tryserver);
10442: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10443: 		    $loadm=$answer;
10444: 		    $unhome=$tryserver;
10445: 		}
10446: 	    }
10447:         }
10448:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10449: 	    return 'error: unable to find a home server for '.$uname.
10450:                    ' in domain '.$udom;
10451:         }
10452:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10453:                          &escape($upass),$unhome);
10454: 	unless ($reply eq 'ok') {
10455:             return 'error: '.$reply;
10456:         }   
10457:         $uhome=&homeserver($uname,$udom,'true');
10458:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10459: 	    return 'error: unable verify users home machine.';
10460:         }
10461:     }   # End of creation of new user
10462: # ---------------------------------------------------------------------- Add ID
10463:     if ($uid) {
10464:        $uid=~tr/A-Z/a-z/;
10465:        my %uidhash=&idrget($udom,$uname);
10466:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10467:          && (!$forceid)) {
10468: 	  unless ($uid eq $uidhash{$uname}) {
10469: 	      return 'error: user id "'.$uid.'" does not match '.
10470:                   'current user id "'.$uidhash{$uname}.'".';
10471:           }
10472:        } else {
10473: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10474:        }
10475:     }
10476: # -------------------------------------------------------------- Add names, etc
10477:     my @tmp=&get('environment',
10478: 		   ['firstname','middlename','lastname','generation','id',
10479:                     'permanentemail','inststatus'],
10480: 		   $udom,$uname);
10481:     my (%names,%oldnames);
10482:     if ($tmp[0] =~ m/^error:.*/) { 
10483:         %names=(); 
10484:     } else {
10485:         %names = @tmp;
10486:         %oldnames = %names;
10487:     }
10488: #
10489: # If name, email and/or uid are blank (e.g., because an uploaded file
10490: # of users did not contain them), do not overwrite existing values
10491: # unless field is in $candelete array ref.  
10492: #
10493: 
10494:     my @fields = ('firstname','middlename','lastname','generation',
10495:                   'permanentemail','id');
10496:     my %newvalues;
10497:     if (ref($candelete) eq 'ARRAY') {
10498:         foreach my $field (@fields) {
10499:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10500:                 if ($field eq 'firstname') {
10501:                     $names{$field} = $first;
10502:                 } elsif ($field eq 'middlename') {
10503:                     $names{$field} = $middle;
10504:                 } elsif ($field eq 'lastname') {
10505:                     $names{$field} = $last;
10506:                 } elsif ($field eq 'generation') { 
10507:                     $names{$field} = $gene;
10508:                 } elsif ($field eq 'permanentemail') {
10509:                     $names{$field} = $email;
10510:                 } elsif ($field eq 'id') {
10511:                     $names{$field}  = $uid;
10512:                 }
10513:             }
10514:         }
10515:     }
10516:     if ($first)  { $names{'firstname'}  = $first; }
10517:     if (defined($middle)) { $names{'middlename'} = $middle; }
10518:     if ($last)   { $names{'lastname'}   = $last; }
10519:     if (defined($gene))   { $names{'generation'} = $gene; }
10520:     if ($email) {
10521:        $email=~s/[^\w\@\.\-\,]//gs;
10522:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10523:     }
10524:     if ($uid) { $names{'id'}  = $uid; }
10525:     if (defined($inststatus)) {
10526:         $names{'inststatus'} = '';
10527:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10528:         if (ref($usertypes) eq 'HASH') {
10529:             my @okstatuses; 
10530:             foreach my $item (split(/:/,$inststatus)) {
10531:                 if (defined($usertypes->{$item})) {
10532:                     push(@okstatuses,$item);  
10533:                 }
10534:             }
10535:             if (@okstatuses) {
10536:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10537:             }
10538:         }
10539:     }
10540:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10541:                  $umode.', '.$first.', '.$middle.', '.
10542:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10543:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10544:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10545:     } else {
10546:         $logmsg .= ' during self creation';
10547:     }
10548:     my $changed;
10549:     if ($newuser) {
10550:         $changed = 1;
10551:     } else {
10552:         foreach my $field (@fields) {
10553:             if ($names{$field} ne $oldnames{$field}) {
10554:                 $changed = 1;
10555:                 last;
10556:             }
10557:         }
10558:     }
10559:     unless ($changed) {
10560:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10561:         &logthis($logmsg);
10562:         return 'ok';
10563:     }
10564:     my $reply = &put('environment', \%names, $udom,$uname);
10565:     if ($reply ne 'ok') { 
10566:         return 'error: '.$reply;
10567:     }
10568:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10569:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10570:     }
10571:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10572:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10573:     $logmsg = 'Success modifying user '.$logmsg;
10574:     &logthis($logmsg);
10575:     return 'ok';
10576: }
10577: 
10578: # -------------------------------------------------------------- Modify student
10579: 
10580: sub modifystudent {
10581:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10582:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10583:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10584:     if (!$cid) {
10585: 	unless ($cid=$env{'request.course.id'}) {
10586: 	    return 'not_in_class';
10587: 	}
10588:     }
10589: # --------------------------------------------------------------- Make the user
10590:     my $reply=&modifyuser
10591: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10592:          $desiredhome,$email,$inststatus);
10593:     unless ($reply eq 'ok') { return $reply; }
10594:     # This will cause &modify_student_enrollment to get the uid from the
10595:     # student's environment
10596:     $uid = undef if (!$forceid);
10597:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10598:                                         $gene,$usec,$end,$start,$type,$locktype,
10599:                                         $cid,$selfenroll,$context,$credits,$instsec);
10600:     return $reply;
10601: }
10602: 
10603: sub modify_student_enrollment {
10604:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10605:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10606:     my ($cdom,$cnum,$chome);
10607:     if (!$cid) {
10608: 	unless ($cid=$env{'request.course.id'}) {
10609: 	    return 'not_in_class';
10610: 	}
10611: 	$cdom=$env{'course.'.$cid.'.domain'};
10612: 	$cnum=$env{'course.'.$cid.'.num'};
10613:     } else {
10614: 	($cdom,$cnum)=split(/_/,$cid);
10615:     }
10616:     $chome=$env{'course.'.$cid.'.home'};
10617:     if (!$chome) {
10618: 	$chome=&homeserver($cnum,$cdom);
10619:     }
10620:     if (!$chome) { return 'unknown_course'; }
10621:     # Make sure the user exists
10622:     my $uhome=&homeserver($uname,$udom);
10623:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10624: 	return 'error: no such user';
10625:     }
10626:     # Get student data if we were not given enough information
10627:     if (!defined($first)  || $first  eq '' || 
10628:         !defined($last)   || $last   eq '' || 
10629:         !defined($uid)    || $uid    eq '' || 
10630:         !defined($middle) || $middle eq '' || 
10631:         !defined($gene)   || $gene   eq '') {
10632:         # They did not supply us with enough data to enroll the student, so
10633:         # we need to pick up more information.
10634:         my %tmp = &get('environment',
10635:                        ['firstname','middlename','lastname', 'generation','id']
10636:                        ,$udom,$uname);
10637: 
10638:         #foreach my $key (keys(%tmp)) {
10639:         #    &logthis("key $key = ".$tmp{$key});
10640:         #}
10641:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10642:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10643:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10644:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10645:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10646:     }
10647:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10648:     my $user = "$uname:$udom";
10649:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10650:     my $reply=cput('classlist',
10651: 		   {$user => 
10652: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10653: 		   $cdom,$cnum);
10654:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10655:         &devalidate_getsection_cache($udom,$uname,$cid);
10656:     } else { 
10657: 	return 'error: '.$reply;
10658:     }
10659:     # Add student role to user
10660:     my $uurl='/'.$cid;
10661:     $uurl=~s/\_/\//g;
10662:     if ($usec) {
10663: 	$uurl.='/'.$usec;
10664:     }
10665:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10666:                              $selfenroll,$context);
10667:     if ($result ne 'ok') {
10668:         if ($old_entry{$user} ne '') {
10669:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10670:         } else {
10671:             $reply = &del('classlist',[$user],$cdom,$cnum);
10672:         }
10673:     }
10674:     return $result; 
10675: }
10676: 
10677: sub format_name {
10678:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10679:     my $name;
10680:     if ($first ne 'lastname') {
10681: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10682:     } else {
10683: 	if ($lastname=~/\S/) {
10684: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10685: 	    $name=~s/\s+,/,/;
10686: 	} else {
10687: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10688: 	}
10689:     }
10690:     $name=~s/^\s+//;
10691:     $name=~s/\s+$//;
10692:     $name=~s/\s+/ /g;
10693:     return $name;
10694: }
10695: 
10696: # ------------------------------------------------- Write to course preferences
10697: 
10698: sub writecoursepref {
10699:     my ($courseid,%prefs)=@_;
10700:     $courseid=~s/^\///;
10701:     $courseid=~s/\_/\//g;
10702:     my ($cdomain,$cnum)=split(/\//,$courseid);
10703:     my $chome=homeserver($cnum,$cdomain);
10704:     if (($chome eq '') || ($chome eq 'no_host')) { 
10705: 	return 'error: no such course';
10706:     }
10707:     my $cstring='';
10708:     foreach my $pref (keys(%prefs)) {
10709: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10710:     }
10711:     $cstring=~s/\&$//;
10712:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10713: }
10714: 
10715: # ---------------------------------------------------------- Make/modify course
10716: 
10717: sub createcourse {
10718:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10719:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10720:     $url=&declutter($url);
10721:     my $cid='';
10722:     if ($context eq 'requestcourses') {
10723:         my $can_create = 0;
10724:         my ($ownername,$ownerdom) = split(':',$course_owner);
10725:         if ($udom eq $ownerdom) {
10726:             my $reload;
10727:             if (($callercontext eq 'auto') &&
10728:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10729:                 $reload = 'reload';
10730:             }
10731:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10732:                                   $context)) {
10733:                 $can_create = 1;
10734:             }
10735:         } else {
10736:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10737:                                            $category);
10738:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10739:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10740:                 if (@curr > 0) {
10741:                     my @options = qw(approval validate autolimit);
10742:                     my $optregex = join('|',@options);
10743:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10744:                         $can_create = 1;
10745:                     }
10746:                 }
10747:             }
10748:         }
10749:         if ($can_create) {
10750:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10751:                 unless (&allowed('ccc',$udom)) {
10752:                     return 'refused'; 
10753:                 }
10754:             }
10755:         } else {
10756:             return 'refused';
10757:         }
10758:     } elsif (!&allowed('ccc',$udom)) {
10759:         return 'refused';
10760:     }
10761: # --------------------------------------------------------------- Get Unique ID
10762:     my $uname;
10763:     if ($cnum =~ /^$match_courseid$/) {
10764:         my $chome=&homeserver($cnum,$udom,'true');
10765:         if (($chome eq '') || ($chome eq 'no_host')) {
10766:             $uname = $cnum;
10767:         } else {
10768:             $uname = &generate_coursenum($udom,$crstype);
10769:         }
10770:     } else {
10771:         $uname = &generate_coursenum($udom,$crstype);
10772:     }
10773:     return $uname if ($uname =~ /^error/);
10774: # -------------------------------------------------- Check supplied server name
10775:     if (!defined($course_server)) {
10776:         if (defined(&domain($udom,'primary'))) {
10777:             $course_server = &domain($udom,'primary');
10778:         } else {
10779:             $course_server = $env{'user.home'}; 
10780:         }
10781:     }
10782:     my %host_servers =
10783:         &Apache::lonnet::get_servers($udom,'library');
10784:     unless ($host_servers{$course_server}) {
10785:         return 'error: invalid home server for course: '.$course_server;
10786:     }
10787: # ------------------------------------------------------------- Make the course
10788:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10789:                       $course_server);
10790:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10791:     my $uhome=&homeserver($uname,$udom,'true');
10792:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10793: 	return 'error: no such course';
10794:     }
10795: # ----------------------------------------------------------------- Course made
10796: # log existence
10797:     my $now = time;
10798:     my $newcourse = {
10799:                     $udom.'_'.$uname => {
10800:                                      description => $description,
10801:                                      inst_code   => $inst_code,
10802:                                      owner       => $course_owner,
10803:                                      type        => $crstype,
10804:                                      creator     => $env{'user.name'}.':'.
10805:                                                     $env{'user.domain'},
10806:                                      created     => $now,
10807:                                      context     => $context,
10808:                                                 },
10809:                     };
10810:     &courseidput($udom,$newcourse,$uhome,'notime');
10811: # set toplevel url
10812:     my $topurl=$url;
10813:     unless ($nonstandard) {
10814: # ------------------------------------------ For standard courses, make top url
10815:         my $mapurl=&clutter($url);
10816:         if ($mapurl eq '/res/') { $mapurl=''; }
10817:         $env{'form.initmap'}=(<<ENDINITMAP);
10818: <map>
10819: <resource id="1" type="start"></resource>
10820: <resource id="2" src="$mapurl"></resource>
10821: <resource id="3" type="finish"></resource>
10822: <link index="1" from="1" to="2"></link>
10823: <link index="2" from="2" to="3"></link>
10824: </map>
10825: ENDINITMAP
10826:         $topurl=&declutter(
10827:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10828:                           );
10829:     }
10830: # ----------------------------------------------------------- Write preferences
10831:     &writecoursepref($udom.'_'.$uname,
10832:                      ('description'              => $description,
10833:                       'url'                      => $topurl,
10834:                       'internal.creator'         => $env{'user.name'}.':'.
10835:                                                     $env{'user.domain'},
10836:                       'internal.created'         => $now,
10837:                       'internal.creationcontext' => $context)
10838:                     );
10839:     return '/'.$udom.'/'.$uname;
10840: }
10841: 
10842: # ------------------------------------------------------------------- Create ID
10843: sub generate_coursenum {
10844:     my ($udom,$crstype) = @_;
10845:     my $domdesc = &domain($udom);
10846:     return 'error: invalid domain' if ($domdesc eq '');
10847:     my $first;
10848:     if ($crstype eq 'Community') {
10849:         $first = '0';
10850:     } else {
10851:         $first = int(1+rand(9)); 
10852:     } 
10853:     my $uname=$first.
10854:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10855:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10856:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10857: # ----------------------------------------------- Make sure that does not exist
10858:     my $uhome=&homeserver($uname,$udom,'true');
10859:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10860:         if ($crstype eq 'Community') {
10861:             $first = '0';
10862:         } else {
10863:             $first = int(1+rand(9));
10864:         }
10865:         $uname=$first.
10866:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10867:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10868:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10869:         $uhome=&homeserver($uname,$udom,'true');
10870:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10871:             return 'error: unable to generate unique course-ID';
10872:         }
10873:     }
10874:     return $uname;
10875: }
10876: 
10877: sub is_course {
10878:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10879:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10880: 
10881:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10882:     my $uhome=&homeserver($cnum,$cdom);
10883:     my $iscourse;
10884:     if (grep { $_ eq $uhome } current_machine_ids()) {
10885:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10886:     } else {
10887:         my $hashid = $cdom.':'.$cnum;
10888:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10889:         unless (defined($cached)) {
10890:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10891:                                         $cnum,undef,undef,'.');
10892:             $iscourse = 0;
10893:             if (exists($courses{$cdom.'_'.$cnum})) {
10894:                 $iscourse = 1;
10895:             }
10896:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10897:         }
10898:     }
10899:     return unless ($iscourse);
10900:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10901: }
10902: 
10903: sub store_userdata {
10904:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10905:     my $result;
10906:     if ($datakey ne '') {
10907:         if (ref($storehash) eq 'HASH') {
10908:             if ($udom eq '' || $uname eq '') {
10909:                 $udom = $env{'user.domain'};
10910:                 $uname = $env{'user.name'};
10911:             }
10912:             my $uhome=&homeserver($uname,$udom);
10913:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10914:                 $result = 'error: no_host';
10915:             } else {
10916:                 $storehash->{'ip'} = &get_requestor_ip();
10917:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10918: 
10919:                 my $namevalue='';
10920:                 foreach my $key (keys(%{$storehash})) {
10921:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10922:                 }
10923:                 $namevalue=~s/\&$//;
10924:                 unless ($namespace eq 'courserequests') {
10925:                     $datakey = &escape($datakey);
10926:                 }
10927:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10928:                                   $namevalue,$uhome);
10929:             }
10930:         } else {
10931:             $result = 'error: data to store was not a hash reference'; 
10932:         }
10933:     } else {
10934:         $result= 'error: invalid requestkey'; 
10935:     }
10936:     return $result;
10937: }
10938: 
10939: # ---------------------------------------------------------- Assign Custom Role
10940: 
10941: sub assigncustomrole {
10942:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10943:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10944:                        $end,$start,$deleteflag,$selfenroll,$context);
10945: }
10946: 
10947: # ----------------------------------------------------------------- Revoke Role
10948: 
10949: sub revokerole {
10950:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10951:     my $now=time;
10952:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10953: }
10954: 
10955: # ---------------------------------------------------------- Revoke Custom Role
10956: 
10957: sub revokecustomrole {
10958:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10959:     my $now=time;
10960:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10961:            $deleteflag,$selfenroll,$context);
10962: }
10963: 
10964: # ------------------------------------------------------------ Disk usage
10965: sub diskusage {
10966:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10967:     $directorypath =~ s/\/$//;
10968:     my $listing=&reply('du2:'.&escape($directorypath).':'
10969:                        .&escape($getpropath).':'.&escape($uname).':'
10970:                        .&escape($udom),homeserver($uname,$udom));
10971:     if ($listing eq 'unknown_cmd') {
10972:         if ($getpropath) {
10973:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10974:         }
10975:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10976:     }
10977:     return $listing;
10978: }
10979: 
10980: sub is_locked {
10981:     my ($file_name, $domain, $user, $which) = @_;
10982:     my @check;
10983:     my $is_locked;
10984:     push (@check,$file_name);
10985:     my %locked = &get('file_permissions',\@check,
10986: 		      $env{'user.domain'},$env{'user.name'});
10987:     my ($tmp)=keys(%locked);
10988:     if ($tmp=~/^error:/) { undef(%locked); }
10989:     
10990:     if (ref($locked{$file_name}) eq 'ARRAY') {
10991:         $is_locked = 'false';
10992:         foreach my $entry (@{$locked{$file_name}}) {
10993:            if (ref($entry) eq 'ARRAY') {
10994:                $is_locked = 'true';
10995:                if (ref($which) eq 'ARRAY') {
10996:                    push(@{$which},$entry);
10997:                } else {
10998:                    last;
10999:                }
11000:            }
11001:        }
11002:     } else {
11003:         $is_locked = 'false';
11004:     }
11005:     return $is_locked;
11006: }
11007: 
11008: sub declutter_portfile {
11009:     my ($file) = @_;
11010:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11011:     return $file;
11012: }
11013: 
11014: # ------------------------------------------------------------- Mark as Read Only
11015: 
11016: sub mark_as_readonly {
11017:     my ($domain,$user,$files,$what) = @_;
11018:     my %current_permissions = &dump('file_permissions',$domain,$user);
11019:     my ($tmp)=keys(%current_permissions);
11020:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11021:     foreach my $file (@{$files}) {
11022: 	$file = &declutter_portfile($file);
11023:         push(@{$current_permissions{$file}},$what);
11024:     }
11025:     &put('file_permissions',\%current_permissions,$domain,$user);
11026:     return;
11027: }
11028: 
11029: # ------------------------------------------------------------Save Selected Files
11030: 
11031: sub save_selected_files {
11032:     my ($user, $path, @files) = @_;
11033:     my $filename = $user."savedfiles";
11034:     my @other_files = &files_not_in_path($user, $path);
11035:     open (OUT,'>',LONCAPA::tempdir().$filename);
11036:     foreach my $file (@files) {
11037:         print (OUT $env{'form.currentpath'}.$file."\n");
11038:     }
11039:     foreach my $file (@other_files) {
11040:         print (OUT $file."\n");
11041:     }
11042:     close (OUT);
11043:     return 'ok';
11044: }
11045: 
11046: sub clear_selected_files {
11047:     my ($user) = @_;
11048:     my $filename = $user."savedfiles";
11049:     open (OUT,'>',LONCAPA::tempdir().$filename);
11050:     print (OUT undef);
11051:     close (OUT);
11052:     return ("ok");    
11053: }
11054: 
11055: sub files_in_path {
11056:     my ($user, $path) = @_;
11057:     my $filename = $user."savedfiles";
11058:     my %return_files;
11059:     open (IN,'<',LONCAPA::tempdir().$filename);
11060:     while (my $line_in = <IN>) {
11061:         chomp ($line_in);
11062:         my @paths_and_file = split (m!/!, $line_in);
11063:         my $file_part = pop (@paths_and_file);
11064:         my $path_part = join ('/', @paths_and_file);
11065:         $path_part.='/';
11066:         my $path_and_file = $path_part.$file_part;
11067:         if ($path_part eq $path) {
11068:             $return_files{$file_part}= 'selected';
11069:         }
11070:     }
11071:     close (IN);
11072:     return (\%return_files);
11073: }
11074: 
11075: # called in portfolio select mode, to show files selected NOT in current directory
11076: sub files_not_in_path {
11077:     my ($user, $path) = @_;
11078:     my $filename = $user."savedfiles";
11079:     my @return_files;
11080:     my $path_part;
11081:     open(IN, '<',LONCAPA::tempdir().$filename);
11082:     while (my $line = <IN>) {
11083:         #ok, I know it's clunky, but I want it to work
11084:         my @paths_and_file = split(m|/|, $line);
11085:         my $file_part = pop(@paths_and_file);
11086:         chomp($file_part);
11087:         my $path_part = join('/', @paths_and_file);
11088:         $path_part .= '/';
11089:         my $path_and_file = $path_part.$file_part;
11090:         if ($path_part ne $path) {
11091:             push(@return_files, ($path_and_file));
11092:         }
11093:     }
11094:     close(OUT);
11095:     return (@return_files);
11096: }
11097: 
11098: #------------------------------Submitted/Handedback Portfolio Files Versioning
11099:  
11100: sub portfiles_versioning {
11101:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11102:     my $portfolio_root = '/userfiles/portfolio';
11103:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11104:     foreach my $file (@{$portfiles}) {
11105:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11106:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11107:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11108:         my $getpropath = 1;
11109:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11110:                                              $stu_name,$getpropath);
11111:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11112:         my $new_answer = 
11113:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11114:         if ($new_answer ne 'problem getting file') {
11115:             push(@{$versioned_portfiles}, $directory.$new_answer);
11116:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11117:                               [$symb,$env{'request.course.id'},'graded']);
11118:         }
11119:     }
11120: }
11121: 
11122: sub get_next_version {
11123:     my ($answer_name, $answer_ext, $dir_list) = @_;
11124:     my $version;
11125:     if (ref($dir_list) eq 'ARRAY') {
11126:         foreach my $row (@{$dir_list}) {
11127:             my ($file) = split(/\&/,$row,2);
11128:             my ($file_name,$file_version,$file_ext) =
11129:                 &file_name_version_ext($file);
11130:             if (($file_name eq $answer_name) &&
11131:                 ($file_ext eq $answer_ext)) {
11132:                      # gets here if filename and extension match,
11133:                      # regardless of version
11134:                 if ($file_version ne '') {
11135:                     # a versioned file is found  so save it for later
11136:                     if ($file_version > $version) {
11137:                         $version = $file_version;
11138:                     }
11139:                 }
11140:             }
11141:         }
11142:     }
11143:     $version ++;
11144:     return($version);
11145: }
11146: 
11147: sub version_selected_portfile {
11148:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11149:     my ($answer_name,$answer_ver,$answer_ext) =
11150:         &file_name_version_ext($file_name);
11151:     my $new_answer;
11152:     $env{'form.copy'} =
11153:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11154:     if($env{'form.copy'} eq '-1') {
11155:         $new_answer = 'problem getting file';
11156:     } else {
11157:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11158:         my $copy_result = 
11159:             &finishuserfileupload($stu_name,$domain,'copy',
11160:                                   '/portfolio'.$directory.$new_answer);
11161:     }
11162:     undef($env{'form.copy'});
11163:     return ($new_answer);
11164: }
11165: 
11166: sub file_name_version_ext {
11167:     my ($file)=@_;
11168:     my @file_parts = split(/\./, $file);
11169:     my ($name,$version,$ext);
11170:     if (@file_parts > 1) {
11171:         $ext=pop(@file_parts);
11172:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11173:             $version=pop(@file_parts);
11174:         }
11175:         $name=join('.',@file_parts);
11176:     } else {
11177:         $name=join('.',@file_parts);
11178:     }
11179:     return($name,$version,$ext);
11180: }
11181: 
11182: #----------------------------------------------Get portfolio file permissions
11183: 
11184: sub get_portfile_permissions {
11185:     my ($domain,$user) = @_;
11186:     my %current_permissions = &dump('file_permissions',$domain,$user);
11187:     my ($tmp)=keys(%current_permissions);
11188:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11189:     return \%current_permissions;
11190: }
11191: 
11192: #---------------------------------------------Get portfolio file access controls
11193: 
11194: sub get_access_controls {
11195:     my ($current_permissions,$group,$file) = @_;
11196:     my %access;
11197:     my $real_file = $file;
11198:     $file =~ s/\.meta$//;
11199:     if (defined($file)) {
11200:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11201:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11202:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11203:             }
11204:         }
11205:     } else {
11206:         foreach my $key (keys(%{$current_permissions})) {
11207:             if ($key =~ /\0accesscontrol$/) {
11208:                 if (defined($group)) {
11209:                     if ($key !~ m-^\Q$group\E/-) {
11210:                         next;
11211:                     }
11212:                 }
11213:                 my ($fullpath) = split(/\0/,$key);
11214:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11215:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11216:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11217:                     }
11218:                 }
11219:             }
11220:         }
11221:     }
11222:     return %access;
11223: }
11224: 
11225: sub modify_access_controls {
11226:     my ($file_name,$changes,$domain,$user)=@_;
11227:     my ($outcome,$deloutcome);
11228:     my %store_permissions;
11229:     my %new_values;
11230:     my %new_control;
11231:     my %translation;
11232:     my @deletions = ();
11233:     my $now = time;
11234:     if (exists($$changes{'activate'})) {
11235:         if (ref($$changes{'activate'}) eq 'HASH') {
11236:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11237:             my $numnew = scalar(@newitems);
11238:             for (my $i=0; $i<$numnew; $i++) {
11239:                 my $newkey = $newitems[$i];
11240:                 my $newid = &Apache::loncommon::get_cgi_id();
11241:                 if ($newkey =~ /^\d+:/) { 
11242:                     $newkey =~ s/^(\d+)/$newid/;
11243:                     $translation{$1} = $newid;
11244:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11245:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11246:                     $translation{$1} = $newid;
11247:                 }
11248:                 $new_values{$file_name."\0".$newkey} = 
11249:                                           $$changes{'activate'}{$newitems[$i]};
11250:                 $new_control{$newkey} = $now;
11251:             }
11252:         }
11253:     }
11254:     my %todelete;
11255:     my %changed_items;
11256:     foreach my $action ('delete','update') {
11257:         if (exists($$changes{$action})) {
11258:             if (ref($$changes{$action}) eq 'HASH') {
11259:                 foreach my $key (keys(%{$$changes{$action}})) {
11260:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11261:                     if ($action eq 'delete') { 
11262:                         $todelete{$itemnum} = 1;
11263:                     } else {
11264:                         $changed_items{$itemnum} = $key;
11265:                     }
11266:                 }
11267:             }
11268:         }
11269:     }
11270:     # get lock on access controls for file.
11271:     my $lockhash = {
11272:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11273:                                                        ':'.$env{'user.domain'},
11274:                    }; 
11275:     my $tries = 0;
11276:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11277:    
11278:     while (($gotlock ne 'ok') && $tries < 10) {
11279:         $tries ++;
11280:         sleep(0.1);
11281:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11282:     }
11283:     if ($gotlock eq 'ok') {
11284:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11285:         my ($tmp)=keys(%curr_permissions);
11286:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11287:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11288:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11289:             if (ref($curr_controls) eq 'HASH') {
11290:                 foreach my $control_item (keys(%{$curr_controls})) {
11291:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11292:                     if (defined($todelete{$itemnum})) {
11293:                         push(@deletions,$file_name."\0".$control_item);
11294:                     } else {
11295:                         if (defined($changed_items{$itemnum})) {
11296:                             $new_control{$changed_items{$itemnum}} = $now;
11297:                             push(@deletions,$file_name."\0".$control_item);
11298:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11299:                         } else {
11300:                             $new_control{$control_item} = $$curr_controls{$control_item};
11301:                         }
11302:                     }
11303:                 }
11304:             }
11305:         }
11306:         my ($group);
11307:         if (&is_course($domain,$user)) {
11308:             ($group,my $file) = split(/\//,$file_name,2);
11309:         }
11310:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11311:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11312:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11313:         #  remove lock
11314:         my @del_lock = ($file_name."\0".'locked_access_records');
11315:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11316:         my $sqlresult =
11317:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11318:                                     $group);
11319:     } else {
11320:         $outcome = "error: could not obtain lockfile\n";  
11321:     }
11322:     return ($outcome,$deloutcome,\%new_values,\%translation);
11323: }
11324: 
11325: sub make_public_indefinitely {
11326:     my (@requrl) = @_;
11327:     return &automated_portfile_access('public',\@requrl);
11328: }
11329: 
11330: sub automated_portfile_access {
11331:     my ($accesstype,$addsref,$delsref,$info) = @_;
11332:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11333:         return 'invalid';
11334:     }
11335:     my %urls;
11336:     if (ref($addsref) eq 'ARRAY') {
11337:         foreach my $requrl (@{$addsref}) {
11338:             if (&is_portfolio_url($requrl)) {
11339:                 unless (exists($urls{$requrl})) {
11340:                     $urls{$requrl} = 'add';
11341:                 }
11342:             }
11343:         }
11344:     }
11345:     if (ref($delsref) eq 'ARRAY') {
11346:         foreach my $requrl (@{$delsref}) { 
11347:             if (&is_portfolio_url($requrl)) {
11348:                 unless (exists($urls{$requrl})) {
11349:                     $urls{$requrl} = 'delete'; 
11350:                 }
11351:             }
11352:         }
11353:     }
11354:     unless (keys(%urls)) {
11355:         return 'invalid';
11356:     }
11357:     my $ip;
11358:     if ($accesstype eq 'ip') {
11359:         if (ref($info) eq 'HASH') {
11360:             if ($info->{'ip'} ne '') {
11361:                 $ip = $info->{'ip'};
11362:             }
11363:         }
11364:         if ($ip eq '') {
11365:             return 'invalid';
11366:         }
11367:     }
11368:     my $errors;
11369:     my $now = time;
11370:     my %current_perms;
11371:     foreach my $requrl (sort(keys(%urls))) {
11372:         my $action;
11373:         if ($urls{$requrl} eq 'add') {
11374:             $action = 'activate';
11375:         } else {
11376:             $action = 'none';
11377:         }
11378:         my $aclnum = 0;
11379:         my (undef,$udom,$unum,$file_name,$group) =
11380:             &parse_portfolio_url($requrl);
11381:         unless (exists($current_perms{$unum.':'.$udom})) {
11382:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11383:         }
11384:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11385:                                                    $group,$file_name);
11386:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11387:             my ($num,$scope,$end,$start) = 
11388:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11389:             if ($scope eq $accesstype) {
11390:                 if (($start <= $now) && ($end == 0)) {
11391:                     if ($accesstype eq 'ip') {
11392:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11393:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11394:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11395:                                     if ($urls{$requrl} eq 'add') {
11396:                                         $action = 'none';
11397:                                         last;
11398:                                     } else {
11399:                                         $action = 'delete';
11400:                                         $aclnum = $num;
11401:                                         last;
11402:                                     }
11403:                                 }
11404:                             }
11405:                         }
11406:                     } elsif ($accesstype eq 'public') {
11407:                         if ($urls{$requrl} eq 'add') {
11408:                             $action = 'none';
11409:                             last;
11410:                         } else {
11411:                             $action = 'delete';
11412:                             $aclnum = $num;
11413:                             last;
11414:                         }
11415:                     }
11416:                 } elsif ($accesstype eq 'public') {
11417:                     $action = 'update';
11418:                     $aclnum = $num;
11419:                     last;
11420:                 }
11421:             }
11422:         }
11423:         if ($action eq 'none') {
11424:             next;
11425:         } else {
11426:             my %changes;
11427:             my $newend = 0;
11428:             my $newstart = $now;
11429:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11430:             $changes{$action}{$newkey} = {
11431:                 type => $accesstype,
11432:                 time => {
11433:                     start => $newstart,
11434:                     end   => $newend,
11435:                 },
11436:             };
11437:             if ($accesstype eq 'ip') {
11438:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11439:             }
11440:             my ($outcome,$deloutcome,$new_values,$translation) =
11441:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11442:             unless ($outcome eq 'ok') {
11443:                 $errors .= $outcome.' ';
11444:             }
11445:         }
11446:     }
11447:     if ($errors) {
11448:         $errors =~ s/\s$//;
11449:         return $errors;
11450:     } else {
11451:         return 'ok';
11452:     }
11453: }
11454: 
11455: #------------------------------------------------------Get Marked as Read Only
11456: 
11457: sub get_marked_as_readonly {
11458:     my ($domain,$user,$what,$group) = @_;
11459:     my $current_permissions = &get_portfile_permissions($domain,$user);
11460:     my @readonly_files;
11461:     my $cmp1=$what;
11462:     if (ref($what)) { $cmp1=join('',@{$what}) };
11463:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11464:         if (defined($group)) {
11465:             if ($file_name !~ m-^\Q$group\E/-) {
11466:                 next;
11467:             }
11468:         }
11469:         if (ref($value) eq "ARRAY"){
11470:             foreach my $stored_what (@{$value}) {
11471:                 my $cmp2=$stored_what;
11472:                 if (ref($stored_what) eq 'ARRAY') {
11473:                     $cmp2=join('',@{$stored_what});
11474:                 }
11475:                 if ($cmp1 eq $cmp2) {
11476:                     push(@readonly_files, $file_name);
11477:                     last;
11478:                 } elsif (!defined($what)) {
11479:                     push(@readonly_files, $file_name);
11480:                     last;
11481:                 }
11482:             }
11483:         }
11484:     }
11485:     return @readonly_files;
11486: }
11487: #-----------------------------------------------------------Get Marked as Read Only Hash
11488: 
11489: sub get_marked_as_readonly_hash {
11490:     my ($current_permissions,$group,$what) = @_;
11491:     my %readonly_files;
11492:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11493:         if (defined($group)) {
11494:             if ($file_name !~ m-^\Q$group\E/-) {
11495:                 next;
11496:             }
11497:         }
11498:         if (ref($value) eq "ARRAY"){
11499:             foreach my $stored_what (@{$value}) {
11500:                 if (ref($stored_what) eq 'ARRAY') {
11501:                     foreach my $lock_descriptor(@{$stored_what}) {
11502:                         if ($lock_descriptor eq 'graded') {
11503:                             $readonly_files{$file_name} = 'graded';
11504:                         } elsif ($lock_descriptor eq 'handback') {
11505:                             $readonly_files{$file_name} = 'handback';
11506:                         } else {
11507:                             if (!exists($readonly_files{$file_name})) {
11508:                                 $readonly_files{$file_name} = 'locked';
11509:                             }
11510:                         }
11511:                     }
11512:                 } 
11513:             }
11514:         } 
11515:     }
11516:     return %readonly_files;
11517: }
11518: # ------------------------------------------------------------ Unmark as Read Only
11519: 
11520: sub unmark_as_readonly {
11521:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11522:     # for portfolio submissions, $what contains [$symb,$crsid] 
11523:     my ($domain,$user,$what,$file_name,$group) = @_;
11524:     $file_name = &declutter_portfile($file_name);
11525:     my $symb_crs = $what;
11526:     if (ref($what)) { $symb_crs=join('',@$what); }
11527:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11528:     my ($tmp)=keys(%current_permissions);
11529:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11530:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11531:     foreach my $file (@readonly_files) {
11532: 	my $clean_file = &declutter_portfile($file);
11533: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11534: 	my $current_locks = $current_permissions{$file};
11535:         my @new_locks;
11536:         my @del_keys;
11537:         if (ref($current_locks) eq "ARRAY"){
11538:             foreach my $locker (@{$current_locks}) {
11539:                 my $compare=$locker;
11540:                 if (ref($locker) eq 'ARRAY') {
11541:                     $compare=join('',@{$locker});
11542:                     if ($compare ne $symb_crs) {
11543:                         push(@new_locks, $locker);
11544:                     }
11545:                 }
11546:             }
11547:             if (scalar(@new_locks) > 0) {
11548:                 $current_permissions{$file} = \@new_locks;
11549:             } else {
11550:                 push(@del_keys, $file);
11551:                 &del('file_permissions',\@del_keys, $domain, $user);
11552:                 delete($current_permissions{$file});
11553:             }
11554:         }
11555:     }
11556:     &put('file_permissions',\%current_permissions,$domain,$user);
11557:     return;
11558: }
11559: 
11560: # ------------------------------------------------------------ Directory lister
11561: 
11562: sub dirlist {
11563:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11564:     $uri=~s/^\///;
11565:     $uri=~s/\/$//;
11566:     my ($udom, $uname);
11567:     if ($getuserdir) {
11568:         $udom = $userdomain;
11569:         $uname = $username;
11570:     } else {
11571:         (undef,$udom,$uname)=split(/\//,$uri);
11572:         if(defined($userdomain)) {
11573:             $udom = $userdomain;
11574:         }
11575:         if(defined($username)) {
11576:             $uname = $username;
11577:         }
11578:     }
11579:     my ($dirRoot,$listing,@listing_results);
11580: 
11581:     $dirRoot = $perlvar{'lonDocRoot'};
11582:     if (defined($getpropath)) {
11583:         $dirRoot = &propath($udom,$uname);
11584:         $dirRoot =~ s/\/$//;
11585:     } elsif (defined($getuserdir)) {
11586:         my $subdir=$uname.'__';
11587:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11588:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11589:                    ."/$udom/$subdir/$uname";
11590:     } elsif (defined($alternateRoot)) {
11591:         $dirRoot = $alternateRoot;
11592:     }
11593: 
11594:     if($udom) {
11595:         if($uname) {
11596:             my $uhome = &homeserver($uname,$udom);
11597:             if ($uhome eq 'no_host') {
11598:                 return ([],'no_host');
11599:             }
11600:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11601:                               .$getuserdir.':'.&escape($dirRoot)
11602:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11603:             if ($listing eq 'unknown_cmd') {
11604:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11605:             } else {
11606:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11607:             }
11608:             if ($listing eq 'unknown_cmd') {
11609:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11610:                 @listing_results = split(/:/,$listing);
11611:             } else {
11612:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11613:             }
11614:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11615:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11616:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11617:                 return ([],$listing);
11618:             } else {
11619:                 return (\@listing_results);
11620:             }
11621:         } elsif(!$alternateRoot) {
11622:             my (%allusers,%listerror);
11623: 	    my %servers = &get_servers($udom,'library');
11624:  	    foreach my $tryserver (keys(%servers)) {
11625:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11626:                                   &escape($udom),$tryserver);
11627:                 if ($listing eq 'unknown_cmd') {
11628: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11629: 				      $udom, $tryserver);
11630:                 } else {
11631:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11632:                 }
11633: 		if ($listing eq 'unknown_cmd') {
11634: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11635: 				      $udom, $tryserver);
11636: 		    @listing_results = split(/:/,$listing);
11637: 		} else {
11638: 		    @listing_results =
11639: 			map { &unescape($_); } split(/:/,$listing);
11640: 		}
11641:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11642:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11643:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11644:                     $listerror{$tryserver} = $listing;
11645:                 } else {
11646: 		    foreach my $line (@listing_results) {
11647: 			my ($entry) = split(/&/,$line,2);
11648: 			$allusers{$entry} = 1;
11649: 		    }
11650: 		}
11651:             }
11652:             my @alluserslist=();
11653:             foreach my $user (sort(keys(%allusers))) {
11654:                 push(@alluserslist,$user.'&user');
11655:             }
11656: 
11657:             if (!%listerror) {
11658:                 # no errors
11659:                 return (\@alluserslist);
11660:             } elsif (scalar(keys(%servers)) == 1) {
11661:                 # one library server, one error 
11662:                 my ($key) = keys(%listerror);
11663:                 return (\@alluserslist, $listerror{$key});
11664:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11665:                 # con_lost indicates that we might miss data from at least one
11666:                 # library server
11667:                 return (\@alluserslist, 'con_lost');
11668:             } else {
11669:                 # multiple library servers and no con_lost -> data should be
11670:                 # complete. 
11671:                 return (\@alluserslist);
11672:             }
11673: 
11674:         } else {
11675:             return ([],'missing username');
11676:         }
11677:     } elsif(!defined($getpropath)) {
11678:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11679:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11680:         return (\@all_domains);
11681:     } else {
11682:         return ([],'missing domain');
11683:     }
11684: }
11685: 
11686: # --------------------------------------------- GetFileTimestamp
11687: # This function utilizes dirlist and returns the date stamp for
11688: # when it was last modified.  It will also return an error of -1
11689: # if an error occurs
11690: 
11691: sub GetFileTimestamp {
11692:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11693:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11694:     $studentName   = &LONCAPA::clean_username($studentName);
11695:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11696:                                     undef,$getuserdir);
11697:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11698:         return -1;
11699:     }
11700:     if (ref($fileref) eq 'ARRAY') {
11701:         my @stats = split('&',$fileref->[0]);
11702:         # @stats contains first the filename, then the stat output
11703:         return $stats[10]; # so this is 10 instead of 9.
11704:     } else {
11705:         return -1;
11706:     }
11707: }
11708: 
11709: sub stat_file {
11710:     my ($uri) = @_;
11711:     $uri = &clutter_with_no_wrapper($uri);
11712: 
11713:     my ($udom,$uname,$file);
11714:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11715: 	($udom,$uname,$file) =
11716: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11717: 	$file = 'userfiles/'.$file;
11718:     }
11719:     if ($uri =~ m-^/res/-) {
11720: 	($udom,$uname) = 
11721: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11722: 	$file = $uri;
11723:     }
11724: 
11725:     if (!$udom || !$uname || !$file) {
11726: 	# unable to handle the uri
11727: 	return ();
11728:     }
11729:     my $getpropath;
11730:     if ($file =~ /^userfiles\//) {
11731:         $getpropath = 1;
11732:     }
11733:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11734:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11735:         return ();
11736:     } else {
11737:         if (ref($listref) eq 'ARRAY') {
11738:             my @stats = split('&',$listref->[0]);
11739: 	    shift(@stats); #filename is first
11740: 	    return @stats;
11741:         }
11742:     }
11743:     return ();
11744: }
11745: 
11746: # --------------------------------------------------------- recursedirs
11747: # Recursive function to traverse either a specific user's Authoring Space
11748: # or corresponding Published Resource Space, and populate the hash ref:
11749: # $dirhashref with URLs of all directories, and if $filehashref hash
11750: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11751: # or .rights files in resource space, and .meta, .save, .log, and .bak
11752: # files in Authoring Space.
11753: #
11754: # Inputs:
11755: #
11756: # $is_home - true if current server is home server for user's space
11757: # $context - either: priv, or res respectively for Authoring or Resource Space.
11758: # $docroot - Document root (i.e., /home/httpd/html
11759: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11760: # $relpath - Current path (relative to top level).
11761: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11762: # $filehashref - reference to hash to populate with URLs of files (Optional)
11763: #
11764: # Returns: nothing
11765: #
11766: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11767: #
11768: # Currently used by interface/londocs.pm to create linked select boxes for
11769: # directory and filename to import a Course "Author" resource into a course, and
11770: # also to create linked select boxes for Authoring Space and Directory to choose
11771: # save location for creation of a new "standard" problem from the Course Editor.
11772: #
11773: 
11774: sub recursedirs {
11775:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11776:     return unless (ref($dirhashref) eq 'HASH');
11777:     my $currpath = $docroot.$toppath;
11778:     if ($relpath) {
11779:         $currpath .= "/$relpath";
11780:     }
11781:     my $savefile;
11782:     if (ref($filehashref)) {
11783:         $savefile = 1;
11784:     }
11785:     if ($is_home) {
11786:         if (opendir(my $dirh,$currpath)) {
11787:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11788:                 next if ($item eq '');
11789:                 if (-d "$currpath/$item") {
11790:                     my $newpath;
11791:                     if ($relpath) {
11792:                         $newpath = "$relpath/$item";
11793:                     } else {
11794:                         $newpath = $item;
11795:                     }
11796:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11797:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11798:                 } elsif ($savefile) {
11799:                     if ($context eq 'priv') {
11800:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11801:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11802:                         }
11803:                     } else {
11804:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11805:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11806:                         }
11807:                     }
11808:                 }
11809:             }
11810:             closedir($dirh);
11811:         }
11812:     } else {
11813:         my ($dirlistref,$listerror) =
11814:             &dirlist($toppath.$relpath);
11815:         my @dir_lines;
11816:         my $dirptr=16384;
11817:         if (ref($dirlistref) eq 'ARRAY') {
11818:             foreach my $dir_line (sort
11819:                               {
11820:                                   my ($afile)=split('&',$a,2);
11821:                                   my ($bfile)=split('&',$b,2);
11822:                                   return (lc($afile) cmp lc($bfile));
11823:                               } (@{$dirlistref})) {
11824:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11825:                     split(/\&/,$dir_line,16);
11826:                 $item =~ s/\s+$//;
11827:                 next if (($item =~ /^\.\.?$/) || ($obs));
11828:                 if ($dirptr&$testdir) {
11829:                     my $newpath;
11830:                     if ($relpath) {
11831:                         $newpath = "$relpath/$item";
11832:                     } else {
11833:                         $relpath = '/';
11834:                         $newpath = $item;
11835:                     }
11836:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11837:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11838:                 } elsif ($savefile) {
11839:                     if ($context eq 'priv') {
11840:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11841:                             $filehashref->{$relpath}{$item} = 1;
11842:                         }
11843:                     } else {
11844:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11845:                             $filehashref->{$relpath}{$item} = 1;
11846:                         }
11847:                     }
11848:                 }
11849:             }
11850:         }
11851:     }
11852:     return;
11853: }
11854: 
11855: # -------------------------------------------------------- Value of a Condition
11856: 
11857: # gets the value of a specific preevaluated condition
11858: #    stored in the string  $env{user.state.<cid>}
11859: # or looks up a condition reference in the bighash and if if hasn't
11860: # already been evaluated recurses into docondval to get the value of
11861: # the condition, then memoizing it to 
11862: #   $env{user.state.<cid>.<condition>}
11863: sub directcondval {
11864:     my $number=shift;
11865:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11866: 	&Apache::lonuserstate::evalstate();
11867:     }
11868:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11869: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11870:     } elsif ($number =~ /^_/) {
11871: 	my $sub_condition;
11872: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11873: 		&GDBM_READER(),0640)) {
11874: 	    $sub_condition=$bighash{'conditions'.$number};
11875: 	    untie(%bighash);
11876: 	}
11877: 	my $value = &docondval($sub_condition);
11878: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11879: 	return $value;
11880:     }
11881:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11882:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11883:     } else {
11884:        return 2;
11885:     }
11886: }
11887: 
11888: # get the collection of conditions for this resource
11889: sub condval {
11890:     my $condidx=shift;
11891:     my $allpathcond='';
11892:     foreach my $cond (split(/\|/,$condidx)) {
11893: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11894: 	    $allpathcond.=
11895: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11896: 	}
11897:     }
11898:     $allpathcond=~s/\|$//;
11899:     return &docondval($allpathcond);
11900: }
11901: 
11902: #evaluates an expression of conditions
11903: sub docondval {
11904:     my ($allpathcond) = @_;
11905:     my $result=0;
11906:     if ($env{'request.course.id'}
11907: 	&& defined($allpathcond)) {
11908: 	my $operand='|';
11909: 	my @stack;
11910: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11911: 	    if ($chunk eq '(') {
11912: 		push @stack,($operand,$result);
11913: 	    } elsif ($chunk eq ')') {
11914: 		my $before=pop @stack;
11915: 		if (pop @stack eq '&') {
11916: 		    $result=$result>$before?$before:$result;
11917: 		} else {
11918: 		    $result=$result>$before?$result:$before;
11919: 		}
11920: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11921: 		$operand=$chunk;
11922: 	    } else {
11923: 		my $new=directcondval($chunk);
11924: 		if ($operand eq '&') {
11925: 		    $result=$result>$new?$new:$result;
11926: 		} else {
11927: 		    $result=$result>$new?$result:$new;
11928: 		}
11929: 	    }
11930: 	}
11931:     }
11932:     return $result;
11933: }
11934: 
11935: # ---------------------------------------------------- Devalidate courseresdata
11936: 
11937: sub devalidatecourseresdata {
11938:     my ($coursenum,$coursedomain)=@_;
11939:     my $hashid=$coursenum.':'.$coursedomain;
11940:     &devalidate_cache_new('courseres',$hashid);
11941: }
11942: 
11943: 
11944: # --------------------------------------------------- Course Resourcedata Query
11945: #
11946: #  Parameters:
11947: #      $coursenum    - Number of the course.
11948: #      $coursedomain - Domain at which the course was created.
11949: #  Returns:
11950: #     A hash of the course parameters along (I think) with timestamps
11951: #     and version info.
11952: 
11953: sub get_courseresdata {
11954:     my ($coursenum,$coursedomain)=@_;
11955:     my $coursehom=&homeserver($coursenum,$coursedomain);
11956:     my $hashid=$coursenum.':'.$coursedomain;
11957:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11958:     my %dumpreply;
11959:     unless (defined($cached)) {
11960: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11961: 	$result=\%dumpreply;
11962: 	my ($tmp) = keys(%dumpreply);
11963: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11964: 	    &do_cache_new('courseres',$hashid,$result,600);
11965: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11966: 	    return $tmp;
11967: 	} elsif ($tmp =~ /^(error)/) {
11968: 	    $result=undef;
11969: 	    &do_cache_new('courseres',$hashid,$result,600);
11970: 	}
11971:     }
11972:     return $result;
11973: }
11974: 
11975: sub devalidateuserresdata {
11976:     my ($uname,$udom)=@_;
11977:     my $hashid="$udom:$uname";
11978:     &devalidate_cache_new('userres',$hashid);
11979: }
11980: 
11981: sub get_userresdata {
11982:     my ($uname,$udom)=@_;
11983:     #most student don\'t have any data set, check if there is some data
11984:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11985: 
11986:     my $hashid="$udom:$uname";
11987:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11988:     if (!defined($cached)) {
11989: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11990: 	$result=\%resourcedata;
11991: 	&do_cache_new('userres',$hashid,$result,600);
11992:     }
11993:     my ($tmp)=keys(%$result);
11994:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11995: 	return $result;
11996:     }
11997:     #error 2 occurs when the .db doesn't exist
11998:     if ($tmp!~/error: 2 /) {
11999:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12000: 	    &logthis("<font color=\"blue\">WARNING:".
12001: 		     " Trying to get resource data for ".
12002: 		     $uname." at ".$udom.": ".
12003: 		     $tmp."</font>");
12004:         }
12005:     } elsif ($tmp=~/error: 2 /) {
12006: 	#&EXT_cache_set($udom,$uname);
12007: 	&do_cache_new('userres',$hashid,undef,600);
12008: 	undef($tmp); # not really an error so don't send it back
12009:     }
12010:     return $tmp;
12011: }
12012: #----------------------------------------------- resdata - return resource data
12013: #  Purpose:
12014: #    Return resource data for either users or for a course.
12015: #  Parameters:
12016: #     $name      - Course/user name.
12017: #     $domain    - Name of the domain the user/course is registered on.
12018: #     $type      - Type of thing $name is (must be 'course' or 'user')
12019: #     $mapp      - decluttered URL of enclosing map  
12020: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12021: #     $recurseup - Ref to array of map URLs, starting with map containing
12022: #                  $mapp up through hierarchy of nested maps to top level map.  
12023: #     $courseid  - CourseID (first part of param identifier).
12024: #     $modifier  - Middle part of param identifier.
12025: #     $what      - Last part of param identifier.
12026: #     @which     - Array of names of resources desired.
12027: #  Returns:
12028: #     The value of the first reasource in @which that is found in the
12029: #     resource hash.
12030: #  Exceptional Conditions:
12031: #     If the $type passed in is not valid (not the string 'course' or 
12032: #     'user', an undefined  reference is returned.
12033: #     If none of the resources are found, an undef is returned
12034: sub resdata {
12035:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12036:         $modifier,$what,@which)=@_;
12037:     my $result;
12038:     if ($type eq 'course') {
12039: 	$result=&get_courseresdata($name,$domain);
12040:     } elsif ($type eq 'user') {
12041: 	$result=&get_userresdata($name,$domain);
12042:     }
12043:     if (!ref($result)) { return $result; }    
12044:     foreach my $item (@which) {
12045:         if ($item->[1] eq 'course') {
12046:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12047:                 unless ($$recursed) {
12048:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12049:                     $$recursed = 1;
12050:                 }
12051:                 foreach my $item (@${recurseup}) {
12052:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12053:                     last if (defined($result->{$norecursechk}));
12054:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12055:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12056:                 }
12057:             }
12058:         }
12059:         if (defined($result->{$item->[0]})) {
12060: 	    return [$result->{$item->[0]},$item->[1]];
12061: 	}
12062:     }
12063:     return undef;
12064: }
12065: 
12066: sub get_domain_lti {
12067:     my ($cdom,$context) = @_;
12068:     my ($name,%lti);
12069:     if ($context eq 'consumer') {
12070:         $name = 'ltitools';
12071:     } elsif ($context eq 'provider') {
12072:         $name = 'lti';
12073:     } else {
12074:         return %lti;
12075:     }
12076:     my ($result,$cached)=&is_cached_new($name,$cdom);
12077:     if (defined($cached)) {
12078:         if (ref($result) eq 'HASH') {
12079:             %lti = %{$result};
12080:         }
12081:     } else {
12082:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12083:         if (ref($domconfig{$name}) eq 'HASH') {
12084:             %lti = %{$domconfig{$name}};
12085:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12086:             if (ref($encdomconfig{$name}) eq 'HASH') {
12087:                 foreach my $id (keys(%lti)) {
12088:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12089:                         foreach my $item ('key','secret') {
12090:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12091:                         }
12092:                     }
12093:                 }
12094:             }
12095:         }
12096:         my $cachetime = 24*60*60;
12097:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12098:     }
12099:     return %lti;
12100: }
12101: 
12102: sub get_numsuppfiles {
12103:     my ($cnum,$cdom,$ignorecache)=@_;
12104:     my $hashid=$cnum.':'.$cdom;
12105:     my ($suppcount,$cached);
12106:     unless ($ignorecache) {
12107:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12108:     }
12109:     unless (defined($cached)) {
12110:         my $chome=&homeserver($cnum,$cdom);
12111:         unless ($chome eq 'no_host') {
12112:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12113:             my $suppmap = 'supplemental.sequence';
12114:             ($suppcount,$supptools,$errors) =
12115:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12116:                                                          $supptools,$errors);
12117:         }
12118:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12119:     }
12120:     return $suppcount;
12121: }
12122: 
12123: #
12124: # EXT resource caching routines
12125: #
12126: 
12127: {
12128: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12129: #
12130: # The course for which we cache
12131: my $cachedmapkey='';
12132: # The cached recursive maps for this course
12133: my %cachedmaps=();
12134: # When this was last done
12135: my $cachedmaptime='';
12136: 
12137: sub clear_EXT_cache_status {
12138:     &delenv('cache.EXT.');
12139: }
12140: 
12141: sub EXT_cache_status {
12142:     my ($target_domain,$target_user) = @_;
12143:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12144:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12145:         # We know already the user has no data
12146:         return 1;
12147:     } else {
12148:         return 0;
12149:     }
12150: }
12151: 
12152: sub EXT_cache_set {
12153:     my ($target_domain,$target_user) = @_;
12154:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12155:     #&appenv({$cachename => time});
12156: }
12157: 
12158: # --------------------------------------------------------- Value of a Variable
12159: sub EXT {
12160: 
12161:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12162:     unless ($varname) { return ''; }
12163:     #get real user name/domain, courseid and symb
12164:     my $courseid;
12165:     my $publicuser;
12166:     if ($symbparm) {
12167: 	$symbparm=&get_symb_from_alias($symbparm);
12168:     }
12169:     if (!($uname && $udom)) {
12170:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12171:       if (!$symbparm) {	$symbparm=$cursymb; }
12172:     } else {
12173: 	$courseid=$env{'request.course.id'};
12174:     }
12175:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12176:     my $rest;
12177:     if (defined($therest[0])) {
12178:        $rest=join('.',@therest);
12179:     } else {
12180:        $rest='';
12181:     }
12182: 
12183:     my $qualifierrest=$qualifier;
12184:     if ($rest) { $qualifierrest.='.'.$rest; }
12185:     my $spacequalifierrest=$space;
12186:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12187:     if ($realm eq 'user') {
12188: # --------------------------------------------------------------- user.resource
12189: 	if ($space eq 'resource') {
12190: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12191: 		  || defined($Apache::lonhomework::parsing_a_task))
12192: 		 &&
12193: 		 ($symbparm eq &symbread()) ) {	
12194: 		# if we are in the middle of processing the resource the
12195: 		# get the value we are planning on committing
12196:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12197:                     return $Apache::lonhomework::results{$qualifierrest};
12198:                 } else {
12199:                     return $Apache::lonhomework::history{$qualifierrest};
12200:                 }
12201: 	    } else {
12202: 		my %restored;
12203: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12204: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12205: 		} else {
12206: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12207: 		}
12208: 		return $restored{$qualifierrest};
12209: 	    }
12210: # ----------------------------------------------------------------- user.access
12211:         } elsif ($space eq 'access') {
12212: 	    # FIXME - not supporting calls for a specific user
12213:             return &allowed($qualifier,$rest);
12214: # ------------------------------------------ user.preferences, user.environment
12215:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12216: 	    if (($uname eq $env{'user.name'}) &&
12217: 		($udom eq $env{'user.domain'})) {
12218: 		return $env{join('.',('environment',$qualifierrest))};
12219: 	    } else {
12220: 		my %returnhash;
12221: 		if (!$publicuser) {
12222: 		    %returnhash=&userenvironment($udom,$uname,
12223: 						 $qualifierrest);
12224: 		}
12225: 		return $returnhash{$qualifierrest};
12226: 	    }
12227: # ----------------------------------------------------------------- user.course
12228:         } elsif ($space eq 'course') {
12229: 	    # FIXME - not supporting calls for a specific user
12230:             return $env{join('.',('request.course',$qualifier))};
12231: # ------------------------------------------------------------------- user.role
12232:         } elsif ($space eq 'role') {
12233: 	    # FIXME - not supporting calls for a specific user
12234:             my ($role,$where)=split(/\./,$env{'request.role'});
12235:             if ($qualifier eq 'value') {
12236: 		return $role;
12237:             } elsif ($qualifier eq 'extent') {
12238:                 return $where;
12239:             }
12240: # ----------------------------------------------------------------- user.domain
12241:         } elsif ($space eq 'domain') {
12242:             return $udom;
12243: # ------------------------------------------------------------------- user.name
12244:         } elsif ($space eq 'name') {
12245:             return $uname;
12246: # ---------------------------------------------------- Any other user namespace
12247:         } else {
12248: 	    my %reply;
12249: 	    if (!$publicuser) {
12250: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12251: 	    }
12252: 	    return $reply{$qualifierrest};
12253:         }
12254:     } elsif ($realm eq 'query') {
12255: # ---------------------------------------------- pull stuff out of query string
12256:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12257: 						[$spacequalifierrest]);
12258: 	return $env{'form.'.$spacequalifierrest}; 
12259:    } elsif ($realm eq 'request') {
12260: # ------------------------------------------------------------- request.browser
12261:         if ($space eq 'browser') {
12262:             return $env{'browser.'.$qualifier};
12263: # ------------------------------------------------------------ request.filename
12264:         } else {
12265:             return $env{'request.'.$spacequalifierrest};
12266:         }
12267:     } elsif ($realm eq 'course') {
12268: # ---------------------------------------------------------- course.description
12269:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12270:     } elsif ($realm eq 'resource') {
12271: 
12272: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12273: 	    if (!$symbparm) { $symbparm=&symbread(); }
12274: 	}
12275: 
12276:         if ($qualifier eq '') {
12277: 	    if ($space eq 'title') {
12278: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12279: 	        return &gettitle($symbparm);
12280: 	    }
12281: 	
12282: 	    if ($space eq 'map') {
12283: 	        my ($map) = &decode_symb($symbparm);
12284: 	        return &symbread($map);
12285: 	    }
12286:             if ($space eq 'maptitle') {
12287:                 my ($map) = &decode_symb($symbparm);
12288:                 return &gettitle($map);
12289:             }
12290: 	    if ($space eq 'filename') {
12291: 	        if ($symbparm) {
12292: 		    return &clutter((&decode_symb($symbparm))[2]);
12293: 	        }
12294: 	        return &hreflocation('',$env{'request.filename'});
12295: 	    }
12296: 
12297:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12298:                 if ($space eq 'visibleparts') {
12299:                     my $navmap = Apache::lonnavmaps::navmap->new();
12300:                     my $item;
12301:                     if (ref($navmap)) {
12302:                         my $res = $navmap->getBySymb($symbparm);
12303:                         my $parts = $res->parts();
12304:                         if (ref($parts) eq 'ARRAY') {
12305:                             $item = join(',',@{$parts});
12306:                         }
12307:                         undef($navmap);
12308:                     }
12309:                     return $item;
12310:                 }
12311:             }
12312:         }
12313: 
12314: 	my ($section, $group, @groups, @recurseup, $recursed);
12315: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12316:         if (($courseid eq '') && ($cid)) {
12317:             $courseid = $cid;
12318:         }
12319: 	if (($symbparm && $courseid) && 
12320: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12321: 
12322: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12323: 
12324: # ----------------------------------------------------- Cascading lookup scheme
12325: 	    my $symbp=$symbparm;
12326: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12327: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12328:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12329: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12330: 	    if (($env{'user.name'} eq $uname) &&
12331: 		($env{'user.domain'} eq $udom)) {
12332: 		$section=$env{'request.course.sec'};
12333:                 @groups = split(/:/,$env{'request.course.groups'});  
12334:                 @groups=&sort_course_groups($courseid,@groups); 
12335: 	    } else {
12336: 		if (! defined($usection)) {
12337: 		    $section=&getsection($udom,$uname,$courseid);
12338: 		} else {
12339: 		    $section = $usection;
12340: 		}
12341:                 @groups = &get_users_groups($udom,$uname,$courseid);
12342: 	    }
12343: 
12344: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12345: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12346:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12347: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12348: 
12349: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12350: 	    my $courselevelr=$courseid.'.'.$symbparm;
12351:             $courseleveli=$courseid.'.'.$recurseparm;
12352: 	    $courselevelm=$courseid.'.'.$mapparm;
12353: 
12354: # ----------------------------------------------------------- first, check user
12355: 
12356: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12357:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12358: 				       ([$courselevelr,'resource'],
12359: 					[$courselevelm,'map'     ],
12360:                                         [$courseleveli,'map'     ],
12361: 					[$courselevel, 'course'  ]));
12362: 	    if (defined($userreply)) { return &get_reply($userreply); }
12363: 
12364: # ------------------------------------------------ second, check some of course
12365:             my $coursereply;
12366:             if (@groups > 0) {
12367:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12368:                                        $recurseparm,$mapparm,$spacequalifierrest,
12369:                                        $mapp,\$recursed,\@recurseup);
12370:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12371:             }
12372: 
12373: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12374: 				  $env{'course.'.$courseid.'.domain'},
12375: 				  'course',$mapp,\$recursed,\@recurseup,
12376:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12377: 				  ([$seclevelr,   'resource'],
12378: 				   [$seclevelm,   'map'     ],
12379:                                    [$secleveli,   'map'     ],
12380: 				   [$seclevel,    'course'  ],
12381: 				   [$courselevelr,'resource']));
12382: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12383: 
12384: # ------------------------------------------------------ third, check map parms
12385: 	    my %parmhash=();
12386: 	    my $thisparm='';
12387: 	    if (tie(%parmhash,'GDBM_File',
12388: 		    $env{'request.course.fn'}.'_parms.db',
12389: 		    &GDBM_READER(),0640)) {
12390: 		$thisparm=$parmhash{$symbparm};
12391: 		untie(%parmhash);
12392: 	    }
12393: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12394: 	}
12395: # ------------------------------------------ fourth, look in resource metadata
12396:  
12397:         my $what = $spacequalifierrest;
12398: 	$what=~s/\./\_/;
12399: 	my $filename;
12400: 	if (!$symbparm) { $symbparm=&symbread(); }
12401: 	if ($symbparm) {
12402: 	    $filename=(&decode_symb($symbparm))[2];
12403: 	} else {
12404: 	    $filename=$env{'request.filename'};
12405: 	}
12406:         my $toolsymb;
12407:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12408:             $toolsymb = $symbparm;
12409:         }
12410: 	my $metadata=&metadata($filename,$what,$toolsymb);
12411: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12412: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12413: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12414: 
12415: # ----------------------------------------------- fifth, look in rest of course
12416: 	if ($symbparm && defined($courseid) && 
12417: 	    $courseid eq $env{'request.course.id'}) {
12418: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12419: 				     $env{'course.'.$courseid.'.domain'},
12420: 				     'course',$mapp,\$recursed,\@recurseup,
12421:                                      $courseid,'.',$spacequalifierrest,
12422: 				     ([$courselevelm,'map'   ],
12423:                                       [$courseleveli,'map'   ],
12424: 				      [$courselevel, 'course']));
12425: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12426: 	}
12427: # ------------------------------------------------------------------ Cascade up
12428: 	unless ($space eq '0') {
12429: 	    my @parts=split(/_/,$space);
12430: 	    my $id=pop(@parts);
12431: 	    my $part=join('_',@parts);
12432: 	    if ($part eq '') { $part='0'; }
12433: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12434: 				 $symbparm,$udom,$uname,$section,1);
12435: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12436: 	}
12437: 	if ($recurse) { return undef; }
12438: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12439: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12440: # ---------------------------------------------------- Any other user namespace
12441:     } elsif ($realm eq 'environment') {
12442: # ----------------------------------------------------------------- environment
12443: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12444: 	    return $env{'environment.'.$spacequalifierrest};
12445: 	} else {
12446: 	    if ($uname eq 'anonymous' && $udom eq '') {
12447: 		return '';
12448: 	    }
12449: 	    my %returnhash=&userenvironment($udom,$uname,
12450: 					    $spacequalifierrest);
12451: 	    return $returnhash{$spacequalifierrest};
12452: 	}
12453:     } elsif ($realm eq 'system') {
12454: # ----------------------------------------------------------------- system.time
12455: 	if ($space eq 'time') {
12456: 	    return time;
12457:         }
12458:     } elsif ($realm eq 'server') {
12459: # ----------------------------------------------------------------- system.time
12460: 	if ($space eq 'name') {
12461: 	    return $ENV{'SERVER_NAME'};
12462:         }
12463:     } elsif ($realm eq 'client') {
12464:         if ($space eq 'remote_addr') {
12465:             return &get_requestor_ip();
12466:         }
12467:     }
12468:     return '';
12469: }
12470: 
12471: sub get_reply {
12472:     my ($reply_value) = @_;
12473:     if (ref($reply_value) eq 'ARRAY') {
12474:         if (wantarray) {
12475: 	    return @$reply_value;
12476:         }
12477:         return $reply_value->[0];
12478:     } else {
12479:         return $reply_value;
12480:     }
12481: }
12482: 
12483: sub check_group_parms {
12484:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12485:         $recursed,$recurseupref) = @_;
12486:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12487:                   [$what,'course']);
12488:     my $coursereply;
12489:     foreach my $group (@{$groups}) {
12490:         my @groupitems = ();
12491:         foreach my $level (@levels) {
12492:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12493:              push(@groupitems,[$item,$level->[1]]);
12494:         }
12495:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12496:                                    $env{'course.'.$courseid.'.domain'},
12497:                                    'course',$mapp,$recursed,$recurseupref,
12498:                                    $courseid,'.['.$group.'].',$what,
12499:                                    @groupitems);
12500:         last if (defined($coursereply));
12501:     }
12502:     return $coursereply;
12503: }
12504: 
12505: sub get_map_hierarchy {
12506:     my ($mapname,$courseid) = @_;
12507:     my @recurseup = ();
12508:     if ($mapname) {
12509:         if (($cachedmapkey eq $courseid) &&
12510:             (abs($cachedmaptime-time)<5)) {
12511:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12512:                 return @{$cachedmaps{$mapname}};
12513:             }
12514:         }
12515:         my $navmap = Apache::lonnavmaps::navmap->new();
12516:         if (ref($navmap)) {
12517:             @recurseup = $navmap->recurseup_maps($mapname);
12518:             undef($navmap);
12519:             $cachedmaps{$mapname} = \@recurseup;
12520:             $cachedmaptime=time;
12521:             $cachedmapkey=$courseid;
12522:         }
12523:     }
12524:     return @recurseup;
12525: }
12526: 
12527: }
12528: 
12529: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12530:     my ($courseid,@groups) = @_;
12531:     @groups = sort(@groups);
12532:     return @groups;
12533: }
12534: 
12535: sub packages_tab_default {
12536:     my ($uri,$varname,$toolsymb)=@_;
12537:     my (undef,$part,$name)=split(/\./,$varname);
12538: 
12539:     my (@extension,@specifics,$do_default);
12540:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12541: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12542: 	if ($pack_type eq 'default') {
12543: 	    $do_default=1;
12544: 	} elsif ($pack_type eq 'extension') {
12545: 	    push(@extension,[$package,$pack_type,$pack_part]);
12546: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12547: 	    # only look at packages defaults for packages that this id is
12548: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12549: 	}
12550:     }
12551:     # first look for a package that matches the requested part id
12552:     foreach my $package (@specifics) {
12553: 	my (undef,$pack_type,$pack_part)=@{$package};
12554: 	next if ($pack_part ne $part);
12555: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12556: 	    return $packagetab{"$pack_type&$name&default"};
12557: 	}
12558:     }
12559:     # look for any possible matching non extension_ package
12560:     foreach my $package (@specifics) {
12561: 	my (undef,$pack_type,$pack_part)=@{$package};
12562: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12563: 	    return $packagetab{"$pack_type&$name&default"};
12564: 	}
12565: 	if ($pack_type eq 'part') { $pack_part='0'; }
12566: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12567: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12568: 	}
12569:     }
12570:     # look for any posible extension_ match
12571:     foreach my $package (@extension) {
12572: 	my ($package,$pack_type)=@{$package};
12573: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12574: 	    return $packagetab{"$pack_type&$name&default"};
12575: 	}
12576: 	if (defined($packagetab{$package."&$name&default"})) {
12577: 	    return $packagetab{$package."&$name&default"};
12578: 	}
12579:     }
12580:     # look for a global default setting
12581:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12582: 	return $packagetab{"default&$name&default"};
12583:     }
12584:     return undef;
12585: }
12586: 
12587: sub add_prefix_and_part {
12588:     my ($prefix,$part)=@_;
12589:     my $keyroot;
12590:     if (defined($prefix) && $prefix !~ /^__/) {
12591: 	# prefix that has a part already
12592: 	$keyroot=$prefix;
12593:     } elsif (defined($prefix)) {
12594: 	# prefix that is missing a part
12595: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12596:     } else {
12597: 	# no prefix at all
12598: 	if (defined($part)) { $keyroot='_'.$part; }
12599:     }
12600:     return $keyroot;
12601: }
12602: 
12603: # ---------------------------------------------------------------- Get metadata
12604: 
12605: my %metaentry;
12606: my %importedpartids;
12607: my %importedrespids;
12608: sub metadata {
12609:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12610:     $uri=&declutter($uri);
12611:     # if it is a non metadata possible uri return quickly
12612:     if (($uri eq '') || 
12613: 	(($uri =~ m|^/*adm/|) && 
12614: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12615:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12616: 	return undef;
12617:     }
12618:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12619: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12620: 	return undef;
12621:     }
12622:     my $filename=$uri;
12623:     $uri=~s/\.meta$//;
12624: #
12625: # Is the metadata already cached?
12626: # Look at timestamp of caching
12627: # Everything is cached by the main uri, libraries are never directly cached
12628: #
12629:     if (!defined($liburi)) {
12630: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12631: 	if (defined($cached)) { return $result->{':'.$what}; }
12632:     }
12633: 
12634: #
12635: # If the uri is for an external tool the file from
12636: # which metadata should be retrieved depends on whether
12637: # the tool had been configured to be gradable (set in the Course
12638: # Editor or Resource Editor).
12639: #
12640: # If a valid symb has been included as the third arg in the call
12641: # to &metadata() that can be used to retrieve the value of
12642: # parameter_0_gradable set for the resource, and included in the
12643: # uploaded map containing the tool. The value is retrieved via
12644: # &EXT(), if a valid symb is available.  Otherwise the value of
12645: # gradable in the exttool_$marker.db file for the tool instance
12646: # is retrieved via &get().
12647: #
12648: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12649: # hiddenresource and encrypturl (during course initialization)
12650: # the map-level parameter for resource.0.gradable included in the 
12651: # uploaded map containing the tool will not yet have been stored
12652: # in the user_course_parms.db file for the user's session, so in 
12653: # this case fall back to retrieving gradable status from the
12654: # exttool_$marker.db file.
12655: #
12656: # In order to avoid an infinite loop, &metadata() will return
12657: # before a call to &EXT(), if the uri is for an external tool
12658: # and the $what for which metadata is being requested is
12659: # parameter_0_gradable or 0_gradable.
12660: #
12661: 
12662:     if ($uri =~ /ext\.tool$/) {
12663:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12664:             return;
12665:         } else {
12666:             my ($checked,$use_passback);
12667:             if ($toolsymb ne '') {
12668:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12669:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12670:                     $checked = 1;
12671:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12672:                         $use_passback = 1;
12673:                     }
12674:                 }
12675:             }
12676:             unless ($checked) {
12677:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12678:                 $marker=~s/\D//g;
12679:                 if ($marker) {
12680:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12681:                     $use_passback = $toolsettings{'gradable'};
12682:                 }
12683:             }
12684:             if ($use_passback) {
12685:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12686:             } else {
12687:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12688:             }
12689:         }
12690:     }
12691: 
12692:     {
12693: # Imported parts would go here
12694:         my @origfiletagids=();
12695:         my $importedparts=0;
12696: 
12697: # Imported responseids would go here
12698:         my $importedresponses=0;
12699: #
12700: # Is this a recursive call for a library?
12701: #
12702: #	if (! exists($metacache{$uri})) {
12703: #	    $metacache{$uri}={};
12704: #	}
12705: 	my $cachetime = 60*60;
12706:         if ($liburi) {
12707: 	    $liburi=&declutter($liburi);
12708:             $filename=$liburi;
12709:         } else {
12710: 	    &devalidate_cache_new('meta',$uri);
12711: 	    undef(%metaentry);
12712: 	}
12713:         my %metathesekeys=();
12714:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12715: 	my $metastring;
12716: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12717: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12718: 	    $metastring = 
12719: 		&Apache::lonnet::ssi_body($which,
12720: 					  ('grade_target' => 'meta'));
12721: 	    $cachetime = 1; # only want this cached in the child not long term
12722: 	} elsif (($uri !~ m -^(editupload)/-) && 
12723:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12724: 	    my $file=&filelocation('',&clutter($filename));
12725: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12726: 	    $metastring=&getfile($file);
12727: 	}
12728:         my $parser=HTML::LCParser->new(\$metastring);
12729:         my $token;
12730:         undef %metathesekeys;
12731:         while ($token=$parser->get_token) {
12732: 	    if ($token->[0] eq 'S') {
12733: 		if (defined($token->[2]->{'package'})) {
12734: #
12735: # This is a package - get package info
12736: #
12737: 		    my $package=$token->[2]->{'package'};
12738: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12739: 		    if (defined($token->[2]->{'id'})) { 
12740: 			$keyroot.='_'.$token->[2]->{'id'}; 
12741: 		    }
12742: 		    if ($metaentry{':packages'}) {
12743: 			$metaentry{':packages'}.=','.$package.$keyroot;
12744: 		    } else {
12745: 			$metaentry{':packages'}=$package.$keyroot;
12746: 		    }
12747: 		    foreach my $pack_entry (keys(%packagetab)) {
12748: 			my $part=$keyroot;
12749: 			$part=~s/^\_//;
12750: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12751: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12752: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12753: 			    # ignore package.tab specified default values
12754:                             # here &package_tab_default() will fetch those
12755: 			    if ($subp eq 'default') { next; }
12756: 			    my $value=$packagetab{$pack_entry};
12757: 			    my $unikey;
12758: 			    if ($pack =~ /_0$/) {
12759: 				$unikey='parameter_0_'.$name;
12760: 				$part=0;
12761: 			    } else {
12762: 				$unikey='parameter'.$keyroot.'_'.$name;
12763: 			    }
12764: 			    if ($subp eq 'display') {
12765: 				$value.=' [Part: '.$part.']';
12766: 			    }
12767: 			    $metaentry{':'.$unikey.'.part'}=$part;
12768: 			    $metathesekeys{$unikey}=1;
12769: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12770: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12771: 			    }
12772: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12773: 				$metaentry{':'.$unikey}=
12774: 				    $metaentry{':'.$unikey.'.default'};
12775: 			    }
12776: 			}
12777: 		    }
12778: 		} else {
12779: #
12780: # This is not a package - some other kind of start tag
12781: #
12782: 		    my $entry=$token->[1];
12783: 		    my $unikey='';
12784: 
12785: 		    if ($entry eq 'import') {
12786: #
12787: # Importing a library here
12788: #
12789:                         my $location=$parser->get_text('/import');
12790:                         my $dir=$filename;
12791:                         $dir=~s|[^/]*$||;
12792:                         $location=&filelocation($dir,$location);
12793: 
12794:                         my $importid=$token->[2]->{'id'};
12795:                         my $importmode=$token->[2]->{'importmode'};
12796: #
12797: # Check metadata for imported file to
12798: # see if it contained response items
12799: #
12800:                         my ($origfile,@libfilekeys);
12801:                         my %currmetaentry = %metaentry;
12802:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12803:                                                            $depthcount+1));
12804:                         if (grep(/^responseorder$/,@libfilekeys)) {
12805:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12806:                                                              undef,$depthcount+1);
12807:                             if ($libresponseorder ne '') {
12808:                                 if ($#origfiletagids<0) {
12809:                                     undef(%importedrespids);
12810:                                     undef(%importedpartids);
12811:                                 }
12812:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12813:                                 if (@respids) {
12814:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12815:                                 }
12816:                                 if ($importedrespids{$importid} ne '') {
12817:                                     $importedresponses = 1;
12818: # We need to get the original file and the imported file to get the response order correct
12819: # Load and inspect original file
12820:                                     if ($#origfiletagids<0) {
12821:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12822:                                         $origfile=&getfile($origfilelocation);
12823:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12824:                                     }
12825:                                 }
12826:                             }
12827:                         }
12828: # Do not overwrite contents of %metaentry hash for resource itself with 
12829: # hash populated for imported library file
12830:                         %metaentry = %currmetaentry;
12831:                         undef(%currmetaentry);
12832:                         if ($importmode eq 'part') {
12833: # Import as part(s)
12834:                            $importedparts=1;
12835: # We need to get the original file and the imported file to get the part order correct
12836: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12837: # Load and inspect original file if we didn't do that already
12838:                            if ($#origfiletagids<0) {
12839:                                undef(%importedrespids);
12840:                                undef(%importedpartids);
12841:                                if ($origfile eq '') {
12842:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12843:                                    $origfile=&getfile($origfilelocation);
12844:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12845:                                }
12846:                            }
12847:                            my @impfilepartids;
12848: # If <partorder> tag is included in metadata for the imported file
12849: # get the parts in the imported file from that.
12850:                            if (grep(/^partorder$/,@libfilekeys)) {
12851:                                %currmetaentry = %metaentry;
12852:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12853:                                                             $depthcount+1);
12854:                                %metaentry = %currmetaentry;
12855:                                undef(%currmetaentry);
12856:                                if ($libpartorder ne '') {
12857:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12858:                                }
12859:                            } else {
12860: # If no <partorder> tag available, load and inspect imported file
12861:                                my $impfile=&getfile($location);
12862:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12863:                            }
12864:                            if ($#impfilepartids>=0) {
12865: # This problem had parts
12866:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12867:                            } else {
12868: # Importing by turning a single problem into a problem part
12869: # It gets the import-tags ID as part-ID
12870:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12871:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12872:                            }
12873:                         } else {
12874: # Import as problem or as normal import
12875:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12876:                             unless ($importmode eq 'problem') {
12877: # Normal import
12878:                                 if (defined($token->[2]->{'id'})) {
12879:                                     $unikey.='_'.$token->[2]->{'id'};
12880:                                 }
12881:                             }
12882: # Check metadata for imported file to
12883: # see if it contained parts
12884:                             if (grep(/^partorder$/,@libfilekeys)) {
12885:                                 %currmetaentry = %metaentry;
12886:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12887:                                                              $depthcount+1);
12888:                                 %metaentry = %currmetaentry;
12889:                                 undef(%currmetaentry);
12890:                                 if ($libpartorder ne '') {
12891:                                     $importedparts = 1;
12892:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12893:                                 }
12894:                             }
12895:                         }
12896: 			if ($depthcount<20) {
12897: 			    my $metadata = 
12898: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12899: 					  $depthcount+1);
12900: 			    foreach my $meta (split(',',$metadata)) {
12901: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12902: 				$metathesekeys{$meta}=1;
12903: 			    }
12904:                         }
12905: 		    } else {
12906: #
12907: # Not importing, some other kind of non-package, non-library start tag
12908: # 
12909:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12910:                         if (defined($token->[2]->{'id'})) {
12911:                             $unikey.='_'.$token->[2]->{'id'};
12912:                         }
12913: 			if (defined($token->[2]->{'name'})) { 
12914: 			    $unikey.='_'.$token->[2]->{'name'}; 
12915: 			}
12916: 			$metathesekeys{$unikey}=1;
12917: 			foreach my $param (@{$token->[3]}) {
12918: 			    $metaentry{':'.$unikey.'.'.$param} =
12919: 				$token->[2]->{$param};
12920: 			}
12921: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12922: 			my $default=$metaentry{':'.$unikey.'.default'};
12923: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12924: 		 # only ws inside the tag, and not in default, so use default
12925: 		 # as value
12926: 			    $metaentry{':'.$unikey}=$default;
12927: 			} elsif ( $internaltext =~ /\S/ ) {
12928: 		  # something interesting inside the tag
12929: 			    $metaentry{':'.$unikey}=$internaltext;
12930: 			} else {
12931: 		  # no interesting values, don't set a default
12932: 			}
12933: # end of not-a-package not-a-library import
12934: 		    }
12935: # end of not-a-package start tag
12936: 		}
12937: # the next is the end of "start tag"
12938: 	    }
12939: 	}
12940: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12941: 	$extension = lc($extension);
12942: 	if ($extension eq 'htm') { $extension='html'; }
12943: 
12944: 	foreach my $key (keys(%packagetab)) {
12945: 	    #no specific packages #how's our extension
12946: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12947: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12948: 					 \%metathesekeys);
12949: 	}
12950: 
12951: 	if (!exists($metaentry{':packages'})
12952: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12953: 	    foreach my $key (keys(%packagetab)) {
12954: 		#no specific packages well let's get default then
12955: 		if ($key!~/^default&/) { next; }
12956: 		&metadata_create_package_def($uri,$key,'default',
12957: 					     \%metathesekeys);
12958: 	    }
12959: 	}
12960: # are there custom rights to evaluate
12961: 	if ($metaentry{':copyright'} eq 'custom') {
12962: 
12963:     #
12964:     # Importing a rights file here
12965:     #
12966: 	    unless ($depthcount) {
12967: 		my $location=$metaentry{':customdistributionfile'};
12968: 		my $dir=$filename;
12969: 		$dir=~s|[^/]*$||;
12970: 		$location=&filelocation($dir,$location);
12971: 		my $rights_metadata =
12972: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12973: 			      $depthcount+1);
12974: 		foreach my $rights (split(',',$rights_metadata)) {
12975: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12976: 		    $metathesekeys{$rights}=1;
12977: 		}
12978: 	    }
12979: 	}
12980: 	# uniqifiy package listing
12981: 	my %seen;
12982: 	my @uniq_packages =
12983: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12984: 	$metaentry{':packages'} = join(',',@uniq_packages);
12985: 
12986:         if (($importedresponses) || ($importedparts)) {
12987:             if ($importedparts) {
12988: # We had imported parts and need to rebuild partorder
12989:                 $metaentry{':partorder'}='';
12990:                 $metathesekeys{'partorder'}=1;
12991:             }
12992:             if ($importedresponses) {
12993: # We had imported responses and need to rebuil responseorder
12994:                 $metaentry{':responseorder'}='';
12995:                 $metathesekeys{'responseorder'}=1;
12996:             }
12997:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12998:                 my $origid = $origfiletagids[$index+1];
12999:                 if ($origfiletagids[$index] eq 'part') {
13000: # Original part, part of the problem
13001:                     if ($importedparts) {
13002:                         $metaentry{':partorder'}.=','.$origid;
13003:                     }
13004:                 } elsif ($origfiletagids[$index] eq 'import') {
13005:                     if ($importedparts) {
13006: # We have imported parts at this position
13007:                         if ($importedpartids{$origid} ne '') {
13008:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13009:                         }
13010:                     }
13011:                     if ($importedresponses) {
13012: # We have imported responses at this position
13013:                         if ($importedrespids{$origid} ne '') {
13014:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13015:                         }
13016:                     }
13017:                 } else {
13018: # Original response item, part of the problem
13019:                     if ($importedresponses) {
13020:                         $metaentry{':responseorder'}.=','.$origid;
13021:                     }
13022:                 }
13023:             }
13024:             if ($importedparts) {
13025:                 $metaentry{':partorder'}=~s/^\,//;
13026:             }
13027:             if ($importedresponses) {
13028:                 $metaentry{':responseorder'}=~s/^\,//;
13029:             }
13030:         }
13031: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13032: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13033: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13034:         unless ($liburi) {
13035: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13036:         }
13037: # this is the end of "was not already recently cached
13038:     }
13039:     return $metaentry{':'.$what};
13040: }
13041: 
13042: sub metadata_create_package_def {
13043:     my ($uri,$key,$package,$metathesekeys)=@_;
13044:     my ($pack,$name,$subp)=split(/\&/,$key);
13045:     if ($subp eq 'default') { next; }
13046:     
13047:     if (defined($metaentry{':packages'})) {
13048: 	$metaentry{':packages'}.=','.$package;
13049:     } else {
13050: 	$metaentry{':packages'}=$package;
13051:     }
13052:     my $value=$packagetab{$key};
13053:     my $unikey;
13054:     $unikey='parameter_0_'.$name;
13055:     $metaentry{':'.$unikey.'.part'}=0;
13056:     $$metathesekeys{$unikey}=1;
13057:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13058: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13059:     }
13060:     if (defined($metaentry{':'.$unikey.'.default'})) {
13061: 	$metaentry{':'.$unikey}=
13062: 	    $metaentry{':'.$unikey.'.default'};
13063:     }
13064: }
13065: 
13066: sub metadata_generate_part0 {
13067:     my ($metadata,$metacache,$uri) = @_;
13068:     my %allnames;
13069:     foreach my $metakey (keys(%$metadata)) {
13070: 	if ($metakey=~/^parameter\_(.*)/) {
13071: 	  my $part=$$metacache{':'.$metakey.'.part'};
13072: 	  my $name=$$metacache{':'.$metakey.'.name'};
13073: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13074: 	    $allnames{$name}=$part;
13075: 	  }
13076: 	}
13077:     }
13078:     foreach my $name (keys(%allnames)) {
13079:       $$metadata{"parameter_0_$name"}=1;
13080:       my $key=":parameter_0_$name";
13081:       $$metacache{"$key.part"}='0';
13082:       $$metacache{"$key.name"}=$name;
13083:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13084: 					   $allnames{$name}.'_'.$name.
13085: 					   '.type'};
13086:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13087: 			     '.display'};
13088:       my $expr='[Part: '.$allnames{$name}.']';
13089:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13090:       $$metacache{"$key.display"}=$olddis;
13091:     }
13092: }
13093: 
13094: # ------------------------------------------------------ Devalidate title cache
13095: 
13096: sub devalidate_title_cache {
13097:     my ($url)=@_;
13098:     if (!$env{'request.course.id'}) { return; }
13099:     my $symb=&symbread($url);
13100:     if (!$symb) { return; }
13101:     my $key=$env{'request.course.id'}."\0".$symb;
13102:     &devalidate_cache_new('title',$key);
13103: }
13104: 
13105: # ------------------------------------------------- Get the title of a course
13106: 
13107: sub current_course_title {
13108:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13109: }
13110: # ------------------------------------------------- Get the title of a resource
13111: 
13112: sub gettitle {
13113:     my $urlsymb=shift;
13114:     my $symb=&symbread($urlsymb);
13115:     if ($symb) {
13116: 	my $key=$env{'request.course.id'}."\0".$symb;
13117: 	my ($result,$cached)=&is_cached_new('title',$key);
13118: 	if (defined($cached)) { 
13119: 	    return $result;
13120: 	}
13121: 	my ($map,$resid,$url)=&decode_symb($symb);
13122: 	my $title='';
13123: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13124: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13125: 	} else {
13126: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13127: 		    &GDBM_READER(),0640)) {
13128: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13129: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13130: 		untie(%bighash);
13131: 	    }
13132: 	}
13133: 	$title=~s/\&colon\;/\:/gs;
13134: 	if ($title) {
13135: # Remember both $symb and $title for dynamic metadata
13136:             $accesshash{$symb.'___crstitle'}=$title;
13137:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13138: # Cache this title and then return it
13139: 	    return &do_cache_new('title',$key,$title,600);
13140: 	}
13141: 	$urlsymb=$url;
13142:     }
13143:     my $title=&metadata($urlsymb,'title');
13144:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13145:     return $title;
13146: }
13147: 
13148: sub get_slot {
13149:     my ($which,$cnum,$cdom)=@_;
13150:     if (!$cnum || !$cdom) {
13151: 	(undef,my $courseid)=&whichuser();
13152: 	$cdom=$env{'course.'.$courseid.'.domain'};
13153: 	$cnum=$env{'course.'.$courseid.'.num'};
13154:     }
13155:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13156:     my %slotinfo;
13157:     if (exists($remembered{$key})) {
13158: 	$slotinfo{$which} = $remembered{$key};
13159:     } else {
13160: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13161: 	&Apache::lonhomework::showhash(%slotinfo);
13162: 	my ($tmp)=keys(%slotinfo);
13163: 	if ($tmp=~/^error:/) { return (); }
13164: 	$remembered{$key} = $slotinfo{$which};
13165:     }
13166:     if (ref($slotinfo{$which}) eq 'HASH') {
13167: 	return %{$slotinfo{$which}};
13168:     }
13169:     return $slotinfo{$which};
13170: }
13171: 
13172: sub get_reservable_slots {
13173:     my ($cnum,$cdom,$uname,$udom) = @_;
13174:     my $now = time;
13175:     my $reservable_info;
13176:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13177:     if (exists($remembered{$key})) {
13178:         $reservable_info = $remembered{$key};
13179:     } else {
13180:         my %resv;
13181:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13182:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13183:         $reservable_info = \%resv;
13184:         $remembered{$key} = $reservable_info;
13185:     }
13186:     return $reservable_info;
13187: }
13188: 
13189: sub get_course_slots {
13190:     my ($cnum,$cdom) = @_;
13191:     my $hashid=$cnum.':'.$cdom;
13192:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13193:     if (defined($cached)) {
13194:         if (ref($result) eq 'HASH') {
13195:             return %{$result};
13196:         }
13197:     } else {
13198:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13199:         my ($tmp) = keys(%slots);
13200:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13201:             &do_cache_new('allslots',$hashid,\%slots,600);
13202:             return %slots;
13203:         }
13204:     }
13205:     return;
13206: }
13207: 
13208: sub devalidate_slots_cache {
13209:     my ($cnum,$cdom)=@_;
13210:     my $hashid=$cnum.':'.$cdom;
13211:     &devalidate_cache_new('allslots',$hashid);
13212: }
13213: 
13214: sub get_coursechange {
13215:     my ($cdom,$cnum) = @_;
13216:     if ($cdom eq '' || $cnum eq '') {
13217:         return unless ($env{'request.course.id'});
13218:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13219:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13220:     }
13221:     my $hashid=$cdom.'_'.$cnum;
13222:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13223:     if ((defined($cached)) && ($change ne '')) {
13224:         return $change;
13225:     } else {
13226:         my %crshash;
13227:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13228:         if ($crshash{'internal.contentchange'} eq '') {
13229:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13230:             if ($change eq '') {
13231:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13232:                 $change = $crshash{'internal.created'};
13233:             }
13234:         } else {
13235:             $change = $crshash{'internal.contentchange'};
13236:         }
13237:         my $cachetime = 600;
13238:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13239:     }
13240:     return $change;
13241: }
13242: 
13243: sub devalidate_coursechange_cache {
13244:     my ($cnum,$cdom)=@_;
13245:     my $hashid=$cnum.':'.$cdom;
13246:     &devalidate_cache_new('crschange',$hashid);
13247: }
13248: 
13249: # ------------------------------------------------- Update symbolic store links
13250: 
13251: sub symblist {
13252:     my ($mapname,%newhash)=@_;
13253:     $mapname=&deversion(&declutter($mapname));
13254:     my %hash;
13255:     if (($env{'request.course.fn'}) && (%newhash)) {
13256:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13257:                       &GDBM_WRCREAT(),0640)) {
13258: 	    foreach my $url (keys(%newhash)) {
13259: 		next if ($url eq 'last_known'
13260: 			 && $env{'form.no_update_last_known'});
13261: 		$hash{declutter($url)}=&encode_symb($mapname,
13262: 						    $newhash{$url}->[1],
13263: 						    $newhash{$url}->[0]);
13264:             }
13265:             if (untie(%hash)) {
13266: 		return 'ok';
13267:             }
13268:         }
13269:     }
13270:     return 'error';
13271: }
13272: 
13273: # --------------------------------------------------------------- Verify a symb
13274: 
13275: sub symbverify {
13276:     my ($symb,$thisurl,$encstate)=@_;
13277:     my $thisfn=$thisurl;
13278:     $thisfn=&declutter($thisfn);
13279: # direct jump to resource in page or to a sequence - will construct own symbs
13280:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13281: # check URL part
13282:     my ($map,$resid,$url)=&decode_symb($symb);
13283: 
13284:     unless ($url eq $thisfn) { return 0; }
13285: 
13286:     $symb=&symbclean($symb);
13287:     $thisurl=&deversion($thisurl);
13288:     $thisfn=&deversion($thisfn);
13289: 
13290:     my %bighash;
13291:     my $okay=0;
13292: 
13293:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13294:                             &GDBM_READER(),0640)) {
13295:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13296:             $thisurl =~ s/\?.+$//;
13297:             if ($map =~ m{^uploaded/.+\.page$}) {
13298:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13299:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13300:             }
13301:         }
13302:         my $ids;
13303:         if ($map =~ m{^uploaded/.+\.page$}) {
13304:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13305:         } else {
13306:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13307:         }
13308:         unless ($ids) {
13309:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13310:             $ids=$bighash{$idkey};
13311:         }
13312:         if ($ids) {
13313: # ------------------------------------------------------------------- Has ID(s)
13314:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13315:                 $symb =~ s/\?.+$//;
13316:             }
13317: 	    foreach my $id (split(/\,/,$ids)) {
13318: 	       my ($mapid,$resid)=split(/\./,$id);
13319:                if (
13320:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13321:    eq $symb) {
13322:                    if (ref($encstate)) {
13323:                        $$encstate = $bighash{'encrypted_'.$id};
13324:                    }
13325: 		   if (($env{'request.role.adv'}) ||
13326: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13327:                        ($thisurl eq '/adm/navmaps')) {
13328: 		       $okay=1;
13329:                        last;
13330: 		   }
13331: 	       }
13332: 	   }
13333:         }
13334: 	untie(%bighash);
13335:     }
13336:     return $okay;
13337: }
13338: 
13339: # --------------------------------------------------------------- Clean-up symb
13340: 
13341: sub symbclean {
13342:     my $symb=shift;
13343:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13344: # remove version from map
13345:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13346: 
13347: # remove version from URL
13348:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13349: 
13350: # remove wrapper
13351: 
13352:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13353:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13354:     return $symb;
13355: }
13356: 
13357: # ---------------------------------------------- Split symb to find map and url
13358: 
13359: sub encode_symb {
13360:     my ($map,$resid,$url)=@_;
13361:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13362: }
13363: 
13364: sub decode_symb {
13365:     my $symb=shift;
13366:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13367:     my ($map,$resid,$url)=split(/___/,$symb);
13368:     return (&fixversion($map),$resid,&fixversion($url));
13369: }
13370: 
13371: sub fixversion {
13372:     my $fn=shift;
13373:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13374:     my %bighash;
13375:     my $uri=&clutter($fn);
13376:     my $key=$env{'request.course.id'}.'_'.$uri;
13377: # is this cached?
13378:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13379:     if (defined($cached)) { return $result; }
13380: # unfortunately not cached, or expired
13381:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13382: 	    &GDBM_READER(),0640)) {
13383:  	if ($bighash{'version_'.$uri}) {
13384:  	    my $version=$bighash{'version_'.$uri};
13385:  	    unless (($version eq 'mostrecent') || 
13386: 		    ($version==&getversion($uri))) {
13387:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13388:  	    }
13389:  	}
13390:  	untie %bighash;
13391:     }
13392:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13393: }
13394: 
13395: sub deversion {
13396:     my $url=shift;
13397:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13398:     return $url;
13399: }
13400: 
13401: # ------------------------------------------------------ Return symb list entry
13402: 
13403: sub symbread {
13404:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13405:         $ignoresymbdb,$noenccheck)=@_;
13406:     my $cache_str='request.symbread.cached.'.$thisfn;
13407:     if (defined($env{$cache_str})) {
13408:         unless (ref($possibles) eq 'HASH') {
13409:             if ($ignorecachednull) {
13410:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13411:             } else {
13412:                 return $env{$cache_str};
13413:             }
13414:         }
13415:     }
13416: # no filename provided? try from environment
13417:     unless ($thisfn) {
13418:         if ($env{'request.symb'}) {
13419:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13420: 	}
13421: 	$thisfn=$env{'request.filename'};
13422:     }
13423:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13424: # is that filename actually a symb? Verify, clean, and return
13425:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13426: 	if (&symbverify($thisfn,$1)) {
13427: 	    return $env{$cache_str}=&symbclean($thisfn);
13428: 	}
13429:     }
13430:     $thisfn=declutter($thisfn);
13431:     my %hash;
13432:     my %bighash;
13433:     my $syval='';
13434:     if (($env{'request.course.fn'}) && ($thisfn)) {
13435:         my $targetfn = $thisfn;
13436:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13437:             $targetfn = 'adm/wrapper/'.$thisfn;
13438:         }
13439: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13440: 	    $targetfn=$1;
13441: 	}
13442:         unless ($ignoresymbdb) {
13443:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13444:                           &GDBM_READER(),0640)) {
13445: 	        $syval=$hash{$targetfn};
13446:                 untie(%hash);
13447:             }
13448:             if ($syval && $checkforblock) {
13449:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13450:                 if (@blockers) {
13451:                     $syval='';
13452:                 }
13453:             }
13454:         }
13455: # ---------------------------------------------------------- There was an entry
13456:         if ($syval) {
13457: 	    #unless ($syval=~/\_\d+$/) {
13458: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13459: 		    #&appenv({'request.ambiguous' => $thisfn});
13460: 		    #return $env{$cache_str}='';
13461: 		#}    
13462: 		#$syval.=$1;
13463: 	    #}
13464:         } else {
13465: # ------------------------------------------------------- Was not in symb table
13466:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13467:                             &GDBM_READER(),0640)) {
13468: # ---------------------------------------------- Get ID(s) for current resource
13469:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13470:               unless ($ids) { 
13471:                  $ids=$bighash{'ids_/'.$thisfn};
13472:               }
13473:               unless ($ids) {
13474: # alias?
13475: 		  $ids=$bighash{'mapalias_'.$thisfn};
13476:               }
13477:               if ($ids) {
13478: # ------------------------------------------------------------------- Has ID(s)
13479:                  my @possibilities=split(/\,/,$ids);
13480:                  if ($#possibilities==0) {
13481: # ----------------------------------------------- There is only one possibility
13482: 		     my ($mapid,$resid)=split(/\./,$ids);
13483: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13484: 						    $resid,$thisfn);
13485:                      if (ref($possibles) eq 'HASH') {
13486:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13487:                              $possibles->{$syval} = 1;
13488:                          }
13489:                      }
13490:                      if ($checkforblock) {
13491:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13492:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13493:                              if (@blockers) {
13494:                                  $syval = '';
13495:                                  untie(%bighash);
13496:                                  return $env{$cache_str}='';
13497:                              }
13498:                          }
13499:                      }
13500:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13501: # ------------------------------------------ There is more than one possibility
13502:                      my $realpossible=0;
13503:                      foreach my $id (@possibilities) {
13504: 			 my $file=$bighash{'src_'.$id};
13505:                          my $canaccess;
13506:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13507:                              $canaccess = 1;
13508:                          } else { 
13509:                              $canaccess = &allowed('bre',$file);
13510:                          }
13511:                          if ($canaccess) {
13512:          		     my ($mapid,$resid)=split(/\./,$id);
13513:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13514:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13515: 						             $resid,$thisfn);
13516:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13517:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13518:                                  if ($checkforblock) {
13519:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13520:                                      if (@blockers > 0) {
13521:                                          $syval = '';
13522:                                      } else {
13523:                                          $syval = $poss_syval;
13524:                                          $realpossible++;
13525:                                      }
13526:                                  } else {
13527:                                      $syval = $poss_syval;
13528:                                      $realpossible++;
13529:                                  }
13530:                                  if ($syval) {
13531:                                      if (ref($possibles) eq 'HASH') {
13532:                                          $possibles->{$syval} = 1;
13533:                                      }
13534:                                  }
13535:                              }
13536: 			 }
13537:                      }
13538: 		     if ($realpossible!=1) { $syval=''; }
13539:                  } else {
13540:                      $syval='';
13541:                  }
13542: 	      }
13543:               untie(%bighash);
13544:            }
13545:         }
13546:         if ($syval) {
13547: 	    return $env{$cache_str}=$syval;
13548:         }
13549:     }
13550:     &appenv({'request.ambiguous' => $thisfn});
13551:     return $env{$cache_str}='';
13552: }
13553: 
13554: # ---------------------------------------------------------- Return random seed
13555: 
13556: sub numval {
13557:     my $txt=shift;
13558:     $txt=~tr/A-J/0-9/;
13559:     $txt=~tr/a-j/0-9/;
13560:     $txt=~tr/K-T/0-9/;
13561:     $txt=~tr/k-t/0-9/;
13562:     $txt=~tr/U-Z/0-5/;
13563:     $txt=~tr/u-z/0-5/;
13564:     $txt=~s/\D//g;
13565:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13566:     return int($txt);
13567: }
13568: 
13569: sub numval2 {
13570:     my $txt=shift;
13571:     $txt=~tr/A-J/0-9/;
13572:     $txt=~tr/a-j/0-9/;
13573:     $txt=~tr/K-T/0-9/;
13574:     $txt=~tr/k-t/0-9/;
13575:     $txt=~tr/U-Z/0-5/;
13576:     $txt=~tr/u-z/0-5/;
13577:     $txt=~s/\D//g;
13578:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13579:     my $total;
13580:     foreach my $val (@txts) { $total+=$val; }
13581:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13582:     return int($total);
13583: }
13584: 
13585: sub numval3 {
13586:     use integer;
13587:     my $txt=shift;
13588:     $txt=~tr/A-J/0-9/;
13589:     $txt=~tr/a-j/0-9/;
13590:     $txt=~tr/K-T/0-9/;
13591:     $txt=~tr/k-t/0-9/;
13592:     $txt=~tr/U-Z/0-5/;
13593:     $txt=~tr/u-z/0-5/;
13594:     $txt=~s/\D//g;
13595:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13596:     my $total;
13597:     foreach my $val (@txts) { $total+=$val; }
13598:     if ($_64bit) { $total=(($total<<32)>>32); }
13599:     return $total;
13600: }
13601: 
13602: sub digest {
13603:     my ($data)=@_;
13604:     my $digest=&Digest::MD5::md5($data);
13605:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13606:     my ($e,$f);
13607:     {
13608:         use integer;
13609:         $e=($a+$b);
13610:         $f=($c+$d);
13611:         if ($_64bit) {
13612:             $e=(($e<<32)>>32);
13613:             $f=(($f<<32)>>32);
13614:         }
13615:     }
13616:     if (wantarray) {
13617: 	return ($e,$f);
13618:     } else {
13619: 	my $g;
13620: 	{
13621: 	    use integer;
13622: 	    $g=($e+$f);
13623: 	    if ($_64bit) {
13624: 		$g=(($g<<32)>>32);
13625: 	    }
13626: 	}
13627: 	return $g;
13628:     }
13629: }
13630: 
13631: sub latest_rnd_algorithm_id {
13632:     return '64bit5';
13633: }
13634: 
13635: sub get_rand_alg {
13636:     my ($courseid)=@_;
13637:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13638:     if ($courseid) {
13639: 	return $env{"course.$courseid.rndseed"};
13640:     }
13641:     return &latest_rnd_algorithm_id();
13642: }
13643: 
13644: sub validCODE {
13645:     my ($CODE)=@_;
13646:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13647:     return 0;
13648: }
13649: 
13650: sub getCODE {
13651:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13652:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13653: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13654: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13655: 	return $Apache::lonhomework::history{'resource.CODE'};
13656:     }
13657:     return undef;
13658: }
13659: #
13660: #  Determines the random seed for a specific context:
13661: #
13662: # parameters:
13663: #   symb      - in course context the symb for the seed.
13664: #   course_id - The course id of the form domain_coursenum.
13665: #   domain    - Domain for the user.
13666: #   course    - Course for the user.
13667: #   cenv      - environment of the course.
13668: #
13669: # NOTE:
13670: #   All parameters are picked out of the environment if missing
13671: #   or not defined.
13672: #   If a symb cannot be determined the current time is used instead.
13673: #
13674: #  For a given well defined symb, courside, domain, username,
13675: #  and course environment, the seed is reproducible.
13676: #
13677: sub rndseed {
13678:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13679:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13680:     if (!defined($symb)) {
13681: 	unless ($symb=$wsymb) { return time; }
13682:     }
13683:     if (!defined $courseid) { 
13684: 	$courseid=$wcourseid; 
13685:     }
13686:     if (!defined $domain) { $domain=$wdomain; }
13687:     if (!defined $username) { $username=$wusername }
13688: 
13689:     my $which;
13690:     if (defined($cenv->{'rndseed'})) {
13691: 	$which = $cenv->{'rndseed'};
13692:     } else {
13693: 	$which =&get_rand_alg($courseid);
13694:     }
13695:     if (defined(&getCODE())) {
13696: 
13697: 	if ($which eq '64bit5') {
13698: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13699: 	} elsif ($which eq '64bit4') {
13700: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13701: 	} else {
13702: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13703: 	}
13704:     } elsif ($which eq '64bit5') {
13705: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13706:     } elsif ($which eq '64bit4') {
13707: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13708:     } elsif ($which eq '64bit3') {
13709: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13710:     } elsif ($which eq '64bit2') {
13711: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13712:     } elsif ($which eq '64bit') {
13713: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13714:     }
13715:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13716: }
13717: 
13718: sub rndseed_32bit {
13719:     my ($symb,$courseid,$domain,$username)=@_;
13720:     {
13721: 	use integer;
13722: 	my $symbchck=unpack("%32C*",$symb) << 27;
13723: 	my $symbseed=numval($symb) << 22;
13724: 	my $namechck=unpack("%32C*",$username) << 17;
13725: 	my $nameseed=numval($username) << 12;
13726: 	my $domainseed=unpack("%32C*",$domain) << 7;
13727: 	my $courseseed=unpack("%32C*",$courseid);
13728: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13729: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13730: 	#&logthis("rndseed :$num:$symb");
13731: 	if ($_64bit) { $num=(($num<<32)>>32); }
13732: 	return $num;
13733:     }
13734: }
13735: 
13736: sub rndseed_64bit {
13737:     my ($symb,$courseid,$domain,$username)=@_;
13738:     {
13739: 	use integer;
13740: 	my $symbchck=unpack("%32S*",$symb) << 21;
13741: 	my $symbseed=numval($symb) << 10;
13742: 	my $namechck=unpack("%32S*",$username);
13743: 	
13744: 	my $nameseed=numval($username) << 21;
13745: 	my $domainseed=unpack("%32S*",$domain) << 10;
13746: 	my $courseseed=unpack("%32S*",$courseid);
13747: 	
13748: 	my $num1=$symbchck+$symbseed+$namechck;
13749: 	my $num2=$nameseed+$domainseed+$courseseed;
13750: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13751: 	#&logthis("rndseed :$num:$symb");
13752: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13753: 	return "$num1,$num2";
13754:     }
13755: }
13756: 
13757: sub rndseed_64bit2 {
13758:     my ($symb,$courseid,$domain,$username)=@_;
13759:     {
13760: 	use integer;
13761: 	# strings need to be an even # of cahracters long, it it is odd the
13762:         # last characters gets thrown away
13763: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13764: 	my $symbseed=numval($symb) << 10;
13765: 	my $namechck=unpack("%32S*",$username.' ');
13766: 	
13767: 	my $nameseed=numval($username) << 21;
13768: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13769: 	my $courseseed=unpack("%32S*",$courseid.' ');
13770: 	
13771: 	my $num1=$symbchck+$symbseed+$namechck;
13772: 	my $num2=$nameseed+$domainseed+$courseseed;
13773: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13774: 	#&logthis("rndseed :$num:$symb");
13775: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13776: 	return "$num1,$num2";
13777:     }
13778: }
13779: 
13780: sub rndseed_64bit3 {
13781:     my ($symb,$courseid,$domain,$username)=@_;
13782:     {
13783: 	use integer;
13784: 	# strings need to be an even # of cahracters long, it it is odd the
13785:         # last characters gets thrown away
13786: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13787: 	my $symbseed=numval2($symb) << 10;
13788: 	my $namechck=unpack("%32S*",$username.' ');
13789: 	
13790: 	my $nameseed=numval2($username) << 21;
13791: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13792: 	my $courseseed=unpack("%32S*",$courseid.' ');
13793: 	
13794: 	my $num1=$symbchck+$symbseed+$namechck;
13795: 	my $num2=$nameseed+$domainseed+$courseseed;
13796: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13797: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13798: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13799: 	
13800: 	return "$num1:$num2";
13801:     }
13802: }
13803: 
13804: sub rndseed_64bit4 {
13805:     my ($symb,$courseid,$domain,$username)=@_;
13806:     {
13807: 	use integer;
13808: 	# strings need to be an even # of cahracters long, it it is odd the
13809:         # last characters gets thrown away
13810: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13811: 	my $symbseed=numval3($symb) << 10;
13812: 	my $namechck=unpack("%32S*",$username.' ');
13813: 	
13814: 	my $nameseed=numval3($username) << 21;
13815: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13816: 	my $courseseed=unpack("%32S*",$courseid.' ');
13817: 	
13818: 	my $num1=$symbchck+$symbseed+$namechck;
13819: 	my $num2=$nameseed+$domainseed+$courseseed;
13820: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13821: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13822: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13823: 	
13824: 	return "$num1:$num2";
13825:     }
13826: }
13827: 
13828: sub rndseed_64bit5 {
13829:     my ($symb,$courseid,$domain,$username)=@_;
13830:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13831:     return "$num1:$num2";
13832: }
13833: 
13834: sub rndseed_CODE_64bit {
13835:     my ($symb,$courseid,$domain,$username)=@_;
13836:     {
13837: 	use integer;
13838: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13839: 	my $symbseed=numval2($symb);
13840: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13841: 	my $CODEseed=numval(&getCODE());
13842: 	my $courseseed=unpack("%32S*",$courseid.' ');
13843: 	my $num1=$symbseed+$CODEchck;
13844: 	my $num2=$CODEseed+$courseseed+$symbchck;
13845: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13846: 	#&logthis("rndseed :$num1:$num2:$symb");
13847: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13848: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13849: 	return "$num1:$num2";
13850:     }
13851: }
13852: 
13853: sub rndseed_CODE_64bit4 {
13854:     my ($symb,$courseid,$domain,$username)=@_;
13855:     {
13856: 	use integer;
13857: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13858: 	my $symbseed=numval3($symb);
13859: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13860: 	my $CODEseed=numval3(&getCODE());
13861: 	my $courseseed=unpack("%32S*",$courseid.' ');
13862: 	my $num1=$symbseed+$CODEchck;
13863: 	my $num2=$CODEseed+$courseseed+$symbchck;
13864: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13865: 	#&logthis("rndseed :$num1:$num2:$symb");
13866: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13867: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13868: 	return "$num1:$num2";
13869:     }
13870: }
13871: 
13872: sub rndseed_CODE_64bit5 {
13873:     my ($symb,$courseid,$domain,$username)=@_;
13874:     my $code = &getCODE();
13875:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13876:     return "$num1:$num2";
13877: }
13878: 
13879: sub setup_random_from_rndseed {
13880:     my ($rndseed)=@_;
13881:     if ($rndseed =~/([,:])/) {
13882:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13883:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13884:             &Math::Random::random_set_seed_from_phrase($rndseed);
13885:         } else {
13886:             &Math::Random::random_set_seed($num1,$num2);
13887:         }
13888:     } else {
13889: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13890:     }
13891: }
13892: 
13893: sub latest_receipt_algorithm_id {
13894:     return 'receipt3';
13895: }
13896: 
13897: sub recunique {
13898:     my $fucourseid=shift;
13899:     my $unique;
13900:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13901: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13902: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13903:     } else {
13904: 	$unique=$perlvar{'lonReceipt'};
13905:     }
13906:     return unpack("%32C*",$unique);
13907: }
13908: 
13909: sub recprefix {
13910:     my $fucourseid=shift;
13911:     my $prefix;
13912:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13913: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13914: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13915:     } else {
13916: 	$prefix=$perlvar{'lonHostID'};
13917:     }
13918:     return unpack("%32C*",$prefix);
13919: }
13920: 
13921: sub ireceipt {
13922:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13923: 
13924:     my $return =&recprefix($fucourseid).'-';
13925: 
13926:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13927: 	$env{'request.state'} eq 'construct') {
13928: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13929: 	return $return;
13930:     }
13931: 
13932:     my $cuname=unpack("%32C*",$funame);
13933:     my $cudom=unpack("%32C*",$fudom);
13934:     my $cucourseid=unpack("%32C*",$fucourseid);
13935:     my $cusymb=unpack("%32C*",$fusymb);
13936:     my $cunique=&recunique($fucourseid);
13937:     my $cpart=unpack("%32S*",$part);
13938:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13939: 
13940: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13941: 			       
13942: 	$return.= ($cunique%$cuname+
13943: 		   $cunique%$cudom+
13944: 		   $cusymb%$cuname+
13945: 		   $cusymb%$cudom+
13946: 		   $cucourseid%$cuname+
13947: 		   $cucourseid%$cudom+
13948: 		   $cpart%$cuname+
13949: 		   $cpart%$cudom);
13950:     } else {
13951: 	$return.= ($cunique%$cuname+
13952: 		   $cunique%$cudom+
13953: 		   $cusymb%$cuname+
13954: 		   $cusymb%$cudom+
13955: 		   $cucourseid%$cuname+
13956: 		   $cucourseid%$cudom);
13957:     }
13958:     return $return;
13959: }
13960: 
13961: sub receipt {
13962:     my ($part)=@_;
13963:     my ($symb,$courseid,$domain,$name) = &whichuser();
13964:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13965: }
13966: 
13967: sub whichuser {
13968:     my ($passedsymb)=@_;
13969:     my ($symb,$courseid,$domain,$name,$publicuser);
13970:     if (defined($env{'form.grade_symb'})) {
13971: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13972: 	my $allowed=&allowed('vgr',$tmp_courseid);
13973: 	if (!$allowed &&
13974: 	    exists($env{'request.course.sec'}) &&
13975: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13976: 	    $allowed=&allowed('vgr',$tmp_courseid.
13977: 			      '/'.$env{'request.course.sec'});
13978: 	}
13979: 	if ($allowed) {
13980: 	    ($symb)=&get_env_multiple('form.grade_symb');
13981: 	    $courseid=$tmp_courseid;
13982: 	    ($domain)=&get_env_multiple('form.grade_domain');
13983: 	    ($name)=&get_env_multiple('form.grade_username');
13984: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13985: 	}
13986:     }
13987:     if (!$passedsymb) {
13988: 	$symb=&symbread();
13989:     } else {
13990: 	$symb=$passedsymb;
13991:     }
13992:     $courseid=$env{'request.course.id'};
13993:     $domain=$env{'user.domain'};
13994:     $name=$env{'user.name'};
13995:     if ($name eq 'public' && $domain eq 'public') {
13996: 	if (!defined($env{'form.username'})) {
13997: 	    $env{'form.username'}.=time.rand(10000000);
13998: 	}
13999: 	$name.=$env{'form.username'};
14000:     }
14001:     return ($symb,$courseid,$domain,$name,$publicuser);
14002: 
14003: }
14004: 
14005: # ------------------------------------------------------------ Serves up a file
14006: # returns either the contents of the file or 
14007: # -1 if the file doesn't exist
14008: #
14009: # if the target is a file that was uploaded via DOCS, 
14010: # a check will be made to see if a current copy exists on the local server,
14011: # if it does this will be served, otherwise a copy will be retrieved from
14012: # the home server for the course and stored in /home/httpd/html/userfiles on
14013: # the local server.   
14014: 
14015: sub getfile {
14016:     my ($file) = @_;
14017:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14018:     &repcopy($file);
14019:     return &readfile($file);
14020: }
14021: 
14022: sub repcopy_userfile {
14023:     my ($file)=@_;
14024:     my $londocroot = $perlvar{'lonDocRoot'};
14025:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14026:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14027:     my ($cdom,$cnum,$filename) = 
14028: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14029:     my $uri="/uploaded/$cdom/$cnum/$filename";
14030:     if (-e "$file") {
14031: # we already have a local copy, check it out
14032: 	my @fileinfo = stat($file);
14033: 	my $rtncode;
14034: 	my $info;
14035: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14036: 	if ($lwpresp ne 'ok') {
14037: # there is no such file anymore, even though we had a local copy
14038: 	    if ($rtncode eq '404') {
14039: 		unlink($file);
14040: 	    }
14041: 	    return -1;
14042: 	}
14043: 	if ($info < $fileinfo[9]) {
14044: # nice, the file we have is up-to-date, just say okay
14045: 	    return 'ok';
14046: 	} else {
14047: # the file is outdated, get rid of it
14048: 	    unlink($file);
14049: 	}
14050:     }
14051: # one way or the other, at this point, we don't have the file
14052: # construct the correct path for the file
14053:     my @parts = ($cdom,$cnum); 
14054:     if ($filename =~ m|^(.+)/[^/]+$|) {
14055: 	push @parts, split(/\//,$1);
14056:     }
14057:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14058:     foreach my $part (@parts) {
14059: 	$path .= '/'.$part;
14060: 	if (!-e $path) {
14061: 	    mkdir($path,0770);
14062: 	}
14063:     }
14064: # now the path exists for sure
14065: # get a user agent
14066:     my $transferfile=$file.'.in.transfer';
14067: # FIXME: this should flock
14068:     if (-e $transferfile) { return 'ok'; }
14069:     my $request;
14070:     $uri=~s/^\///;
14071:     my $homeserver = &homeserver($cnum,$cdom);
14072:     my $hostname = &hostname($homeserver);
14073:     my $protocol = $protocol{$homeserver};
14074:     $protocol = 'http' if ($protocol ne 'https');
14075:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14076:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14077: # did it work?
14078:     if ($response->is_error()) {
14079: 	unlink($transferfile);
14080: 	&logthis("Userfile repcopy failed for $uri");
14081: 	return -1;
14082:     }
14083: # worked, rename the transfer file
14084:     rename($transferfile,$file);
14085:     return 'ok';
14086: }
14087: 
14088: sub tokenwrapper {
14089:     my $uri=shift;
14090:     $uri=~s|^https?\://([^/]+)||;
14091:     $uri=~s|^/||;
14092:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14093:     my $token=$1;
14094:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14095:     if ($udom && $uname && $file) {
14096: 	$file=~s|(\?\.*)*$||;
14097:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14098:         my $homeserver = &homeserver($uname,$udom);
14099:         my $hostname = &hostname($homeserver);
14100:         my $protocol = $protocol{$homeserver};
14101:         $protocol = 'http' if ($protocol ne 'https');
14102:         return $protocol.'://'.$hostname.'/'.$uri.
14103:                (($uri=~/\?/)?'&':'?').'token='.$token.
14104:                                '&tokenissued='.$perlvar{'lonHostID'};
14105:     } else {
14106:         return '/adm/notfound.html';
14107:     }
14108: }
14109: 
14110: # call with reqtype HEAD: get last modification time
14111: # call with reqtype GET: get the file contents
14112: # Do not call this with reqtype GET for large files! It loads everything into memory
14113: #
14114: sub getuploaded {
14115:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14116:     $uri=~s/^\///;
14117:     my $homeserver = &homeserver($cnum,$cdom);
14118:     my $hostname = &hostname($homeserver);
14119:     my $protocol = $protocol{$homeserver};
14120:     $protocol = 'http' if ($protocol ne 'https');
14121:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14122:     my $request=new HTTP::Request($reqtype,$uri);
14123:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14124:     $$rtncode = $response->code;
14125:     if (! $response->is_success()) {
14126: 	return 'failed';
14127:     }      
14128:     if ($reqtype eq 'HEAD') {
14129: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14130:     } elsif ($reqtype eq 'GET') {
14131: 	$$info = $response->content;
14132:     }
14133:     return 'ok';
14134: }
14135: 
14136: sub readfile {
14137:     my $file = shift;
14138:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14139:     my $fh;
14140:     open($fh,"<",$file);
14141:     my $a='';
14142:     while (my $line = <$fh>) { $a .= $line; }
14143:     return $a;
14144: }
14145: 
14146: sub filelocation {
14147:     my ($dir,$file) = @_;
14148:     my $location;
14149:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14150: 
14151:     if ($file =~ m-^/adm/-) {
14152: 	$file=~s-^/adm/wrapper/-/-;
14153: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14154:     }
14155: 
14156:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14157:         $location = $file;
14158:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14159:         my ($udom,$uname,$filename)=
14160:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14161:         my $home=&homeserver($uname,$udom);
14162:         my $is_me=0;
14163:         my @ids=&current_machine_ids();
14164:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14165:         if ($is_me) {
14166:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14167:         } else {
14168:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14169:   	      $udom.'/'.$uname.'/'.$filename;
14170:         }
14171:     } elsif ($file =~ m-^/adm/-) {
14172: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14173:     } else {
14174:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14175:         $file=~s:^/(res|priv)/:/:;
14176:         my $space=$1;
14177:         if ( !( $file =~ m:^/:) ) {
14178:             $location = $dir. '/'.$file;
14179:         } else {
14180:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14181:         }
14182:     }
14183:     $location=~s://+:/:g; # remove duplicate /
14184:     while ($location=~m{/\.\./}) {
14185: 	if ($location =~ m{/[^/]+/\.\./}) {
14186: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14187: 	} else {
14188: 	    $location=~ s{/\.\./}{/}g;
14189: 	}
14190:     } #remove dir/..
14191:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14192:     return $location;
14193: }
14194: 
14195: sub hreflocation {
14196:     my ($dir,$file)=@_;
14197:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14198: 	$file=filelocation($dir,$file);
14199:     } elsif ($file=~m-^/adm/-) {
14200: 	$file=~s-^/adm/wrapper/-/-;
14201: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14202:     }
14203:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14204: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14205:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14206: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14207: 	        {/uploaded/$1/$2/}x;
14208:     }
14209:     if ($file=~ m{^/userfiles/}) {
14210: 	$file =~ s{^/userfiles/}{/uploaded/};
14211:     }
14212:     return $file;
14213: }
14214: 
14215: 
14216: 
14217: 
14218: 
14219: sub current_machine_domains {
14220:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14221: }
14222: 
14223: sub machine_domains {
14224:     my ($hostname) = @_;
14225:     my @domains;
14226:     my %hostname = &all_hostnames();
14227:     while( my($id, $name) = each(%hostname)) {
14228: #	&logthis("-$id-$name-$hostname-");
14229: 	if ($hostname eq $name) {
14230: 	    push(@domains,&host_domain($id));
14231: 	}
14232:     }
14233:     return @domains;
14234: }
14235: 
14236: sub current_machine_ids {
14237:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14238: }
14239: 
14240: sub machine_ids {
14241:     my ($hostname) = @_;
14242:     $hostname ||= &hostname($perlvar{'lonHostID'});
14243:     my @ids;
14244:     my %name_to_host = &all_names();
14245:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14246: 	return @{ $name_to_host{$hostname} };
14247:     }
14248:     return;
14249: }
14250: 
14251: sub additional_machine_domains {
14252:     my @domains;
14253:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14254:     while( my $line = <$fh>) {
14255:         $line =~ s/\s//g;
14256:         push(@domains,$line);
14257:     }
14258:     return @domains;
14259: }
14260: 
14261: sub default_login_domain {
14262:     my $domain = $perlvar{'lonDefDomain'};
14263:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14264:     foreach my $posdom (&current_machine_domains(),
14265:                         &additional_machine_domains()) {
14266:         if (lc($posdom) eq lc($testdomain)) {
14267:             $domain=$posdom;
14268:             last;
14269:         }
14270:     }
14271:     return $domain;
14272: }
14273: 
14274: sub shared_institution {
14275:     my ($dom,$lonhost) = @_;
14276:     if ($lonhost eq '') {
14277:         $lonhost = $perlvar{'lonHostID'};
14278:     }
14279:     my $same_intdom;
14280:     my $hostintdom = &internet_dom($lonhost);
14281:     if ($hostintdom ne '') {
14282:         my %iphost = &get_iphost();
14283:         my $primary_id = &domain($dom,'primary');
14284:         my $primary_ip = &get_host_ip($primary_id);
14285:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14286:             foreach my $id (@{$iphost{$primary_ip}}) {
14287:                 my $intdom = &internet_dom($id);
14288:                 if ($intdom eq $hostintdom) {
14289:                     $same_intdom = 1;
14290:                     last;
14291:                 }
14292:             }
14293:         }
14294:     }
14295:     return $same_intdom;
14296: }
14297: 
14298: sub uses_sts {
14299:     my ($ignore_cache) = @_;
14300:     my $lonhost = $perlvar{'lonHostID'};
14301:     my $hostname = &hostname($lonhost);
14302:     my $sts_on;
14303:     if ($protocol{$lonhost} eq 'https') {
14304:         my $cachetime = 12*3600;
14305:         if (!$ignore_cache) {
14306:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14307:             if (defined($cached)) {
14308:                 return $sts_on;
14309:             }
14310:         }
14311:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14312:         my $request=new HTTP::Request('HEAD',$url);
14313:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14314:         if ($response->is_success) {
14315:             my $has_sts = $response->header('Strict-Transport-Security');
14316:             if ($has_sts eq '') {
14317:                 $sts_on = 0;
14318:             } else {
14319:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14320:                     my $maxage = $1;
14321:                     if ($maxage) {
14322:                         $sts_on = 1;
14323:                     } else {
14324:                         $sts_on = 0;
14325:                     }
14326:                 } else {
14327:                     $sts_on = 0;
14328:                 }
14329:             }
14330:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14331:         }
14332:     }
14333:     return;
14334: }
14335: 
14336: sub get_requestor_ip {
14337:     my ($r,$nolookup,$noproxy) = @_;
14338:     my $from_ip;
14339:     if (ref($r)) {
14340:         $from_ip = $r->get_remote_host($nolookup);
14341:     } else {
14342:         $from_ip = $ENV{'REMOTE_ADDR'};
14343:     }
14344:     return $from_ip if ($noproxy); 
14345:     # Who controls proxy settings for server
14346:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14347:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14348:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14349:         if ($proxyinfo->{'vpnint'}) {
14350:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14351:                 return $from_ip;
14352:             }
14353:         }
14354:         if ($proxyinfo->{'trusted'}) {
14355:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14356:                 my $ipheader = $proxyinfo->{'ipheader'};
14357:                 my ($ip,$xfor);
14358:                 if (ref($r)) {
14359:                     if ($ipheader) {
14360:                         $ip = $r->headers_in->{$ipheader};
14361:                     }
14362:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14363:                 } else {
14364:                     if ($ipheader) {
14365:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14366:                     }
14367:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14368:                 }
14369:                 if (($ip eq '') && ($xfor ne '')) {
14370:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14371:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14372:                             $ip = $poss_ip;
14373:                             last;
14374:                         }
14375:                     }
14376:                 }
14377:                 if ($ip ne '') {
14378:                     return $ip;
14379:                 }
14380:             }
14381:         }
14382:     }
14383:     return $from_ip;
14384: }
14385: 
14386: sub get_proxy_settings {
14387:     my ($dom_in_use) = @_;
14388:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14389:     my $proxyinfo = {
14390:                        ipheader => $domdefaults{'waf_ipheader'},
14391:                        trusted  => $domdefaults{'waf_trusted'},
14392:                        vpnint   => $domdefaults{'waf_vpnint'},
14393:                        vpnext   => $domdefaults{'waf_vpnext'},
14394:                     };
14395:     return $proxyinfo;
14396: }
14397: 
14398: sub ip_match {
14399:     my ($ip,$pattern_str) = @_;
14400:     $ip=Net::CIDR::cidrvalidate($ip);
14401:     if ($ip) {
14402:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14403:     }
14404:     return;
14405: }
14406: 
14407: sub get_proxy_alias {
14408:     my $lonhost = $perlvar{'lonHostID'};
14409:     if ($lonhost ne '') {
14410:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
14411:         if ($cached) {
14412:             return $alias;
14413:         }
14414:         my $dom = &Apache::lonnet::host_domain($lonhost);
14415:         if ($dom ne '') {
14416:             my $cachetime = 60*60*24;
14417:             my %domconfig =
14418:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14419:             my $alias;
14420:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14421:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14422:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonhost};
14423:                 }
14424:             }
14425:             return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
14426:         }
14427:     }
14428:     return;
14429: }
14430: 
14431: # ------------------------------------------------------------- Declutters URLs
14432: 
14433: sub declutter {
14434:     my $thisfn=shift;
14435:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14436:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14437:         $thisfn=~s{^/home/httpd/html}{};
14438:     }
14439:     $thisfn=~s/^\///;
14440:     $thisfn=~s|^adm/wrapper/||;
14441:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14442:     $thisfn=~s/^res\///;
14443:     $thisfn=~s/^priv\///;
14444:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14445:         $thisfn=~s/\?.+$//;
14446:     }
14447:     return $thisfn;
14448: }
14449: 
14450: # ------------------------------------------------------------- Clutter up URLs
14451: 
14452: sub clutter {
14453:     my $thisfn='/'.&declutter(shift);
14454:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14455: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14456:        $thisfn='/res'.$thisfn; 
14457:     }
14458:     if ($thisfn !~m|^/adm|) {
14459: 	if ($thisfn =~ m|^/ext/|) {
14460: 	    $thisfn='/adm/wrapper'.$thisfn;
14461: 	} else {
14462: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14463: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14464: 	    if ($embstyle eq 'ssi'
14465: 		|| ($embstyle eq 'hdn')
14466: 		|| ($embstyle eq 'rat')
14467: 		|| ($embstyle eq 'prv')
14468: 		|| ($embstyle eq 'ign')) {
14469: 		#do nothing with these
14470: 	    } elsif (($embstyle eq 'img') 
14471: 		|| ($embstyle eq 'emb')
14472: 		|| ($embstyle eq 'wrp')) {
14473: 		$thisfn='/adm/wrapper'.$thisfn;
14474: 	    } elsif ($embstyle eq 'unk'
14475: 		     && $thisfn!~/\.(sequence|page)$/) {
14476: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14477: 	    } else {
14478: #		&logthis("Got a blank emb style");
14479: 	    }
14480: 	}
14481:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14482:         $thisfn='/adm/wrapper'.$thisfn;
14483:     }
14484:     return $thisfn;
14485: }
14486: 
14487: sub clutter_with_no_wrapper {
14488:     my $uri = &clutter(shift);
14489:     if ($uri =~ m-^/adm/-) {
14490: 	$uri =~ s-^/adm/wrapper/-/-;
14491: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14492:     }
14493:     return $uri;
14494: }
14495: 
14496: sub freeze_escape {
14497:     my ($value)=@_;
14498:     if (ref($value)) {
14499: 	$value=&nfreeze($value);
14500: 	return '__FROZEN__'.&escape($value);
14501:     }
14502:     return &escape($value);
14503: }
14504: 
14505: 
14506: sub thaw_unescape {
14507:     my ($value)=@_;
14508:     if ($value =~ /^__FROZEN__/) {
14509: 	substr($value,0,10,undef);
14510: 	$value=&unescape($value);
14511: 	return &thaw($value);
14512:     }
14513:     return &unescape($value);
14514: }
14515: 
14516: sub correct_line_ends {
14517:     my ($result)=@_;
14518:     $$result =~s/\r\n/\n/mg;
14519:     $$result =~s/\r/\n/mg;
14520: }
14521: # ================================================================ Main Program
14522: 
14523: sub goodbye {
14524:    &logthis("Starting Shut down");
14525: #not converted to using infrastruture and probably shouldn't be
14526:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14527: #converted
14528: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14529:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14530: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14531: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14532: #1.1 only
14533: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14534: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14535: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14536: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14537:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14538:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14539:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14540:    &flushcourselogs();
14541:    &logthis("Shutting down");
14542: }
14543: 
14544: sub get_dns {
14545:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14546:     if (!$ignore_cache) {
14547: 	my ($content,$cached)=
14548: 	    &Apache::lonnet::is_cached_new('dns',$url);
14549: 	if ($cached) {
14550: 	    &$func($content,$hashref);
14551: 	    return;
14552: 	}
14553:     }
14554: 
14555:     my %alldns;
14556:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14557:         foreach my $dns (<$config>) {
14558: 	    next if ($dns !~ /^\^(\S*)/x);
14559:             my $line = $1;
14560:             my ($host,$protocol) = split(/:/,$line);
14561:             if ($protocol ne 'https') {
14562:                 $protocol = 'http';
14563:             }
14564: 	    $alldns{$host} = $protocol;
14565:         }
14566:         close($config);
14567:     }
14568:     while (%alldns) {
14569: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14570: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14571:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14572:         delete($alldns{$dns});
14573: 	next if ($response->is_error());
14574:         if ($url eq '/adm/dns/loncapaCRL') {
14575:             return &$func($response);
14576:         } else {
14577: 	    my @content = split("\n",$response->content);
14578: 	    unless ($nocache) {
14579: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14580: 	    }
14581: 	    &$func(\@content,$hashref);
14582:             return;
14583:         }
14584:     }
14585:     my $which = (split('/',$url,4))[3];
14586:     if ($which eq 'loncapaCRL') {
14587:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14588:         if (-e $diskfile) {
14589:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14590:         } else {
14591:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14592:         }
14593:     } else {
14594:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14595:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14596:             my @content = <$config>;
14597:             close($config);
14598:             &$func(\@content,$hashref);
14599:         }
14600:     }
14601:     return;
14602: }
14603: 
14604: # ------------------------------------------------------Get DNS checksums file
14605: sub parse_dns_checksums_tab {
14606:     my ($lines,$hashref) = @_;
14607:     my $lonhost = $perlvar{'lonHostID'};
14608:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14609:     my $loncaparev = &get_server_loncaparev($machine_dom);
14610:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14611:     my $webconfdir = '/etc/httpd/conf';
14612:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14613:         $webconfdir = '/etc/apache2';
14614:     } elsif ($distro =~ /^sles(\d+)$/) {
14615:         if ($1 >= 10) {
14616:             $webconfdir = '/etc/apache2';
14617:         }
14618:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14619:         if ($1 >= 10.0) {
14620:             $webconfdir = '/etc/apache2';
14621:         }
14622:     }
14623:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14624:     my (%chksum,%revnum);
14625:     if (ref($lines) eq 'ARRAY') {
14626:         chomp(@{$lines});
14627:         my $version = shift(@{$lines});
14628:         if ($version eq $release) {  
14629:             foreach my $line (@{$lines}) {
14630:                 my ($file,$version,$shasum) = split(/,/,$line);
14631:                 if ($file =~ m{^/etc/httpd/conf}) {
14632:                     if ($webconfdir eq '/etc/apache2') {
14633:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14634:                     }
14635:                 }
14636:                 $chksum{$file} = $shasum;
14637:                 $revnum{$file} = $version;
14638:             }
14639:             if (ref($hashref) eq 'HASH') {
14640:                 %{$hashref} = (
14641:                                 sums     => \%chksum,
14642:                                 versions => \%revnum,
14643:                               );
14644:             }
14645:         }
14646:     }
14647:     return;
14648: }
14649: 
14650: sub fetch_dns_checksums {
14651:     my %checksums;
14652:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14653:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14654:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14655:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14656:              \%checksums);
14657:     return \%checksums;
14658: }
14659: 
14660: sub fetch_crl_pemfile {
14661:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14662: }
14663: 
14664: sub save_crl_pem {
14665:     my ($response) = @_;
14666:     my ($msg,$hadchanges);
14667:     if (ref($response)) {
14668:         my $now = time;
14669:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14670:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14671:         if (open(my $fh,'>',"$tmpcrl")) {
14672:             print $fh $response->content;
14673:             close($fh);
14674:             if (-e $lonca) {
14675:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14676:                     my $check = <PIPE>;
14677:                     close(PIPE);
14678:                     chomp($check);
14679:                     if ($check eq 'verify OK') {
14680:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14681:                         my $backup;
14682:                         if (-e $dest) {
14683:                             if (&File::Copy::move($dest,"$dest.bak")) {
14684:                                 $backup = 'ok';
14685:                             }
14686:                         }
14687:                         if (&File::Copy::move($tmpcrl,$dest)) {
14688:                             $msg = 'ok';
14689:                             if ($backup) {
14690:                                 my (%oldnums,%newnums);
14691:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14692:                                     while (<PIPE>) {
14693:                                         $oldnums{(split(/:/))[1]} = 1;
14694:                                     }
14695:                                     close(PIPE);
14696:                                 }
14697:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14698:                                     while(<PIPE>) {
14699:                                         $newnums{(split(/:/))[1]} = 1;
14700:                                     }
14701:                                     close(PIPE);
14702:                                 }
14703:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14704:                                     unless (exists($oldnums{$key})) {
14705:                                         $hadchanges = 1;
14706:                                         last;
14707:                                     }
14708:                                 }
14709:                                 unless ($hadchanges) {
14710:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14711:                                         unless (exists($newnums{$key})) {
14712:                                             $hadchanges = 1;
14713:                                             last;
14714:                                         }
14715:                                     }
14716:                                 }
14717:                             }
14718:                         }
14719:                     } else {
14720:                         unlink($tmpcrl);
14721:                     }
14722:                 } else {
14723:                     unlink($tmpcrl);
14724:                 }
14725:             } else {
14726:                 unlink($tmpcrl);
14727:             }
14728:         }
14729:     }
14730:     return ($msg,$hadchanges);
14731: }
14732: 
14733: # ------------------------------------------------------------ Read domain file
14734: {
14735:     my $loaded;
14736:     my %domain;
14737: 
14738:     sub parse_domain_tab {
14739: 	my ($lines) = @_;
14740: 	foreach my $line (@$lines) {
14741: 	    next if ($line =~ /^(\#|\s*$ )/x);
14742: 
14743: 	    chomp($line);
14744: 	    my ($name,@elements) = split(/:/,$line,9);
14745: 	    my %this_domain;
14746: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14747: 			       'lang_def', 'city', 'longi', 'lati',
14748: 			       'primary') {
14749: 		$this_domain{$field} = shift(@elements);
14750: 	    }
14751: 	    $domain{$name} = \%this_domain;
14752: 	}
14753:     }
14754: 
14755:     sub reset_domain_info {
14756: 	undef($loaded);
14757: 	undef(%domain);
14758:     }
14759: 
14760:     sub load_domain_tab {
14761: 	my ($ignore_cache,$nocache) = @_;
14762: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14763: 	my $fh;
14764: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14765: 	    my @lines = <$fh>;
14766: 	    &parse_domain_tab(\@lines);
14767: 	}
14768: 	close($fh);
14769: 	$loaded = 1;
14770:     }
14771: 
14772:     sub domain {
14773: 	&load_domain_tab() if (!$loaded);
14774: 
14775: 	my ($name,$what) = @_;
14776: 	return if ( !exists($domain{$name}) );
14777: 
14778: 	if (!$what) {
14779: 	    return $domain{$name}{'description'};
14780: 	}
14781: 	return $domain{$name}{$what};
14782:     }
14783: 
14784:     sub domain_info {
14785:         &load_domain_tab() if (!$loaded);
14786:         return %domain;
14787:     }
14788: 
14789: }
14790: 
14791: 
14792: # ------------------------------------------------------------- Read hosts file
14793: {
14794:     my %hostname;
14795:     my %hostdom;
14796:     my %libserv;
14797:     my $loaded;
14798:     my %name_to_host;
14799:     my %internetdom;
14800:     my %LC_dns_serv;
14801: 
14802:     sub parse_hosts_tab {
14803: 	my ($file) = @_;
14804: 	foreach my $configline (@$file) {
14805: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14806:             chomp($configline);
14807: 	    if ($configline =~ /^\^/) {
14808:                 if ($configline =~ /^\^([\w.\-]+)/) {
14809:                     $LC_dns_serv{$1} = 1;
14810:                 }
14811:                 next;
14812:             }
14813: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14814: 	    $name=~s/\s//g;
14815: 	    if ($id && $domain && $role && $name) {
14816:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14817:                     my $curr = $hostname{$id};
14818:                     my $skip;
14819:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14820:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14821:                             $skip = 1;
14822:                         } else {
14823:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14824:                         }
14825:                     }
14826:                     unless ($skip) {
14827:                         push(@{$name_to_host{$name}},$id);
14828:                     }
14829:                 } else {
14830:                     push(@{$name_to_host{$name}},$id);
14831:                 }
14832: 		$hostname{$id}=$name;
14833: 		$hostdom{$id}=$domain;
14834: 		if ($role eq 'library') { $libserv{$id}=$name; }
14835:                 if (defined($protocol)) {
14836:                     if ($protocol eq 'https') {
14837:                         $protocol{$id} = $protocol;
14838:                     } else {
14839:                         $protocol{$id} = 'http'; 
14840:                     }
14841:                 } else {
14842:                     $protocol{$id} = 'http';
14843:                 }
14844:                 if (defined($intdom)) {
14845:                     $internetdom{$id} = $intdom;
14846:                 }
14847: 	    }
14848: 	}
14849:     }
14850:     
14851:     sub reset_hosts_info {
14852: 	&purge_remembered();
14853: 	&reset_domain_info();
14854: 	&reset_hosts_ip_info();
14855:         undef(%internetdom);
14856: 	undef(%name_to_host);
14857: 	undef(%hostname);
14858: 	undef(%hostdom);
14859: 	undef(%libserv);
14860: 	undef($loaded);
14861:     }
14862: 
14863:     sub load_hosts_tab {
14864: 	my ($ignore_cache,$nocache) = @_;
14865: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14866: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14867: 	my @config = <$config>;
14868: 	&parse_hosts_tab(\@config);
14869: 	close($config);
14870: 	$loaded=1;
14871:     }
14872: 
14873:     sub hostname {
14874: 	&load_hosts_tab() if (!$loaded);
14875: 
14876: 	my ($lonid) = @_;
14877: 	return $hostname{$lonid};
14878:     }
14879: 
14880:     sub all_hostnames {
14881: 	&load_hosts_tab() if (!$loaded);
14882: 
14883: 	return %hostname;
14884:     }
14885: 
14886:     sub all_names {
14887:         my ($ignore_cache,$nocache) = @_;
14888: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14889: 
14890: 	return %name_to_host;
14891:     }
14892: 
14893:     sub all_host_domain {
14894:         &load_hosts_tab() if (!$loaded);
14895:         return %hostdom;
14896:     }
14897: 
14898:     sub all_host_intdom {
14899:         &load_hosts_tab() if (!$loaded);
14900:         return %internetdom;
14901:     }
14902: 
14903:     sub is_library {
14904: 	&load_hosts_tab() if (!$loaded);
14905: 
14906: 	return exists($libserv{$_[0]});
14907:     }
14908: 
14909:     sub all_library {
14910: 	&load_hosts_tab() if (!$loaded);
14911: 
14912: 	return %libserv;
14913:     }
14914: 
14915:     sub unique_library {
14916: 	#2x reverse removes all hostnames that appear more than once
14917:         my %unique = reverse &all_library();
14918:         return reverse %unique;
14919:     }
14920: 
14921:     sub get_servers {
14922: 	&load_hosts_tab() if (!$loaded);
14923: 
14924: 	my ($domain,$type) = @_;
14925: 	my %possible_hosts = ($type eq 'library') ? %libserv
14926: 	                                          : %hostname;
14927: 	my %result;
14928: 	if (ref($domain) eq 'ARRAY') {
14929: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14930: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14931: 		    $result{$host} = $hostname;
14932: 		}
14933: 	    }
14934: 	} else {
14935: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14936: 		if ($hostdom{$host} eq $domain) {
14937: 		    $result{$host} = $hostname;
14938: 		}
14939: 	    }
14940: 	}
14941: 	return %result;
14942:     }
14943: 
14944:     sub get_unique_servers {
14945:         my %unique = reverse &get_servers(@_);
14946: 	return reverse %unique;
14947:     }
14948: 
14949:     sub host_domain {
14950: 	&load_hosts_tab() if (!$loaded);
14951: 
14952: 	my ($lonid) = @_;
14953: 	return $hostdom{$lonid};
14954:     }
14955: 
14956:     sub all_domains {
14957: 	&load_hosts_tab() if (!$loaded);
14958: 
14959: 	my %seen;
14960: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14961: 	return @uniq;
14962:     }
14963: 
14964:     sub internet_dom {
14965:         &load_hosts_tab() if (!$loaded);
14966: 
14967:         my ($lonid) = @_;
14968:         return $internetdom{$lonid};
14969:     }
14970: 
14971:     sub is_LC_dns {
14972:         &load_hosts_tab() if (!$loaded);
14973: 
14974:         my ($hostname) = @_;
14975:         return exists($LC_dns_serv{$hostname});
14976:     }
14977: 
14978: }
14979: 
14980: { 
14981:     my %iphost;
14982:     my %name_to_ip;
14983:     my %lonid_to_ip;
14984: 
14985:     sub get_hosts_from_ip {
14986: 	my ($ip) = @_;
14987: 	my %iphosts = &get_iphost();
14988: 	if (ref($iphosts{$ip})) {
14989: 	    return @{$iphosts{$ip}};
14990: 	}
14991: 	return;
14992:     }
14993:     
14994:     sub reset_hosts_ip_info {
14995: 	undef(%iphost);
14996: 	undef(%name_to_ip);
14997: 	undef(%lonid_to_ip);
14998:     }
14999: 
15000:     sub get_host_ip {
15001: 	my ($lonid) = @_;
15002: 	if (exists($lonid_to_ip{$lonid})) {
15003: 	    return $lonid_to_ip{$lonid};
15004: 	}
15005: 	my $name=&hostname($lonid);
15006:    	my $ip = gethostbyname($name);
15007: 	return if (!$ip || length($ip) ne 4);
15008: 	$ip=inet_ntoa($ip);
15009: 	$name_to_ip{$name}   = $ip;
15010: 	$lonid_to_ip{$lonid} = $ip;
15011: 	return $ip;
15012:     }
15013:     
15014:     sub get_iphost {
15015: 	my ($ignore_cache,$nocache) = @_;
15016: 
15017: 	if (!$ignore_cache) {
15018: 	    if (%iphost) {
15019: 		return %iphost;
15020: 	    }
15021: 	    my ($ip_info,$cached)=
15022: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15023: 	    if ($cached) {
15024: 		%iphost      = %{$ip_info->[0]};
15025: 		%name_to_ip  = %{$ip_info->[1]};
15026: 		%lonid_to_ip = %{$ip_info->[2]};
15027: 		return %iphost;
15028: 	    }
15029: 	}
15030: 
15031: 	# get yesterday's info for fallback
15032: 	my %old_name_to_ip;
15033: 	my ($ip_info,$cached)=
15034: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15035: 	if ($cached) {
15036: 	    %old_name_to_ip = %{$ip_info->[1]};
15037: 	}
15038: 
15039: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15040: 	foreach my $name (keys(%name_to_host)) {
15041: 	    my $ip;
15042: 	    if (!exists($name_to_ip{$name})) {
15043: 		$ip = gethostbyname($name);
15044: 		if (!$ip || length($ip) ne 4) {
15045: 		    if (defined($old_name_to_ip{$name})) {
15046: 			$ip = $old_name_to_ip{$name};
15047: 			&logthis("Can't find $name defaulting to old $ip");
15048: 		    } else {
15049: 			&logthis("Name $name no IP found");
15050: 			next;
15051: 		    }
15052: 		} else {
15053: 		    $ip=inet_ntoa($ip);
15054: 		}
15055: 		$name_to_ip{$name} = $ip;
15056: 	    } else {
15057: 		$ip = $name_to_ip{$name};
15058: 	    }
15059: 	    foreach my $id (@{ $name_to_host{$name} }) {
15060: 		$lonid_to_ip{$id} = $ip;
15061: 	    }
15062: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15063: 	}
15064:         unless ($nocache) {
15065: 	    &do_cache_new('iphost','iphost',
15066: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15067: 		          48*60*60);
15068:         }
15069: 
15070: 	return %iphost;
15071:     }
15072: 
15073:     #
15074:     #  Given a DNS returns the loncapa host name for that DNS 
15075:     # 
15076:     sub host_from_dns {
15077:         my ($dns) = @_;
15078:         my @hosts;
15079:         my $ip;
15080: 
15081:         if (exists($name_to_ip{$dns})) {
15082:             $ip = $name_to_ip{$dns};
15083:         }
15084:         if (!$ip) {
15085:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15086:             if (length($ip) == 4) { 
15087: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15088:             }
15089:         }
15090:         if ($ip) {
15091: 	    @hosts = get_hosts_from_ip($ip);
15092: 	    return $hosts[0];
15093:         }
15094:         return undef;
15095:     }
15096: 
15097:     sub get_internet_names {
15098:         my ($lonid) = @_;
15099:         return if ($lonid eq '');
15100:         my ($idnref,$cached)=
15101:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15102:         if ($cached) {
15103:             return $idnref;
15104:         }
15105:         my $ip = &get_host_ip($lonid);
15106:         my @hosts = &get_hosts_from_ip($ip);
15107:         my %iphost = &get_iphost();
15108:         my (@idns,%seen);
15109:         foreach my $id (@hosts) {
15110:             my $dom = &host_domain($id);
15111:             my $prim_id = &domain($dom,'primary');
15112:             my $prim_ip = &get_host_ip($prim_id);
15113:             next if ($seen{$prim_ip});
15114:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15115:                 foreach my $id (@{$iphost{$prim_ip}}) {
15116:                     my $intdom = &internet_dom($id);
15117:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15118:                         push(@idns,$intdom);
15119:                     }
15120:                 }
15121:             }
15122:             $seen{$prim_ip} = 1;
15123:         }
15124:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15125:     }
15126: 
15127: }
15128: 
15129: sub all_loncaparevs {
15130:     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);
15131: }
15132: 
15133: # ---------------------------------------------------------- Read loncaparev table
15134: {
15135:     sub load_loncaparevs { 
15136:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15137:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15138:                 while (my $configline=<$config>) {
15139:                     chomp($configline);
15140:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15141:                     $loncaparevs{$hostid}=$loncaparev;
15142:                 }
15143:                 close($config);
15144:             }
15145:         }
15146:     }
15147: }
15148: 
15149: # ---------------------------------------------------------- Read serverhostID table
15150: {
15151:     sub load_serverhomeIDs {
15152:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15153:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15154:                 while (my $configline=<$config>) {
15155:                     chomp($configline);
15156:                     my ($name,$id)=split(/:/,$configline);
15157:                     $serverhomeIDs{$name}=$id;
15158:                 }
15159:                 close($config);
15160:             }
15161:         }
15162:     }
15163: }
15164: 
15165: 
15166: BEGIN {
15167: 
15168: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15169:     unless ($readit) {
15170: {
15171:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15172:     %perlvar = (%perlvar,%{$configvars});
15173: }
15174: 
15175: 
15176: # ------------------------------------------------------ Read spare server file
15177: {
15178:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15179: 
15180:     while (my $configline=<$config>) {
15181:        chomp($configline);
15182:        if ($configline) {
15183: 	   my ($host,$type) = split(':',$configline,2);
15184: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15185: 	   push(@{ $spareid{$type} }, $host);
15186:        }
15187:     }
15188:     close($config);
15189: }
15190: # ------------------------------------------------------------ Read permissions
15191: {
15192:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15193: 
15194:     while (my $configline=<$config>) {
15195: 	chomp($configline);
15196: 	if ($configline) {
15197: 	    my ($role,$perm)=split(/ /,$configline);
15198: 	    if ($perm ne '') { $pr{$role}=$perm; }
15199: 	}
15200:     }
15201:     close($config);
15202: }
15203: 
15204: # -------------------------------------------- Read plain texts for permissions
15205: {
15206:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15207: 
15208:     while (my $configline=<$config>) {
15209: 	chomp($configline);
15210: 	if ($configline) {
15211: 	    my ($short,@plain)=split(/:/,$configline);
15212:             %{$prp{$short}} = ();
15213: 	    if (@plain > 0) {
15214:                 $prp{$short}{'std'} = $plain[0];
15215:                 for (my $i=1; $i<@plain; $i++) {
15216:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15217:                 }
15218:             }
15219: 	}
15220:     }
15221:     close($config);
15222: }
15223: 
15224: # ---------------------------------------------------------- Read package table
15225: {
15226:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15227: 
15228:     while (my $configline=<$config>) {
15229: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15230: 	chomp($configline);
15231: 	my ($short,$plain)=split(/:/,$configline);
15232: 	my ($pack,$name)=split(/\&/,$short);
15233: 	if ($plain ne '') {
15234: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15235: 	    $packagetab{$short}=$plain; 
15236: 	}
15237:     }
15238:     close($config);
15239: }
15240: 
15241: # ---------------------------------------------------------- Read loncaparev table
15242: 
15243: &load_loncaparevs();
15244: 
15245: # ---------------------------------------------------------- Read serverhostID table
15246: 
15247: &load_serverhomeIDs();
15248: 
15249: # ---------------------------------------------------------- Read releaseslist XML
15250: {
15251:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15252:     if (-e $file) {
15253:         my $parser = HTML::LCParser->new($file);
15254:         while (my $token = $parser->get_token()) {
15255:             if ($token->[0] eq 'S') {
15256:                 my $item = $token->[1];
15257:                 my $name = $token->[2]{'name'};
15258:                 my $value = $token->[2]{'value'};
15259:                 my $valuematch = $token->[2]{'valuematch'};
15260:                 my $namematch = $token->[2]{'namematch'};
15261:                 if ($item eq 'parameter') {
15262:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15263:                         my $release = $parser->get_text();
15264:                         $release =~ s/(^\s*|\s*$ )//gx;
15265:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15266:                     }
15267:                 } elsif ($item ne '' && $name ne '') {
15268:                     my $release = $parser->get_text();
15269:                     $release =~ s/(^\s*|\s*$ )//gx;
15270:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15271:                 }
15272:             }
15273:         }
15274:     }
15275: }
15276: 
15277: # ---------------------------------------------------------- Read managers table
15278: {
15279:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15280:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15281:             while (my $configline=<$config>) {
15282:                 chomp($configline);
15283:                 next if ($configline =~ /^\#/);
15284:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15285:                     $managerstab{$configline} = 1;
15286:                 }
15287:             }
15288:             close($config);
15289:         }
15290:     }
15291: }
15292: 
15293: # ------------- set up temporary directory
15294: {
15295:     $tmpdir = LONCAPA::tempdir();
15296: 
15297: }
15298: 
15299: # ------------- set default texengine (domain default overrides this)
15300: {
15301:     $deftex = LONCAPA::texengine();
15302: }
15303: 
15304: # ------------- set default minimum length for passwords for internal auth users
15305: {
15306:     $passwdmin = LONCAPA::passwd_min();
15307: }
15308: 
15309: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15310: 				'compress_threshold'=> 20_000,
15311:  			        });
15312: 
15313: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15314: $dumpcount=0;
15315: $locknum=0;
15316: 
15317: &logtouch();
15318: &logthis('<font color="yellow">INFO: Read configuration</font>');
15319: $readit=1;
15320:     {
15321: 	use integer;
15322: 	my $test=(2**32)+1;
15323: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15324: 	&logthis(" Detected 64bit platform ($_64bit)");
15325:     }
15326: }
15327: }
15328: 
15329: 1;
15330: __END__
15331: 
15332: =pod
15333: 
15334: =head1 NAME
15335: 
15336: Apache::lonnet - Subroutines to ask questions about things in the network.
15337: 
15338: =head1 SYNOPSIS
15339: 
15340: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15341: 
15342:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15343: 
15344: Common parameters:
15345: 
15346: =over 4
15347: 
15348: =item *
15349: 
15350: $uname : an internal username (if $cname expecting a course Id specifically)
15351: 
15352: =item *
15353: 
15354: $udom : a domain (if $cdom expecting a course's domain specifically)
15355: 
15356: =item *
15357: 
15358: $symb : a resource instance identifier
15359: 
15360: =item *
15361: 
15362: $namespace : the name of a .db file that contains the data needed or
15363: being set.
15364: 
15365: =back
15366: 
15367: =head1 OVERVIEW
15368: 
15369: lonnet provides subroutines which interact with the
15370: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15371: about classes, users, and resources.
15372: 
15373: For many of these objects you can also use this to store data about
15374: them or modify them in various ways.
15375: 
15376: =head2 Symbs
15377: 
15378: To identify a specific instance of a resource, LON-CAPA uses symbols
15379: or "symbs"X<symb>. These identifiers are built from the URL of the
15380: map, the resource number of the resource in the map, and the URL of
15381: the resource itself. The latter is somewhat redundant, but might help
15382: if maps change.
15383: 
15384: An example is
15385: 
15386:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15387: 
15388: The respective map entry is
15389: 
15390:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15391:   title="Problem 2">
15392:  </resource>
15393: 
15394: Symbs are used by the random number generator, as well as to store and
15395: restore data specific to a certain instance of for example a problem.
15396: 
15397: =head2 Storing And Retrieving Data
15398: 
15399: X<store()>X<cstore()>X<restore()>Three of the most important functions
15400: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15401: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15402: is is the non-critical message twin of cstore. These functions are for
15403: handlers to store a perl hash to a user's permanent data space in an
15404: easy manner, and to retrieve it again on another call. It is expected
15405: that a handler would use this once at the beginning to retrieve data,
15406: and then again once at the end to send only the new data back.
15407: 
15408: The data is stored in the user's data directory on the user's
15409: homeserver under the ID of the course.
15410: 
15411: The hash that is returned by restore will have all of the previous
15412: value for all of the elements of the hash.
15413: 
15414: Example:
15415: 
15416:  #creating a hash
15417:  my %hash;
15418:  $hash{'foo'}='bar';
15419: 
15420:  #storing it
15421:  &Apache::lonnet::cstore(\%hash);
15422: 
15423:  #changing a value
15424:  $hash{'foo'}='notbar';
15425: 
15426:  #adding a new value
15427:  $hash{'bar'}='foo';
15428:  &Apache::lonnet::cstore(\%hash);
15429: 
15430:  #retrieving the hash
15431:  my %history=&Apache::lonnet::restore();
15432: 
15433:  #print the hash
15434:  foreach my $key (sort(keys(%history))) {
15435:    print("\%history{$key} = $history{$key}");
15436:  }
15437: 
15438: Will print out:
15439: 
15440:  %history{1:foo} = bar
15441:  %history{1:keys} = foo:timestamp
15442:  %history{1:timestamp} = 990455579
15443:  %history{2:bar} = foo
15444:  %history{2:foo} = notbar
15445:  %history{2:keys} = foo:bar:timestamp
15446:  %history{2:timestamp} = 990455580
15447:  %history{bar} = foo
15448:  %history{foo} = notbar
15449:  %history{timestamp} = 990455580
15450:  %history{version} = 2
15451: 
15452: Note that the special hash entries C<keys>, C<version> and
15453: C<timestamp> were added to the hash. C<version> will be equal to the
15454: total number of versions of the data that have been stored. The
15455: C<timestamp> attribute will be the UNIX time the hash was
15456: stored. C<keys> is available in every historical section to list which
15457: keys were added or changed at a specific historical revision of a
15458: hash.
15459: 
15460: B<Warning>: do not store the hash that restore returns directly. This
15461: will cause a mess since it will restore the historical keys as if the
15462: were new keys. I.E. 1:foo will become 1:1:foo etc.
15463: 
15464: Calling convention:
15465: 
15466:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15467:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15468: 
15469: For more detailed information, see lonnet specific documentation.
15470: 
15471: =head1 RETURN MESSAGES
15472: 
15473: =over 4
15474: 
15475: =item * B<con_lost>: unable to contact remote host
15476: 
15477: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15478: when the connection is brought back up
15479: 
15480: =item * B<con_failed>: unable to contact remote host and unable to save message
15481: for later delivery
15482: 
15483: =item * B<error:>: an error a occurred, a description of the error follows the :
15484: 
15485: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15486: that was requested
15487: 
15488: =back
15489: 
15490: =head1 PUBLIC SUBROUTINES
15491: 
15492: =head2 Session Environment Functions
15493: 
15494: =over 4
15495: 
15496: =item * 
15497: X<appenv()>
15498: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15499: the user envirnoment file, and will be restored for each access this
15500: user makes during this session, also modifies the %env for the current
15501: process. Optional rolesarrayref - if defined contains a reference to an array
15502: of roles which are exempt from the restriction on modifying user.role entries 
15503: in the user's environment.db and in %env.    
15504: 
15505: =item *
15506: X<delenv()>
15507: B<delenv($delthis,$regexp)>: removes all items from the session
15508: environment file that begin with $delthis. If the 
15509: optional second arg - $regexp - is true, $delthis is treated as a 
15510: regular expression, otherwise \Q$delthis\E is used. 
15511: The values are also deleted from the current processes %env.
15512: 
15513: =item * get_env_multiple($name) 
15514: 
15515: gets $name from the %env hash, it seemlessly handles the cases where multiple
15516: values may be defined and end up as an array ref.
15517: 
15518: returns an array of values
15519: 
15520: =back
15521: 
15522: =head2 User Information
15523: 
15524: =over 4
15525: 
15526: =item *
15527: X<queryauthenticate()>
15528: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15529: authentication scheme
15530: 
15531: =item *
15532: X<authenticate()>
15533: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15534: authenticate user from domain's lib servers (first use the current
15535: one). C<$upass> should be the users password.
15536: $checkdefauth is optional (value is 1 if a check should be made to
15537:    authenticate user using default authentication method, and allow
15538:    account creation if username does not have account in the domain).
15539: $clientcancheckhost is optional (value is 1 if checking whether the
15540:    server can host will occur on the client side in lonauth.pm).   
15541: 
15542: =item *
15543: X<homeserver()>
15544: B<homeserver($uname,$udom)>: find the server which has
15545: the user's directory and files (there must be only one), this caches
15546: the answer, and also caches if there is a borken connection.
15547: 
15548: =item *
15549: X<idget()>
15550: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15551: a list of student/employee IDs or clicker IDs
15552: (student/employee IDs are a unique resource in a domain, there must be 
15553: only 1 ID per username, and only 1 username per ID in a specific domain).
15554: clickerIDs are not necessarily unique, as students might share clickers.
15555: (returns hash: id=>name,id=>name)
15556: 
15557: =item *
15558: X<idrget()>
15559: B<idrget($udom,@unames)>: find the IDs behind a list of
15560: usernames (returns hash: name=>id,name=>id)
15561: 
15562: =item *
15563: X<idput()>
15564: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15565: names and associated student/employee IDs or clicker IDs.
15566: 
15567: =item *
15568: X<iddel()>
15569: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15570: student/employee ID or clicker ID username look-ups from domain.
15571: The homeserver ($uhome) and namespace ($namespace) are optional.
15572: If no $uhome is provided, it will be determined usig &homeserver()
15573: for each user.  If no $namespace is provided, the default is ids.
15574: 
15575: =item *
15576: X<updateclickers()>
15577: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15578: clicker ID-to-username look-ups in clickers.db on library server.
15579: Permitted actions are add or del (i.e., add or delete). The 
15580: clickers.db contains clickerID as keys (escaped), and each corresponding
15581: value is an escaped comma-separated list of usernames (for whom the
15582: library server is the homeserver), who registered that particular ID.
15583: If $critical is true, the update will be sent via &critical, otherwise
15584: &reply() will be used.
15585: 
15586: =item *
15587: X<rolesinit()>
15588: B<rolesinit($udom,$username)>: get user privileges.
15589: returns user role, first access and timer interval hashes
15590: 
15591: =item *
15592: X<privileged()>
15593: B<privileged($username,$domain)>: returns a true if user has a
15594: privileged and active role (i.e. su or dc), false otherwise.
15595: 
15596: =item *
15597: X<getsection()>
15598: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15599: course $cname, return section name/number or '' for "not in course"
15600: and '-1' for "no section"
15601: 
15602: =item *
15603: X<userenvironment()>
15604: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15605: passed in @what from the requested user's environment, returns a hash
15606: 
15607: =item * 
15608: X<userlog_query()>
15609: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15610: activity.log file. %filters defines filters applied when parsing the
15611: log file. These can be start or end timestamps, or the type of action
15612: - log to look for Login or Logout events, check for Checkin or
15613: Checkout, role for role selection. The response is in the form
15614: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15615: escaped strings of the action recorded in the activity.log file.
15616: 
15617: =back
15618: 
15619: =head2 User Roles
15620: 
15621: =over 4
15622: 
15623: =item *
15624: 
15625: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15626: returns codes for allowed actions.
15627: 
15628: The first argument is required, all others are optional.
15629: 
15630: $priv is the privilege being checked.
15631: $uri contains additional information about what is being checked for access (e.g.,
15632: URL, course ID etc.). 
15633: $symb is the unique resource instance identifier in a course; if needed,
15634: but not provided, it will be retrieved via a call to &symbread(). 
15635: $role is the role for which a priv is being checked (only used if priv is evb). 
15636: $clientip is the user's IP address (only used when checking for access to portfolio 
15637: files).
15638: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15639: prevents recursive calls to &allowed.
15640: 
15641:  F: full access
15642:  U,I,K: authentication modes (cxx only)
15643:  '': forbidden
15644:  1: user needs to choose course
15645:  2: browse allowed
15646:  A: passphrase authentication needed
15647:  B: access temporarily blocked because of a blocking event in a course.
15648:  D: access blocked because access is required via session initiated via deep-link 
15649: 
15650: =item *
15651: 
15652: constructaccess($url,$setpriv) : check for access to construction space URL
15653: 
15654: See if the owner domain and name in the URL match those in the
15655: expected environment.  If so, return three element list
15656: ($ownername,$ownerdomain,$ownerhome).
15657: 
15658: Otherwise return the null string.
15659: 
15660: If second argument 'setpriv' is true, it assigns the privileges,
15661: and returns the same three element list, unless the owner has
15662: blocked "ad hoc" Domain Coordinator access to the Author Space,
15663: in which case the null string is returned.
15664: 
15665: =item *
15666: 
15667: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15668: define a custom role rolename set privileges in format of lonTabs/roles.tab
15669: for system, domain, and course level. $uname and $udom are optional (current
15670: user's username and domain will be used when either of $uname or $udom are absent.
15671: 
15672: =item *
15673: 
15674: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15675: (rolesplain.tab); plain text explanation of a user role term.
15676: $type is Course (default) or Community.
15677: If $forcedefault evaluates to true, text returned will be default 
15678: text for $type. Otherwise, if this is a course, the text returned 
15679: will be a custom name for the role (if defined in the course's 
15680: environment).  If no custom name is defined the default is returned.
15681:    
15682: =item *
15683: 
15684: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15685: All arguments are optional. Returns a hash of a roles, either for
15686: co-author/assistant author roles for a user's Construction Space
15687: (default), or if $context is 'userroles', roles for the user himself,
15688: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15689: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15690: For each key, value is set to colon-separated start and end times for
15691: the role.  If no username and domain are specified, will default to
15692: current user/domain. Types, roles, and roledoms are references to arrays
15693: of role statuses (active, future or previous), roles 
15694: (e.g., cc,in, st etc.) and domains of the roles which can be used
15695: to restrict the list of roles reported. If no array ref is 
15696: provided for types, will default to return only active roles.
15697: 
15698: =item *
15699: 
15700: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15701: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15702: 
15703: Additional optional arguments are: $type (if role checking is to be restricted 
15704: to certain user status types -- previous (expired roles), active (currently
15705: available roles) or future (roles available in the future), and
15706: $hideprivileged -- if true will not report course roles for users who
15707: have active Domain Coordinator role in course's domain or in additional
15708: domains (specified in 'Domains to check for privileged users' in course
15709: environment -- set via:  Course Settings -> Classlists and staff listing).
15710: 
15711: =item *
15712: 
15713: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15714: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15715: $possdomains and $possroles are optional array refs -- to domains to check and
15716: roles to check.  If $possdomains is not specified, a dump will be done of the
15717: users' roles.db to check for a dc or su role in any domain. This can be
15718: time consuming if &privileged is called repeatedly (e.g., when displaying a
15719: classlist), so in such cases, supplying a $possdomains array is preferred, as
15720: this then allows &privileged_by_domain() to be used, which caches the identity
15721: of privileged users, eliminating the need for repeated calls to &dump().
15722: 
15723: =item *
15724: 
15725: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15726: where the outer hash keys are domains specified in the $possdomains array ref,
15727: next inner hash keys are privileged roles specified in the $roles array ref,
15728: and the innermost hash contains key = value pairs for username:domain = end:start
15729: for active or future "privileged" users with that role in that domain. To avoid
15730: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15731: innerhash are cached using priv_$role and $dom as the identifiers.
15732: 
15733: =back
15734: 
15735: =head2 User Modification
15736: 
15737: =over 4
15738: 
15739: =item *
15740: 
15741: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15742: user for the level given by URL.  Optional start and end dates (leave empty
15743: string or zero for "no date")
15744: 
15745: =item *
15746: 
15747: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15748: change a users, password, possible return values are: ok,
15749: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15750: refused
15751: 
15752: =item *
15753: 
15754: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15755: 
15756: =item *
15757: 
15758: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15759:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15760: 
15761: will update user information (firstname,middlename,lastname,generation,
15762: permanentemail), and if forceid is true, student/employee ID also.
15763: A user's institutional affiliation(s) can also be updated.
15764: User information fields will not be overwritten with empty entries 
15765: unless the field is included in the $candelete array reference.
15766: This array is included when a single user is modified via "Manage Users",
15767: or when Autoupdate.pl is run by cron in a domain.
15768: 
15769: =item *
15770: 
15771: modifystudent
15772: 
15773: modify a student's enrollment and identification information.
15774: The course id is resolved based on the current user's environment.  
15775: This means the invoking user must be a course coordinator or otherwise
15776: associated with a course.
15777: 
15778: This call is essentially a wrapper for lonnet::modifyuser and
15779: lonnet::modify_student_enrollment
15780: 
15781: Inputs: 
15782: 
15783: =over 4
15784: 
15785: =item B<$udom> Student's loncapa domain
15786: 
15787: =item B<$uname> Student's loncapa login name
15788: 
15789: =item B<$uid> Student/Employee ID
15790: 
15791: =item B<$umode> Student's authentication mode
15792: 
15793: =item B<$upass> Student's password
15794: 
15795: =item B<$first> Student's first name
15796: 
15797: =item B<$middle> Student's middle name
15798: 
15799: =item B<$last> Student's last name
15800: 
15801: =item B<$gene> Student's generation
15802: 
15803: =item B<$usec> Student's section in course
15804: 
15805: =item B<$end> Unix time of the roles expiration
15806: 
15807: =item B<$start> Unix time of the roles start date
15808: 
15809: =item B<$forceid> If defined, allow $uid to be changed
15810: 
15811: =item B<$desiredhome> server to use as home server for student
15812: 
15813: =item B<$email> Student's permanent e-mail address
15814: 
15815: =item B<$type> Type of enrollment (auto or manual)
15816: 
15817: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15818: 
15819: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15820: 
15821: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15822: 
15823: =item B<$context> role change context (shown in User Management Logs display in a course)
15824: 
15825: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15826: 
15827: =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.
15828: 
15829: =back
15830: 
15831: =item *
15832: 
15833: modify_student_enrollment
15834: 
15835: Change a student's enrollment status in a class.  The environment variable
15836: 'role.request.course' must be defined for this function to proceed.
15837: 
15838: Inputs:
15839: 
15840: =over 4
15841: 
15842: =item $udom, student's domain
15843: 
15844: =item $uname, student's name
15845: 
15846: =item $uid, student's user id
15847: 
15848: =item $first, student's first name
15849: 
15850: =item $middle
15851: 
15852: =item $last
15853: 
15854: =item $gene
15855: 
15856: =item $usec
15857: 
15858: =item $end
15859: 
15860: =item $start
15861: 
15862: =item $type
15863: 
15864: =item $locktype
15865: 
15866: =item $cid
15867: 
15868: =item $selfenroll
15869: 
15870: =item $context
15871: 
15872: =item $credits, number of credits student will earn from this class
15873: 
15874: =item $instsec, institutional course section code for student
15875: 
15876: =back
15877: 
15878: 
15879: =item *
15880: 
15881: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15882: custom role; give a custom role to a user for the level given by URL.  Specify
15883: name and domain of role author, and role name
15884: 
15885: =item *
15886: 
15887: revokerole($udom,$uname,$url,$role) : revoke a role for url
15888: 
15889: =item *
15890: 
15891: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15892: 
15893: =back
15894: 
15895: =head2 Course Infomation
15896: 
15897: =over 4
15898: 
15899: =item *
15900: 
15901: coursedescription($courseid,$options) : returns a hash of information about the
15902: specified course id, including all environment settings for the
15903: course, the description of the course will be in the hash under the
15904: key 'description'
15905: 
15906: $options is an optional parameter that if supplied is a hash reference that controls
15907: what how this function works.  It has the following key/values:
15908: 
15909: =over 4
15910: 
15911: =item freshen_cache
15912: 
15913: If defined, and the environment cache for the course is valid, it is 
15914: returned in the returned hash.
15915: 
15916: =item one_time
15917: 
15918: If defined, the last cache time is set to _now_
15919: 
15920: =item user
15921: 
15922: If defined, the supplied username is used instead of the current user.
15923: 
15924: 
15925: =back
15926: 
15927: =item *
15928: 
15929: resdata($name,$domain,$type,@which) : request for current parameter
15930: setting for a specific $type, where $type is either 'course' or 'user',
15931: @what should be a list of parameters to ask about. This routine caches
15932: answers for 10 minutes.
15933: 
15934: =item *
15935: 
15936: get_courseresdata($courseid, $domain) : dump the entire course resource
15937: data base, returning a hash that is keyed by the resource name and has
15938: values that are the resource value.  I believe that the timestamps and
15939: versions are also returned.
15940: 
15941: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15942: supplemental content area. This routine caches the number of files for 
15943: 10 minutes.
15944: 
15945: =back
15946: 
15947: =head2 Course Modification
15948: 
15949: =over 4
15950: 
15951: =item *
15952: 
15953: writecoursepref($courseid,%prefs) : write preferences (environment
15954: database) for a course
15955: 
15956: =item *
15957: 
15958: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15959: 
15960: =item *
15961: 
15962: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15963: 
15964: =item *
15965: 
15966: is_course($courseid), is_course($cdom, $cnum)
15967: 
15968: Accepts either a combined $courseid (in the form of domain_courseid) or the
15969: two component version $cdom, $cnum. It checks if the specified course exists.
15970: 
15971: Returns:
15972:     undef if the course doesn't exist, otherwise
15973:     in scalar context the combined courseid.
15974:     in list context the two components of the course identifier, domain and 
15975:     courseid.    
15976: 
15977: =back
15978: 
15979: =head2 Bubblesheet Configuration
15980: 
15981: =over 4
15982: 
15983: =item *
15984: 
15985: get_scantron_config($which)
15986: 
15987: $which - the name of the configuration to parse from the file.
15988: 
15989: Parses and returns the bubblesheet configuration line selected as a
15990: hash of configuration file fields.
15991: 
15992: 
15993: Returns:
15994:     If the named configuration is not in the file, an empty
15995:     hash is returned.
15996: 
15997:     a hash with the fields
15998:       name         - internal name for the this configuration setup
15999:       description  - text to display to operator that describes this config
16000:       CODElocation - if 0 or the string 'none'
16001:                           - no CODE exists for this config
16002:                      if -1 || the string 'letter'
16003:                           - a CODE exists for this config and is
16004:                             a string of letters
16005:                      Unsupported value (but planned for future support)
16006:                           if a positive integer
16007:                                - The CODE exists as the first n items from
16008:                                  the question section of the form
16009:                           if the string 'number'
16010:                                - The CODE exists for this config and is
16011:                                  a string of numbers
16012:       CODEstart   - (only matter if a CODE exists) column in the line where
16013:                      the CODE starts
16014:       CODElength  - length of the CODE
16015:       IDstart     - column where the student/employee ID starts
16016:       IDlength    - length of the student/employee ID info
16017:       Qstart      - column where the information from the bubbled
16018:                     'questions' start
16019:       Qlength     - number of columns comprising a single bubble line from
16020:                     the sheet. (usually either 1 or 10)
16021:       Qon         - either a single character representing the character used
16022:                     to signal a bubble was chosen in the positional setup, or
16023:                     the string 'letter' if the letter of the chosen bubble is
16024:                     in the final, or 'number' if a number representing the
16025:                     chosen bubble is in the file (1->A 0->J)
16026:       Qoff        - the character used to represent that a bubble was
16027:                     left blank
16028:       PaperID     - if the scanning process generates a unique number for each
16029:                     sheet scanned the column that this ID number starts in
16030:       PaperIDlength - number of columns that comprise the unique ID number
16031:                       for the sheet of paper
16032:       FirstName   - column that the first name starts in
16033:       FirstNameLength - number of columns that the first name spans
16034:       LastName    - column that the last name starts in
16035:       LastNameLength - number of columns that the last name spans
16036:       BubblesPerRow - number of bubbles available in each row used to
16037:                       bubble an answer. (If not specified, 10 assumed).
16038: 
16039: 
16040: =item *
16041: 
16042: get_scantronformat_file($cdom)
16043: 
16044: $cdom - the course's domain (optional); if not supplied, uses
16045: domain for current $env{'request.course.id'}.
16046: 
16047: Returns an array containing lines from the scantron format file for
16048: the domain of the course.
16049: 
16050: If a url for a custom.tab file is listed in domain's configuration.db,
16051: lines are from this file.
16052: 
16053: Otherwise, if a default.tab has been published in RES space by the
16054: domainconfig user, lines are from this file.
16055: 
16056: Otherwise, fall back to getting lines from the legacy file on the
16057: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16058: 
16059: =back
16060: 
16061: =head2 Resource Subroutines
16062: 
16063: =over 4
16064: 
16065: =item *
16066: 
16067: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16068: 
16069: =item *
16070: 
16071: repcopy($filename) : subscribes to the requested file, and attempts to
16072: replicate from the owning library server, Might return
16073: 'unavailable', 'not_found', 'forbidden', 'ok', or
16074: 'bad_request', also attempts to grab the metadata for the
16075: resource. Expects the local filesystem pathname
16076: (/home/httpd/html/res/....)
16077: 
16078: =back
16079: 
16080: =head2 Resource Information
16081: 
16082: =over 4
16083: 
16084: =item *
16085: 
16086: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16087: and returns the value of a variety of different possible values,
16088: $varname should be a request string, and the other parameters can be
16089: used to specify who and what one is asking about. Ordinarily, $cid 
16090: does not need to be specified, as it is retrived from 
16091: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16092: within lonuserstate::loadmap() when initializing a course, before
16093: $env{'request.course.id'} has been set, so it needs to be provided
16094: in that one case.
16095: 
16096: Possible values for $varname are environment.lastname (or other item
16097: from the envirnment hash), user.name (or someother aspect about the
16098: user), resource.0.maxtries (or some other part and parameter of a
16099: resource)
16100: 
16101: =item *
16102: 
16103: directcondval($number) : get current value of a condition; reads from a state
16104: string
16105: 
16106: =item *
16107: 
16108: condval($condidx) : value of condition index based on state
16109: 
16110: =item *
16111: 
16112: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16113: resource's metadata, $what should be either a specific key, or either
16114: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16115: packages that this resource currently uses, the last 3 arguments are 
16116: only used internally for recursive metadata.
16117: 
16118: the toolsymb is only used where the uri is for an external tool (for which
16119: the uri as well as the symb are guaranteed to be unique).
16120: 
16121: this function automatically caches all requests except any made recursively
16122: to retrieve a list of metadata keys for an imported library file ($liburi is 
16123: defined).
16124: 
16125: =item *
16126: 
16127: metadata_query($query,$custom,$customshow) : make a metadata query against the
16128: network of library servers; returns file handle of where SQL and regex results
16129: will be stored for query
16130: 
16131: =item *
16132: 
16133: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16134: return symbolic list entry (all arguments optional). 
16135: 
16136: Args: filename is the filename (including path) for the file for which a symb 
16137: is required; donotrecurse, if true will prevent calls to allowed() being made 
16138: to check access status if more than one resource was found in the bighash 
16139: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16140: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16141: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16142: cause possible symbs to be checked to determine if they are subject to content
16143: blocking, if so they will not be included as possible symbs; possibles is a
16144: ref to a hash, which, as a side effect, will be populated with all possible 
16145: symbs (content blocking not tested).
16146:  
16147: returns the data handle
16148: 
16149: =item *
16150: 
16151: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16152: and is a possible symb for the URL in $thisfn, and if is an encrypted
16153: resource that the user accessed using /enc/ returns a 1 on success, 0
16154: on failure, user must be in a course, as it assumes the existence of
16155: the course initial hash, and uses $env('request.course.id'}.  The third
16156: arg is an optional reference to a scalar.  If this arg is passed in the 
16157: call to symbverify, it will be set to 1 if the symb has been set to be 
16158: encrypted; otherwise it will be null.  
16159: 
16160: =item *
16161: 
16162: symbclean($symb) : removes versions numbers from a symb, returns the
16163: cleaned symb
16164: 
16165: =item *
16166: 
16167: is_on_map($uri) : checks if the $uri is somewhere on the current
16168: course map, user must be in a course for it to work.
16169: 
16170: =item *
16171: 
16172: numval($salt) : return random seed value (addend for rndseed)
16173: 
16174: =item *
16175: 
16176: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16177: a random seed, all arguments are optional, if they aren't sent it uses the
16178: environment to derive them. Note: if symb isn't sent and it can't get one
16179: from &symbread it will use the current time as its return value
16180: 
16181: =item *
16182: 
16183: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16184: unfakeable, receipt
16185: 
16186: =item *
16187: 
16188: receipt() : API to ireceipt working off of env values; given out to users
16189: 
16190: =item *
16191: 
16192: countacc($url) : count the number of accesses to a given URL
16193: 
16194: =item *
16195: 
16196: 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
16197: 
16198: =item *
16199: 
16200: 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)
16201: 
16202: =item *
16203: 
16204: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16205: 
16206: =item *
16207: 
16208: devalidate($symb) : devalidate temporary spreadsheet calculations,
16209: forcing spreadsheet to reevaluate the resource scores next time.
16210: 
16211: =item * 
16212: 
16213: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16214: when viewing in course context.
16215: 
16216:  input: six args -- filename (decluttered), course number, course domain,
16217:                     url, symb (if registered) and group (if this is a 
16218:                     group item -- e.g., bulletin board, group page etc.).
16219: 
16220:  output: array of five scalars --
16221:          $cfile -- url for file editing if editable on current server
16222:          $home -- homeserver of resource (i.e., for author if published,
16223:                                           or course if uploaded.).
16224:          $switchserver --  1 if server switch will be needed.
16225:          $forceedit -- 1 if icon/link should be to go to edit mode 
16226:          $forceview -- 1 if icon/link should be to go to view mode
16227: 
16228: =item *
16229: 
16230: is_course_upload($file,$cnum,$cdom)
16231: 
16232: Used in course context to determine if current file was uploaded to 
16233: the course (i.e., would be found in /userfiles/docs on the course's 
16234: homeserver.
16235: 
16236:   input: 3 args -- filename (decluttered), course number and course domain.
16237:   output: boolean -- 1 if file was uploaded.
16238: 
16239: =back
16240: 
16241: =head2 Storing/Retreiving Data
16242: 
16243: =over 4
16244: 
16245: =item *
16246: 
16247: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16248: permanently for this url; hashref needs to be given and should be a \%hashname;
16249: the remaining args aren't required and if they aren't passed or are '' they will
16250: be derived from the env (with the exception of $laststore, which is an 
16251: optional arg used when a user's submission is stored in grading).
16252: $laststore is $version=$timestamp, where $version is the most recent version
16253: number retrieved for the corresponding $symb in the $namespace db file, and
16254: $timestamp is the timestamp for that transaction (UNIX time).
16255: $laststore is currently only passed when cstore() is called by 
16256: structuretags::finalize_storage().
16257: 
16258: =item *
16259: 
16260: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16261: but uses critical subroutine
16262: 
16263: =item *
16264: 
16265: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16266: all args are optional
16267: 
16268: =item *
16269: 
16270: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16271: dumps the complete (or key matching regexp) namespace into a hash
16272: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16273: normally &store()ed into
16274: 
16275: $range should be either an integer '100' (give me the first 100
16276:                                            matching records)
16277:               or be  two integers sperated by a - with no spaces
16278:                  '30-50' (give me the 30th through the 50th matching
16279:                           records)
16280: 
16281: 
16282: =item *
16283: 
16284: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16285: replaces a &store() version of data with a replacement set of data
16286: for a particular resource in a namespace passed in the $storehash hash 
16287: reference. If $tolog is true, the transaction is logged in the courselog
16288: with an action=PUTSTORE.
16289: 
16290: =item *
16291: 
16292: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16293: works very similar to store/cstore, but all data is stored in a
16294: temporary location and can be reset using tmpreset, $storehash should
16295: be a hash reference, returns nothing on success
16296: 
16297: =item *
16298: 
16299: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16300: similar to restore, but all data is stored in a temporary location and
16301: can be reset using tmpreset. Returns a hash of values on success,
16302: error string otherwise.
16303: 
16304: =item *
16305: 
16306: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16307: deltes all keys for $symb form the temporary storage hash.
16308: 
16309: =item *
16310: 
16311: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16312: reference filled in from namesp ($udom and $uname are optional)
16313: 
16314: =item *
16315: 
16316: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16317: namesp ($udom and $uname are optional)
16318: 
16319: =item *
16320: 
16321: dump($namespace,$udom,$uname,$regexp,$range) : 
16322: dumps the complete (or key matching regexp) namespace into a hash
16323: ($udom, $uname, $regexp, $range are optional)
16324: 
16325: $range should be either an integer '100' (give me the first 100
16326:                                            matching records)
16327:               or be  two integers sperated by a - with no spaces
16328:                  '30-50' (give me the 30th through the 50th matching
16329:                           records)
16330: =item *
16331: 
16332: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16333: $store can be a scalar, an array reference, or if the amount to be 
16334: incremented is > 1, a hash reference.
16335: 
16336: ($udom and $uname are optional)
16337: 
16338: =item *
16339: 
16340: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16341: ($udom and $uname are optional)
16342: 
16343: =item *
16344: 
16345: cput($namespace,$storehash,$udom,$uname) : critical put
16346: ($udom and $uname are optional)
16347: 
16348: =item *
16349: 
16350: newput($namespace,$storehash,$udom,$uname) :
16351: 
16352: Attempts to store the items in the $storehash, but only if they don't
16353: currently exist, if this succeeds you can be certain that you have 
16354: successfully created a new key value pair in the $namespace db.
16355: 
16356: 
16357: Args:
16358:  $namespace: name of database to store values to
16359:  $storehash: hashref to store to the db
16360:  $udom: (optional) domain of user containing the db
16361:  $uname: (optional) name of user caontaining the db
16362: 
16363: Returns:
16364:  'ok' -> succeeded in storing all keys of $storehash
16365:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16366:                         least <key> already existed in the db (other
16367:                         requested keys may also already exist)
16368:  'error: <msg>' -> unable to tie the DB or other error occurred
16369:  'con_lost' -> unable to contact request server
16370:  'refused' -> action was not allowed by remote machine
16371: 
16372: 
16373: =item *
16374: 
16375: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16376: reference filled in from namesp (encrypts the return communication)
16377: ($udom and $uname are optional)
16378: 
16379: =item *
16380: 
16381: log($udom,$name,$home,$message) : write to permanent log for user; use
16382: critical subroutine
16383: 
16384: =item *
16385: 
16386: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16387: array reference filled in from namespace found in domain level on either
16388: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16389: 
16390: =item *
16391: 
16392: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16393: domain level either on specified domain server ($uhome) or primary domain 
16394: server ($udom and $uhome are optional)
16395: 
16396: =item * 
16397: 
16398: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16399: for: authentication, language, quotas, timezone, date locale, and portal URL in
16400: the target domain.
16401: 
16402: May also include additional key => value pairs for the following groups:
16403: 
16404: =over
16405: 
16406: =item
16407: disk quotas (MB allocated by default to portfolios and authoring spaces).
16408: 
16409: =over
16410: 
16411: =item defaultquota, authorquota
16412: 
16413: =back
16414: 
16415: =item
16416: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16417: portfolio for users).
16418: 
16419: =over
16420: 
16421: =item
16422: aboutme, blog, webdav, portfolio
16423: 
16424: =back
16425: 
16426: =item
16427: requestcourses: ability to request courses, and how requests are processed.
16428: 
16429: =over
16430: 
16431: =item
16432: official, unofficial, community, textbook, placement
16433: 
16434: =back
16435: 
16436: =item
16437: inststatus: types of institutional affiliation, and order in which they are displayed.
16438: 
16439: =over
16440: 
16441: =item
16442: inststatustypes, inststatusorder, inststatusguest
16443: 
16444: =back
16445: 
16446: =item
16447: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16448: for course's uploaded content.
16449: 
16450: =over
16451: 
16452: =item
16453: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16454: communityquota, textbookquota, placementquota
16455: 
16456: =back
16457: 
16458: =item
16459: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16460: on your servers.
16461: 
16462: =over
16463: 
16464: =item 
16465: remotesessions, hostedsessions
16466: 
16467: =back
16468: 
16469: =back
16470: 
16471: In cases where a domain coordinator has never used the "Set Domain Configuration"
16472: utility to create a configuration.db file on a domain's primary library server 
16473: only the following domain defaults: auth_def, auth_arg_def, lang_def
16474: -- corresponding values are authentication type (internal, krb4, krb5,
16475: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16476: will be available. Values are retrieved from cache (if current), unless the
16477: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16478: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16479: 
16480: Typical usage:
16481: 
16482: %domdefaults = &get_domain_defaults($target_domain);
16483: 
16484: =back
16485: 
16486: =head2 Network Status Functions
16487: 
16488: =over 4
16489: 
16490: =item *
16491: 
16492: dirlist() : return directory list based on URI (first arg).
16493: 
16494: Inputs: 1 required, 5 optional.
16495: 
16496: =over
16497: 
16498: =item 
16499: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16500: 
16501: =item
16502: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16503: 
16504: =item
16505: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16506: 
16507: =item
16508: $getpropath - boolean: 1 if prepend path using &propath(). 
16509: 
16510: =item
16511: $getuserdir - boolean: 1 if prepend path for "userfiles".
16512: 
16513: =item 
16514: $alternateRoot - path to prepend in place of path from $uri.
16515: 
16516: =back
16517: 
16518: Returns: Array of up to two items.
16519: 
16520: =over
16521: 
16522: a reference to an array of files/subdirectories
16523: 
16524: =over
16525: 
16526: Each element in the array of files/subdirectories is a & separated list of
16527: item name and the result of running stat on the item.  If dirlist was requested
16528: for a file instead of a directory, the item name will be ''. For a directory 
16529: listing, if the item is a metadata file, the element will end &N&M 
16530: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16531: default copyright set (1).  
16532: 
16533: =back
16534: 
16535: a scalar containing error condition (if encountered).
16536: 
16537: =over
16538: 
16539: =item 
16540: no_host (no homeserver identified for $username:$domain).
16541: 
16542: =item 
16543: no_such_host (server contacted for listing not identified as valid host).
16544: 
16545: =item 
16546: con_lost (connection to remote server failed).
16547: 
16548: =item 
16549: refused (invalid $username:$domain received on lond side).
16550: 
16551: =item 
16552: no_such_dir (directory at specified path on lond side does not exist). 
16553: 
16554: =item 
16555: empty (directory at specified path on lond side is empty).
16556: 
16557: =over
16558: 
16559: This is currently not encountered because the &ls3, &ls2, 
16560: &ls (_handler) routines on the lond side do not filter out
16561: . and .. from a directory listing. 
16562: 
16563: =back
16564: 
16565: =back
16566: 
16567: =back
16568: 
16569: =item *
16570: 
16571: spareserver() : find server with least workload from spare.tab
16572: 
16573: 
16574: =item *
16575: 
16576: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16577: if there is no corresponding loncapa host.
16578: 
16579: =back
16580: 
16581: 
16582: =head2 Apache Request
16583: 
16584: =over 4
16585: 
16586: =item *
16587: 
16588: ssi($url,%hash) : server side include, does a complete request cycle on url to
16589: localhost, posts hash
16590: 
16591: =back
16592: 
16593: =head2 Data to String to Data
16594: 
16595: =over 4
16596: 
16597: =item *
16598: 
16599: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16600: and '&' separators, supports elements that are arrayrefs and hashrefs
16601: 
16602: =item *
16603: 
16604: hashref2str($hashref) : convert a hashref into a string complete with
16605: escaping and '=' and '&' separators, supports elements that are
16606: arrayrefs and hashrefs
16607: 
16608: =item *
16609: 
16610: arrayref2str($arrayref) : convert an arrayref into a string complete
16611: with escaping and '&' separators, supports elements that are arrayrefs
16612: and hashrefs
16613: 
16614: =item *
16615: 
16616: str2hash($string) : convert string to hash using unescaping and
16617: splitting on '=' and '&', supports elements that are arrayrefs and
16618: hashrefs
16619: 
16620: =item *
16621: 
16622: str2array($string) : convert string to hash using unescaping and
16623: splitting on '&', supports elements that are arrayrefs and hashrefs
16624: 
16625: =back
16626: 
16627: =head2 Logging Routines
16628: 
16629: 
16630: These routines allow one to make log messages in the lonnet.log and
16631: lonnet.perm logfiles.
16632: 
16633: =over 4
16634: 
16635: =item *
16636: 
16637: logtouch() : make sure the logfile, lonnet.log, exists
16638: 
16639: =item *
16640: 
16641: logthis() : append message to the normal lonnet.log file, it gets
16642: preiodically rolled over and deleted.
16643: 
16644: =item *
16645: 
16646: logperm() : append a permanent message to lonnet.perm.log, this log
16647: file never gets deleted by any automated portion of the system, only
16648: messages of critical importance should go in here.
16649: 
16650: 
16651: =back
16652: 
16653: =head2 General File Helper Routines
16654: 
16655: =over 4
16656: 
16657: =item *
16658: 
16659: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16660: (a) files in /uploaded
16661:   (i) If a local copy of the file exists - 
16662:       compares modification date of local copy with last-modified date for 
16663:       definitive version stored on home server for course. If local copy is 
16664:       stale, requests a new version from the home server and stores it. 
16665:       If the original has been removed from the home server, then local copy 
16666:       is unlinked.
16667:   (ii) If local copy does not exist -
16668:       requests the file from the home server and stores it. 
16669:   
16670:   If $caller is 'uploadrep':  
16671:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16672:     for request for files originally uploaded via DOCS. 
16673:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16674:   
16675:   Otherwise:
16676:      This indicates a call from the content generation phase of the request.
16677:      -  returns the entire contents of the file or -1.
16678:      
16679: (b) files in /res
16680:    - returns the entire contents of a file or -1; 
16681:    it properly subscribes to and replicates the file if neccessary.
16682: 
16683: 
16684: =item *
16685: 
16686: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16687:                   reference
16688: 
16689: returns either a stat() list of data about the file or an empty list
16690: if the file doesn't exist or couldn't find out about it (connection
16691: problems or user unknown)
16692: 
16693: =item *
16694: 
16695: filelocation($dir,$file) : returns file system location of a file
16696: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16697: directory that relative $file lookups are to looked in ($dir of /a/dir
16698: and a file of ../bob will become /a/bob)
16699: 
16700: =item *
16701: 
16702: hreflocation($dir,$file) : returns file system location or a URL; same as
16703: filelocation except for hrefs
16704: 
16705: =item *
16706: 
16707: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16708: also removes beginning /home/httpd/html unless /priv/ follows it.
16709: 
16710: =back
16711: 
16712: =head2 Usererfile file routines (/uploaded*)
16713: 
16714: =over 4
16715: 
16716: =item *
16717: 
16718: userfileupload(): main rotine for putting a file in a user or course's
16719:                   filespace, arguments are,
16720: 
16721:  formname - required - this is the name of the element in $env where the
16722:            filename, and the contents of the file to create/modifed exist
16723:            the filename is in $env{'form.'.$formname.'.filename'} and the
16724:            contents of the file is located in $env{'form.'.$formname}
16725:  context - if coursedoc, store the file in the course of the active role
16726:              of the current user; 
16727:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16728:            if 'canceloverwrite': delete file in tmp/overwrites directory
16729:  subdir - required - subdirectory to put the file in under ../userfiles/
16730:          if undefined, it will be placed in "unknown"
16731: 
16732:  (This routine calls clean_filename() to remove any dangerous
16733:  characters from the filename, and then calls finuserfileupload() to
16734:  complete the transaction)
16735: 
16736:  returns either the url of the uploaded file (/uploaded/....) if successful
16737:  and /adm/notfound.html if unsuccessful
16738: 
16739: =item *
16740: 
16741: clean_filename(): routine for cleaing a filename up for storage in
16742:                  userfile space, argument is:
16743: 
16744:  filename - proposed filename
16745: 
16746: returns: the new clean filename
16747: 
16748: =item *
16749: 
16750: finishuserfileupload(): routine that creates and sends the file to
16751: userspace, probably shouldn't be called directly
16752: 
16753:   docuname: username or courseid of destination for the file
16754:   docudom: domain of user/course of destination for the file
16755:   formname: same as for userfileupload()
16756:   fname: filename (including subdirectories) for the file
16757:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16758:           if hashref, and context is scantron, will convert csv format to standard format
16759:   allfiles: reference to hash used to store objects found by parser
16760:   codebase: reference to hash used for codebases of java objects found by parser
16761:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16762:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16763:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16764:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16765:   context: if 'overwrite', will move the uploaded file from its temporary location to
16766:             userfiles to facilitate overwriting a previously uploaded file with same name.
16767:   mimetype: reference to scalar to accommodate mime type determined
16768:             from File::MMagic if $parser = parse.
16769: 
16770:  returns either the url of the uploaded file (/uploaded/....) if successful
16771:  and /adm/notfound.html if unsuccessful (or an error message if context 
16772:  was 'overwrite').
16773:  
16774: 
16775: =item *
16776: 
16777: renameuserfile(): renames an existing userfile to a new name
16778: 
16779:   Args:
16780:    docuname: username or courseid of destination for the file
16781:    docudom: domain of user/course of destination for the file
16782:    old: current file name (including any subdirs under userfiles)
16783:    new: desired file name (including any subdirs under userfiles)
16784: 
16785: =item *
16786: 
16787: mkdiruserfile(): creates a directory is a userfiles dir
16788: 
16789:   Args:
16790:    docuname: username or courseid of destination for the file
16791:    docudom: domain of user/course of destination for the file
16792:    dir: dir to create (including any subdirs under userfiles)
16793: 
16794: =item *
16795: 
16796: removeuserfile(): removes a file that exists in userfiles
16797: 
16798:   Args:
16799:    docuname: username or courseid of destination for the file
16800:    docudom: domain of user/course of destination for the file
16801:    fname: filname to delete (including any subdirs under userfiles)
16802: 
16803: =item *
16804: 
16805: removeuploadedurl(): convience function for removeuserfile()
16806: 
16807:   Args:
16808:    url:  a full /uploaded/... url to delete
16809: 
16810: =item * 
16811: 
16812: get_portfile_permissions():
16813:   Args:
16814:     domain: domain of user or course contain the portfolio files
16815:     user: name of user or num of course contain the portfolio files
16816:   Returns:
16817:     hashref of a dump of the proper file_permissions.db
16818:    
16819: 
16820: =item * 
16821: 
16822: get_access_controls():
16823: 
16824: Args:
16825:   current_permissions: the hash ref returned from get_portfile_permissions()
16826:   group: (optional) the group you want the files associated with
16827:   file: (optional) the file you want access info on
16828: 
16829: Returns:
16830:     a hash (keys are file names) of hashes containing
16831:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16832:         values are XML containing access control settings (see below) 
16833: 
16834: Internal notes:
16835: 
16836:  access controls are stored in file_permissions.db as key=value pairs.
16837:     key -> path to file/file_name\0uniqueID:scope_end_start
16838:         where scope -> public,guest,course,group,domains or users.
16839:               end -> UNIX time for end of access (0 -> no end date)
16840:               start -> UNIX time for start of access
16841: 
16842:     value -> XML description of access control
16843:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16844:             <start></start>
16845:             <end></end>
16846: 
16847:             <password></password>  for scope type = guest
16848: 
16849:             <domain></domain>     for scope type = course or group
16850:             <number></number>
16851:             <roles id="">
16852:              <role></role>
16853:              <access></access>
16854:              <section></section>
16855:              <group></group>
16856:             </roles>
16857: 
16858:             <dom></dom>         for scope type = domains
16859: 
16860:             <users>             for scope type = users
16861:              <user>
16862:               <uname></uname>
16863:               <udom></udom>
16864:              </user>
16865:             </users>
16866:            </scope> 
16867:               
16868:  Access data is also aggregated for each file in an additional key=value pair:
16869:  key -> path to file/file_name\0accesscontrol 
16870:  value -> reference to hash
16871:           hash contains key = value pairs
16872:           where key = uniqueID:scope_end_start
16873:                 value = UNIX time record was last updated
16874: 
16875:           Used to improve speed of look-ups of access controls for each file.  
16876:  
16877:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16878: 
16879: =item *
16880: 
16881: modify_access_controls():
16882: 
16883: Modifies access controls for a portfolio file
16884: Args
16885: 1. file name
16886: 2. reference to hash of required changes,
16887: 3. domain
16888: 4. username
16889:   where domain,username are the domain of the portfolio owner 
16890:   (either a user or a course) 
16891: 
16892: Returns:
16893: 1. result of additions or updates ('ok' or 'error', with error message). 
16894: 2. result of deletions ('ok' or 'error', with error message).
16895: 3. reference to hash of any new or updated access controls.
16896: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16897:    key = integer (inbound ID)
16898:    value = uniqueID
16899: 
16900: =item *
16901: 
16902: get_timebased_id():
16903: 
16904: Attempts to get a unique timestamp-based suffix for use with items added to a 
16905: course via the Course Editor (e.g., folders, composite pages, 
16906: group bulletin boards).
16907: 
16908: Args: (first three required; six others optional)
16909: 
16910: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16911:    docssequence, or name of group
16912: 
16913: 2. keyid (alphanumeric): name of temporary locking key in hash,
16914:    e.g., num, boardids
16915: 
16916: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16917:    file will be named nohist_namespace.db
16918: 
16919: 4. cdom: domain of course; default is current course domain from %env
16920: 
16921: 5. cnum: course number; default is current course number from %env
16922: 
16923: 6. idtype: set to concat if an additional digit is to be appended to the 
16924:    unix timestamp to form the suffix, if the plain timestamp is already
16925:    in use.  Default is to not do this, but simply increment the unix 
16926:    timestamp by 1 until a unique key is obtained.
16927: 
16928: 7. who: holder of locking key; defaults to user:domain for user.
16929: 
16930: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16931:    retrying); default is 3.
16932: 
16933: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16934: 
16935: Returns:
16936: 
16937: 1. suffix obtained (numeric)
16938: 
16939: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16940: 
16941: 3. error: contains (localized) error message if an error occurred.
16942: 
16943: 
16944: =back
16945: 
16946: =head2 HTTP Helper Routines
16947: 
16948: =over 4
16949: 
16950: =item *
16951: 
16952: escape() : unpack non-word characters into CGI-compatible hex codes
16953: 
16954: =item *
16955: 
16956: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16957: 
16958: =back
16959: 
16960: =head1 PRIVATE SUBROUTINES
16961: 
16962: =head2 Underlying communication routines (Shouldn't call)
16963: 
16964: =over 4
16965: 
16966: =item *
16967: 
16968: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16969: 
16970: =item *
16971: 
16972: reply() : uses subreply to send a message to remote machine, logs all failures
16973: 
16974: =item *
16975: 
16976: critical() : passes a critical message to another server; if cannot
16977: get through then place message in connection buffer directory and
16978: returns con_delayed, if incapable of saving message, returns
16979: con_failed
16980: 
16981: =item *
16982: 
16983: reconlonc() : tries to reconnect lonc client processes.
16984: 
16985: =back
16986: 
16987: =head2 Resource Access Logging
16988: 
16989: =over 4
16990: 
16991: =item *
16992: 
16993: flushcourselogs() : flush (save) buffer logs and access logs
16994: 
16995: =item *
16996: 
16997: courselog($what) : save message for course in hash
16998: 
16999: =item *
17000: 
17001: courseacclog($what) : save message for course using &courselog().  Perform
17002: special processing for specific resource types (problems, exams, quizzes, etc).
17003: 
17004: =item *
17005: 
17006: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17007: as a PerlChildExitHandler
17008: 
17009: =back
17010: 
17011: =head2 Other
17012: 
17013: =over 4
17014: 
17015: =item *
17016: 
17017: symblist($mapname,%newhash) : update symbolic storage links
17018: 
17019: =back
17020: 
17021: =cut
17022: 

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