File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1480: download - view: text, annotated - select for diffs
Sun Feb 6 21:37:07 2022 UTC (2 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  - Domain default to determine whether LTI launch of deep-linked URL requires
    student to authenticate; can be overridden for specific course(s).
  - If domain config permits it, link protection setting in a course can
    specify whether to accept username included in LTI payload, and action
    to take if username is not for an enrolled student.
  - Second arg passed to ltiauth::invalid_request() is text string stating why
    LTI launch was invalid.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1480 2022/02/06 21:37:07 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 Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: # -------------------------------------------------- Non-critical communication
  419: sub subreply {
  420:     my ($cmd,$server)=@_;
  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  422:     #
  423:     #  With loncnew process trimming, there's a timing hole between lonc server
  424:     #  process exit and the master server picking up the listen on the AF_UNIX
  425:     #  socket.  In that time interval, a lock file will exist:
  426: 
  427:     my $lockfile=$peerfile.".lock";
  428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  429: 	sleep(0.1);
  430:     }
  431:     # At this point, either a loncnew parent is listening or an old lonc
  432:     # or loncnew child is listening so we can connect or everything's dead.
  433:     #
  434:     #   We'll give the connection a few tries before abandoning it.  If
  435:     #   connection is not possible, we'll con_lost back to the client.
  436:     #   
  437:     my $client;
  438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  440: 				      Type    => SOCK_STREAM,
  441: 				      Timeout => 10);
  442: 	if ($client) {
  443: 	    last;		# Connected!
  444: 	} else {
  445: 	    &create_connection(&hostname($server),$server);
  446: 	}
  447:         sleep(0.1);	# Try again later if failed connection.
  448:     }
  449:     my $answer;
  450:     if ($client) {
  451: 	print $client "sethost:$server:$cmd\n";
  452: 	$answer=<$client>;
  453: 	if (!$answer) { $answer="con_lost"; }
  454: 	chomp($answer);
  455:     } else {
  456: 	$answer = 'con_lost';	# Failed connection.
  457:     }
  458:     return $answer;
  459: }
  460: 
  461: sub reply {
  462:     my ($cmd,$server)=@_;
  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  464:     my $answer=subreply($cmd,$server);
  465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  466:         my $logged = $cmd;
  467:         if ($cmd =~ /^encrypt:([^:]+):/) {
  468:             my $subcmd = $1;
  469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  472:                 ($subcmd eq 'put')) {
  473:                 (undef,undef,my @rest) = split(/:/,$cmd);
  474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  475:                     splice(@rest,2,1,'Hidden');
  476:                 } elsif ($subcmd eq 'passwd') {
  477:                     splice(@rest,2,2,('Hidden','Hidden'));
  478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  480:                     splice(@rest,3,1,'Hidden');
  481:                 }
  482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  483:             }
  484:         }
  485:         &logthis("<font color=\"blue\">WARNING:".
  486:                  " $logged to $server returned $answer</font>");
  487:     }
  488:     return $answer;
  489: }
  490: 
  491: # ----------------------------------------------------------- Send USR1 to lonc
  492: 
  493: sub reconlonc {
  494:     my ($lonid) = @_;
  495:     if ($lonid) {
  496:         my $hostname = &hostname($lonid);
  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  498: 	if ($hostname && -e $peerfile) {
  499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  501: 					     Type    => SOCK_STREAM,
  502: 					     Timeout => 10);
  503: 	    if ($client) {
  504: 		print $client ("reset_retries\n");
  505: 		my $answer=<$client>;
  506: 		#reset just this one.
  507: 	    }
  508: 	}
  509: 	return;
  510:     }
  511: 
  512:     &logthis("Trying to reconnect lonc");
  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  514:     if (open(my $fh,"<",$loncfile)) {
  515: 	my $loncpid=<$fh>;
  516:         chomp($loncpid);
  517:         if (kill 0 => $loncpid) {
  518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  519:             kill USR1 => $loncpid;
  520:             sleep 1;
  521:         } else {
  522: 	    &logthis(
  523:                "<font color=\"blue\">WARNING:".
  524:                " lonc at pid $loncpid not responding, giving up</font>");
  525:         }
  526:     } else {
  527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  528:     }
  529: }
  530: 
  531: # ------------------------------------------------------ Critical communication
  532: 
  533: sub critical {
  534:     my ($cmd,$server)=@_;
  535:     unless (&hostname($server)) {
  536:         &logthis("<font color=\"blue\">WARNING:".
  537:                " Critical message to unknown server ($server)</font>");
  538:         return 'no_such_host';
  539:     }
  540:     my $answer=reply($cmd,$server);
  541:     if ($answer eq 'con_lost') {
  542: 	&reconlonc($server);
  543: 	my $answer=reply($cmd,$server);
  544:         if ($answer eq 'con_lost') {
  545:             my $now=time;
  546:             my $middlename=$cmd;
  547:             $middlename=substr($middlename,0,16);
  548:             $middlename=~s/\W//g;
  549:             my $dfilename=
  550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  551:             $dumpcount++;
  552:             {
  553: 		my $dfh;
  554: 		if (open($dfh,">",$dfilename)) {
  555: 		    print $dfh "$cmd\n"; 
  556: 		    close($dfh);
  557: 		}
  558:             }
  559:             sleep 1;
  560:             my $wcmd='';
  561:             {
  562: 		my $dfh;
  563: 		if (open($dfh,"<",$dfilename)) {
  564: 		    $wcmd=<$dfh>; 
  565: 		    close($dfh);
  566: 		}
  567:             }
  568:             chomp($wcmd);
  569:             if ($wcmd eq $cmd) {
  570: 		&logthis("<font color=\"blue\">WARNING: ".
  571:                          "Connection buffer $dfilename: $cmd</font>");
  572:                 &logperm("D:$server:$cmd");
  573: 	        return 'con_delayed';
  574:             } else {
  575:                 &logthis("<font color=\"red\">CRITICAL:"
  576:                         ." Critical connection failed: $server $cmd</font>");
  577:                 &logperm("F:$server:$cmd");
  578:                 return 'con_failed';
  579:             }
  580:         }
  581:     }
  582:     return $answer;
  583: }
  584: 
  585: # ------------------------------------------- check if return value is an error
  586: 
  587: sub error {
  588:     my ($result) = @_;
  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  590: 	if ($2 == 2) { return undef; }
  591: 	return $1;
  592:     }
  593:     return undef;
  594: }
  595: 
  596: sub convert_and_load_session_env {
  597:     my ($lonidsdir,$handle)=@_;
  598:     my @profile;
  599:     {
  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  601: 	if (!$opened) {
  602: 	    return 0;
  603: 	}
  604: 	flock($idf,LOCK_SH);
  605: 	@profile=<$idf>;
  606: 	close($idf);
  607:     }
  608:     my %temp_env;
  609:     foreach my $line (@profile) {
  610: 	if ($line !~ m/=/) {
  611: 	    return 0;
  612: 	}
  613: 	chomp($line);
  614: 	my ($envname,$envvalue)=split(/=/,$line,2);
  615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  616:     }
  617:     unlink("$lonidsdir/$handle.id");
  618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  619: 	    0640)) {
  620: 	%disk_env = %temp_env;
  621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  622: 	untie(%disk_env);
  623:     }
  624:     return 1;
  625: }
  626: 
  627: # ------------------------------------------- Transfer profile into environment
  628: my $env_loaded;
  629: sub transfer_profile_to_env {
  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
  631:     if (!$force_transfer && $env_loaded) { return; } 
  632: 
  633:     if (!defined($lonidsdir)) {
  634: 	$lonidsdir = $perlvar{'lonIDsDir'};
  635:     }
  636:     if (!defined($handle)) {
  637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  638:     }
  639: 
  640:     my $convert;
  641:     {
  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  643: 	if (!$opened) {
  644: 	    return;
  645: 	}
  646: 	flock($idf,LOCK_SH);
  647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  648: 		&GDBM_READER(),0640)) {
  649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  650: 	    untie(%disk_env);
  651: 	} else {
  652: 	    $convert = 1;
  653: 	}
  654:     }
  655:     if ($convert) {
  656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  657: 	    &logthis("Failed to load session, or convert session.");
  658: 	}
  659:     }
  660: 
  661:     my %remove;
  662:     while ( my $envname = each(%env) ) {
  663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  664:             if ($time < time-300) {
  665:                 $remove{$key}++;
  666:             }
  667:         }
  668:     }
  669: 
  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  671:     $env_loaded=1;
  672:     foreach my $expired_key (keys(%remove)) {
  673:         &delenv($expired_key);
  674:     }
  675: }
  676: 
  677: # ---------------------------------------------------- Check for valid session 
  678: sub check_for_valid_session {
  679:     my ($r,$name,$userhashref,$domref) = @_;
  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  682:     if ($name eq 'lonDAV') {
  683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  684:     } else {
  685:         $lonidsdir=$r->dir_config('lonIDsDir');
  686:         if ($name eq '') {
  687:             $name = 'lonID';
  688:         }
  689:     }
  690:     if ($name eq 'lonID') {
  691:         $secure = 'lonSID';
  692:         $linkname = 'lonLinkID';
  693:         $pubname = 'lonPubID';
  694:         if (exists($cookies{$secure})) {
  695:             $lonid=$cookies{$secure};
  696:         } elsif (exists($cookies{$name})) {
  697:             $lonid=$cookies{$name};
  698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  699:             $lonid=$cookies{$linkname};
  700:         } elsif (exists($cookies{$pubname})) {
  701:             $lonid=$cookies{$pubname};
  702:         }
  703:     } else {
  704:         $lonid=$cookies{$name};
  705:     }
  706:     return undef if (!$lonid);
  707: 
  708:     my $handle=&LONCAPA::clean_handle($lonid->value);
  709:     if (-l "$lonidsdir/$handle.id") {
  710:         my $link = readlink("$lonidsdir/$handle.id");
  711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  712:             $handle = $1;
  713:         }
  714:     }
  715:     if (!-e "$lonidsdir/$handle.id") {
  716:         if ((ref($domref)) && ($name eq 'lonID') && 
  717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  720:                 $$domref = $possudom;
  721:             }
  722:         }
  723:         return undef;
  724:     }
  725: 
  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  727:     return undef if (!$opened);
  728: 
  729:     flock($idf,LOCK_SH);
  730:     my %disk_env;
  731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  732: 	    &GDBM_READER(),0640)) {
  733: 	return undef;	
  734:     }
  735: 
  736:     if (!defined($disk_env{'user.name'})
  737: 	|| !defined($disk_env{'user.domain'})) {
  738:         untie(%disk_env);
  739: 	return undef;
  740:     }
  741: 
  742:     if (ref($userhashref) eq 'HASH') {
  743:         $userhashref->{'name'} = $disk_env{'user.name'};
  744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  745:         if ($disk_env{'request.role'}) {
  746:             $userhashref->{'role'} = $disk_env{'request.role'};
  747:         }
  748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  749:         if ($userhashref->{'lti'}) {
  750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  752:         }
  753:     }
  754:     untie(%disk_env);
  755: 
  756:     return $handle;
  757: }
  758: 
  759: sub timed_flock {
  760:     my ($file,$lock_type) = @_;
  761:     my $failed=0;
  762:     eval {
  763: 	local $SIG{__DIE__}='DEFAULT';
  764: 	local $SIG{ALRM}=sub {
  765: 	    $failed=1;
  766: 	    die("failed lock");
  767: 	};
  768: 	alarm(13);
  769: 	flock($file,$lock_type);
  770: 	alarm(0);
  771:     };
  772:     if ($failed) {
  773: 	return undef;
  774:     } else {
  775: 	return 1;
  776:     }
  777: }
  778: 
  779: sub get_sessionfile_vars {
  780:     my ($handle,$lonidsdir,$storearr) = @_;
  781:     my %returnhash;
  782:     unless (ref($storearr) eq 'ARRAY') {
  783:         return %returnhash;
  784:     }
  785:     if (-l "$lonidsdir/$handle.id") {
  786:         my $link = readlink("$lonidsdir/$handle.id");
  787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  788:             $handle = $1;
  789:         }
  790:     }
  791:     if ((-e "$lonidsdir/$handle.id") &&
  792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  796:                 flock($idf,LOCK_SH);
  797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  798:                         &GDBM_READER(),0640)) {
  799:                     foreach my $item (@{$storearr}) {
  800:                         $returnhash{$item} = $disk_env{$item};
  801:                     }
  802:                     untie(%disk_env);
  803:                 }
  804:             }
  805:         }
  806:     }
  807:     return %returnhash;
  808: }
  809: 
  810: # ---------------------------------------------------------- Append Environment
  811: 
  812: sub appenv {
  813:     my ($newenv,$roles) = @_;
  814:     if (ref($newenv) eq 'HASH') {
  815:         foreach my $key (keys(%{$newenv})) {
  816:             my $refused = 0;
  817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  818:                 $refused = 1;
  819:                 if (ref($roles) eq 'ARRAY') {
  820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  822:                         $refused = 0;
  823:                     }
  824:                 }
  825:             }
  826:             if ($refused) {
  827:                 &logthis("<font color=\"blue\">WARNING: ".
  828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  829:                          .'</font>');
  830: 	        delete($newenv->{$key});
  831:             } else {
  832:                 $env{$key}=$newenv->{$key};
  833:             }
  834:         }
  835:         my $lonids = $perlvar{'lonIDsDir'};
  836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  838:             if ($opened
  839: 	        && &timed_flock($env_file,LOCK_EX)
  840: 	        &&
  841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  843: 	        while (my ($key,$value) = each(%{$newenv})) {
  844: 	            $disk_env{$key} = $value;
  845: 	        }
  846: 	        untie(%disk_env);
  847:             }
  848:         }
  849:     }
  850:     return 'ok';
  851: }
  852: # ----------------------------------------------------- Delete from Environment
  853: 
  854: sub delenv {
  855:     my ($delthis,$regexp,$roles) = @_;
  856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  857:         my $refused = 1;
  858:         if (ref($roles) eq 'ARRAY') {
  859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  860:             if (grep(/^\Q$role\E$/,@{$roles})) {
  861:                 $refused = 0;
  862:             }
  863:         }
  864:         if ($refused) {
  865:             &logthis("<font color=\"blue\">WARNING: ".
  866:                      "Attempt to delete from environment ".$delthis);
  867:             return 'error';
  868:         }
  869:     }
  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  871:     if ($opened
  872: 	&& &timed_flock($env_file,LOCK_EX)
  873: 	&&
  874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  876: 	foreach my $key (keys(%disk_env)) {
  877: 	    if ($regexp) {
  878:                 if ($key=~/^$delthis/) {
  879:                     delete($env{$key});
  880:                     delete($disk_env{$key});
  881:                 } 
  882:             } else {
  883:                 if ($key=~/^\Q$delthis\E/) {
  884: 		    delete($env{$key});
  885: 		    delete($disk_env{$key});
  886: 	        }
  887:             }
  888: 	}
  889: 	untie(%disk_env);
  890:     }
  891:     return 'ok';
  892: }
  893: 
  894: sub get_env_multiple {
  895:     my ($name) = @_;
  896:     my @values;
  897:     if (defined($env{$name})) {
  898:         # exists is it an array
  899:         if (ref($env{$name})) {
  900:             @values=@{ $env{$name} };
  901:         } else {
  902:             $values[0]=$env{$name};
  903:         }
  904:     }
  905:     return(@values);
  906: }
  907: 
  908: # ------------------------------------------------------------------- Locking
  909: 
  910: sub set_lock {
  911:     my ($text)=@_;
  912:     $locknum++;
  913:     my $id=$$.'-'.$locknum;
  914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  915:              'session.lock.'.$id => $text});
  916:     return $id;
  917: }
  918: 
  919: sub get_locks {
  920:     my $num=0;
  921:     my %texts=();
  922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  923:        if ($lock=~/\w/) {
  924:           $num++;
  925:           $texts{$lock}=$env{'session.lock.'.$lock};
  926:        }
  927:    }
  928:    return ($num,%texts);
  929: }
  930: 
  931: sub remove_lock {
  932:     my ($id)=@_;
  933:     my $newlocks='';
  934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  935:        if (($lock=~/\w/) && ($lock ne $id)) {
  936:           $newlocks.=','.$lock;
  937:        }
  938:     }
  939:     &appenv({'session.locks' => $newlocks});
  940:     &delenv('session.lock.'.$id);
  941: }
  942: 
  943: sub remove_all_locks {
  944:     my $activelocks=$env{'session.locks'};
  945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  946:        if ($lock=~/\w/) {
  947:           &remove_lock($lock);
  948:        }
  949:     }
  950: }
  951: 
  952: 
  953: # ------------------------------------------ Find out current server userload
  954: sub userload {
  955:     my $numusers=0;
  956:     {
  957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  958: 	my $filename;
  959: 	my $curtime=time;
  960: 	while ($filename=readdir(LONIDS)) {
  961: 	    next if ($filename eq '.' || $filename eq '..');
  962: 	    next if ($filename =~ /publicuser_\d+\.id/);
  963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  966: 	}
  967: 	closedir(LONIDS);
  968:     }
  969:     my $userloadpercent=0;
  970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  971:     if ($maxuserload) {
  972: 	$userloadpercent=100*$numusers/$maxuserload;
  973:     }
  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  975:     return $userloadpercent;
  976: }
  977: 
  978: # ------------------------------ Find server with least workload from spare.tab
  979: 
  980: sub spareserver {
  981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  982:     my $spare_server;
  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  985:                                                      :  $userloadpercent;
  986:     my ($uint_dom,$remotesessions);
  987:     if (($udom ne '') && (&domain($udom) ne '')) {
  988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  991:         $remotesessions = $udomdefaults{'remotesessions'};
  992:     }
  993:     my $spareshash = &this_host_spares($udom);
  994:     if (ref($spareshash) eq 'HASH') {
  995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  998:                                              $try_server));
  999: 	        ($spare_server, $lowest_load) =
 1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1001:             }
 1002:         }
 1003: 
 1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1005: 
 1006:         if (!$found_server) {
 1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1009:                     next unless (&spare_can_host($udom,$uint_dom,
 1010:                                                  $remotesessions,$try_server));
 1011: 	            ($spare_server, $lowest_load) =
 1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1013:                 }
 1014: 	    }
 1015:         }
 1016:     }
 1017: 
 1018:     if (!$want_server_name) {
 1019:         if (defined($spare_server)) {
 1020:             my $hostname = &hostname($spare_server);
 1021:             if (defined($hostname)) {
 1022:                 my $protocol = 'http';
 1023:                 if ($protocol{$spare_server} eq 'https') {
 1024:                     $protocol = $protocol{$spare_server};
 1025:                 }
 1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
 1027:                 $hostname = $alias if ($alias ne '');
 1028: 	        $spare_server = $protocol.'://'.$hostname;
 1029:             }
 1030:         }
 1031:     }
 1032:     return $spare_server;
 1033: }
 1034: 
 1035: sub compare_server_load {
 1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1037: 
 1038:     if ($required) {
 1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1042:         if (($major eq '' && $minor eq '') ||
 1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1044:             return ($spare_server,$lowest_load);
 1045:         }
 1046:     }
 1047: 
 1048:     my $loadans     = &reply('load',    $try_server);
 1049:     my $userloadans = &reply('userload',$try_server);
 1050: 
 1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1053:     }
 1054: 
 1055:     my $load;
 1056:     if ($loadans =~ /\d/) {
 1057: 	if ($userloadans =~ /\d/) {
 1058: 	    #both are numbers, pick the bigger one
 1059: 	    $load = ($loadans > $userloadans) ? $loadans 
 1060: 		                              : $userloadans;
 1061: 	} else {
 1062: 	    $load = $loadans;
 1063: 	}
 1064:     } else {
 1065: 	$load = $userloadans;
 1066:     }
 1067: 
 1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1069: 	$spare_server = $try_server;
 1070: 	$lowest_load  = $load;
 1071:     }
 1072:     return ($spare_server,$lowest_load);
 1073: }
 1074: 
 1075: # --------------------------- ask offload servers if user already has a session
 1076: sub find_existing_session {
 1077:     my ($udom,$uname) = @_;
 1078:     my $spareshash = &this_host_spares($udom);
 1079:     if (ref($spareshash) eq 'HASH') {
 1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1083:             }
 1084:         }
 1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1088:             }
 1089:         }
 1090:     }
 1091:     return;
 1092: }
 1093: 
 1094: sub delusersession {
 1095:     my ($lonid,$udom,$uname) = @_;
 1096:     my $uprimary_id = &domain($udom,'primary');
 1097:     my $uintdom = &internet_dom($uprimary_id);
 1098:     my $intdom = &internet_dom($lonid);
 1099:     my $serverhomedom = &host_domain($lonid);
 1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1101:         return &reply(join(':','delusersession',
 1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1103:     }
 1104:     return;
 1105: }
 1106: 
 1107: # check if user's browser sent load balancer cookie and server still has session
 1108: # and is not overloaded.
 1109: sub check_for_balancer_cookie {
 1110:     my ($r,$update_mtime) = @_;
 1111:     my ($otherserver,$cookie);
 1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1113:     if (exists($cookies{'balanceID'})) {
 1114:         my $balid = $cookies{'balanceID'};
 1115:         $cookie=&LONCAPA::clean_handle($balid->value);
 1116:         my $balancedir=$r->dir_config('lonBalanceDir');
 1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1119:                 my ($possudom,$possuname) = ($1,$2);
 1120:                 my $has_session = 0;
 1121:                 if ((&domain($possudom) ne '') &&
 1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1123:                     my $try_server;
 1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1125:                     if ($opened) {
 1126:                         flock($idf,LOCK_SH);
 1127:                         while (my $line = <$idf>) {
 1128:                             chomp($line);
 1129:                             if (&hostname($line) ne '') {
 1130:                                 $try_server = $line;
 1131:                                 last;
 1132:                             }
 1133:                         }
 1134:                         close($idf);
 1135:                         if (($try_server) &&
 1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1137:                             my $lowest_load = 30000;
 1138:                             ($otherserver,$lowest_load) =
 1139:                                 &compare_server_load($try_server,undef,$lowest_load);
 1140:                             if ($otherserver ne '' && $lowest_load < 100) {
 1141:                                 $has_session = 1;
 1142:                             } else {
 1143:                                 undef($otherserver);
 1144:                             }
 1145:                         }
 1146:                     }
 1147:                 }
 1148:                 if ($has_session) {
 1149:                     if ($update_mtime) {
 1150:                         my $atime = my $mtime = time;
 1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1152:                     }
 1153:                 } else {
 1154:                     unlink("$balancedir/$cookie.id");
 1155:                 }
 1156:             }
 1157:         }
 1158:     }
 1159:     return ($otherserver,$cookie);
 1160: }
 1161: 
 1162: sub updatebalcookie {
 1163:     my ($cookie,$balancer,$lastentry)=@_;
 1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1165:         my ($udom,$uname) = ($1,$2);
 1166:         my $uprimary_id = &domain($udom,'primary');
 1167:         my $uintdom = &internet_dom($uprimary_id);
 1168:         my $intdom = &internet_dom($balancer);
 1169:         my $serverhomedom = &host_domain($balancer);
 1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1172:         }
 1173:     }
 1174:     return;
 1175: }
 1176: 
 1177: sub delbalcookie {
 1178:     my ($cookie,$balancer) =@_;
 1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1180:         my ($udom,$uname) = ($1,$2);
 1181:         my $uprimary_id = &domain($udom,'primary');
 1182:         my $uintdom = &internet_dom($uprimary_id);
 1183:         my $intdom = &internet_dom($balancer);
 1184:         my $serverhomedom = &host_domain($balancer);
 1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1187:         }
 1188:     }
 1189: }
 1190: 
 1191: # -------------------------------- ask if server already has a session for user
 1192: sub has_user_session {
 1193:     my ($lonid,$udom,$uname) = @_;
 1194:     my $result = &reply(join(':','userhassession',
 1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1196:     return 1 if ($result eq 'ok');
 1197: 
 1198:     return 0;
 1199: }
 1200: 
 1201: # --------- determine least loaded server in a user's domain which allows login
 1202: 
 1203: sub choose_server {
 1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1206:     my %servers = &get_servers($udom);
 1207:     my $lowest_load = 30000;
 1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1209:     if ($skiploadbal) {
 1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1211:         unless (defined($cached)) {
 1212:             my $cachetime = 60*60*24;
 1213:             my %domconfig =
 1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1217:                                            $cachetime);
 1218:             }
 1219:         }
 1220:     }
 1221:     foreach my $lonhost (keys(%servers)) {
 1222:         if ($skiploadbal) {
 1223:             if (ref($balancers) eq 'HASH') {
 1224:                 next if (exists($balancers->{$lonhost}));
 1225:             }
 1226:         }
 1227:         my $loginvia;
 1228:         if ($checkloginvia) {
 1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1230:             if ($loginvia) {
 1231:                 my ($server,$path) = split(/:/,$loginvia);
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $server) {
 1235:                     $portal_path = $path;
 1236:                     $isredirect = 1;
 1237:                 }
 1238:             } else {
 1239:                 ($login_host, $lowest_load) =
 1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1241:                 if ($login_host eq $lonhost) {
 1242:                     $portal_path = '';
 1243:                     $isredirect = ''; 
 1244:                 }
 1245:             }
 1246:         } else {
 1247:             ($login_host, $lowest_load) =
 1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1249:         }
 1250:     }
 1251:     if ($login_host ne '') {
 1252:         $hostname = &hostname($login_host);
 1253:     }
 1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1255: }
 1256: 
 1257: sub get_course_sessions {
 1258:     my ($cnum,$cdom,$lastactivity) = @_;
 1259:     my %servers = &internet_dom_servers($cdom);
 1260:     my %returnhash;
 1261:     foreach my $server (sort(keys(%servers))) {
 1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1263:         my @pairs=split(/\&/,$rep);
 1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1265:             foreach my $item (@pairs) {
 1266:                 my ($key,$value)=split(/=/,$item,2);
 1267:                 $key = &unescape($key);
 1268:                 next if ($key =~ /^error: 2 /);
 1269:                 if (exists($returnhash{$key})) {
 1270:                     next if ($value < $returnhash{$key});
 1271:                 }
 1272:                 $returnhash{$key}=$value;
 1273:             }
 1274:         }
 1275:     }
 1276:     return %returnhash;
 1277: }
 1278: 
 1279: # --------------------------------------------- Try to change a user's password
 1280: 
 1281: sub changepass {
 1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1283:     $currentpass = &escape($currentpass);
 1284:     $newpass     = &escape($newpass);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1287: 		       $server);
 1288:     if (! $answer) {
 1289: 	&logthis("No reply on password change request to $server ".
 1290: 		 "by $uname in domain $udom.");
 1291:     } elsif ($answer =~ "^ok") {
 1292:         &logthis("$uname in $udom successfully changed their password ".
 1293: 		 "on $server.");
 1294:     } elsif ($answer =~ "^pwchange_failure") {
 1295: 	&logthis("$uname in $udom was unable to change their password ".
 1296: 		 "on $server.  The action was blocked by either lcpasswd ".
 1297: 		 "or pwchange");
 1298:     } elsif ($answer =~ "^non_authorized") {
 1299:         &logthis("$uname in $udom did not get their password correct when ".
 1300: 		 "attempting to change it on $server.");
 1301:     } elsif ($answer =~ "^auth_mode_error") {
 1302:         &logthis("$uname in $udom attempted to change their password despite ".
 1303: 		 "not being locally or internally authenticated on $server.");
 1304:     } elsif ($answer =~ "^unknown_user") {
 1305:         &logthis("$uname in $udom attempted to change their password ".
 1306: 		 "on $server but were unable to because $server is not ".
 1307: 		 "their home server.");
 1308:     } elsif ($answer =~ "^refused") {
 1309: 	&logthis("$server refused to change $uname in $udom password because ".
 1310: 		 "it was sent an unencrypted request to change the password.");
 1311:     } elsif ($answer =~ "invalid_client") {
 1312:         &logthis("$server refused to change $uname in $udom password because ".
 1313:                  "it was a reset by e-mail originating from an invalid server.");
 1314:     } elsif ($answer =~ "^prioruse") {
 1315:        &logthis("$server refused to change $uname in $udom password because ".
 1316:                 "the password had been used before");
 1317:     }
 1318:     return $answer;
 1319: }
 1320: 
 1321: # ----------------------- Try to determine user's current authentication scheme
 1322: 
 1323: sub queryauthenticate {
 1324:     my ($uname,$udom)=@_;
 1325:     my $uhome=&homeserver($uname,$udom);
 1326:     if (!$uhome) {
 1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1328: 	return 'no_host';
 1329:     }
 1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1333:     }
 1334:     return $answer;
 1335: }
 1336: 
 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
 1338: 
 1339: sub authenticate {
 1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1341:     $upass=&escape($upass);
 1342:     $uname= &LONCAPA::clean_username($uname);
 1343:     my $uhome=&homeserver($uname,$udom,1);
 1344:     my $newhome;
 1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1346: # Maybe the machine was offline and only re-appeared again recently?
 1347:         &reconlonc();
 1348: # One more
 1349: 	$uhome=&homeserver($uname,$udom,1);
 1350:         if (($uhome eq 'no_host') && $checkdefauth) {
 1351:             if (defined(&domain($udom,'primary'))) {
 1352:                 $newhome=&domain($udom,'primary');
 1353:             }
 1354:             if ($newhome ne '') {
 1355:                 $uhome = $newhome;
 1356:             }
 1357:         }
 1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1360: 	    return 'no_host';
 1361:         }
 1362:     }
 1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1364:     if ($answer eq 'authorized') {
 1365:         if ($newhome) {
 1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1367:             return 'no_account_on_host'; 
 1368:         } else {
 1369:             &logthis("User $uname at $udom authorized by $uhome");
 1370:             return $uhome;
 1371:         }
 1372:     }
 1373:     if ($answer eq 'non_authorized') {
 1374: 	&logthis("User $uname at $udom rejected by $uhome");
 1375: 	return 'no_host'; 
 1376:     }
 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1378:     return 'no_host';
 1379: }
 1380: 
 1381: sub can_host_session {
 1382:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1383:     my $canhost = 1;
 1384:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1385:     if (ref($remotesessions) eq 'HASH') {
 1386:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1388:                 $canhost = 0;
 1389:             } else {
 1390:                 $canhost = 1;
 1391:             }
 1392:         }
 1393:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1394:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1395:                 $canhost = 1;
 1396:             } else {
 1397:                 $canhost = 0;
 1398:             }
 1399:         }
 1400:         if ($canhost) {
 1401:             if ($remotesessions->{'version'} ne '') {
 1402:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1403:                 if ($reqmajor ne '' && $reqminor ne '') {
 1404:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1405:                         my $major = $1;
 1406:                         my $minor = $2;
 1407:                         if (($major < $reqmajor ) ||
 1408:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1409:                             $canhost = 0;
 1410:                         }
 1411:                     } else {
 1412:                         $canhost = 0;
 1413:                     }
 1414:                 }
 1415:             }
 1416:         }
 1417:     }
 1418:     if ($canhost) {
 1419:         if (ref($hostedsessions) eq 'HASH') {
 1420:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1421:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1422:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1423:                 if (($uint_dom ne '') && 
 1424:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1425:                     $canhost = 0;
 1426:                 } else {
 1427:                     $canhost = 1;
 1428:                 }
 1429:             }
 1430:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1431:                 if (($uint_dom ne '') && 
 1432:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1433:                     $canhost = 1;
 1434:                 } else {
 1435:                     $canhost = 0;
 1436:                 }
 1437:             }
 1438:         }
 1439:     }
 1440:     return $canhost;
 1441: }
 1442: 
 1443: sub spare_can_host {
 1444:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1445:     my $canhost=1;
 1446:     my $try_server_hostname = &hostname($try_server);
 1447:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1448:     my $serverhomedom = &host_domain($serverhomeID);
 1449:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1450:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1451:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1452:             $canhost = 0;
 1453:         }
 1454:     }
 1455:     if ($canhost) {
 1456:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1457:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1458:                 unless (&shared_institution($udom,$try_server)) {
 1459:                     $canhost = 0;
 1460:                 }
 1461:             }
 1462:         }
 1463:     }
 1464:     if (($canhost) && ($uint_dom)) {
 1465:         my @intdoms;
 1466:         my $internet_names = &get_internet_names($try_server);
 1467:         if (ref($internet_names) eq 'ARRAY') {
 1468:             @intdoms = @{$internet_names};
 1469:         }
 1470:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1471:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1472:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1473:                                          $remotesessions,
 1474:                                          $defdomdefaults{'hostedsessions'});
 1475:         }
 1476:     }
 1477:     return $canhost;
 1478: }
 1479: 
 1480: sub this_host_spares {
 1481:     my ($dom) = @_;
 1482:     my ($dom_in_use,$lonhost_in_use,$result);
 1483:     my @hosts = &current_machine_ids();
 1484:     foreach my $lonhost (@hosts) {
 1485:         if (&host_domain($lonhost) eq $dom) {
 1486:             $dom_in_use = $dom;
 1487:             $lonhost_in_use = $lonhost;
 1488:             last;
 1489:         }
 1490:     }
 1491:     if ($dom_in_use ne '') {
 1492:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1493:     }
 1494:     if (ref($result) ne 'HASH') {
 1495:         $lonhost_in_use = $perlvar{'lonHostID'};
 1496:         $dom_in_use = &host_domain($lonhost_in_use);
 1497:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1498:         if (ref($result) ne 'HASH') {
 1499:             $result = \%spareid;
 1500:         }
 1501:     }
 1502:     return $result;
 1503: }
 1504: 
 1505: sub spares_for_offload  {
 1506:     my ($dom_in_use,$lonhost_in_use) = @_;
 1507:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1508:     if (defined($cached)) {
 1509:         return $result;
 1510:     } else {
 1511:         my $cachetime = 60*60*24;
 1512:         my %domconfig =
 1513:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1514:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1515:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1516:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1517:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1518:                 }
 1519:             }
 1520:         }
 1521:     }
 1522:     return;
 1523: }
 1524: 
 1525: sub get_lonbalancer_config {
 1526:     my ($servers) = @_;
 1527:     my ($currbalancer,$currtargets);
 1528:     if (ref($servers) eq 'HASH') {
 1529:         foreach my $server (keys(%{$servers})) {
 1530:             my %what = (
 1531:                          spareid => 1,
 1532:                          perlvar => 1,
 1533:                        );
 1534:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1535:             if ($result eq 'ok') {
 1536:                 if (ref($returnhash) eq 'HASH') {
 1537:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1538:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1539:                             $currbalancer = $server;
 1540:                             $currtargets = {};
 1541:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1542:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1543:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1544:                                 }
 1545:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1546:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1547:                                 }
 1548:                             }
 1549:                             last;
 1550:                         }
 1551:                     }
 1552:                 }
 1553:             }
 1554:         }
 1555:     }
 1556:     return ($currbalancer,$currtargets);
 1557: }
 1558: 
 1559: sub check_loadbalancing {
 1560:     my ($uname,$udom,$caller) = @_;
 1561:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1562:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1563:     my $lonhost = $perlvar{'lonHostID'};
 1564:     my @hosts = &current_machine_ids();
 1565:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1566:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1567:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1568:     my $serverhomedom = &host_domain($lonhost);
 1569:     my $domneedscache;
 1570:     my $cachetime = 60*60*24;
 1571: 
 1572:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1573:         $dom_in_use = $udom;
 1574:         $homeintdom = 1;
 1575:     } else {
 1576:         $dom_in_use = $serverhomedom;
 1577:     }
 1578:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1579:     unless (defined($cached)) {
 1580:         my %domconfig =
 1581:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1582:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1583:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1584:         } else {
 1585:             $domneedscache = $dom_in_use;
 1586:         }
 1587:     }
 1588:     if (ref($result) eq 'HASH') {
 1589:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1590:             &check_balancer_result($result,@hosts);
 1591:         if ($is_balancer) {
 1592:             if (ref($currrules) eq 'HASH') {
 1593:                 if ($homeintdom) {
 1594:                     if ($uname ne '') {
 1595:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1596:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1597:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1598:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1599:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1600:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1601:                             }
 1602:                         }
 1603:                         if ($rule_in_effect eq '') {
 1604:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1605:                             if ($userenv{'inststatus'} ne '') {
 1606:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1607:                                 my ($othertitle,$usertypes,$types) =
 1608:                                     &Apache::loncommon::sorted_inst_types($udom);
 1609:                                 if (ref($types) eq 'ARRAY') {
 1610:                                     foreach my $type (@{$types}) {
 1611:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1612:                                             if (exists($currrules->{$type})) {
 1613:                                                 $rule_in_effect = $currrules->{$type};
 1614:                                             }
 1615:                                         }
 1616:                                     }
 1617:                                 }
 1618:                             } else {
 1619:                                 if (exists($currrules->{'default'})) {
 1620:                                     $rule_in_effect = $currrules->{'default'};
 1621:                                 }
 1622:                             }
 1623:                         }
 1624:                     } else {
 1625:                         if (exists($currrules->{'default'})) {
 1626:                             $rule_in_effect = $currrules->{'default'};
 1627:                         }
 1628:                     }
 1629:                 } else {
 1630:                     if ($currrules->{'_LC_external'} ne '') {
 1631:                         $rule_in_effect = $currrules->{'_LC_external'};
 1632:                     }
 1633:                 }
 1634:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1635:                                                        $uname,$udom);
 1636:             }
 1637:         }
 1638:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1639:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1640:         unless (defined($cached)) {
 1641:             my %domconfig =
 1642:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1643:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1644:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1645:             } else {
 1646:                 $domneedscache = $serverhomedom;
 1647:             }
 1648:         }
 1649:         if (ref($result) eq 'HASH') {
 1650:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1651:                 &check_balancer_result($result,@hosts);
 1652:             if ($is_balancer) {
 1653:                 if (ref($currrules) eq 'HASH') {
 1654:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1655:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1656:                     }
 1657:                 }
 1658:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1659:                                                        $uname,$udom);
 1660:             }
 1661:         } else {
 1662:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1663:                 $is_balancer = 1;
 1664:                 $offloadto = &this_host_spares($dom_in_use);
 1665:             }
 1666:             unless (defined($cached)) {
 1667:                 $domneedscache = $serverhomedom;
 1668:             }
 1669:         }
 1670:     } else {
 1671:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1672:             $is_balancer = 1;
 1673:             $offloadto = &this_host_spares($dom_in_use);
 1674:         }
 1675:         unless (defined($cached)) {
 1676:             $domneedscache = $serverhomedom;
 1677:         }
 1678:     }
 1679:     if ($domneedscache) {
 1680:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1681:     }
 1682:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1683:         my $lowest_load = 30000;
 1684:         if (ref($offloadto) eq 'HASH') {
 1685:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1686:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1687:                     ($otherserver,$lowest_load) =
 1688:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1689:                 }
 1690:             }
 1691:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1692: 
 1693:             if (!$found_server) {
 1694:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1695:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1696:                         ($otherserver,$lowest_load) =
 1697:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1698:                     }
 1699:                 }
 1700:             }
 1701:         } elsif (ref($offloadto) eq 'ARRAY') {
 1702:             if (@{$offloadto} == 1) {
 1703:                 $otherserver = $offloadto->[0];
 1704:             } elsif (@{$offloadto} > 1) {
 1705:                 foreach my $try_server (@{$offloadto}) {
 1706:                     ($otherserver,$lowest_load) =
 1707:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1708:                 }
 1709:             }
 1710:         }
 1711:         unless ($caller eq 'login') {
 1712:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1713:                 $is_balancer = 0;
 1714:                 if ($uname ne '' && $udom ne '') {
 1715:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1716:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1717:                                  'user.loadbalcheck.time' => time});
 1718:                     }
 1719:                 }
 1720:             }
 1721:         }
 1722:     }
 1723:     if (($is_balancer) && (!$homeintdom)) {
 1724:         undef($setcookie);
 1725:     }
 1726:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1727: }
 1728: 
 1729: sub check_balancer_result {
 1730:     my ($result,@hosts) = @_;
 1731:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1732:     if (ref($result) eq 'HASH') {
 1733:         if ($result->{'lonhost'} ne '') {
 1734:             my $currbalancer = $result->{'lonhost'};
 1735:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1736:                 $is_balancer = 1;
 1737:                 $currtargets = $result->{'targets'};
 1738:                 $currrules = $result->{'rules'};
 1739:             }
 1740:             $dom_balancers = $currbalancer;
 1741:         } else {
 1742:             if (keys(%{$result})) {
 1743:                 foreach my $key (keys(%{$result})) {
 1744:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1745:                         (ref($result->{$key}) eq 'HASH')) {
 1746:                         $is_balancer = 1;
 1747:                         $currrules = $result->{$key}{'rules'};
 1748:                         $currtargets = $result->{$key}{'targets'};
 1749:                         $setcookie = $result->{$key}{'cookie'};
 1750:                         last;
 1751:                     }
 1752:                 }
 1753:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1754:             }
 1755:         }
 1756:     }
 1757:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1758: }
 1759: 
 1760: sub get_loadbalancer_targets {
 1761:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1762:     my $offloadto;
 1763:     if ($rule_in_effect eq 'none') {
 1764:         return [$perlvar{'lonHostID'}];
 1765:     } elsif ($rule_in_effect eq '') {
 1766:         $offloadto = $currtargets;
 1767:     } else {
 1768:         if ($rule_in_effect eq 'homeserver') {
 1769:             my $homeserver = &homeserver($uname,$udom);
 1770:             if ($homeserver ne 'no_host') {
 1771:                 $offloadto = [$homeserver];
 1772:             }
 1773:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1774:             my %domconfig =
 1775:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1776:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1777:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1778:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1779:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1780:                     }
 1781:                 }
 1782:             } else {
 1783:                 my %servers = &internet_dom_servers($udom);
 1784:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1785:                 if (&hostname($remotebalancer) ne '') {
 1786:                     $offloadto = [$remotebalancer];
 1787:                 }
 1788:             }
 1789:         } elsif (&hostname($rule_in_effect) ne '') {
 1790:             $offloadto = [$rule_in_effect];
 1791:         }
 1792:     }
 1793:     return $offloadto;
 1794: }
 1795: 
 1796: sub internet_dom_servers {
 1797:     my ($dom) = @_;
 1798:     my (%uniqservers,%servers);
 1799:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1800:     my @machinedoms = &machine_domains($primaryserver);
 1801:     foreach my $mdom (@machinedoms) {
 1802:         my %currservers = %servers;
 1803:         my %server = &get_servers($mdom);
 1804:         %servers = (%currservers,%server);
 1805:     }
 1806:     my %by_hostname;
 1807:     foreach my $id (keys(%servers)) {
 1808:         push(@{$by_hostname{$servers{$id}}},$id);
 1809:     }
 1810:     foreach my $hostname (sort(keys(%by_hostname))) {
 1811:         if (@{$by_hostname{$hostname}} > 1) {
 1812:             my $match = 0;
 1813:             foreach my $id (@{$by_hostname{$hostname}}) {
 1814:                 if (&host_domain($id) eq $dom) {
 1815:                     $uniqservers{$id} = $hostname;
 1816:                     $match = 1;
 1817:                 }
 1818:             }
 1819:             unless ($match) {
 1820:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1821:             }
 1822:         } else {
 1823:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1824:         }
 1825:     }
 1826:     return %uniqservers;
 1827: }
 1828: 
 1829: sub trusted_domains {
 1830:     my ($cmdtype,$calldom) = @_;
 1831:     my ($trusted,$untrusted);
 1832:     if (&domain($calldom) eq '') {
 1833:         return ($trusted,$untrusted);
 1834:     }
 1835:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1836:         return ($trusted,$untrusted);
 1837:     }
 1838:     my $callprimary = &domain($calldom,'primary');
 1839:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1840:     if ($intcalldom eq '') {
 1841:         return ($trusted,$untrusted);
 1842:     }
 1843: 
 1844:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1845:     unless (defined($cached)) {
 1846:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1847:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1848:         $trustconfig = $domconfig{'trust'};
 1849:     }
 1850:     if (ref($trustconfig)) {
 1851:         my (%possexc,%possinc,@allexc,@allinc); 
 1852:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1853:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1854:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1855:             }
 1856:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1857:                 $possinc{$intcalldom} = 1;
 1858:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1859:             }
 1860:         }
 1861:         if (keys(%possexc)) {
 1862:             if (keys(%possinc)) {
 1863:                 foreach my $key (sort(keys(%possexc))) {
 1864:                     next if ($key eq $intcalldom);
 1865:                     unless ($possinc{$key}) {
 1866:                         push(@allexc,$key);
 1867:                     }
 1868:                 }
 1869:             } else {
 1870:                 @allexc = sort(keys(%possexc));
 1871:             }
 1872:         }
 1873:         if (keys(%possinc)) {
 1874:             $possinc{$intcalldom} = 1;
 1875:             @allinc = sort(keys(%possinc));
 1876:         }
 1877:         if ((@allexc > 0) || (@allinc > 0)) {
 1878:             my %doms_by_intdom;
 1879:             my %allintdoms = &all_host_intdom();
 1880:             my %alldoms = &all_host_domain();
 1881:             foreach my $key (%allintdoms) {
 1882:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1883:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1884:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1885:                     }
 1886:                 } else {
 1887:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1888:                 }
 1889:             }
 1890:             foreach my $exc (@allexc) {
 1891:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1892:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1893:                 }
 1894:             }
 1895:             foreach my $inc (@allinc) {
 1896:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1897:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1898:                 }
 1899:             }
 1900:         }
 1901:     }
 1902:     return ($trusted,$untrusted);
 1903: }
 1904: 
 1905: sub will_trust {
 1906:     my ($cmdtype,$domain,$possdom) = @_;
 1907:     return 1 if ($domain eq $possdom);
 1908:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1909:     my $willtrust; 
 1910:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1911:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1912:             $willtrust = 1;
 1913:         }
 1914:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1915:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1916:             $willtrust = 1;
 1917:         }
 1918:     } else {
 1919:         $willtrust = 1;
 1920:     }
 1921:     return $willtrust;
 1922: }
 1923: 
 1924: # ---------------------- Find the homebase for a user from domain's lib servers
 1925: 
 1926: my %homecache;
 1927: sub homeserver {
 1928:     my ($uname,$udom,$ignoreBadCache)=@_;
 1929:     my $index="$uname:$udom";
 1930: 
 1931:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1932: 
 1933:     my %servers = &get_servers($udom,'library');
 1934:     foreach my $tryserver (keys(%servers)) {
 1935:         next if ($ignoreBadCache ne 'true' && 
 1936: 		 exists($badServerCache{$tryserver}));
 1937: 
 1938: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1939: 	if ($answer eq 'found') {
 1940: 	    delete($badServerCache{$tryserver}); 
 1941: 	    return $homecache{$index}=$tryserver;
 1942: 	} elsif ($answer eq 'no_host') {
 1943: 	    $badServerCache{$tryserver}=1;
 1944: 	}
 1945:     }    
 1946:     return 'no_host';
 1947: }
 1948: 
 1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1950: 
 1951: sub idget {
 1952:     my ($udom,$idsref,$namespace)=@_;
 1953:     my %returnhash=();
 1954:     my @ids=(); 
 1955:     if (ref($idsref) eq 'ARRAY') {
 1956:         @ids = @{$idsref};
 1957:     } else {
 1958:         return %returnhash; 
 1959:     }
 1960:     if ($namespace eq '') {
 1961:         $namespace = 'ids';
 1962:     }
 1963:     
 1964:     my %servers = &get_servers($udom,'library');
 1965:     foreach my $tryserver (keys(%servers)) {
 1966: 	my $idlist=join('&', map { &escape($_); } @ids);
 1967: 	if ($namespace eq 'ids') {
 1968: 	    $idlist=~tr/A-Z/a-z/;
 1969: 	}
 1970: 	my $reply;
 1971: 	if ($namespace eq 'ids') {
 1972: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1973: 	} else {
 1974: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1975: 	}
 1976: 	my @answer=();
 1977: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1978: 	    @answer=split(/\&/,$reply);
 1979: 	}                    ;
 1980: 	my $i;
 1981: 	for ($i=0;$i<=$#ids;$i++) {
 1982: 	    if ($answer[$i]) {
 1983: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1984: 	    }
 1985: 	}
 1986:     }
 1987:     return %returnhash;
 1988: }
 1989: 
 1990: # ------------------------------------- Find the IDs behind a list of usernames
 1991: 
 1992: sub idrget {
 1993:     my ($udom,@unames)=@_;
 1994:     my %returnhash=();
 1995:     foreach my $uname (@unames) {
 1996:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1997:     }
 1998:     return %returnhash;
 1999: }
 2000: 
 2001: # Store away a list of names and associated student/employee IDs or clicker IDs
 2002: 
 2003: sub idput {
 2004:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2005:     my %servers=();
 2006:     my %ids=();
 2007:     my %byid = ();
 2008:     if (ref($idsref) eq 'HASH') {
 2009:         %ids=%{$idsref};
 2010:     }
 2011:     if ($namespace eq '') {
 2012:         $namespace = 'ids'; 
 2013:     }
 2014:     foreach my $uname (keys(%ids)) {
 2015: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2016:         if ($uhom eq '') {
 2017:             $uhom=&homeserver($uname,$udom);
 2018:         }
 2019:         if ($uhom ne 'no_host') {
 2020:             my $esc_unam=&escape($uname);
 2021:             if ($namespace eq 'ids') {
 2022:                 my $id=&escape($ids{$uname});
 2023:                 $id=~tr/A-Z/a-z/;
 2024:                 my $esc_unam=&escape($uname);
 2025:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2026:             } else {
 2027:                 my @currids = split(/,/,$ids{$uname});
 2028:                 foreach my $id (@currids) {
 2029:                     $byid{$uhom}{$id} .= $uname.',';
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     if ($namespace eq 'clickers') {
 2035:         foreach my $server (keys(%byid)) {
 2036:             if (ref($byid{$server}) eq 'HASH') {
 2037:                 foreach my $id (keys(%{$byid{$server}})) {
 2038:                     $byid{$server} =~ s/,$//;
 2039:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2040:                 }
 2041:             }
 2042:         }
 2043:     }
 2044:     foreach my $server (keys(%servers)) {
 2045:         $servers{$server} =~ s/\&$//;
 2046:         if ($namespace eq 'ids') {     
 2047:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2048:         } else {
 2049:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2050:         }
 2051:     }
 2052: }
 2053: 
 2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2055: 
 2056: sub iddel {
 2057:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2058:     my %result=();
 2059:     my %ids=();
 2060:     my %byid = ();
 2061:     if (ref($idshashref) eq 'HASH') {
 2062:         %ids=%{$idshashref};
 2063:     } else {
 2064:         return %result;
 2065:     }
 2066:     if ($namespace eq '') {
 2067:         $namespace = 'ids';
 2068:     }
 2069:     my %servers=();
 2070:     while (my ($id,$unamestr) = each(%ids)) {
 2071:         if ($namespace eq 'ids') {
 2072:             my $uhom = $uhome;
 2073:             if ($uhom eq '') { 
 2074:                 $uhom=&homeserver($unamestr,$udom);
 2075:             }
 2076:             if ($uhom ne 'no_host') {
 2077:                 $servers{$uhom}.='&'.&escape($id);
 2078:             }
 2079:          } else {
 2080:             my @curritems = split(/,/,$ids{$id});
 2081:             foreach my $uname (@curritems) {
 2082:                 my $uhom = $uhome;
 2083:                 if ($uhom eq '') {
 2084:                     $uhom=&homeserver($uname,$udom);
 2085:                 }
 2086:                 if ($uhom ne 'no_host') { 
 2087:                     $byid{$uhom}{$id} .= $uname.',';
 2088:                 }
 2089:             }
 2090:         }
 2091:     }
 2092:     if ($namespace eq 'clickers') {
 2093:         foreach my $server (keys(%byid)) {
 2094:             if (ref($byid{$server}) eq 'HASH') {
 2095:                 foreach my $id (keys(%{$byid{$server}})) {
 2096:                     $byid{$server}{$id} =~ s/,$//;
 2097:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2098:                 }
 2099:             }
 2100:         }
 2101:     }
 2102:     foreach my $server (keys(%servers)) {
 2103:         $servers{$server} =~ s/\&$//;
 2104:         if ($namespace eq 'ids') {
 2105:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2106:         } elsif ($namespace eq 'clickers') {
 2107:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2108:         }
 2109:     }
 2110:     return %result;
 2111: }
 2112: 
 2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2114: 
 2115: sub updateclickers {
 2116:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2117:     my %clickers;
 2118:     if (ref($idshashref) eq 'HASH') {
 2119:         %clickers=%{$idshashref};
 2120:     } else {
 2121:         return;
 2122:     }
 2123:     my $items='';
 2124:     foreach my $item (keys(%clickers)) {
 2125:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2126:     }
 2127:     $items=~s/\&$//;
 2128:     my $request = "updateclickers:$udom:$action:$items";
 2129:     if ($critical) {
 2130:         return &critical($request,$uhome);
 2131:     } else {
 2132:         return &reply($request,$uhome);
 2133:     }
 2134: }
 2135: 
 2136: # ------------------------------dump from db file owned by domainconfig user
 2137: sub dump_dom {
 2138:     my ($namespace, $udom, $regexp) = @_;
 2139: 
 2140:     $udom ||= $env{'user.domain'};
 2141: 
 2142:     return () unless $udom;
 2143: 
 2144:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2145: }
 2146: 
 2147: # ------------------------------------------ get items from domain db files   
 2148: 
 2149: sub get_dom {
 2150:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2151:     return if ($udom eq 'public');
 2152:     my $items='';
 2153:     foreach my $item (@$storearr) {
 2154:         $items.=&escape($item).'&';
 2155:     }
 2156:     $items=~s/\&$//;
 2157:     if (!$udom) {
 2158:         $udom=$env{'user.domain'};
 2159:         return if ($udom eq 'public');
 2160:         if (defined(&domain($udom,'primary'))) {
 2161:             $uhome=&domain($udom,'primary');
 2162:         } else {
 2163:             undef($uhome);
 2164:         }
 2165:     } else {
 2166:         if (!$uhome) {
 2167:             if (defined(&domain($udom,'primary'))) {
 2168:                 $uhome=&domain($udom,'primary');
 2169:             }
 2170:         }
 2171:     }
 2172:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2173:         my $rep;
 2174:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2175:             # domain information is hosted on this machine
 2176:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2177:         } else {
 2178:             if ($encrypt) {
 2179:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2180:             } else {
 2181:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2182:             }
 2183:         }
 2184:         my %returnhash;
 2185:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2186:             return %returnhash;
 2187:         }
 2188:         my @pairs=split(/\&/,$rep);
 2189:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2190:             return @pairs;
 2191:         }
 2192:         my $i=0;
 2193:         foreach my $item (@$storearr) {
 2194:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2195:             $i++;
 2196:         }
 2197:         return %returnhash;
 2198:     } else {
 2199:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2200:     }
 2201: }
 2202: 
 2203: # -------------------------------------------- put items in domain db files 
 2204: 
 2205: sub put_dom {
 2206:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2207:     if (!$udom) {
 2208:         $udom=$env{'user.domain'};
 2209:         if (defined(&domain($udom,'primary'))) {
 2210:             $uhome=&domain($udom,'primary');
 2211:         } else {
 2212:             undef($uhome);
 2213:         }
 2214:     } else {
 2215:         if (!$uhome) {
 2216:             if (defined(&domain($udom,'primary'))) {
 2217:                 $uhome=&domain($udom,'primary');
 2218:             }
 2219:         }
 2220:     } 
 2221:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2222:         my $items='';
 2223:         foreach my $item (keys(%$storehash)) {
 2224:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2225:         }
 2226:         $items=~s/\&$//;
 2227:         if ($encrypt) {
 2228:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2229:         } else {
 2230:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2231:         }
 2232:     } else {
 2233:         &logthis("put_dom failed - no homeserver and/or domain");
 2234:     }
 2235: }
 2236: 
 2237: # --------------------- newput for items in db file owned by domainconfig user
 2238: sub newput_dom {
 2239:     my ($namespace,$storehash,$udom) = @_;
 2240:     my $result;
 2241:     if (!$udom) {
 2242:         $udom=$env{'user.domain'};
 2243:     }
 2244:     if ($udom) {
 2245:         my $uname = &get_domainconfiguser($udom);
 2246:         $result = &newput($namespace,$storehash,$udom,$uname);
 2247:     }
 2248:     return $result;
 2249: }
 2250: 
 2251: # --------------------- delete for items in db file owned by domainconfig user
 2252: sub del_dom {
 2253:     my ($namespace,$storearr,$udom)=@_;
 2254:     if (ref($storearr) eq 'ARRAY') {
 2255:         if (!$udom) {
 2256:             $udom=$env{'user.domain'};
 2257:         }
 2258:         if ($udom) {
 2259:             my $uname = &get_domainconfiguser($udom); 
 2260:             return &del($namespace,$storearr,$udom,$uname);
 2261:         }
 2262:     }
 2263: }
 2264: 
 2265: # ----------------------------------construct domainconfig user for a domain 
 2266: sub get_domainconfiguser {
 2267:     my ($udom) = @_;
 2268:     return $udom.'-domainconfig';
 2269: }
 2270: 
 2271: sub retrieve_inst_usertypes {
 2272:     my ($udom) = @_;
 2273:     my (%returnhash,@order);
 2274:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2275:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2276:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2277:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2278:     } else {
 2279:         if (defined(&domain($udom,'primary'))) {
 2280:             my $uhome=&domain($udom,'primary');
 2281:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2282:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2283:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2284:                 return (\%returnhash,\@order);
 2285:             }
 2286:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2287:             my @pairs=split(/\&/,$hashitems);
 2288:             foreach my $item (@pairs) {
 2289:                 my ($key,$value)=split(/=/,$item,2);
 2290:                 $key = &unescape($key);
 2291:                 next if ($key =~ /^error: 2 /);
 2292:                 $returnhash{$key}=&thaw_unescape($value);
 2293:             }
 2294:             my @esc_order = split(/\&/,$orderitems);
 2295:             foreach my $item (@esc_order) {
 2296:                 push(@order,&unescape($item));
 2297:             }
 2298:         } else {
 2299:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2300:         }
 2301:         return (\%returnhash,\@order);
 2302:     }
 2303: }
 2304: 
 2305: sub is_domainimage {
 2306:     my ($url) = @_;
 2307:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2308:         if (&domain($1) ne '') {
 2309:             return '1';
 2310:         }
 2311:     }
 2312:     return;
 2313: }
 2314: 
 2315: sub inst_directory_query {
 2316:     my ($srch) = @_;
 2317:     my $udom = $srch->{'srchdomain'};
 2318:     my %results;
 2319:     my $homeserver = &domain($udom,'primary');
 2320:     my $outcome;
 2321:     if ($homeserver ne '') {
 2322:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2323:             if ($srch->{'srchby'} eq 'email') {
 2324:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2325:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2326:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2327:                     (($major == 2) && ($minor < 12))) {
 2328:                     return;
 2329:                 }
 2330:             }
 2331:         }
 2332: 	my $queryid=&reply("querysend:instdirsearch:".
 2333: 			   &escape($srch->{'srchby'}).':'.
 2334: 			   &escape($srch->{'srchterm'}).':'.
 2335: 			   &escape($srch->{'srchtype'}),$homeserver);
 2336: 	my $host=&hostname($homeserver);
 2337: 	if ($queryid !~/^\Q$host\E\_/) {
 2338: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2339: 	    return;
 2340: 	}
 2341: 	my $response = &get_query_reply($queryid);
 2342: 	my $maxtries = 5;
 2343: 	my $tries = 1;
 2344: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2345: 	    $response = &get_query_reply($queryid);
 2346: 	    $tries ++;
 2347: 	}
 2348: 
 2349:         if (!&error($response) && $response ne 'refused') {
 2350:             if ($response eq 'unavailable') {
 2351:                 $outcome = $response;
 2352:             } else {
 2353:                 $outcome = 'ok';
 2354:                 my @matches = split(/\n/,$response);
 2355:                 foreach my $match (@matches) {
 2356:                     my ($key,$value) = split(/=/,$match);
 2357:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2358:                 }
 2359:             }
 2360:         }
 2361:     }
 2362:     return ($outcome,%results);
 2363: }
 2364: 
 2365: sub usersearch {
 2366:     my ($srch) = @_;
 2367:     my $dom = $srch->{'srchdomain'};
 2368:     my %results;
 2369:     my %libserv = &all_library();
 2370:     my $query = 'usersearch';
 2371:     foreach my $tryserver (keys(%libserv)) {
 2372:         if (&host_domain($tryserver) eq $dom) {
 2373:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2374:                 if ($srch->{'srchby'} eq 'email') {
 2375:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2376:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2377:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2378:                              (($major == 2) && ($minor < 12)));
 2379:                 }
 2380:             }
 2381:             my $host=&hostname($tryserver);
 2382:             my $queryid=
 2383:                 &reply("querysend:".&escape($query).':'.
 2384:                        &escape($srch->{'srchby'}).':'.
 2385:                        &escape($srch->{'srchtype'}).':'.
 2386:                        &escape($srch->{'srchterm'}),$tryserver);
 2387:             if ($queryid !~/^\Q$host\E\_/) {
 2388:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2389:                 next;
 2390:             }
 2391:             my $reply = &get_query_reply($queryid);
 2392:             my $maxtries = 1;
 2393:             my $tries = 1;
 2394:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2395:                 $reply = &get_query_reply($queryid);
 2396:                 $tries ++;
 2397:             }
 2398:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2399:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2400:             } else {
 2401:                 my @matches;
 2402:                 if ($reply =~ /\n/) {
 2403:                     @matches = split(/\n/,$reply);
 2404:                 } else {
 2405:                     @matches = split(/\&/,$reply);
 2406:                 }
 2407:                 foreach my $match (@matches) {
 2408:                     my ($uname,$udom,%userhash);
 2409:                     foreach my $entry (split(/:/,$match)) {
 2410:                         my ($key,$value) =
 2411:                             map {&unescape($_);} split(/=/,$entry);
 2412:                         $userhash{$key} = $value;
 2413:                         if ($key eq 'username') {
 2414:                             $uname = $value;
 2415:                         } elsif ($key eq 'domain') {
 2416:                             $udom = $value;
 2417:                         }
 2418:                     }
 2419:                     $results{$uname.':'.$udom} = \%userhash;
 2420:                 }
 2421:             }
 2422:         }
 2423:     }
 2424:     return %results;
 2425: }
 2426: 
 2427: sub get_instuser {
 2428:     my ($udom,$uname,$id) = @_;
 2429:     my $homeserver = &domain($udom,'primary');
 2430:     my ($outcome,%results);
 2431:     if ($homeserver ne '') {
 2432:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2433:                            &escape($id).':'.&escape($udom),$homeserver);
 2434:         my $host=&hostname($homeserver);
 2435:         if ($queryid !~/^\Q$host\E\_/) {
 2436:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2437:             return;
 2438:         }
 2439:         my $response = &get_query_reply($queryid);
 2440:         my $maxtries = 5;
 2441:         my $tries = 1;
 2442:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2443:             $response = &get_query_reply($queryid);
 2444:             $tries ++;
 2445:         }
 2446:         if (!&error($response) && $response ne 'refused') {
 2447:             if ($response eq 'unavailable') {
 2448:                 $outcome = $response;
 2449:             } else {
 2450:                 $outcome = 'ok';
 2451:                 my @matches = split(/\n/,$response);
 2452:                 foreach my $match (@matches) {
 2453:                     my ($key,$value) = split(/=/,$match);
 2454:                     $results{&unescape($key)} = &thaw_unescape($value);
 2455:                 }
 2456:             }
 2457:         }
 2458:     }
 2459:     my %userinfo;
 2460:     if (ref($results{$uname}) eq 'HASH') {
 2461:         %userinfo = %{$results{$uname}};
 2462:     } 
 2463:     return ($outcome,%userinfo);
 2464: }
 2465: 
 2466: sub get_multiple_instusers {
 2467:     my ($udom,$users,$caller) = @_;
 2468:     my ($outcome,$results);
 2469:     if (ref($users) eq 'HASH') {
 2470:         my $count = keys(%{$users}); 
 2471:         my $requested = &freeze_escape($users);
 2472:         my $homeserver = &domain($udom,'primary');
 2473:         if ($homeserver ne '') {
 2474:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2475:             my $host=&hostname($homeserver);
 2476:             if ($queryid !~/^\Q$host\E\_/) {
 2477:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2478:                          ' for host: '.$homeserver.'in domain '.$udom);
 2479:                 return ($outcome,$results);
 2480:             }
 2481:             my $response = &get_query_reply($queryid);
 2482:             my $maxtries = 5;
 2483:             if ($count > 100) {
 2484:                 $maxtries = 1+int($count/20);
 2485:             }
 2486:             my $tries = 1;
 2487:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2488:                 $response = &get_query_reply($queryid);
 2489:                 $tries ++;
 2490:             }
 2491:             if ($response eq '') {
 2492:                 $results = {};
 2493:                 foreach my $key (keys(%{$users})) {
 2494:                     my ($uname,$id);
 2495:                     if ($caller eq 'id') {
 2496:                         $id = $key;
 2497:                     } else {
 2498:                         $uname = $key;
 2499:                     }
 2500:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2501:                     $outcome = $resp;
 2502:                     if ($resp eq 'ok') {
 2503:                         %{$results} = (%{$results}, %info);
 2504:                     } else {
 2505:                         last;
 2506:                     }
 2507:                 }
 2508:             } elsif(!&error($response) && ($response ne 'refused')) {
 2509:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2510:                     $outcome = $response;
 2511:                 } else {
 2512:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2513:                     if ($outcome eq 'ok') {
 2514:                         $results = &thaw_unescape($userdata); 
 2515:                     }
 2516:                 }
 2517:             }
 2518:         }
 2519:     }
 2520:     return ($outcome,$results);
 2521: }
 2522: 
 2523: sub inst_rulecheck {
 2524:     my ($udom,$uname,$id,$item,$rules) = @_;
 2525:     my %returnhash;
 2526:     if ($udom ne '') {
 2527:         if (ref($rules) eq 'ARRAY') {
 2528:             @{$rules} = map {&escape($_);} (@{$rules});
 2529:             my $rulestr = join(':',@{$rules});
 2530:             my $homeserver=&domain($udom,'primary');
 2531:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2532:                 my $response;
 2533:                 if ($item eq 'username') {                
 2534:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2535:                                               ':'.&escape($uname).':'.$rulestr,
 2536:                                               $homeserver));
 2537:                 } elsif ($item eq 'id') {
 2538:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2539:                                               ':'.&escape($id).':'.$rulestr,
 2540:                                               $homeserver));
 2541:                 } elsif ($item eq 'selfcreate') {
 2542:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2543:                                                &escape($udom).':'.&escape($uname).
 2544:                                               ':'.$rulestr,$homeserver));
 2545:                 }
 2546:                 if ($response ne 'refused') {
 2547:                     my @pairs=split(/\&/,$response);
 2548:                     foreach my $item (@pairs) {
 2549:                         my ($key,$value)=split(/=/,$item,2);
 2550:                         $key = &unescape($key);
 2551:                         next if ($key =~ /^error: 2 /);
 2552:                         $returnhash{$key}=&thaw_unescape($value);
 2553:                     }
 2554:                 }
 2555:             }
 2556:         }
 2557:     }
 2558:     return %returnhash;
 2559: }
 2560: 
 2561: sub inst_userrules {
 2562:     my ($udom,$check) = @_;
 2563:     my (%ruleshash,@ruleorder);
 2564:     if ($udom ne '') {
 2565:         my $homeserver=&domain($udom,'primary');
 2566:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2567:             my $response;
 2568:             if ($check eq 'id') {
 2569:                 $response=&reply('instidrules:'.&escape($udom),
 2570:                                  $homeserver);
 2571:             } elsif ($check eq 'email') {
 2572:                 $response=&reply('instemailrules:'.&escape($udom),
 2573:                                  $homeserver);
 2574:             } else {
 2575:                 $response=&reply('instuserrules:'.&escape($udom),
 2576:                                  $homeserver);
 2577:             }
 2578:             if (($response ne 'refused') && ($response ne 'error') && 
 2579:                 ($response ne 'unknown_cmd') && 
 2580:                 ($response ne 'no_such_host')) {
 2581:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2582:                 my @pairs=split(/\&/,$hashitems);
 2583:                 foreach my $item (@pairs) {
 2584:                     my ($key,$value)=split(/=/,$item,2);
 2585:                     $key = &unescape($key);
 2586:                     next if ($key =~ /^error: 2 /);
 2587:                     $ruleshash{$key}=&thaw_unescape($value);
 2588:                 }
 2589:                 my @esc_order = split(/\&/,$orderitems);
 2590:                 foreach my $item (@esc_order) {
 2591:                     push(@ruleorder,&unescape($item));
 2592:                 }
 2593:             }
 2594:         }
 2595:     }
 2596:     return (\%ruleshash,\@ruleorder);
 2597: }
 2598: 
 2599: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2600: 
 2601: sub get_domain_defaults {
 2602:     my ($domain,$ignore_cache) = @_;
 2603:     return if (($domain eq '') || ($domain eq 'public'));
 2604:     my $cachetime = 60*60*24;
 2605:     unless ($ignore_cache) {
 2606:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2607:         if (defined($cached)) {
 2608:             if (ref($result) eq 'HASH') {
 2609:                 return %{$result};
 2610:             }
 2611:         }
 2612:     }
 2613:     my %domdefaults;
 2614:     my %domconfig =
 2615:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2616:                                   'requestcourses','inststatus',
 2617:                                   'coursedefaults','usersessions',
 2618:                                   'requestauthor','selfenrollment',
 2619:                                   'coursecategories','ssl','autoenroll',
 2620:                                   'trust','helpsettings','wafproxy'],$domain);
 2621:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2622:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2623:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2624:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2625:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2626:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2627:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2628:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2629:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2630:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2631:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2632:     } else {
 2633:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2634:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2635:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2636:     }
 2637:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2638:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2639:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2640:         } else {
 2641:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2642:         }
 2643:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2644:         foreach my $item (@usertools) {
 2645:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2646:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2647:             }
 2648:         }
 2649:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2650:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2651:         }
 2652:     }
 2653:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2654:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2655:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2656:         }
 2657:     }
 2658:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2659:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2660:     }
 2661:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2662:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2663:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2664:         }
 2665:     }
 2666:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2667:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2668:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2669:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2670:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2671:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2672:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2673:         }
 2674:         foreach my $type (@coursetypes) {
 2675:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2676:                 unless ($type eq 'community') {
 2677:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2678:                 }
 2679:             }
 2680:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2681:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2682:             }
 2683:             if ($domdefaults{'postsubmit'} eq 'on') {
 2684:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2685:                     $domdefaults{$type.'postsubtimeout'} = 
 2686:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2687:                 }
 2688:             }
 2689:         }
 2690:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2691:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2692:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2693:                 if (@clonecodes) {
 2694:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2695:                 }
 2696:             }
 2697:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2698:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2699:         }
 2700:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2701:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2702:         }
 2703:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2704:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2705:         }
 2706:     }
 2707:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2708:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2709:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2710:         }
 2711:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2712:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2713:         }
 2714:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2715:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2716:         }
 2717:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2718:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2719:         }
 2720:     }
 2721:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2722:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2723:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2724:                             'approval','limit');
 2725:             foreach my $type (@coursetypes) {
 2726:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2727:                     my @mgrdc = ();
 2728:                     foreach my $item (@settings) {
 2729:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2730:                             push(@mgrdc,$item);
 2731:                         }
 2732:                     }
 2733:                     if (@mgrdc) {
 2734:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2735:                     }
 2736:                 }
 2737:             }
 2738:         }
 2739:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2740:             foreach my $type (@coursetypes) {
 2741:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2742:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2743:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2744:                     }
 2745:                 }
 2746:             }
 2747:         }
 2748:     }
 2749:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2750:         $domdefaults{'catauth'} = 'std';
 2751:         $domdefaults{'catunauth'} = 'std';
 2752:         if ($domconfig{'coursecategories'}{'auth'}) {
 2753:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2754:         }
 2755:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2756:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2757:         }
 2758:     }
 2759:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2760:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2761:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2762:         }
 2763:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2764:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2765:         }
 2766:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2767:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2768:         }
 2769:     }
 2770:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2771:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2772:         foreach my $prefix (@prefixes) {
 2773:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2774:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2775:             }
 2776:         }
 2777:     }
 2778:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2779:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2780:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2781:     }
 2782:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2783:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2784:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2785:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2786:         }
 2787:     }
 2788:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2789:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2790:             if ($domconfig{'wafproxy'}{$item}) {
 2791:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2792:             }
 2793:         }
 2794:     } 
 2795:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2796:     return %domdefaults;
 2797: }
 2798: 
 2799: sub get_dom_cats {
 2800:     my ($dom) = @_;
 2801:     return unless (&domain($dom));
 2802:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2803:     unless (defined($cached)) {
 2804:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2805:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2806:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2807:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2808:             } else {
 2809:                 $cats = {};
 2810:             }
 2811:         } else {
 2812:             $cats = {};
 2813:         }
 2814:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2815:     }
 2816:     return $cats;
 2817: }
 2818: 
 2819: sub get_dom_instcats {
 2820:     my ($dom) = @_;
 2821:     return unless (&domain($dom));
 2822:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2823:     unless (defined($cached)) {
 2824:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2825:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2826:         if ($totcodes > 0) {
 2827:             my $caller = 'global';
 2828:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2829:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2830:                 $instcats = {
 2831:                                 codes => \%codes,
 2832:                                 codetitles => \@codetitles,
 2833:                                 cat_titles => \%cat_titles,
 2834:                                 cat_order => \%cat_order,
 2835:                             };
 2836:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2837:             }
 2838:         }
 2839:     }
 2840:     return $instcats;
 2841: }
 2842: 
 2843: sub retrieve_instcodes {
 2844:     my ($coursecodes,$dom) = @_;
 2845:     my $totcodes;
 2846:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2847:     foreach my $course (keys(%courses)) {
 2848:         if (ref($courses{$course}) eq 'HASH') {
 2849:             if ($courses{$course}{'inst_code'} ne '') {
 2850:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2851:                 $totcodes ++;
 2852:             }
 2853:         }
 2854:     }
 2855:     return $totcodes;
 2856: }
 2857: 
 2858: sub course_portal_url {
 2859:     my ($cnum,$cdom,$r) = @_;
 2860:     my $chome = &homeserver($cnum,$cdom);
 2861:     my $hostname = &hostname($chome);
 2862:     my $protocol = $protocol{$chome};
 2863:     $protocol = 'http' if ($protocol ne 'https');
 2864:     my %domdefaults = &get_domain_defaults($cdom);
 2865:     my $firsturl;
 2866:     if ($domdefaults{'portal_def'}) {
 2867:         $firsturl = $domdefaults{'portal_def'};
 2868:     } else {
 2869:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2870:         $hostname = $alias if ($alias ne '');
 2871:         $firsturl = $protocol.'://'.$hostname;
 2872:     }
 2873:     return $firsturl;
 2874: }
 2875: 
 2876: # --------------------------------------------- Get domain config for passwords
 2877: 
 2878: sub get_passwdconf {
 2879:     my ($dom) = @_;
 2880:     my (%passwdconf,$gotconf,$lookup);
 2881:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2882:     if (defined($cached)) {
 2883:         if (ref($result) eq 'HASH') {
 2884:             %passwdconf = %{$result};
 2885:             $gotconf = 1;
 2886:         }
 2887:     }
 2888:     unless ($gotconf) {
 2889:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2890:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2891:             %passwdconf = %{$domconfig{'passwords'}};
 2892:         }
 2893:         my $cachetime = 24*60*60;
 2894:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2895:     }
 2896:     return %passwdconf;
 2897: }
 2898: 
 2899: # --------------------------------------------------- Assign a key to a student
 2900: 
 2901: sub assign_access_key {
 2902: #
 2903: # a valid key looks like uname:udom#comments
 2904: # comments are being appended
 2905: #
 2906:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2907:     $kdom=
 2908:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2909:     $knum=
 2910:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2911:     $cdom=
 2912:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2913:     $cnum=
 2914:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2915:     $udom=$env{'user.name'} unless (defined($udom));
 2916:     $uname=$env{'user.domain'} unless (defined($uname));
 2917:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2918:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2919:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2920:                                                   # assigned to this person
 2921:                                                   # - this should not happen,
 2922:                                                   # unless something went wrong
 2923:                                                   # the first time around
 2924: # ready to assign
 2925:         $logentry=$1.'; '.$logentry;
 2926:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2927:                                                  $kdom,$knum) eq 'ok') {
 2928: # key now belongs to user
 2929: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2930:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2931:                 &appenv({'environment.'.$envkey => $ckey});
 2932:                 return 'ok';
 2933:             } else {
 2934:                 return 
 2935:   'error: Count not permanently assign key, will need to be re-entered later.';
 2936: 	    }
 2937:         } else {
 2938:             return 'error: Could not assign key, try again later.';
 2939:         }
 2940:     } elsif (!$existing{$ckey}) {
 2941: # the key does not exist
 2942: 	return 'error: The key does not exist';
 2943:     } else {
 2944: # the key is somebody else's
 2945: 	return 'error: The key is already in use';
 2946:     }
 2947: }
 2948: 
 2949: # ------------------------------------------ put an additional comment on a key
 2950: 
 2951: sub comment_access_key {
 2952: #
 2953: # a valid key looks like uname:udom#comments
 2954: # comments are being appended
 2955: #
 2956:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2957:     $cdom=
 2958:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2959:     $cnum=
 2960:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2961:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2962:     if ($existing{$ckey}) {
 2963:         $existing{$ckey}.='; '.$logentry;
 2964: # ready to assign
 2965:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2966:                                                  $cdom,$cnum) eq 'ok') {
 2967: 	    return 'ok';
 2968:         } else {
 2969: 	    return 'error: Count not store comment.';
 2970:         }
 2971:     } else {
 2972: # the key does not exist
 2973: 	return 'error: The key does not exist';
 2974:     }
 2975: }
 2976: 
 2977: # ------------------------------------------------------ Generate a set of keys
 2978: 
 2979: sub generate_access_keys {
 2980:     my ($number,$cdom,$cnum,$logentry)=@_;
 2981:     $cdom=
 2982:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2983:     $cnum=
 2984:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2985:     unless (&allowed('mky',$cdom)) { return 0; }
 2986:     unless (($cdom) && ($cnum)) { return 0; }
 2987:     if ($number>10000) { return 0; }
 2988:     sleep(2); # make sure don't get same seed twice
 2989:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2990:     my $total=0;
 2991:     for (my $i=1;$i<=$number;$i++) {
 2992:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2993:                   sprintf("%lx",int(100000*rand)).'-'.
 2994:                   sprintf("%lx",int(100000*rand));
 2995:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2996:        $newkey=~s/0/h/g; # and also 0 and O
 2997:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2998:        if ($existing{$newkey}) {
 2999:            $i--;
 3000:        } else {
 3001: 	  if (&put('accesskeys',
 3002:               { $newkey => '# generated '.localtime().
 3003:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3004:                            '; '.$logentry },
 3005: 		   $cdom,$cnum) eq 'ok') {
 3006:               $total++;
 3007: 	  }
 3008:        }
 3009:     }
 3010:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3011:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3012:     return $total;
 3013: }
 3014: 
 3015: # ------------------------------------------------------- Validate an accesskey
 3016: 
 3017: sub validate_access_key {
 3018:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3019:     $cdom=
 3020:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3021:     $cnum=
 3022:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3023:     $udom=$env{'user.domain'} unless (defined($udom));
 3024:     $uname=$env{'user.name'} unless (defined($uname));
 3025:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3026:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3027: }
 3028: 
 3029: # ------------------------------------- Find the section of student in a course
 3030: sub devalidate_getsection_cache {
 3031:     my ($udom,$unam,$courseid)=@_;
 3032:     my $hashid="$udom:$unam:$courseid";
 3033:     &devalidate_cache_new('getsection',$hashid);
 3034: }
 3035: 
 3036: sub courseid_to_courseurl {
 3037:     my ($courseid) = @_;
 3038:     #already url style courseid
 3039:     return $courseid if ($courseid =~ m{^/});
 3040: 
 3041:     if (exists($env{'course.'.$courseid.'.num'})) {
 3042: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3043: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3044: 	return "/$cdom/$cnum";
 3045:     }
 3046: 
 3047:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3048:     if (exists($courseinfo{'num'})) {
 3049: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3050:     }
 3051: 
 3052:     return undef;
 3053: }
 3054: 
 3055: sub getsection {
 3056:     my ($udom,$unam,$courseid)=@_;
 3057:     my $cachetime=1800;
 3058: 
 3059:     my $hashid="$udom:$unam:$courseid";
 3060:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3061:     if (defined($cached)) { return $result; }
 3062: 
 3063:     my %Pending; 
 3064:     my %Expired;
 3065:     #
 3066:     # Each role can either have not started yet (pending), be active, 
 3067:     #    or have expired.
 3068:     #
 3069:     # If there is an active role, we are done.
 3070:     #
 3071:     # If there is more than one role which has not started yet, 
 3072:     #     choose the one which will start sooner
 3073:     # If there is one role which has not started yet, return it.
 3074:     #
 3075:     # If there is more than one expired role, choose the one which ended last.
 3076:     # If there is a role which has expired, return it.
 3077:     #
 3078:     $courseid = &courseid_to_courseurl($courseid);
 3079:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3080:     foreach my $key (keys(%roleshash)) {
 3081:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3082:         my $section=$1;
 3083:         if ($key eq $courseid.'_st') { $section=''; }
 3084:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3085:         my $now=time;
 3086:         if (defined($end) && $end && ($now > $end)) {
 3087:             $Expired{$end}=$section;
 3088:             next;
 3089:         }
 3090:         if (defined($start) && $start && ($now < $start)) {
 3091:             $Pending{$start}=$section;
 3092:             next;
 3093:         }
 3094:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3095:     }
 3096:     #
 3097:     # Presumedly there will be few matching roles from the above
 3098:     # loop and the sorting time will be negligible.
 3099:     if (scalar(keys(%Pending))) {
 3100:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3101:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3102:     } 
 3103:     if (scalar(keys(%Expired))) {
 3104:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3105:         my $time = pop(@sorted);
 3106:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3107:     }
 3108:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3109: }
 3110: 
 3111: sub save_cache {
 3112:     &purge_remembered();
 3113:     #&Apache::loncommon::validate_page();
 3114:     undef(%env);
 3115:     undef($env_loaded);
 3116: }
 3117: 
 3118: my $to_remember=-1;
 3119: my %remembered;
 3120: my %accessed;
 3121: my $kicks=0;
 3122: my $hits=0;
 3123: sub make_key {
 3124:     my ($name,$id) = @_;
 3125:     if (length($id) > 65 
 3126: 	&& length(&escape($id)) > 200) {
 3127: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3128:     }
 3129:     return &escape($name.':'.$id);
 3130: }
 3131: 
 3132: sub devalidate_cache_new {
 3133:     my ($name,$id,$debug) = @_;
 3134:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3135:     my $remembered_id=$name.':'.$id;
 3136:     $id=&make_key($name,$id);
 3137:     $memcache->delete($id);
 3138:     delete($remembered{$remembered_id});
 3139:     delete($accessed{$remembered_id});
 3140: }
 3141: 
 3142: sub is_cached_new {
 3143:     my ($name,$id,$debug) = @_;
 3144:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3145:     if (exists($remembered{$remembered_id})) {
 3146: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3147: 	$accessed{$remembered_id}=[&gettimeofday()];
 3148: 	$hits++;
 3149: 	return ($remembered{$remembered_id},1);
 3150:     }
 3151:     $id=&make_key($name,$id);
 3152:     my $value = $memcache->get($id);
 3153:     if (!(defined($value))) {
 3154: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3155: 	return (undef,undef);
 3156:     }
 3157:     if ($value eq '__undef__') {
 3158: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3159: 	$value=undef;
 3160:     }
 3161:     &make_room($remembered_id,$value,$debug);
 3162:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3163:     return ($value,1);
 3164: }
 3165: 
 3166: sub do_cache_new {
 3167:     my ($name,$id,$value,$time,$debug) = @_;
 3168:     my $remembered_id=$name.':'.$id;
 3169:     $id=&make_key($name,$id);
 3170:     my $setvalue=$value;
 3171:     if (!defined($setvalue)) {
 3172: 	$setvalue='__undef__';
 3173:     }
 3174:     if (!defined($time) ) {
 3175: 	$time=600;
 3176:     }
 3177:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3178:     my $result = $memcache->set($id,$setvalue,$time);
 3179:     if (! $result) {
 3180: 	&logthis("caching of id -> $id  failed");
 3181: 	$memcache->disconnect_all();
 3182:     }
 3183:     # need to make a copy of $value
 3184:     &make_room($remembered_id,$value,$debug);
 3185:     return $value;
 3186: }
 3187: 
 3188: sub make_room {
 3189:     my ($remembered_id,$value,$debug)=@_;
 3190: 
 3191:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3192:                                     : $value;
 3193:     if ($to_remember<0) { return; }
 3194:     $accessed{$remembered_id}=[&gettimeofday()];
 3195:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3196:     my $to_kick;
 3197:     my $max_time=0;
 3198:     foreach my $other (keys(%accessed)) {
 3199: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3200: 	    $to_kick=$other;
 3201: 	    $max_time=&tv_interval($accessed{$other});
 3202: 	}
 3203:     }
 3204:     delete($remembered{$to_kick});
 3205:     delete($accessed{$to_kick});
 3206:     $kicks++;
 3207:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3208:     return;
 3209: }
 3210: 
 3211: sub purge_remembered {
 3212:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3213:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3214:     undef(%remembered);
 3215:     undef(%accessed);
 3216: }
 3217: # ------------------------------------- Read an entry from a user's environment
 3218: 
 3219: sub userenvironment {
 3220:     my ($udom,$unam,@what)=@_;
 3221:     my $items;
 3222:     foreach my $item (@what) {
 3223:         $items.=&escape($item).'&';
 3224:     }
 3225:     $items=~s/\&$//;
 3226:     my %returnhash=();
 3227:     my $uhome = &homeserver($unam,$udom);
 3228:     unless ($uhome eq 'no_host') {
 3229:         my @answer=split(/\&/, 
 3230:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3231:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3232:             return %returnhash;
 3233:         }
 3234:         my $i;
 3235:         for ($i=0;$i<=$#what;$i++) {
 3236: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3237:         }
 3238:     }
 3239:     return %returnhash;
 3240: }
 3241: 
 3242: # ---------------------------------------------------------- Get a studentphoto
 3243: sub studentphoto {
 3244:     my ($udom,$unam,$ext) = @_;
 3245:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3246:     if (defined($env{'request.course.id'})) {
 3247:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3248:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3249:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 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:         }
 3260:     } else {
 3261:         my ($result,$perm_reqd) = 
 3262: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3263:         if ($result eq 'ok') {
 3264:             if (!($perm_reqd eq 'yes')) {
 3265:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3266:             }
 3267:         }
 3268:     }
 3269:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3270: }
 3271: 
 3272: sub retrievestudentphoto {
 3273:     my ($udom,$unam,$ext,$type) = @_;
 3274:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3275:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3276:     if ($ret eq 'ok') {
 3277:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3278:         if ($type eq 'thumbnail') {
 3279:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3280:         }
 3281:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3282:         return $tokenurl;
 3283:     } else {
 3284:         if ($type eq 'thumbnail') {
 3285:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3286:         } else { 
 3287:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3288:         }
 3289:     }
 3290: }
 3291: 
 3292: # -------------------------------------------------------------------- New chat
 3293: 
 3294: sub chatsend {
 3295:     my ($newentry,$anon,$group)=@_;
 3296:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3297:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3298:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3299:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3300: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3301: 		   &escape($newentry)).':'.$group,$chome);
 3302: }
 3303: 
 3304: # ------------------------------------------ Find current version of a resource
 3305: 
 3306: sub getversion {
 3307:     my $fname=&clutter(shift);
 3308:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3309:     return &currentversion(&filelocation('',$fname));
 3310: }
 3311: 
 3312: sub currentversion {
 3313:     my $fname=shift;
 3314:     my $author=$fname;
 3315:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3316:     my ($udom,$uname)=split(/\//,$author);
 3317:     my $home=&homeserver($uname,$udom);
 3318:     if ($home eq 'no_host') { 
 3319:         return -1; 
 3320:     }
 3321:     my $answer=&reply("currentversion:$fname",$home);
 3322:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3323: 	return -1;
 3324:     }
 3325:     return $answer;
 3326: }
 3327: 
 3328: #
 3329: # Return special version number of resource if set by override, empty otherwise
 3330: #
 3331: sub usedversion {
 3332:     my $fname=shift;
 3333:     unless ($fname) { $fname=$env{'request.uri'}; }
 3334:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3335:     if ($urlversion) { return $urlversion; }
 3336:     return '';
 3337: }
 3338: 
 3339: # ----------------------------- Subscribe to a resource, return URL if possible
 3340: 
 3341: sub subscribe {
 3342:     my $fname=shift;
 3343:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3344:     $fname=~s/[\n\r]//g;
 3345:     my $author=$fname;
 3346:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3347:     my ($udom,$uname)=split(/\//,$author);
 3348:     my $home=homeserver($uname,$udom);
 3349:     if ($home eq 'no_host') {
 3350:         return 'not_found';
 3351:     }
 3352:     my $answer=reply("sub:$fname",$home);
 3353:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3354: 	$answer.=' by '.$home;
 3355:     }
 3356:     return $answer;
 3357: }
 3358:     
 3359: # -------------------------------------------------------------- Replicate file
 3360: 
 3361: sub repcopy {
 3362:     my $filename=shift;
 3363:     $filename=~s/\/+/\//g;
 3364:     my $londocroot = $perlvar{'lonDocRoot'};
 3365:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3366:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3367:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3368: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3369: 	return &repcopy_userfile($filename);
 3370:     }
 3371:     $filename=~s/[\n\r]//g;
 3372:     my $transname="$filename.in.transfer";
 3373: # FIXME: this should flock
 3374:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3375:     my $remoteurl=subscribe($filename);
 3376:     if ($remoteurl =~ /^con_lost by/) {
 3377: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3378:            return 'unavailable';
 3379:     } elsif ($remoteurl eq 'not_found') {
 3380: 	   #&logthis("Subscribe returned not_found: $filename");
 3381: 	   return 'not_found';
 3382:     } elsif ($remoteurl =~ /^rejected by/) {
 3383: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3384:            return 'forbidden';
 3385:     } elsif ($remoteurl eq 'directory') {
 3386:            return 'ok';
 3387:     } else {
 3388:         my $author=$filename;
 3389:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3390:         my ($udom,$uname)=split(/\//,$author);
 3391:         my $home=homeserver($uname,$udom);
 3392:         unless ($home eq $perlvar{'lonHostID'}) {
 3393:            my @parts=split(/\//,$filename);
 3394:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3395:            if ($path ne "$londocroot/res") {
 3396:                &logthis("Malconfiguration for replication: $filename");
 3397: 	       return 'bad_request';
 3398:            }
 3399:            my $count;
 3400:            for ($count=5;$count<$#parts;$count++) {
 3401:                $path.="/$parts[$count]";
 3402:                if ((-e $path)!=1) {
 3403: 		   mkdir($path,0777);
 3404:                }
 3405:            }
 3406:            my $request=new HTTP::Request('GET',"$remoteurl");
 3407:            my $response;
 3408:            if ($remoteurl =~ m{/raw/}) {
 3409:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3410:            } else {
 3411:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3412:            }
 3413:            if ($response->is_error()) {
 3414: 	       unlink($transname);
 3415:                my $message=$response->status_line;
 3416:                &logthis("<font color=\"blue\">WARNING:"
 3417:                        ." LWP get: $message: $filename</font>");
 3418:                return 'unavailable';
 3419:            } else {
 3420: 	       if ($remoteurl!~/\.meta$/) {
 3421:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3422:                   my $mresponse;
 3423:                   if ($remoteurl =~ m{/raw/}) {
 3424:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3425:                   } else {
 3426:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3427:                   }
 3428:                   if ($mresponse->is_error()) {
 3429: 		      unlink($filename.'.meta');
 3430:                       &logthis(
 3431:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3432:                   }
 3433: 	       }
 3434:                rename($transname,$filename);
 3435:                return 'ok';
 3436:            }
 3437:        }
 3438:     }
 3439: }
 3440: 
 3441: # ------------------------------------------------- Unsubscribe from a resource
 3442: 
 3443: sub unsubscribe {
 3444:     my ($fname) = @_;
 3445:     my $answer;
 3446:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3447:     $fname=~s/[\n\r]//g;
 3448:     my $author=$fname;
 3449:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3450:     my ($udom,$uname)=split(/\//,$author);
 3451:     my $home=homeserver($uname,$udom);
 3452:     if ($home eq 'no_host') {
 3453:         $answer = 'no_host';
 3454:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3455:         $answer = 'home';
 3456:     } else {
 3457:         my $defdom = $perlvar{'lonDefDomain'};
 3458:         if (&will_trust('content',$defdom,$udom)) {
 3459:             $answer = reply("unsub:$fname",$home);
 3460:         } else {
 3461:             $answer = 'untrusted';
 3462:         }
 3463:     }
 3464:     return $answer;
 3465: }
 3466: 
 3467: # ------------------------------------------------ Get server side include body
 3468: sub ssi_body {
 3469:     my ($filelink,%form)=@_;
 3470:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3471:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3472:     }
 3473:     my $output='';
 3474:     my $response;
 3475:     if ($filelink=~/^https?\:/) {
 3476:        ($output,$response)=&externalssi($filelink);
 3477:     } else {
 3478:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3479:        $filelink .= 'inhibitmenu=yes';
 3480:        ($output,$response)=&ssi($filelink,%form);
 3481:     }
 3482:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3483:     $output=~s/^.*?\<body[^\>]*\>//si;
 3484:     $output=~s/\<\/body\s*\>.*?$//si;
 3485:     if (wantarray) {
 3486:         return ($output, $response);
 3487:     } else {
 3488:         return $output;
 3489:     }
 3490: }
 3491: 
 3492: # --------------------------------------------------------- Server Side Include
 3493: 
 3494: sub absolute_url {
 3495:     my ($host_name,$unalias,$keep_proto) = @_;
 3496:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3497:     if ($host_name eq '') {
 3498: 	$host_name = $ENV{'SERVER_NAME'};
 3499:     }
 3500:     if ($unalias) {
 3501:         my $alias = &get_proxy_alias();
 3502:         if ($alias eq $host_name) {
 3503:             my $lonhost = $perlvar{'lonHostID'};
 3504:             my $hostname = &hostname($lonhost);
 3505:             my $lcproto; 
 3506:             if (($keep_proto) || ($hostname eq '')) {
 3507:                 $lcproto = $protocol;
 3508:             } else {
 3509:                 $lcproto = $protocol{$lonhost};
 3510:                 $lcproto = 'http' if ($lcproto ne 'https');
 3511:                 $lcproto .= '://';
 3512:             }
 3513:             unless ($hostname eq '') {
 3514:                 return $lcproto.$hostname;
 3515:             }
 3516:         }
 3517:     }
 3518:     return $protocol.$host_name;
 3519: }
 3520: 
 3521: #
 3522: #   Server side include.
 3523: # Parameters:
 3524: #  fn     Possibly encrypted resource name/id.
 3525: #  form   Hash that describes how the rendering should be done
 3526: #         and other things.
 3527: # Returns:
 3528: #   Scalar context: The content of the response.
 3529: #   Array context:  2 element list of the content and the full response object.
 3530: #     
 3531: sub ssi {
 3532: 
 3533:     my ($fn,%form)=@_;
 3534:     my ($host,$request,$response);
 3535:     $host = &absolute_url('',1);
 3536: 
 3537:     $form{'no_update_last_known'}=1;
 3538:     &Apache::lonenc::check_encrypt(\$fn);
 3539:     if (%form) {
 3540:       $request=new HTTP::Request('POST',$host.$fn);
 3541:       $request->content(join('&',map { 
 3542:             my $name = escape($_);
 3543:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3544:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3545:             : &escape($form{$_}) );    
 3546:         } keys(%form)));
 3547:     } else {
 3548:       $request=new HTTP::Request('GET',$host.$fn);
 3549:     }
 3550: 
 3551:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3552:     my $lonhost = $perlvar{'lonHostID'};
 3553:     my $islocal;
 3554:     if (($env{'request.course.id'}) &&
 3555:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3556:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3557:         ($form{'grade_symb'} ne '') &&
 3558:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3559:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3560:         $islocal = 1;
 3561:     }
 3562:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3563:                                              '','','',$islocal);
 3564: 
 3565:     if (wantarray) {
 3566: 	return ($response->content, $response);
 3567:     } else {
 3568: 	return $response->content;
 3569:     }
 3570: }
 3571: 
 3572: sub externalssi {
 3573:     my ($url)=@_;
 3574:     my $request=new HTTP::Request('GET',$url);
 3575:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3576:     if (wantarray) {
 3577:         return ($response->content, $response);
 3578:     } else {
 3579:         return $response->content;
 3580:     }
 3581: }
 3582: 
 3583: 
 3584: # If the local copy of a replicated resource is outdated, trigger a  
 3585: # connection from the homeserver to flush the delayed queue. If no update 
 3586: # happens, remove local copies of outdated resource (and corresponding
 3587: # metadata file).
 3588: 
 3589: sub remove_stale_resfile {
 3590:     my ($url) = @_;
 3591:     my $removed;
 3592:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3593:         my $audom = $1;
 3594:         my $auname = $2;
 3595:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3596:             my $homeserver = &homeserver($auname,$audom);
 3597:             unless (($homeserver eq 'no_host') ||
 3598:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3599:                 my $fname = &filelocation('',$url);
 3600:                 if (-e $fname) {
 3601:                     my $hostname = &hostname($homeserver);
 3602:                     if ($hostname) {
 3603:                         my $protocol = $protocol{$homeserver};
 3604:                         $protocol = 'http' if ($protocol ne 'https');
 3605:                         my $uri = &declutter($url);
 3606:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3607:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3608:                         if ($response->is_success()) {
 3609:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3610:                             my $locmodtime = (stat($fname))[9];
 3611:                             if ($locmodtime < $remmodtime) {
 3612:                                 my $stale;
 3613:                                 my $answer = &reply('pong',$homeserver);
 3614:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3615:                                     sleep(0.2);
 3616:                                     $locmodtime = (stat($fname))[9];
 3617:                                     if ($locmodtime < $remmodtime) {
 3618:                                         my $posstransfer = $fname.'.in.transfer';
 3619:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3620:                                             $removed = 1;
 3621:                                         } else {
 3622:                                             $stale = 1;
 3623:                                         }
 3624:                                     } else {
 3625:                                         $removed = 1;
 3626:                                     }
 3627:                                 } else {
 3628:                                     $stale = 1;
 3629:                                 }
 3630:                                 if ($stale) {
 3631:                                     if (unlink($fname)) {
 3632:                                         if ($uri!~/\.meta$/) {
 3633:                                             if (-e $fname.'.meta') {
 3634:                                                 unlink($fname.'.meta');
 3635:                                             }
 3636:                                         }
 3637:                                         my $unsubresult = &unsubscribe($fname);
 3638:                                         unless ($unsubresult eq 'ok') {
 3639:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3640:                                         }
 3641:                                         $removed = 1;
 3642:                                     }
 3643:                                 }
 3644:                             }
 3645:                         }
 3646:                     }
 3647:                 }
 3648:             }
 3649:         }
 3650:     }
 3651:     return $removed;
 3652: }
 3653: 
 3654: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3655: 
 3656: sub allowuploaded {
 3657:     my ($srcurl,$url)=@_;
 3658:     $url=&clutter(&declutter($url));
 3659:     my $dir=$url;
 3660:     $dir=~s/\/[^\/]+$//;
 3661:     my %httpref=();
 3662:     my $httpurl=&hreflocation('',$url);
 3663:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3664:     &Apache::lonnet::appenv(\%httpref);
 3665: }
 3666: 
 3667: #
 3668: # Determine if the current user should be able to edit a particular resource,
 3669: # when viewing in course context.
 3670: # (a) When viewing resource used to determine if "Edit" item is included in 
 3671: #     Functions.
 3672: # (b) When displaying folder contents in course editor, used to determine if
 3673: #     "Edit" link will be displayed alongside resource.
 3674: #
 3675: #  input: six args -- filename (decluttered), course number, course domain,
 3676: #                   url, symb (if registered) and group (if this is a group
 3677: #                   item -- e.g., bulletin board, group page etc.).
 3678: #  output: array of five scalars -- 
 3679: #          $cfile -- url for file editing if editable on current server
 3680: #          $home -- homeserver of resource (i.e., for author if published,
 3681: #                                           or course if uploaded.).
 3682: #          $switchserver --  1 if server switch will be needed.
 3683: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3684: #          $forceview -- 1 if icon/link should be to go to view mode
 3685: #
 3686: 
 3687: sub can_edit_resource {
 3688:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3689:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3690: #
 3691: # For aboutme pages user can only edit his/her own.
 3692: #
 3693:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3694:         my ($sdom,$sname) = ($1,$2);
 3695:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3696:             $home = $env{'user.home'};
 3697:             $cfile = $resurl;
 3698:             if ($env{'form.forceedit'}) {
 3699:                 $forceview = 1;
 3700:             } else {
 3701:                 $forceedit = 1;
 3702:             }
 3703:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3704:         } else {
 3705:             return;
 3706:         }
 3707:     }
 3708: 
 3709:     if ($env{'request.course.id'}) {
 3710:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3711:         if ($group ne '') {
 3712: # if this is a group homepage or group bulletin board, check group privs
 3713:             my $allowed = 0;
 3714:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3715:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3716:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3717:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3718:                     $allowed = 1;
 3719:                 }
 3720:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3721:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3722:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3723:                     $allowed = 1;
 3724:                 }
 3725:             }
 3726:             if ($allowed) {
 3727:                 $home=&homeserver($cnum,$cdom);
 3728:                 if ($env{'form.forceedit'}) {
 3729:                     $forceview = 1;
 3730:                 } else {
 3731:                     $forceedit = 1;
 3732:                 }
 3733:                 $cfile = $resurl;
 3734:             } else {
 3735:                 return;
 3736:             }
 3737:         } else {
 3738:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3739:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3740:                     return;
 3741:                 }
 3742:             } elsif (!$crsedit) {
 3743: #
 3744: # No edit allowed where CC has switched to student role.
 3745: #
 3746:                 return;
 3747:             }
 3748:         }
 3749:     }
 3750: 
 3751:     if ($file ne '') {
 3752:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3753:             if (&is_course_upload($file,$cnum,$cdom)) {
 3754:                 $uploaded = 1;
 3755:                 $incourse = 1;
 3756:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3757:                     $cfile = &hreflocation('',$file);
 3758:                     if ($env{'form.forceedit'}) {
 3759:                         $forceview = 1;
 3760:                     } else {
 3761:                         $forceedit = 1;
 3762:                     }
 3763:                 }
 3764:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3765:                 $incourse = 1;
 3766:                 if ($env{'form.forceedit'}) {
 3767:                     $forceview = 1;
 3768:                 } else {
 3769:                     $forceedit = 1;
 3770:                 }
 3771:                 $cfile = $resurl;
 3772:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3773:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3774:                     $incourse = 1;
 3775:                     if ($env{'form.forceedit'}) {
 3776:                         $forceview = 1;
 3777:                     } else {
 3778:                         $forceedit = 1;
 3779:                     }
 3780:                     $cfile = $resurl;
 3781:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3782:                     $incourse = 1;
 3783:                     $cfile = $resurl.'/smpedit';
 3784:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3785:                     $incourse = 1;
 3786:                     if ($env{'form.forceedit'}) {
 3787:                         $forceview = 1;
 3788:                     } else {
 3789:                         $forceedit = 1;
 3790:                     }
 3791:                     $cfile = $resurl;
 3792:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3793:                     my ($map,$id,$res) = &decode_symb($symb);
 3794:                     if ($map =~ /\.page$/) {
 3795:                         $incourse = 1;
 3796:                         if ($env{'form.forceedit'}) {
 3797:                             $forceview = 1;
 3798:                             $cfile = $map;
 3799:                         } else {
 3800:                             $forceedit = 1;
 3801:                             $cfile =  '/adm/wrapper'.$resurl;
 3802:                         }
 3803:                     }
 3804:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3805:                     $incourse = 1;
 3806:                     if ($env{'form.forceedit'}) {
 3807:                         $forceview = 1;
 3808:                     } else {
 3809:                         $forceedit = 1;
 3810:                     }
 3811:                     $cfile = $resurl;
 3812:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3813:                     $incourse = 1;
 3814:                     if ($env{'form.forceedit'}) {
 3815:                         $forceview = 1;
 3816:                     } else {
 3817:                         $forceedit = 1;
 3818:                     }
 3819:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3820:                 }
 3821:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3822:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3823:                 if (&is_on_map($template)) { 
 3824:                     $incourse = 1;
 3825:                     $forceview = 1;
 3826:                     $cfile = $template;
 3827:                 }
 3828:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3829:                 $incourse = 1;
 3830:                 if ($env{'form.forceedit'}) {
 3831:                     $forceview = 1;
 3832:                 } else {
 3833:                     $forceedit = 1;
 3834:                 }
 3835:                 $cfile = $resurl;
 3836:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3837:                 $incourse = 1;
 3838:                 if ($env{'form.forceedit'}) {
 3839:                     $forceview = 1;
 3840:                 } else {
 3841:                     $forceedit = 1;
 3842:                 }
 3843:                 $cfile = $resurl;
 3844:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3845:                 $incourse = 1;
 3846:                 $forceview = 1;
 3847:                 if ($symb) {
 3848:                     my ($map,$id,$res)=&decode_symb($symb);
 3849:                     $env{'request.symb'} = $symb;
 3850:                     $cfile = &clutter($res);
 3851:                 } else {
 3852:                     $cfile = $env{'form.suppurl'};
 3853:                     my $escfile = &unescape($cfile);
 3854:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3855:                         $cfile = '/adm/wrapper'.$escfile;
 3856:                     } else {
 3857:                         $escfile =~ s{^http://}{};
 3858:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3859:                     }
 3860:                 }
 3861:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3862:                 if ($env{'form.forceedit'}) {
 3863:                     $forceview = 1;
 3864:                 } else {
 3865:                     $forceedit = 1;
 3866:                 }
 3867:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3868:             }
 3869:         }
 3870:         if ($uploaded || $incourse) {
 3871:             $home=&homeserver($cnum,$cdom);
 3872:         } elsif ($file !~ m{/$}) {
 3873:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3874:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3875:             # Check that the user has permission to edit this resource
 3876:             my $setpriv = 1;
 3877:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3878:             if (defined($cfudom)) {
 3879:                 $home=&homeserver($cfuname,$cfudom);
 3880:                 $cfile=$file;
 3881:             }
 3882:         }
 3883:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3884:             (($home ne '') && ($home ne 'no_host'))) {
 3885:             my @ids=&current_machine_ids();
 3886:             unless (grep(/^\Q$home\E$/,@ids)) {
 3887:                 $switchserver=1;
 3888:             }
 3889:         }
 3890:     }
 3891:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3892: }
 3893: 
 3894: sub is_course_upload {
 3895:     my ($file,$cnum,$cdom) = @_;
 3896:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3897:     $uploadpath =~ s{^\/}{};
 3898:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3899:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3900:         return 1;
 3901:     }
 3902:     return;
 3903: }
 3904: 
 3905: sub in_course {
 3906:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3907:     if ($hideprivileged) {
 3908:         my $skipuser;
 3909:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3910:         my @possdoms = ($cdom);  
 3911:         if ($coursehash{'checkforpriv'}) { 
 3912:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3913:         }
 3914:         if (&privileged($uname,$udom,\@possdoms)) {
 3915:             $skipuser = 1;
 3916:             if ($coursehash{'nothideprivileged'}) {
 3917:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3918:                     my $user;
 3919:                     if ($item =~ /:/) {
 3920:                         $user = $item;
 3921:                     } else {
 3922:                         $user = join(':',split(/[\@]/,$item));
 3923:                     }
 3924:                     if ($user eq $uname.':'.$udom) {
 3925:                         undef($skipuser);
 3926:                         last;
 3927:                     }
 3928:                 }
 3929:             }
 3930:             if ($skipuser) {
 3931:                 return 0;
 3932:             }
 3933:         }
 3934:     }
 3935:     $type ||= 'any';
 3936:     if (!defined($cdom) || !defined($cnum)) {
 3937:         my $cid  = $env{'request.course.id'};
 3938:         $cdom = $env{'course.'.$cid.'.domain'};
 3939:         $cnum = $env{'course.'.$cid.'.num'};
 3940:     }
 3941:     my $typesref;
 3942:     if (($type eq 'any') || ($type eq 'all')) {
 3943:         $typesref = ['active','previous','future'];
 3944:     } elsif ($type eq 'previous' || $type eq 'future') {
 3945:         $typesref = [$type];
 3946:     }
 3947:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3948:                               $typesref,undef,[$cdom]);
 3949:     my ($tmp) = keys(%roles);
 3950:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3951:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3952:     if (@course_roles > 0) {
 3953:         return 1;
 3954:     }
 3955:     return 0;
 3956: }
 3957: 
 3958: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3959: # input: action, courseID, current domain, intended
 3960: #        path to file, source of file, instruction to parse file for objects,
 3961: #        ref to hash for embedded objects,
 3962: #        ref to hash for codebase of java objects.
 3963: #        reference to scalar to accommodate mime type determined
 3964: #          from File::MMagic if $parser = parse.
 3965: #
 3966: # output: url to file (if action was uploaddoc), 
 3967: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3968: #
 3969: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3970: # course.
 3971: #
 3972: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3973: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3974: #          course's home server.
 3975: #
 3976: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3977: #          be copied from $source (current location) to 
 3978: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3979: #         and will then be copied to
 3980: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3981: #         course's home server.
 3982: #
 3983: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3984: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3985: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3986: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3987: #         in course's home server.
 3988: #
 3989: 
 3990: sub process_coursefile {
 3991:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3992:         $mimetype)=@_;
 3993:     my $fetchresult;
 3994:     my $home=&homeserver($docuname,$docudom);
 3995:     if ($action eq 'propagate') {
 3996:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3997: 			     $home);
 3998:     } else {
 3999:         my $fpath = '';
 4000:         my $fname = $file;
 4001:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4002:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4003:         my $filepath = &build_filepath($fpath);
 4004:         if ($action eq 'copy') {
 4005:             if ($source eq '') {
 4006:                 $fetchresult = 'no source file';
 4007:                 return $fetchresult;
 4008:             } else {
 4009:                 my $destination = $filepath.'/'.$fname;
 4010:                 rename($source,$destination);
 4011:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4012:                                  $home);
 4013:             }
 4014:         } elsif ($action eq 'uploaddoc') {
 4015:             open(my $fh,'>',$filepath.'/'.$fname);
 4016:             print $fh $env{'form.'.$source};
 4017:             close($fh);
 4018:             if ($parser eq 'parse') {
 4019:                 my $mm = new File::MMagic;
 4020:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4021:                 if ($type eq 'text/html') {
 4022:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4023:                     unless ($parse_result eq 'ok') {
 4024:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4025:                     }
 4026:                 }
 4027:                 if (ref($mimetype)) {
 4028:                     $$mimetype = $type;
 4029:                 } 
 4030:             }
 4031:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4032:                                  $home);
 4033:             if ($fetchresult eq 'ok') {
 4034:                 return '/uploaded/'.$fpath.'/'.$fname;
 4035:             } else {
 4036:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4037:                         ' to host '.$home.': '.$fetchresult);
 4038:                 return '/adm/notfound.html';
 4039:             }
 4040:         }
 4041:     }
 4042:     unless ( $fetchresult eq 'ok') {
 4043:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4044:              ' to host '.$home.': '.$fetchresult);
 4045:     }
 4046:     return $fetchresult;
 4047: }
 4048: 
 4049: sub build_filepath {
 4050:     my ($fpath) = @_;
 4051:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4052:     unless ($fpath eq '') {
 4053:         my @parts=split('/',$fpath);
 4054:         foreach my $part (@parts) {
 4055:             $filepath.= '/'.$part;
 4056:             if ((-e $filepath)!=1) {
 4057:                 mkdir($filepath,0777);
 4058:             }
 4059:         }
 4060:     }
 4061:     return $filepath;
 4062: }
 4063: 
 4064: sub store_edited_file {
 4065:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4066:     my $file = $primary_url;
 4067:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4068:     my $fpath = '';
 4069:     my $fname = $file;
 4070:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4071:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4072:     my $filepath = &build_filepath($fpath);
 4073:     open(my $fh,'>',$filepath.'/'.$fname);
 4074:     print $fh $content;
 4075:     close($fh);
 4076:     my $home=&homeserver($docuname,$docudom);
 4077:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4078: 			  $home);
 4079:     if ($$fetchresult eq 'ok') {
 4080:         return '/uploaded/'.$fpath.'/'.$fname;
 4081:     } else {
 4082:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4083: 		 ' to host '.$home.': '.$$fetchresult);
 4084:         return '/adm/notfound.html';
 4085:     }
 4086: }
 4087: 
 4088: sub clean_filename {
 4089:     my ($fname,$args)=@_;
 4090: # Replace Windows backslashes by forward slashes
 4091:     $fname=~s/\\/\//g;
 4092:     if (!$args->{'keep_path'}) {
 4093:         # Get rid of everything but the actual filename
 4094: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4095:     }
 4096: # Replace spaces by underscores
 4097:     $fname=~s/\s+/\_/g;
 4098: # Transliterate non-ascii text to ascii
 4099:     my $lang = &Apache::lonlocal::current_language();
 4100:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4101: # Replace all other weird characters by nothing
 4102:     $fname=~s{[^/\w\.\-]}{}g;
 4103: # Replace all .\d. sequences with _\d. so they no longer look like version
 4104: # numbers
 4105:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4106: # Replace three or more adjacent underscores with one for consistency 
 4107: # with loncfile::filename_check() so complete url can be extracted by
 4108: # lonnet::decode_symb()
 4109:     $fname=~s/_{3,}/_/g;
 4110:     return $fname;
 4111: }
 4112: 
 4113: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4114: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4115: # image with the same aspect ratio as the original, but with dimensions which do 
 4116: # not exceed $resizewidth and $resizeheight.
 4117:  
 4118: sub resizeImage {
 4119:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4120:     my $ima = Image::Magick->new;
 4121:     my $resized;
 4122:     if (-e $img_path) {
 4123:         $ima->Read($img_path);
 4124:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4125:             my $width = $ima->Get('width');
 4126:             my $height = $ima->Get('height');
 4127:             if ($width > $resizewidth) {
 4128: 	        my $factor = $width/$resizewidth;
 4129:                 my $newheight = $height/$factor;
 4130:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4131:                 $resized = 1;
 4132:             }
 4133:         }
 4134:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4135:             my $width = $ima->Get('width');
 4136:             my $height = $ima->Get('height');
 4137:             if ($height > $resizeheight) {
 4138:                 my $factor = $height/$resizeheight;
 4139:                 my $newwidth = $width/$factor;
 4140:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4141:                 $resized = 1;
 4142:             }
 4143:         }
 4144:         if ($resized) {
 4145:             $ima->Write($img_path);
 4146:         }
 4147:     }
 4148:     return;
 4149: }
 4150: 
 4151: # --------------- Take an uploaded file and put it into the userfiles directory
 4152: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4153: #                    the desired filename is in $env{"form.$formname.filename"}
 4154: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4155: #                                    canceloverwrite, scantron or ''.
 4156: #                   if 'coursedoc': upload to the current course
 4157: #                   if 'existingfile': write file to tmp/overwrites directory 
 4158: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4159: #                   $context is passed as argument to &finishuserfileupload
 4160: #        $subdir - directory in userfile to store the file into
 4161: #        $parser - instruction to parse file for objects ($parser = parse) or
 4162: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4163: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4164: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4165: #        $allfiles - reference to hash for embedded objects
 4166: #        $codebase - reference to hash for codebase of java objects
 4167: #        $desuname - username for permanent storage of uploaded file
 4168: #        $dsetudom - domain for permanaent storage of uploaded file
 4169: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4170: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4171: #        $resizewidth - width (pixels) to which to resize uploaded image
 4172: #        $resizeheight - height (pixels) to which to resize uploaded image
 4173: #        $mimetype - reference to scalar to accommodate mime type determined
 4174: #                    from File::MMagic.
 4175: # 
 4176: # output: url of file in userspace, or error: <message> 
 4177: #             or /adm/notfound.html if failure to upload occurse
 4178: 
 4179: sub userfileupload {
 4180:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4181:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4182:     if (!defined($subdir)) { $subdir='unknown'; }
 4183:     my $fname=$env{'form.'.$formname.'.filename'};
 4184:     $fname=&clean_filename($fname);
 4185:     # See if there is anything left
 4186:     unless ($fname) { return 'error: no uploaded file'; }
 4187:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4188:     if ($fname =~ /^\./) {
 4189:         my ($s,$usec) = &gettimeofday();
 4190:         while (length($usec) < 6) {
 4191:             $usec = '0'.$usec;
 4192:         }
 4193:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4194:     }
 4195:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4196:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4197:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4198:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4199:         my $now = time;
 4200:         my $filepath;
 4201:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4202:              $filepath = 'tmp/helprequests/'.$now;
 4203:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4204:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4205:                          '_'.$env{'user.domain'}.'/pending';
 4206:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4207:             my ($docuname,$docudom);
 4208:             if ($destudom =~ /^$match_domain$/) {
 4209:                 $docudom = $destudom;
 4210:             } else {
 4211:                 $docudom = $env{'user.domain'};
 4212:             }
 4213:             if ($destuname =~ /^$match_username$/) {
 4214:                 $docuname = $destuname;
 4215:             } else {
 4216:                 $docuname = $env{'user.name'};
 4217:             }
 4218:             if (exists($env{'form.group'})) {
 4219:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4220:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4221:             }
 4222:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4223:             if ($context eq 'canceloverwrite') {
 4224:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4225:                 if (-e  $tempfile) {
 4226:                     my @info = stat($tempfile);
 4227:                     if ($info[9] eq $env{'form.timestamp'}) {
 4228:                         unlink($tempfile);
 4229:                     }
 4230:                 }
 4231:                 return;
 4232:             }
 4233:         }
 4234:         # Create the directory if not present
 4235:         my @parts=split(/\//,$filepath);
 4236:         my $fullpath = $perlvar{'lonDaemons'};
 4237:         for (my $i=0;$i<@parts;$i++) {
 4238:             $fullpath .= '/'.$parts[$i];
 4239:             if ((-e $fullpath)!=1) {
 4240:                 mkdir($fullpath,0777);
 4241:             }
 4242:         }
 4243:         open(my $fh,'>',$fullpath.'/'.$fname);
 4244:         print $fh $env{'form.'.$formname};
 4245:         close($fh);
 4246:         if ($context eq 'existingfile') {
 4247:             my @info = stat($fullpath.'/'.$fname);
 4248:             return ($fullpath.'/'.$fname,$info[9]);
 4249:         } else {
 4250:             return $fullpath.'/'.$fname;
 4251:         }
 4252:     }
 4253:     if ($subdir eq 'scantron') {
 4254:         $fname = 'scantron_orig_'.$fname;
 4255:     } else {
 4256:         $fname="$subdir/$fname";
 4257:     }
 4258:     if ($context eq 'coursedoc') {
 4259: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4260: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4261:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4262:             return &finishuserfileupload($docuname,$docudom,
 4263: 					 $formname,$fname,$parser,$allfiles,
 4264: 					 $codebase,$thumbwidth,$thumbheight,
 4265:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4266:         } else {
 4267:             if ($env{'form.folder'}) {
 4268:                 $fname=$env{'form.folder'}.'/'.$fname;
 4269:             }
 4270:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4271: 				       $fname,$formname,$parser,
 4272: 				       $allfiles,$codebase,$mimetype);
 4273:         }
 4274:     } elsif (defined($destuname)) {
 4275:         my $docuname=$destuname;
 4276:         my $docudom=$destudom;
 4277: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4278: 				     $parser,$allfiles,$codebase,
 4279:                                      $thumbwidth,$thumbheight,
 4280:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4281:     } else {
 4282:         my $docuname=$env{'user.name'};
 4283:         my $docudom=$env{'user.domain'};
 4284:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4285:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4286:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4287:         }
 4288: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4289: 				     $parser,$allfiles,$codebase,
 4290:                                      $thumbwidth,$thumbheight,
 4291:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4292:     }
 4293: }
 4294: 
 4295: sub finishuserfileupload {
 4296:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4297:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4298:     my $path=$docudom.'/'.$docuname.'/';
 4299:     my $filepath=$perlvar{'lonDocRoot'};
 4300:   
 4301:     my ($fnamepath,$file,$fetchthumb);
 4302:     $file=$fname;
 4303:     if ($fname=~m|/|) {
 4304:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4305: 	$path.=$fnamepath.'/';
 4306:     }
 4307:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4308:     my $count;
 4309:     for ($count=4;$count<=$#parts;$count++) {
 4310:         $filepath.="/$parts[$count]";
 4311:         if ((-e $filepath)!=1) {
 4312: 	    mkdir($filepath,0777);
 4313:         }
 4314:     }
 4315: 
 4316: # Save the file
 4317:     {
 4318: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4319: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4320: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4321: 	    return '/adm/notfound.html';
 4322: 	}
 4323:         if ($context eq 'overwrite') {
 4324:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4325:             my $target = $filepath.'/'.$file;
 4326:             if (-e $source) {
 4327:                 my @info = stat($source);
 4328:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4329:                     unless (&File::Copy::move($source,$target)) {
 4330:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4331:                         return "Moving from $source failed";
 4332:                     }
 4333:                 } else {
 4334:                     return "Temporary file: $source had unexpected date/time for last modification";
 4335:                 }
 4336:             } else {
 4337:                 return "Temporary file: $source missing";
 4338:             }
 4339:         } elsif (!print FH ($env{'form.'.$formname})) {
 4340: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4341: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4342: 	    return '/adm/notfound.html';
 4343: 	}
 4344: 	close(FH);
 4345:         if ($resizewidth && $resizeheight) {
 4346:             my $mm = new File::MMagic;
 4347:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4348:             if ($mime_type =~ m{^image/}) {
 4349: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4350:             }  
 4351: 	}
 4352:     }
 4353:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4354:         if (ref($mimetype)) {
 4355:             if ($$mimetype eq '') {
 4356:                 my $mm = new File::MMagic;
 4357:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4358:                 $$mimetype = $type;
 4359:             }
 4360:         }
 4361:     }
 4362:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4363:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4364:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4365:                                                        $allfiles,$codebase);
 4366:             unless ($parse_result eq 'ok') {
 4367:                 &logthis('Failed to parse '.$filepath.$file.
 4368: 	   	         ' for embedded media: '.$parse_result); 
 4369:             }
 4370:         }
 4371:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4372:         my $format = $env{'form.scantron_format'};
 4373:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4374:     }
 4375:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4376:         my $input = $filepath.'/'.$file;
 4377:         my $output = $filepath.'/'.'tn-'.$file;
 4378:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4379:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4380:         system({$args[0]} @args);
 4381:         if (-e $filepath.'/'.'tn-'.$file) {
 4382:             $fetchthumb  = 1; 
 4383:         }
 4384:     }
 4385:  
 4386: # Notify homeserver to grep it
 4387: #
 4388:     my $docuhome=&homeserver($docuname,$docudom);	
 4389:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4390:     if ($fetchresult eq 'ok') {
 4391:         if ($fetchthumb) {
 4392:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4393:             if ($thumbresult ne 'ok') {
 4394:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4395:                          $docuhome.': '.$thumbresult);
 4396:             }
 4397:         }
 4398: #
 4399: # Return the URL to it
 4400:         return '/uploaded/'.$path.$file;
 4401:     } else {
 4402:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4403: 		 ': '.$fetchresult);
 4404:         return '/adm/notfound.html';
 4405:     }
 4406: }
 4407: 
 4408: sub extract_embedded_items {
 4409:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4410:     my @state = ();
 4411:     my (%lastids,%related,%shockwave,%flashvars);
 4412:     my %javafiles = (
 4413:                       codebase => '',
 4414:                       code => '',
 4415:                       archive => ''
 4416:                     );
 4417:     my %mediafiles = (
 4418:                       src => '',
 4419:                       movie => '',
 4420:                      );
 4421:     my $p;
 4422:     if ($content) {
 4423:         $p = HTML::LCParser->new($content);
 4424:     } else {
 4425:         $p = HTML::LCParser->new($fullpath);
 4426:     }
 4427:     while (my $t=$p->get_token()) {
 4428: 	if ($t->[0] eq 'S') {
 4429: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4430: 	    push(@state, $tagname);
 4431:             if (lc($tagname) eq 'allow') {
 4432:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4433:             }
 4434: 	    if (lc($tagname) eq 'img') {
 4435: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4436: 	    }
 4437: 	    if (lc($tagname) eq 'a') {
 4438:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4439:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4440:                 }
 4441: 	    }
 4442:             if (lc($tagname) eq 'script') {
 4443:                 my $src;
 4444:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4445:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4446:                 } else {
 4447:                     if ($attr->{'src'} ne '') {
 4448:                         $src = $attr->{'src'};
 4449:                         &add_filetype($allfiles,$src,'src');
 4450:                     }
 4451:                 }
 4452:                 my $text = $p->get_trimmed_text();
 4453:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4454:                     my @swfargs = split(/,/,$1);
 4455:                     foreach my $item (@swfargs) {
 4456:                         $item =~ s/["']//g;
 4457:                         $item =~ s/^\s+//;
 4458:                         $item =~ s/\s+$//;
 4459:                     }
 4460:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4461:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4462:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4463:                         } else {
 4464:                             $related{$swfargs[0]} = [$swfargs[2]];
 4465:                         }
 4466:                     }
 4467:                 }
 4468:             }
 4469:             if (lc($tagname) eq 'link') {
 4470:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4471:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4472:                 }
 4473:             }
 4474: 	    if (lc($tagname) eq 'object' ||
 4475: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4476: 		foreach my $item (keys(%javafiles)) {
 4477: 		    $javafiles{$item} = '';
 4478: 		}
 4479:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4480:                     $lastids{lc($tagname)} = $attr->{'id'};
 4481:                 }
 4482: 	    }
 4483: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4484: 		my $name = lc($attr->{'name'});
 4485: 		foreach my $item (keys(%javafiles)) {
 4486: 		    if ($name eq $item) {
 4487: 			$javafiles{$item} = $attr->{'value'};
 4488: 			last;
 4489: 		    }
 4490: 		}
 4491:                 my $pathfrom;
 4492: 		foreach my $item (keys(%mediafiles)) {
 4493: 		    if ($name eq $item) {
 4494:                         $pathfrom = $attr->{'value'};
 4495:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4496: 			&add_filetype($allfiles,$pathfrom,$name);
 4497: 			last;
 4498: 		    }
 4499: 		}
 4500:                 if ($name eq 'flashvars') {
 4501:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4502:                 }
 4503:                 if ($pathfrom ne '') {
 4504:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4505:                                          $pathfrom);
 4506:                 }
 4507: 	    }
 4508: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4509: 		foreach my $item (keys(%javafiles)) {
 4510: 		    if ($attr->{$item}) {
 4511: 			$javafiles{$item} = $attr->{$item};
 4512: 			last;
 4513: 		    }
 4514: 		}
 4515: 		foreach my $item (keys(%mediafiles)) {
 4516: 		    if ($attr->{$item}) {
 4517: 			&add_filetype($allfiles,$attr->{$item},$item);
 4518: 			last;
 4519: 		    }
 4520: 		}
 4521:                 if (lc($tagname) eq 'embed') {
 4522:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4523:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4524:                                              $attr->{'src'});
 4525:                     }
 4526:                 }
 4527: 	    }
 4528:             if (lc($tagname) eq 'iframe') {
 4529:                 my $src = $attr->{'src'} ;
 4530:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4531:                     &add_filetype($allfiles,$src,'src');
 4532:                 } elsif ($src =~ m{^/}) {
 4533:                     if ($env{'request.course.id'}) {
 4534:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4535:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4536:                         my $url = &hreflocation('',$fullpath);
 4537:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4538:                             my $relpath = $1;
 4539:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4540:                                 &add_filetype($allfiles,$1,'src');
 4541:                             }
 4542:                         }
 4543:                     }
 4544:                 }
 4545:             }
 4546:             if ($t->[4] =~ m{/>$}) {
 4547:                 pop(@state);
 4548:             }
 4549: 	} elsif ($t->[0] eq 'E') {
 4550: 	    my ($tagname) = ($t->[1]);
 4551: 	    if ($javafiles{'codebase'} ne '') {
 4552: 		$javafiles{'codebase'} .= '/';
 4553: 	    }  
 4554: 	    if (lc($tagname) eq 'applet' ||
 4555: 		lc($tagname) eq 'object' ||
 4556: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4557: 		) {
 4558: 		foreach my $item (keys(%javafiles)) {
 4559: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4560: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4561: 			&add_filetype($allfiles,$file,$item);
 4562: 		    }
 4563: 		}
 4564: 	    } 
 4565: 	    pop @state;
 4566: 	}
 4567:     }
 4568:     foreach my $id (sort(keys(%flashvars))) {
 4569:         if ($shockwave{$id} ne '') {
 4570:             my @pairs = split(/\&/,$flashvars{$id});
 4571:             foreach my $pair (@pairs) {
 4572:                 my ($key,$value) = split(/\=/,$pair);
 4573:                 if ($key eq 'thumb') {
 4574:                     &add_filetype($allfiles,$value,$key);
 4575:                 } elsif ($key eq 'content') {
 4576:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4577:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4578:                     if ($ext ne '') {
 4579:                         &add_filetype($allfiles,$path.$value,$ext);
 4580:                     }
 4581:                 }
 4582:             }
 4583:         }
 4584:     }
 4585:     return 'ok';
 4586: }
 4587: 
 4588: sub add_filetype {
 4589:     my ($allfiles,$file,$type)=@_;
 4590:     if (exists($allfiles->{$file})) {
 4591: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4592: 	    push(@{$allfiles->{$file}}, &escape($type));
 4593: 	}
 4594:     } else {
 4595: 	@{$allfiles->{$file}} = (&escape($type));
 4596:     }
 4597: }
 4598: 
 4599: sub embedded_dependency {
 4600:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4601:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4602:         if (($identifier ne '') &&
 4603:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4604:             ($pathfrom ne '')) {
 4605:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4606:             foreach my $dep (@{$related->{$identifier}}) {
 4607:                 &add_filetype($allfiles,$path.$dep,'object');
 4608:             }
 4609:         }
 4610:     }
 4611:     return;
 4612: }
 4613: 
 4614: sub bubblesheet_converter {
 4615:     my ($cdom,$fullpath,$config,$format) = @_;
 4616:     if ((&domain($cdom) ne '') &&
 4617:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4618:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4619:         my (%csvcols,%csvoptions);
 4620:         if (ref($config->{'fields'}) eq 'HASH') {  
 4621:             %csvcols = %{$config->{'fields'}};
 4622:         }
 4623:         if (ref($config->{'options'}) eq 'HASH') {
 4624:             %csvoptions = %{$config->{'options'}};
 4625:         }
 4626:         my %csvbynum = reverse(%csvcols);
 4627:         my %scantronconf = &get_scantron_config($format,$cdom);
 4628:         if (keys(%scantronconf)) {
 4629:             my %bynum = (
 4630:                           $scantronconf{CODEstart} => 'CODEstart',
 4631:                           $scantronconf{IDstart}   => 'IDstart',
 4632:                           $scantronconf{PaperID}   => 'PaperID',
 4633:                           $scantronconf{FirstName} => 'FirstName',
 4634:                           $scantronconf{LastName}  => 'LastName',
 4635:                           $scantronconf{Qstart}    => 'Qstart',
 4636:                         );
 4637:             my @ordered;
 4638:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4639:                 push(@ordered,$bynum{$item});
 4640:             }
 4641:             my %mapstart = (
 4642:                               CODEstart => 'CODE',
 4643:                               IDstart   => 'ID',
 4644:                               PaperID   => 'PaperID',
 4645:                               FirstName => 'FirstName',
 4646:                               LastName  => 'LastName',
 4647:                               Qstart    => 'FirstQuestion',
 4648:                            );
 4649:             my %maplength = (
 4650:                               CODEstart => 'CODElength',
 4651:                               IDstart   => 'IDlength',
 4652:                               PaperID   => 'PaperIDlength',
 4653:                               FirstName => 'FirstNamelength',
 4654:                               LastName  => 'LastNamelength',
 4655:             );
 4656:             if (open(my $fh,'<',$fullpath)) {
 4657:                 my $output;
 4658:                 my %lettdig = &letter_to_digits();
 4659:                 my %diglett = reverse(%lettdig);
 4660:                 my $numletts = scalar(keys(%lettdig));
 4661:                 my $num = 0;
 4662:                 while (my $line=<$fh>) {
 4663:                     $num ++;
 4664:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4665:                     $line =~ s{[\r\n]+$}{};
 4666:                     my %found;
 4667:                     my @values = split(/,/,$line,-1);
 4668:                     my ($qstart,$record);
 4669:                     for (my $i=0; $i<@values; $i++) {
 4670:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4671:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4672:                             if ($values[$i] eq '') {
 4673:                                 $values[$i] = $scantronconf{'Qoff'};
 4674:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4675:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4676:                                     $values[$i] = $lettdig{uc($values[$i])};
 4677:                                 }
 4678:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4679:                                 if ($values[$i] =~ /^[0-9]$/) {
 4680:                                     $values[$i] = $diglett{$values[$i]};
 4681:                                 }
 4682:                             } else {
 4683:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4684:                                     my $digit;
 4685:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4686:                                         $digit = $lettdig{uc($values[$i])}-1;
 4687:                                         if ($values[$i] eq 'J') {
 4688:                                             $digit += $numletts;
 4689:                                         }
 4690:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4691:                                         $digit = $values[$i]-1;
 4692:                                         if ($values[$i] eq '0') {
 4693:                                             $digit += $numletts;
 4694:                                         }
 4695:                                     }
 4696:                                     my $qval='';
 4697:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4698:                                         if ($j == $digit) {
 4699:                                             $qval .= $scantronconf{'Qon'};
 4700:                                         } else {
 4701:                                             $qval .= $scantronconf{'Qoff'};
 4702:                                         }
 4703:                                     }
 4704:                                     $values[$i] = $qval;
 4705:                                 }
 4706:                             }
 4707:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4708:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4709:                             }
 4710:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4711:                             if ($numblank > 0) {
 4712:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4713:                             }
 4714:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4715:                                 $qstart = $i;
 4716:                                 $found{$csvbynum{$i}} = $values[$i];
 4717:                             } else {
 4718:                                 $found{'FirstQuestion'} .= $values[$i];
 4719:                             }
 4720:                         } elsif (exists($csvbynum{$i})) {
 4721:                             if ($csvoptions{'rem'}) {
 4722:                                 $values[$i] =~ s/^\s+//;
 4723:                             }
 4724:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4725:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4726:                                     $values[$i] = '0'.$values[$i];
 4727:                                 }
 4728:                             }
 4729:                             $found{$csvbynum{$i}} = $values[$i];
 4730:                         }
 4731:                     }
 4732:                     foreach my $item (@ordered) {
 4733:                         my $currlength = 1+length($record);
 4734:                         my $numspaces = $scantronconf{$item} - $currlength;
 4735:                         if ($numspaces > 0) {
 4736:                             $record .= (' ' x $numspaces);
 4737:                         }
 4738:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4739:                             unless ($item eq 'Qstart') {
 4740:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4741:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4742:                                 }
 4743:                             }
 4744:                             $record .= $found{$mapstart{$item}};
 4745:                         }
 4746:                     }
 4747:                     $output .= "$record\n";
 4748:                 }
 4749:                 close($fh);
 4750:                 if ($output) {
 4751:                     if (open(my $fh,'>',$fullpath)) {
 4752:                         print $fh $output;
 4753:                         close($fh);
 4754:                     }
 4755:                 }
 4756:             }
 4757:         }
 4758:         return;
 4759:     }
 4760: }
 4761: 
 4762: sub letter_to_digits {
 4763:     my %lettdig = (
 4764:                     A => 1,
 4765:                     B => 2,
 4766:                     C => 3,
 4767:                     D => 4,
 4768:                     E => 5,
 4769:                     F => 6,
 4770:                     G => 7,
 4771:                     H => 8,
 4772:                     I => 9,
 4773:                     J => 0,
 4774:                   );
 4775:     return %lettdig;
 4776: }
 4777: 
 4778: sub get_scantron_config {
 4779:     my ($which,$cdom) = @_;
 4780:     my @lines = &get_scantronformat_file($cdom);
 4781:     my %config;
 4782:     #FIXME probably should move to XML it has already gotten a bit much now
 4783:     foreach my $line (@lines) {
 4784:         my ($name,$descrip)=split(/:/,$line);
 4785:         if ($name ne $which ) { next; }
 4786:         chomp($line);
 4787:         my @config=split(/:/,$line);
 4788:         $config{'name'}=$config[0];
 4789:         $config{'description'}=$config[1];
 4790:         $config{'CODElocation'}=$config[2];
 4791:         $config{'CODEstart'}=$config[3];
 4792:         $config{'CODElength'}=$config[4];
 4793:         $config{'IDstart'}=$config[5];
 4794:         $config{'IDlength'}=$config[6];
 4795:         $config{'Qstart'}=$config[7];
 4796:         $config{'Qlength'}=$config[8];
 4797:         $config{'Qoff'}=$config[9];
 4798:         $config{'Qon'}=$config[10];
 4799:         $config{'PaperID'}=$config[11];
 4800:         $config{'PaperIDlength'}=$config[12];
 4801:         $config{'FirstName'}=$config[13];
 4802:         $config{'FirstNamelength'}=$config[14];
 4803:         $config{'LastName'}=$config[15];
 4804:         $config{'LastNamelength'}=$config[16];
 4805:         $config{'BubblesPerRow'}=$config[17];
 4806:         last;
 4807:     }
 4808:     return %config;
 4809: }
 4810: 
 4811: sub get_scantronformat_file {
 4812:     my ($cdom) = @_;
 4813:     if ($cdom eq '') {
 4814:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4815:     }
 4816:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4817:     my $gottab = 0;
 4818:     my @lines;
 4819:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4820:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4821:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4822:             if ($formatfile ne '-1') {
 4823:                 @lines = split("\n",$formatfile,-1);
 4824:                 $gottab = 1;
 4825:             }
 4826:         }
 4827:     }
 4828:     if (!$gottab) {
 4829:         my $confname = $cdom.'-domainconfig';
 4830:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4831:         my $formatfile = &getfile($default);
 4832:         if ($formatfile ne '-1') {
 4833:             @lines = split("\n",$formatfile,-1);
 4834:             $gottab = 1;
 4835:         }
 4836:     }
 4837:     if (!$gottab) {
 4838:         my @domains = &current_machine_domains();
 4839:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4840:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4841:                 @lines = <$fh>;
 4842:                 close($fh);
 4843:             }
 4844:         } else {
 4845:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4846:                 @lines = <$fh>;
 4847:                 close($fh);
 4848:             }
 4849:         }
 4850:     }
 4851:     return @lines;
 4852: }
 4853: 
 4854: sub removeuploadedurl {
 4855:     my ($url)=@_;	
 4856:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4857:     return &removeuserfile($uname,$udom,$fname);
 4858: }
 4859: 
 4860: sub removeuserfile {
 4861:     my ($docuname,$docudom,$fname)=@_;
 4862:     my $home=&homeserver($docuname,$docudom);    
 4863:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4864:     if ($result eq 'ok') {	
 4865:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4866:             my $metafile = $fname.'.meta';
 4867:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4868: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4869:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4870:             my $sqlresult = 
 4871:                 &update_portfolio_table($docuname,$docudom,$file,
 4872:                                         'portfolio_metadata',$group,
 4873:                                         'delete');
 4874:         }
 4875:     }
 4876:     return $result;
 4877: }
 4878: 
 4879: sub mkdiruserfile {
 4880:     my ($docuname,$docudom,$dir)=@_;
 4881:     my $home=&homeserver($docuname,$docudom);
 4882:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4883: }
 4884: 
 4885: sub renameuserfile {
 4886:     my ($docuname,$docudom,$old,$new)=@_;
 4887:     my $home=&homeserver($docuname,$docudom);
 4888:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4889:                         &escape("$old").':'.&escape("$new"),$home);
 4890:     if ($result eq 'ok') {
 4891:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4892:             my $oldmeta = $old.'.meta';
 4893:             my $newmeta = $new.'.meta';
 4894:             my $metaresult = 
 4895:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4896: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4897:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4898:             my $sqlresult = 
 4899:                 &update_portfolio_table($docuname,$docudom,$file,
 4900:                                         'portfolio_metadata',$group,
 4901:                                         'delete');
 4902:         }
 4903:     }
 4904:     return $result;
 4905: }
 4906: 
 4907: # ------------------------------------------------------------------------- Log
 4908: 
 4909: sub log {
 4910:     my ($dom,$nam,$hom,$what)=@_;
 4911:     return critical("log:$dom:$nam:$what",$hom);
 4912: }
 4913: 
 4914: # ------------------------------------------------------------------ Course Log
 4915: #
 4916: # This routine flushes several buffers of non-mission-critical nature
 4917: #
 4918: 
 4919: sub flushcourselogs {
 4920:     &logthis('Flushing log buffers');
 4921: #
 4922: # course logs
 4923: # This is a log of all transactions in a course, which can be used
 4924: # for data mining purposes
 4925: #
 4926: # It also collects the courseid database, which lists last transaction
 4927: # times and course titles for all courseids
 4928: #
 4929:     my %courseidbuffer=();
 4930:     foreach my $crsid (keys(%courselogs)) {
 4931:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4932: 		          &escape($courselogs{$crsid}),
 4933: 		          $coursehombuf{$crsid}) eq 'ok') {
 4934: 	    delete $courselogs{$crsid};
 4935:         } else {
 4936:             &logthis('Failed to flush log buffer for '.$crsid);
 4937:             if (length($courselogs{$crsid})>40000) {
 4938:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4939:                         " exceeded maximum size, deleting.</font>");
 4940:                delete $courselogs{$crsid};
 4941:             }
 4942:         }
 4943:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4944:             'description' => $coursedescrbuf{$crsid},
 4945:             'inst_code'    => $courseinstcodebuf{$crsid},
 4946:             'type'        => $coursetypebuf{$crsid},
 4947:             'owner'       => $courseownerbuf{$crsid},
 4948:         };
 4949:     }
 4950: #
 4951: # Write course id database (reverse lookup) to homeserver of courses 
 4952: # Is used in pickcourse
 4953: #
 4954:     foreach my $crs_home (keys(%courseidbuffer)) {
 4955:         my $response = &courseidput(&host_domain($crs_home),
 4956:                                     $courseidbuffer{$crs_home},
 4957:                                     $crs_home,'timeonly');
 4958:     }
 4959: #
 4960: # File accesses
 4961: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4962: #
 4963:     foreach my $entry (keys(%accesshash)) {
 4964:         if ($entry =~ /___count$/) {
 4965:             my ($dom,$name);
 4966:             ($dom,$name,undef)=
 4967: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4968:             if (! defined($dom) || $dom eq '' || 
 4969:                 ! defined($name) || $name eq '') {
 4970:                 my $cid = $env{'request.course.id'};
 4971: #
 4972: # FIXME 11/29/2021
 4973: # Typo in rev. 1.458 (2003/12/09)??
 4974: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 4975: #
 4976: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 4977: # $dom and $name will always be null, so the &inc() call will default to storing this data
 4978: # in a nohist_accesscount.db file for the user rather than the course.
 4979: #
 4980: # That said there is a lot of noise in the data being stored.
 4981: # So counts for prtspool/  and adm/ etc. are recorded.
 4982: #
 4983: # A review of which items ending '___count' are written to %accesshash should likely be 
 4984: # made before deciding whether to set these to 'course.' instead of 'request.'
 4985: #
 4986: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 4987: # accesses for things which are not published resources, regardless of course, and
 4988: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 4989: # anyone in the course for things which are not published resources.
 4990: #
 4991: # For an author, nohist_accesscount.db ends up having records for other items
 4992: # mixed up with the legitimate access counts for the author's published resources.
 4993: #
 4994:                 $dom  = $env{'request.'.$cid.'.domain'};
 4995:                 $name = $env{'request.'.$cid.'.num'};
 4996:             }
 4997:             my $value = $accesshash{$entry};
 4998:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4999:             my %temphash=($url => $value);
 5000:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5001:             if ($result eq 'ok') {
 5002:                 delete $accesshash{$entry};
 5003:             }
 5004:         } else {
 5005:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5006:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5007:             my %temphash=($entry => $accesshash{$entry});
 5008:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5009:                 delete $accesshash{$entry};
 5010:             }
 5011:         }
 5012:     }
 5013: #
 5014: # Roles
 5015: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5016: #
 5017:     foreach my $entry (keys(%userrolehash)) {
 5018:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5019: 	    split(/\:/,$entry);
 5020:         if (&Apache::lonnet::put('nohist_userroles',
 5021:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5022:                 $rudom,$runame) eq 'ok') {
 5023: 	    delete $userrolehash{$entry};
 5024:         }
 5025:     }
 5026: #
 5027: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5028: #
 5029:     my %domrolebuffer = ();
 5030:     foreach my $entry (keys(%domainrolehash)) {
 5031:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5032:         if ($domrolebuffer{$rudom}) {
 5033:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5034:                       '='.&escape($domainrolehash{$entry});
 5035:         } else {
 5036:             $domrolebuffer{$rudom}.=&escape($entry).
 5037:                       '='.&escape($domainrolehash{$entry});
 5038:         }
 5039:         delete $domainrolehash{$entry};
 5040:     }
 5041:     foreach my $dom (keys(%domrolebuffer)) {
 5042: 	my %servers;
 5043: 	if (defined(&domain($dom,'primary'))) {
 5044: 	    my $primary=&domain($dom,'primary');
 5045: 	    my $hostname=&hostname($primary);
 5046: 	    $servers{$primary} = $hostname;
 5047: 	} else { 
 5048: 	    %servers = &get_servers($dom,'library');
 5049: 	}
 5050: 	foreach my $tryserver (keys(%servers)) {
 5051: 	    if (&reply('domroleput:'.$dom.':'.
 5052: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5053: 		last;
 5054: 	    } else {  
 5055: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5056: 	    }
 5057:         }
 5058:     }
 5059:     $dumpcount++;
 5060: }
 5061: 
 5062: sub courselog {
 5063:     my $what=shift;
 5064:     $what=time.':'.$what;
 5065:     unless ($env{'request.course.id'}) { return ''; }
 5066:     $coursedombuf{$env{'request.course.id'}}=
 5067:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5068:     $coursenumbuf{$env{'request.course.id'}}=
 5069:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5070:     $coursehombuf{$env{'request.course.id'}}=
 5071:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5072:     $coursedescrbuf{$env{'request.course.id'}}=
 5073:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5074:     $courseinstcodebuf{$env{'request.course.id'}}=
 5075:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5076:     $courseownerbuf{$env{'request.course.id'}}=
 5077:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5078:     $coursetypebuf{$env{'request.course.id'}}=
 5079:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5080:     if (defined $courselogs{$env{'request.course.id'}}) {
 5081: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5082:     } else {
 5083: 	$courselogs{$env{'request.course.id'}}.=$what;
 5084:     }
 5085:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5086: 	&flushcourselogs();
 5087:     }
 5088: }
 5089: 
 5090: sub courseacclog {
 5091:     my $fnsymb=shift;
 5092:     unless ($env{'request.course.id'}) { return ''; }
 5093:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5094:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5095:         $what.=':POST';
 5096:         # FIXME: Probably ought to escape things....
 5097: 	foreach my $key (keys(%env)) {
 5098:             if ($key=~/^form\.(.*)/) {
 5099:                 my $formitem = $1;
 5100:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5101:                     $what.=':'.$formitem.'='.$env{$key};
 5102:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5103:                     if ($formitem eq 'proctorpassword') {
 5104:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5105:                     } else {
 5106:                         $what.=':'.$formitem.'='.$env{$key};
 5107:                     }
 5108:                 }
 5109:             }
 5110:         }
 5111:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5112:         # FIXME: We should not be depending on a form parameter that someone
 5113:         # editing lonsearchcat.pm might change in the future.
 5114:         if ($env{'form.phase'} eq 'course_search') {
 5115:             $what.= ':POST';
 5116:             # FIXME: Probably ought to escape things....
 5117:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5118:                                  'crsdiscuss') {
 5119:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5120:             }
 5121:         }
 5122:     }
 5123:     &courselog($what);
 5124: }
 5125: 
 5126: sub countacc {
 5127:     my $url=&declutter(shift);
 5128:     return if (! defined($url) || $url eq '');
 5129:     unless ($env{'request.course.id'}) { return ''; }
 5130: #
 5131: # Mark that this url was used in this course
 5132: #
 5133:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5134: #
 5135: # Increase the access count for this resource in this child process
 5136: #
 5137:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5138:     $accesshash{$key}++;
 5139: }
 5140: 
 5141: sub linklog {
 5142:     my ($from,$to)=@_;
 5143:     $from=&declutter($from);
 5144:     $to=&declutter($to);
 5145:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5146:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5147: }
 5148: 
 5149: sub statslog {
 5150:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5151:     if ($users<2) { return; }
 5152:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5153:             'course'       => $env{'request.course.id'},
 5154:             'sections'     => '"all"',
 5155:             'num_students' => $users,
 5156:             'part'         => $part,
 5157:             'symb'         => $symb,
 5158:             'mean_tries'   => $av_attempts,
 5159:             'deg_of_diff'  => $degdiff});
 5160:     foreach my $key (keys(%dynstore)) {
 5161:         $accesshash{$key}=$dynstore{$key};
 5162:     }
 5163: }
 5164:   
 5165: sub userrolelog {
 5166:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5167:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5168:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5169:        $userrolehash
 5170:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5171:                     =$tend.':'.$tstart;
 5172:     }
 5173:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5174:        $userrolehash
 5175:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5176:                     =$tend.':'.$tstart;
 5177:     }
 5178:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5179:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5180:        $domainrolehash
 5181:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5182:                     = $tend.':'.$tstart;
 5183:     }
 5184: }
 5185: 
 5186: sub courserolelog {
 5187:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5188:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5189:         my $cdom = $1;
 5190:         my $cnum = $2;
 5191:         my $sec = $3;
 5192:         my $namespace = 'rolelog';
 5193:         my %storehash = (
 5194:                            role    => $trole,
 5195:                            start   => $tstart,
 5196:                            end     => $tend,
 5197:                            selfenroll => $selfenroll,
 5198:                            context    => $context,
 5199:                         );
 5200:         if ($trole eq 'gr') {
 5201:             $namespace = 'groupslog';
 5202:             $storehash{'group'} = $sec;
 5203:         } else {
 5204:             $storehash{'section'} = $sec;
 5205:         }
 5206:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5207:                    $domain,$cnum,$cdom);
 5208:         if (($trole ne 'st') || ($sec ne '')) {
 5209:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5210:         }
 5211:     }
 5212:     return;
 5213: }
 5214: 
 5215: sub domainrolelog {
 5216:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5217:     if ($area =~ m{^/($match_domain)/$}) {
 5218:         my $cdom = $1;
 5219:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5220:         my $namespace = 'rolelog';
 5221:         my %storehash = (
 5222:                            role    => $trole,
 5223:                            start   => $tstart,
 5224:                            end     => $tend,
 5225:                            context => $context,
 5226:                         );
 5227:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5228:                    $domain,$domconfiguser,$cdom);
 5229:     }
 5230:     return;
 5231: 
 5232: }
 5233: 
 5234: sub coauthorrolelog {
 5235:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5236:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5237:         my $audom = $1;
 5238:         my $auname = $2;
 5239:         my $namespace = 'rolelog';
 5240:         my %storehash = (
 5241:                            role    => $trole,
 5242:                            start   => $tstart,
 5243:                            end     => $tend,
 5244:                            context => $context,
 5245:                         );
 5246:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5247:                    $domain,$auname,$audom);
 5248:     }
 5249:     return;
 5250: }
 5251: 
 5252: sub get_course_adv_roles {
 5253:     my ($cid,$codes) = @_;
 5254:     $cid=$env{'request.course.id'} unless (defined($cid));
 5255:     my %coursehash=&coursedescription($cid);
 5256:     my $crstype = &Apache::loncommon::course_type($cid);
 5257:     my %nothide=();
 5258:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5259:         if ($user !~ /:/) {
 5260: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5261:         } else {
 5262:             $nothide{$user}=1;
 5263:         }
 5264:     }
 5265:     my @possdoms = ($coursehash{'domain'});
 5266:     if ($coursehash{'checkforpriv'}) {
 5267:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5268:     }
 5269:     my %returnhash=();
 5270:     my %dumphash=
 5271:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5272:     my $now=time;
 5273:     my %privileged;
 5274:     foreach my $entry (keys(%dumphash)) {
 5275: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5276:         if (($tstart) && ($tstart<0)) { next; }
 5277:         if (($tend) && ($tend<$now)) { next; }
 5278:         if (($tstart) && ($now<$tstart)) { next; }
 5279:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5280: 	if ($username eq '' || $domain eq '') { next; }
 5281:         if ((&privileged($username,$domain,\@possdoms)) &&
 5282:             (!$nothide{$username.':'.$domain})) { next; }
 5283: 	if ($role eq 'cr') { next; }
 5284:         if ($codes) {
 5285:             if ($section) { $role .= ':'.$section; }
 5286:             if ($returnhash{$role}) {
 5287:                 $returnhash{$role}.=','.$username.':'.$domain;
 5288:             } else {
 5289:                 $returnhash{$role}=$username.':'.$domain;
 5290:             }
 5291:         } else {
 5292:             my $key=&plaintext($role,$crstype);
 5293:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5294:             if ($returnhash{$key}) {
 5295: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5296:             } else {
 5297:                 $returnhash{$key}=$username.':'.$domain;
 5298:             }
 5299:         }
 5300:     }
 5301:     return %returnhash;
 5302: }
 5303: 
 5304: sub get_my_roles {
 5305:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5306:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5307:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5308:     my (%dumphash,%nothide);
 5309:     if ($context eq 'userroles') {
 5310:         %dumphash = &dump('roles',$udom,$uname);
 5311:     } else {
 5312:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5313:         if ($hidepriv) {
 5314:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5315:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5316:                 if ($user !~ /:/) {
 5317:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5318:                 } else {
 5319:                     $nothide{$user} = 1;
 5320:                 }
 5321:             }
 5322:         }
 5323:     }
 5324:     my %returnhash=();
 5325:     my $now=time;
 5326:     my %privileged;
 5327:     foreach my $entry (keys(%dumphash)) {
 5328:         my ($role,$tend,$tstart);
 5329:         if ($context eq 'userroles') {
 5330:             next if ($entry =~ /^rolesdef/);
 5331: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5332:         } else {
 5333:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5334:         }
 5335:         if (($tstart) && ($tstart<0)) { next; }
 5336:         my $status = 'active';
 5337:         if (($tend) && ($tend<=$now)) {
 5338:             $status = 'previous';
 5339:         } 
 5340:         if (($tstart) && ($now<$tstart)) {
 5341:             $status = 'future';
 5342:         }
 5343:         if (ref($types) eq 'ARRAY') {
 5344:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5345:                 next;
 5346:             } 
 5347:         } else {
 5348:             if ($status ne 'active') {
 5349:                 next;
 5350:             }
 5351:         }
 5352:         my ($rolecode,$username,$domain,$section,$area);
 5353:         if ($context eq 'userroles') {
 5354:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5355:             (undef,$domain,$username,$section) = split(/\//,$area);
 5356:         } else {
 5357:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5358:         }
 5359:         if (ref($roledoms) eq 'ARRAY') {
 5360:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5361:                 next;
 5362:             }
 5363:         }
 5364:         if (ref($roles) eq 'ARRAY') {
 5365:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5366:                 if ($role =~ /^cr\//) {
 5367:                     if (!grep(/^cr$/,@{$roles})) {
 5368:                         next;
 5369:                     }
 5370:                 } elsif ($role =~ /^gr\//) {
 5371:                     if (!grep(/^gr$/,@{$roles})) {
 5372:                         next;
 5373:                     }
 5374:                 } else {
 5375:                     next;
 5376:                 }
 5377:             }
 5378:         }
 5379:         if ($hidepriv) {
 5380:             my @privroles = ('dc','su');
 5381:             if ($context eq 'userroles') {
 5382:                 next if (grep(/^\Q$role\E$/,@privroles));
 5383:             } else {
 5384:                 my $possdoms = [$domain];
 5385:                 if (ref($roledoms) eq 'ARRAY') {
 5386:                    push(@{$possdoms},@{$roledoms}); 
 5387:                 }
 5388:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5389:                     if (!$nothide{$username.':'.$domain}) {
 5390:                         next;
 5391:                     }
 5392:                 }
 5393:             }
 5394:         }
 5395:         if ($withsec) {
 5396:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5397:                 $tstart.':'.$tend;
 5398:         } else {
 5399:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5400:         }
 5401:     }
 5402:     return %returnhash;
 5403: }
 5404: 
 5405: sub get_all_adhocroles {
 5406:     my ($dom) = @_;
 5407:     my @roles_by_num = ();
 5408:     my %domdefaults = &get_domain_defaults($dom);
 5409:     my (%description,%access_in_dom,%access_info);
 5410:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5411:         my $count = 0;
 5412:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5413:         my %ordered;
 5414:         foreach my $role (sort(keys(%domcurrent))) {
 5415:             my ($order,$desc,$access_in_dom);
 5416:             if (ref($domcurrent{$role}) eq 'HASH') {
 5417:                 $order = $domcurrent{$role}{'order'};
 5418:                 $desc = $domcurrent{$role}{'desc'};
 5419:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5420:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5421:             }
 5422:             if ($order eq '') {
 5423:                 $order = $count;
 5424:             }
 5425:             $ordered{$order} = $role;
 5426:             if ($desc ne '') {
 5427:                 $description{$role} = $desc;
 5428:             } else {
 5429:                 $description{$role}= $role;
 5430:             }
 5431:             $count++;
 5432:         }
 5433:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5434:             push(@roles_by_num,$ordered{$item});
 5435:         }
 5436:     }
 5437:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5438: }
 5439: 
 5440: sub get_my_adhocroles {
 5441:     my ($cid,$checkreg) = @_;
 5442:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5443:     if ($env{'request.course.id'} eq $cid) {
 5444:         $cdom = $env{'course.'.$cid.'.domain'};
 5445:         $cnum = $env{'course.'.$cid.'.num'};
 5446:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5447:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5448:         $cdom = $1;
 5449:         $cnum = $2;
 5450:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5451:                                      $cdom,$cnum);
 5452:     }
 5453:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5454:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5455:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5456:         if ($rosterhash{$user} ne '') {
 5457:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5458:             return ([],{}) if ($type eq 'auto');
 5459:         }
 5460:     }
 5461:     if (($cdom ne '') && ($cnum ne ''))  {
 5462:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5463:             my $then=$env{'user.login.time'};
 5464:             my $update=$env{'user.update.time'};
 5465:             if (!$update) {
 5466:                 $update = $then;
 5467:             }
 5468:             my @liveroles;
 5469:             foreach my $role ('dh','da') {
 5470:                 if ($env{"user.role.$role./$cdom/"}) {
 5471:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5472:                     my $limit = $update;
 5473:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5474:                         $limit = $then;
 5475:                     }
 5476:                     my $activerole = 1;
 5477:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5478:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5479:                     if ($activerole) {
 5480:                         push(@liveroles,$role);
 5481:                     }
 5482:                 }
 5483:             }
 5484:             if (@liveroles) {
 5485:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5486:                     my ($accessref,$accessinfo,%access_in_dom);
 5487:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5488:                     if (ref($roles_by_num) eq 'ARRAY') {
 5489:                         if (@{$roles_by_num}) {
 5490:                             my %settings;
 5491:                             if ($env{'request.course.id'} eq $cid) {
 5492:                                 foreach my $envkey (keys(%env)) {
 5493:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5494:                                         $settings{$1} = $env{$envkey};
 5495:                                     }
 5496:                                 }
 5497:                             } else {
 5498:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5499:                             }
 5500:                             my %setincrs;
 5501:                             if ($settings{'internal.adhocaccess'}) {
 5502:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5503:                             }
 5504:                             my @statuses;
 5505:                             if ($env{'environment.inststatus'}) {
 5506:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5507:                             }
 5508:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5509:                             if (ref($accessref) eq 'HASH') {
 5510:                                 %access_in_dom = %{$accessref};
 5511:                             }
 5512:                             foreach my $role (@{$roles_by_num}) {
 5513:                                 my ($curraccess,@okstatus,@personnel);
 5514:                                 if ($setincrs{$role}) {
 5515:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5516:                                     if ($curraccess eq 'status') {
 5517:                                         @okstatus = split(/\&/,$rest);
 5518:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5519:                                         @personnel = split(/\&/,$rest);
 5520:                                     }
 5521:                                 } else {
 5522:                                     $curraccess = $access_in_dom{$role};
 5523:                                     if (ref($accessinfo) eq 'HASH') {
 5524:                                         if ($curraccess eq 'status') {
 5525:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5526:                                                 @okstatus = @{$accessinfo->{$role}};
 5527:                                             }
 5528:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5529:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5530:                                                 @personnel = @{$accessinfo->{$role}};
 5531:                                             }
 5532:                                         }
 5533:                                     }
 5534:                                 }
 5535:                                 if ($curraccess eq 'none') {
 5536:                                     next;
 5537:                                 } elsif ($curraccess eq 'all') {
 5538:                                     push(@possroles,$role);
 5539:                                 } elsif ($curraccess eq 'dh') {
 5540:                                     if (grep(/^dh$/,@liveroles)) {
 5541:                                         push(@possroles,$role);
 5542:                                     } else {
 5543:                                         next;
 5544:                                     }
 5545:                                 } elsif ($curraccess eq 'da') {
 5546:                                     if (grep(/^da$/,@liveroles)) {
 5547:                                         push(@possroles,$role);
 5548:                                     } else {
 5549:                                         next;
 5550:                                     }
 5551:                                 } elsif ($curraccess eq 'status') {
 5552:                                     if (@okstatus) {
 5553:                                         if (!@statuses) {
 5554:                                             if (grep(/^default$/,@okstatus)) {
 5555:                                                 push(@possroles,$role);
 5556:                                             }
 5557:                                         } else {
 5558:                                             foreach my $status (@okstatus) {
 5559:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5560:                                                     push(@possroles,$role);
 5561:                                                     last;
 5562:                                                 }
 5563:                                             }
 5564:                                         }
 5565:                                     }
 5566:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5567:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5568:                                         if ($curraccess eq 'exc') {
 5569:                                             push(@possroles,$role);
 5570:                                         }
 5571:                                     } elsif ($curraccess eq 'inc') {
 5572:                                         push(@possroles,$role);
 5573:                                     }
 5574:                                 }
 5575:                             }
 5576:                         }
 5577:                     }
 5578:                 }
 5579:             }
 5580:         }
 5581:     }
 5582:     unless (ref($description) eq 'HASH') {
 5583:         if (ref($roles_by_num) eq 'ARRAY') {
 5584:             my %desc;
 5585:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5586:             $description = \%desc;
 5587:         } else {
 5588:             $description = {};
 5589:         }
 5590:     }
 5591:     return (\@possroles,$description);
 5592: }
 5593: 
 5594: # ----------------------------------------------------- Frontpage Announcements
 5595: #
 5596: #
 5597: 
 5598: sub postannounce {
 5599:     my ($server,$text)=@_;
 5600:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5601:     unless ($text=~/\w/) { $text=''; }
 5602:     return &reply('setannounce:'.&escape($text),$server);
 5603: }
 5604: 
 5605: sub getannounce {
 5606: 
 5607:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5608: 	my $announcement='';
 5609: 	while (my $line = <$fh>) { $announcement .= $line; }
 5610: 	close($fh);
 5611: 	if ($announcement=~/\w/) { 
 5612: 	    return 
 5613:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5614:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5615: 	} else {
 5616: 	    return '';
 5617: 	}
 5618:     } else {
 5619: 	return '';
 5620:     }
 5621: }
 5622: 
 5623: # ---------------------------------------------------------- Course ID routines
 5624: # Deal with domain's nohist_courseid.db files
 5625: #
 5626: 
 5627: sub courseidput {
 5628:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5629:     return unless (ref($storehash) eq 'HASH');
 5630:     my $outcome;
 5631:     if ($caller eq 'timeonly') {
 5632:         my $cids = '';
 5633:         foreach my $item (keys(%$storehash)) {
 5634:             $cids.=&escape($item).'&';
 5635:         }
 5636:         $cids=~s/\&$//;
 5637:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5638:                           $coursehome);       
 5639:     } else {
 5640:         my $items = '';
 5641:         foreach my $item (keys(%$storehash)) {
 5642:             $items.= &escape($item).'='.
 5643:                      &freeze_escape($$storehash{$item}).'&';
 5644:         }
 5645:         $items=~s/\&$//;
 5646:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5647:                           $coursehome);
 5648:     }
 5649:     if ($outcome eq 'unknown_cmd') {
 5650:         my $what;
 5651:         foreach my $cid (keys(%$storehash)) {
 5652:             $what .= &escape($cid).'=';
 5653:             foreach my $item ('description','inst_code','owner','type') {
 5654:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5655:             }
 5656:             $what =~ s/\:$/&/;
 5657:         }
 5658:         $what =~ s/\&$//;  
 5659:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5660:     } else {
 5661:         return $outcome;
 5662:     }
 5663: }
 5664: 
 5665: sub courseiddump {
 5666:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5667:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5668:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5669:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5670:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5671:     my $as_hash = 1;
 5672:     my %returnhash;
 5673:     if (!$domfilter) { $domfilter=''; }
 5674:     my %libserv = &all_library();
 5675:     foreach my $tryserver (keys(%libserv)) {
 5676:         if ( (  $hostidflag == 1 
 5677: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5678: 	     || (!defined($hostidflag)) ) {
 5679: 
 5680: 	    if (($domfilter eq '') ||
 5681: 		(&host_domain($tryserver) eq $domfilter)) {
 5682:                 my $rep;
 5683:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5684:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5685:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5686:                                 &escape($descfilter), &escape($instcodefilter), 
 5687:                                 &escape($ownerfilter), &escape($coursefilter),
 5688:                                 &escape($typefilter), &escape($regexp_ok), 
 5689:                                 $as_hash, &escape($selfenrollonly), 
 5690:                                 &escape($catfilter), $showhidden, $caller, 
 5691:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5692:                                 &escape($createdbefore), &escape($createdafter), 
 5693:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5694:                                 $reqcrsdom,&escape($reqinstcode))));
 5695:                 } else {
 5696:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5697:                              $sincefilter.':'.&escape($descfilter).':'.
 5698:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5699:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5700:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5701:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5702:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5703:                              &escape($cc_clone).':'.$cloneonly.':'.
 5704:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5705:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5706:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5707:                 }
 5708:                      
 5709:                 my @pairs=split(/\&/,$rep);
 5710:                 foreach my $item (@pairs) {
 5711:                     my ($key,$value)=split(/\=/,$item,2);
 5712:                     $key = &unescape($key);
 5713:                     next if ($key =~ /^error: 2 /);
 5714:                     my $result = &thaw_unescape($value);
 5715:                     if (ref($result) eq 'HASH') {
 5716:                         $returnhash{$key}=$result;
 5717:                     } else {
 5718:                         my @responses = split(/:/,$value);
 5719:                         my @items = ('description','inst_code','owner','type');
 5720:                         for (my $i=0; $i<@responses; $i++) {
 5721:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5722:                         }
 5723:                     }
 5724:                 }
 5725:             }
 5726:         }
 5727:     }
 5728:     return %returnhash;
 5729: }
 5730: 
 5731: sub courselastaccess {
 5732:     my ($cdom,$cnum,$hostidref) = @_;
 5733:     my %returnhash;
 5734:     if ($cdom && $cnum) {
 5735:         my $chome = &homeserver($cnum,$cdom);
 5736:         if ($chome ne 'no_host') {
 5737:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5738:             &extract_lastaccess(\%returnhash,$rep);
 5739:         }
 5740:     } else {
 5741:         if (!$cdom) { $cdom=''; }
 5742:         my %libserv = &all_library();
 5743:         foreach my $tryserver (keys(%libserv)) {
 5744:             if (ref($hostidref) eq 'ARRAY') {
 5745:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5746:             } 
 5747:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5748:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5749:                 &extract_lastaccess(\%returnhash,$rep);
 5750:             }
 5751:         }
 5752:     }
 5753:     return %returnhash;
 5754: }
 5755: 
 5756: sub extract_lastaccess {
 5757:     my ($returnhash,$rep) = @_;
 5758:     if (ref($returnhash) eq 'HASH') {
 5759:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5760:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5761:                  $rep eq '') {
 5762:             my @pairs=split(/\&/,$rep);
 5763:             foreach my $item (@pairs) {
 5764:                 my ($key,$value)=split(/\=/,$item,2);
 5765:                 $key = &unescape($key);
 5766:                 next if ($key =~ /^error: 2 /);
 5767:                 $returnhash->{$key} = &thaw_unescape($value);
 5768:             }
 5769:         }
 5770:     }
 5771:     return;
 5772: }
 5773: 
 5774: # ---------------------------------------------------------- DC e-mail
 5775: 
 5776: sub dcmailput {
 5777:     my ($domain,$msgid,$message,$server)=@_;
 5778:     my $status = &Apache::lonnet::critical(
 5779:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5780:        &escape($message),$server);
 5781:     return $status;
 5782: }
 5783: 
 5784: sub dcmaildump {
 5785:     my ($dom,$startdate,$enddate,$senders) = @_;
 5786:     my %returnhash=();
 5787: 
 5788:     if (defined(&domain($dom,'primary'))) {
 5789:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5790:                                                          &escape($enddate).':';
 5791: 	my @esc_senders=map { &escape($_)} @$senders;
 5792: 	$cmd.=&escape(join('&',@esc_senders));
 5793: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5794:             my ($key,$value) = split(/\=/,$line,2);
 5795:             if (($key) && ($value)) {
 5796:                 $returnhash{&unescape($key)} = &unescape($value);
 5797:             }
 5798:         }
 5799:     }
 5800:     return %returnhash;
 5801: }
 5802: # ---------------------------------------------------------- Domain roles
 5803: 
 5804: sub get_domain_roles {
 5805:     my ($dom,$roles,$startdate,$enddate)=@_;
 5806:     if ((!defined($startdate)) || ($startdate eq '')) {
 5807:         $startdate = '.';
 5808:     }
 5809:     if ((!defined($enddate)) || ($enddate eq '')) {
 5810:         $enddate = '.';
 5811:     }
 5812:     my $rolelist;
 5813:     if (ref($roles) eq 'ARRAY') {
 5814:         $rolelist = join('&',@{$roles});
 5815:     }
 5816:     my %personnel = ();
 5817: 
 5818:     my %servers = &get_servers($dom,'library');
 5819:     foreach my $tryserver (keys(%servers)) {
 5820: 	%{$personnel{$tryserver}}=();
 5821: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5822: 					    &escape($startdate).':'.
 5823: 					    &escape($enddate).':'.
 5824: 					    &escape($rolelist), $tryserver))) {
 5825: 	    my ($key,$value) = split(/\=/,$line,2);
 5826: 	    if (($key) && ($value)) {
 5827: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5828: 	    }
 5829: 	}
 5830:     }
 5831:     return %personnel;
 5832: }
 5833: 
 5834: sub get_active_domroles {
 5835:     my ($dom,$roles) = @_;
 5836:     return () unless (ref($roles) eq 'ARRAY');
 5837:     my $now = time;
 5838:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5839:     my %domroles;
 5840:     foreach my $server (keys(%dompersonnel)) {
 5841:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5842:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5843:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5844:         }
 5845:     }
 5846:     return %domroles;
 5847: }
 5848: 
 5849: # ----------------------------------------------------------- Interval timing 
 5850: 
 5851: {
 5852: # Caches needed for speedup of navmaps
 5853: # We don't want to cache this for very long at all (5 seconds at most)
 5854: # 
 5855: # The user for whom we cache
 5856: my $cachedkey='';
 5857: # The cached times for this user
 5858: my %cachedtimes=();
 5859: # When this was last done
 5860: my $cachedtime='';
 5861: 
 5862: sub load_all_first_access {
 5863:     my ($uname,$udom,$ignorecache)=@_;
 5864:     if (($cachedkey eq $uname.':'.$udom) &&
 5865:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5866:         (!$ignorecache)) {
 5867:         return;
 5868:     }
 5869:     $cachedtime=time;
 5870:     $cachedkey=$uname.':'.$udom;
 5871:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5872: }
 5873: 
 5874: sub get_first_access {
 5875:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5876:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5877:     if ($argsymb) { $symb=$argsymb; }
 5878:     my ($map,$id,$res)=&decode_symb($symb);
 5879:     if ($argmap) { $map = $argmap; }
 5880:     if ($type eq 'course') {
 5881: 	$res='course';
 5882:     } elsif ($type eq 'map') {
 5883: 	$res=&symbread($map);
 5884:     } else {
 5885: 	$res=$symb;
 5886:     }
 5887:     &load_all_first_access($uname,$udom,$ignorecache);
 5888:     return $cachedtimes{"$courseid\0$res"};
 5889: }
 5890: 
 5891: sub set_first_access {
 5892:     my ($type,$interval)=@_;
 5893:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5894:     my ($map,$id,$res)=&decode_symb($symb);
 5895:     if ($type eq 'course') {
 5896: 	$res='course';
 5897:     } elsif ($type eq 'map') {
 5898: 	$res=&symbread($map);
 5899:     } else {
 5900: 	$res=$symb;
 5901:     }
 5902:     $cachedkey='';
 5903:     my $firstaccess=&get_first_access($type,$symb,$map);
 5904:     if ($firstaccess) {
 5905:         &logthis("First access time already set ($firstaccess) when attempting ".
 5906:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5907:                  "in $courseid");
 5908:         return 'already_set';
 5909:     } else {
 5910:         my $start = time;
 5911: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5912:                           $udom,$uname);
 5913:         if ($putres eq 'ok') {
 5914:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5915:                  $udom,$uname); 
 5916:             &appenv(
 5917:                      {
 5918:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5919:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5920:                      }
 5921:                   );
 5922:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5923:                 $cachedtimes{"$courseid\0$res"} = $start;
 5924:             }
 5925:         } elsif ($putres ne 'refused') {
 5926:             &logthis("Result: $putres when attempting to set first access time ".
 5927:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5928:         }
 5929:         return $putres;
 5930:     }
 5931:     return 'already_set';
 5932: }
 5933: }
 5934: 
 5935: # --------------------------------------------- Set Expire Date for Spreadsheet
 5936: 
 5937: sub expirespread {
 5938:     my ($uname,$udom,$stype,$usymb)=@_;
 5939:     my $cid=$env{'request.course.id'}; 
 5940:     if ($cid) {
 5941:        my $now=time;
 5942:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5943:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5944:                             $env{'course.'.$cid.'.num'}.
 5945: 	        	    ':nohist_expirationdates:'.
 5946:                             &escape($key).'='.$now,
 5947:                             $env{'course.'.$cid.'.home'})
 5948:     }
 5949:     return 'ok';
 5950: }
 5951: 
 5952: # ----------------------------------------------------- Devalidate Spreadsheets
 5953: 
 5954: sub devalidate {
 5955:     my ($symb,$uname,$udom)=@_;
 5956:     my $cid=$env{'request.course.id'}; 
 5957:     if ($cid) {
 5958:         # delete the stored spreadsheets for
 5959:         # - the student level sheet of this user in course's homespace
 5960:         # - the assessment level sheet for this resource 
 5961:         #   for this user in user's homespace
 5962: 	# - current conditional state info
 5963: 	my $key=$uname.':'.$udom.':';
 5964:         my $status=
 5965: 	    &del('nohist_calculatedsheets',
 5966: 		 [$key.'studentcalc:'],
 5967: 		 $env{'course.'.$cid.'.domain'},
 5968: 		 $env{'course.'.$cid.'.num'})
 5969: 		.' '.
 5970: 	    &del('nohist_calculatedsheets_'.$cid,
 5971: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5972:         unless ($status eq 'ok ok') {
 5973:            &logthis('Could not devalidate spreadsheet '.
 5974:                     $uname.' at '.$udom.' for '.
 5975: 		    $symb.': '.$status);
 5976:         }
 5977: 	&delenv('user.state.'.$cid);
 5978:     }
 5979: }
 5980: 
 5981: sub get_scalar {
 5982:     my ($string,$end) = @_;
 5983:     my $value;
 5984:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5985: 	$value = $1;
 5986:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5987: 	$value = $1;
 5988:     }
 5989:     return &unescape($value);
 5990: }
 5991: 
 5992: sub array2str {
 5993:   my (@array) = @_;
 5994:   my $result=&arrayref2str(\@array);
 5995:   $result=~s/^__ARRAY_REF__//;
 5996:   $result=~s/__END_ARRAY_REF__$//;
 5997:   return $result;
 5998: }
 5999: 
 6000: sub arrayref2str {
 6001:   my ($arrayref) = @_;
 6002:   my $result='__ARRAY_REF__';
 6003:   foreach my $elem (@$arrayref) {
 6004:     if(ref($elem) eq 'ARRAY') {
 6005:       $result.=&arrayref2str($elem).'&';
 6006:     } elsif(ref($elem) eq 'HASH') {
 6007:       $result.=&hashref2str($elem).'&';
 6008:     } elsif(ref($elem)) {
 6009:       #print("Got a ref of ".(ref($elem))." skipping.");
 6010:     } else {
 6011:       $result.=&escape($elem).'&';
 6012:     }
 6013:   }
 6014:   $result=~s/\&$//;
 6015:   $result .= '__END_ARRAY_REF__';
 6016:   return $result;
 6017: }
 6018: 
 6019: sub hash2str {
 6020:   my (%hash) = @_;
 6021:   my $result=&hashref2str(\%hash);
 6022:   $result=~s/^__HASH_REF__//;
 6023:   $result=~s/__END_HASH_REF__$//;
 6024:   return $result;
 6025: }
 6026: 
 6027: sub hashref2str {
 6028:   my ($hashref)=@_;
 6029:   my $result='__HASH_REF__';
 6030:   foreach my $key (sort(keys(%$hashref))) {
 6031:     if (ref($key) eq 'ARRAY') {
 6032:       $result.=&arrayref2str($key).'=';
 6033:     } elsif (ref($key) eq 'HASH') {
 6034:       $result.=&hashref2str($key).'=';
 6035:     } elsif (ref($key)) {
 6036:       $result.='=';
 6037:       #print("Got a ref of ".(ref($key))." skipping.");
 6038:     } else {
 6039: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6040:     }
 6041: 
 6042:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6043:       $result.=&arrayref2str($hashref->{$key}).'&';
 6044:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6045:       $result.=&hashref2str($hashref->{$key}).'&';
 6046:     } elsif(ref($hashref->{$key})) {
 6047:        $result.='&';
 6048:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6049:     } else {
 6050:       $result.=&escape($hashref->{$key}).'&';
 6051:     }
 6052:   }
 6053:   $result=~s/\&$//;
 6054:   $result .= '__END_HASH_REF__';
 6055:   return $result;
 6056: }
 6057: 
 6058: sub str2hash {
 6059:     my ($string)=@_;
 6060:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6061:     return %$hash;
 6062: }
 6063: 
 6064: sub str2hashref {
 6065:   my ($string) = @_;
 6066: 
 6067:   my %hash;
 6068: 
 6069:   if($string !~ /^__HASH_REF__/) {
 6070:       if (! ($string eq '' || !defined($string))) {
 6071: 	  $hash{'error'}='Not hash reference';
 6072:       }
 6073:       return (\%hash, $string);
 6074:   }
 6075: 
 6076:   $string =~ s/^__HASH_REF__//;
 6077: 
 6078:   while($string !~ /^__END_HASH_REF__/) {
 6079:       #key
 6080:       my $key='';
 6081:       if($string =~ /^__HASH_REF__/) {
 6082:           ($key, $string)=&str2hashref($string);
 6083:           if(defined($key->{'error'})) {
 6084:               $hash{'error'}='Bad data';
 6085:               return (\%hash, $string);
 6086:           }
 6087:       } elsif($string =~ /^__ARRAY_REF__/) {
 6088:           ($key, $string)=&str2arrayref($string);
 6089:           if($key->[0] eq 'Array reference error') {
 6090:               $hash{'error'}='Bad data';
 6091:               return (\%hash, $string);
 6092:           }
 6093:       } else {
 6094:           $string =~ s/^(.*?)=//;
 6095: 	  $key=&unescape($1);
 6096:       }
 6097:       $string =~ s/^=//;
 6098: 
 6099:       #value
 6100:       my $value='';
 6101:       if($string =~ /^__HASH_REF__/) {
 6102:           ($value, $string)=&str2hashref($string);
 6103:           if(defined($value->{'error'})) {
 6104:               $hash{'error'}='Bad data';
 6105:               return (\%hash, $string);
 6106:           }
 6107:       } elsif($string =~ /^__ARRAY_REF__/) {
 6108:           ($value, $string)=&str2arrayref($string);
 6109:           if($value->[0] eq 'Array reference error') {
 6110:               $hash{'error'}='Bad data';
 6111:               return (\%hash, $string);
 6112:           }
 6113:       } else {
 6114: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6115:       }
 6116:       $string =~ s/^&//;
 6117: 
 6118:       $hash{$key}=$value;
 6119:   }
 6120: 
 6121:   $string =~ s/^__END_HASH_REF__//;
 6122: 
 6123:   return (\%hash, $string);
 6124: }
 6125: 
 6126: sub str2array {
 6127:     my ($string)=@_;
 6128:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6129:     return @$array;
 6130: }
 6131: 
 6132: sub str2arrayref {
 6133:   my ($string) = @_;
 6134:   my @array;
 6135: 
 6136:   if($string !~ /^__ARRAY_REF__/) {
 6137:       if (! ($string eq '' || !defined($string))) {
 6138: 	  $array[0]='Array reference error';
 6139:       }
 6140:       return (\@array, $string);
 6141:   }
 6142: 
 6143:   $string =~ s/^__ARRAY_REF__//;
 6144: 
 6145:   while($string !~ /^__END_ARRAY_REF__/) {
 6146:       my $value='';
 6147:       if($string =~ /^__HASH_REF__/) {
 6148:           ($value, $string)=&str2hashref($string);
 6149:           if(defined($value->{'error'})) {
 6150:               $array[0] ='Array reference error';
 6151:               return (\@array, $string);
 6152:           }
 6153:       } elsif($string =~ /^__ARRAY_REF__/) {
 6154:           ($value, $string)=&str2arrayref($string);
 6155:           if($value->[0] eq 'Array reference error') {
 6156:               $array[0] ='Array reference error';
 6157:               return (\@array, $string);
 6158:           }
 6159:       } else {
 6160: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6161:       }
 6162:       $string =~ s/^&//;
 6163: 
 6164:       push(@array, $value);
 6165:   }
 6166: 
 6167:   $string =~ s/^__END_ARRAY_REF__//;
 6168: 
 6169:   return (\@array, $string);
 6170: }
 6171: 
 6172: # -------------------------------------------------------------------Temp Store
 6173: 
 6174: sub tmpreset {
 6175:   my ($symb,$namespace,$domain,$stuname) = @_;
 6176:   if (!$symb) {
 6177:     $symb=&symbread();
 6178:     if (!$symb) { $symb= $env{'request.url'}; }
 6179:   }
 6180:   $symb=escape($symb);
 6181: 
 6182:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6183:   $namespace=~s/\//\_/g;
 6184:   $namespace=~s/\W//g;
 6185: 
 6186:   if (!$domain) { $domain=$env{'user.domain'}; }
 6187:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6188:   if ($domain eq 'public' && $stuname eq 'public') {
 6189:       $stuname=&get_requestor_ip();
 6190:   }
 6191:   my $path=LONCAPA::tempdir();
 6192:   my %hash;
 6193:   if (tie(%hash,'GDBM_File',
 6194: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6195: 	  &GDBM_WRCREAT(),0640)) {
 6196:     foreach my $key (keys(%hash)) {
 6197:       if ($key=~ /:$symb/) {
 6198: 	delete($hash{$key});
 6199:       }
 6200:     }
 6201:   }
 6202: }
 6203: 
 6204: sub tmpstore {
 6205:   my ($storehash,$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) {
 6214:     # I don't think we would ever want to store this for a course.
 6215:     # it seems this will only be used if we don't have a course.
 6216:     #$namespace=$env{'request.course.id'};
 6217:     #if (!$namespace) {
 6218:       $namespace=$env{'request.state'};
 6219:     #}
 6220:   }
 6221:   $namespace=~s/\//\_/g;
 6222:   $namespace=~s/\W//g;
 6223:   if (!$domain) { $domain=$env{'user.domain'}; }
 6224:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6225:   if ($domain eq 'public' && $stuname eq 'public') {
 6226:       $stuname=&get_requestor_ip();
 6227:   }
 6228:   my $now=time;
 6229:   my %hash;
 6230:   my $path=LONCAPA::tempdir();
 6231:   if (tie(%hash,'GDBM_File',
 6232: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6233: 	  &GDBM_WRCREAT(),0640)) {
 6234:     $hash{"version:$symb"}++;
 6235:     my $version=$hash{"version:$symb"};
 6236:     my $allkeys=''; 
 6237:     foreach my $key (keys(%$storehash)) {
 6238:       $allkeys.=$key.':';
 6239:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6240:     }
 6241:     $hash{"$version:$symb:timestamp"}=$now;
 6242:     $allkeys.='timestamp';
 6243:     $hash{"$version:keys:$symb"}=$allkeys;
 6244:     if (untie(%hash)) {
 6245:       return 'ok';
 6246:     } else {
 6247:       return "error:$!";
 6248:     }
 6249:   } else {
 6250:     return "error:$!";
 6251:   }
 6252: }
 6253: 
 6254: # -----------------------------------------------------------------Temp Restore
 6255: 
 6256: sub tmprestore {
 6257:   my ($symb,$namespace,$domain,$stuname) = @_;
 6258: 
 6259:   if (!$symb) {
 6260:     $symb=&symbread();
 6261:     if (!$symb) { $symb= $env{'request.url'}; }
 6262:   }
 6263:   $symb=escape($symb);
 6264: 
 6265:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6266: 
 6267:   if (!$domain) { $domain=$env{'user.domain'}; }
 6268:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6269:   if ($domain eq 'public' && $stuname eq 'public') {
 6270:       $stuname=&get_requestor_ip();
 6271:   }
 6272:   my %returnhash;
 6273:   $namespace=~s/\//\_/g;
 6274:   $namespace=~s/\W//g;
 6275:   my %hash;
 6276:   my $path=LONCAPA::tempdir();
 6277:   if (tie(%hash,'GDBM_File',
 6278: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6279: 	  &GDBM_READER(),0640)) {
 6280:     my $version=$hash{"version:$symb"};
 6281:     $returnhash{'version'}=$version;
 6282:     my $scope;
 6283:     for ($scope=1;$scope<=$version;$scope++) {
 6284:       my $vkeys=$hash{"$scope:keys:$symb"};
 6285:       my @keys=split(/:/,$vkeys);
 6286:       my $key;
 6287:       $returnhash{"$scope:keys"}=$vkeys;
 6288:       foreach $key (@keys) {
 6289: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6290: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6291:       }
 6292:     }
 6293:     if (!(untie(%hash))) {
 6294:       return "error:$!";
 6295:     }
 6296:   } else {
 6297:     return "error:$!";
 6298:   }
 6299:   return %returnhash;
 6300: }
 6301: 
 6302: # ----------------------------------------------------------------------- Store
 6303: 
 6304: sub store {
 6305:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6306:     my $home='';
 6307: 
 6308:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6309: 
 6310:     $symb=&symbclean($symb);
 6311:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6312: 
 6313:     if (!$domain) { $domain=$env{'user.domain'}; }
 6314:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6315: 
 6316:     &devalidate($symb,$stuname,$domain);
 6317: 
 6318:     $symb=escape($symb);
 6319:     if (!$namespace) { 
 6320:        unless ($namespace=$env{'request.course.id'}) { 
 6321:           return ''; 
 6322:        } 
 6323:     }
 6324:     if (!$home) { $home=$env{'user.home'}; }
 6325: 
 6326:     $$storehash{'ip'}=&get_requestor_ip();
 6327:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6328: 
 6329:     my $namevalue='';
 6330:     foreach my $key (keys(%$storehash)) {
 6331:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6332:     }
 6333:     $namevalue=~s/\&$//;
 6334:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6335:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6336: }
 6337: 
 6338: # -------------------------------------------------------------- Critical Store
 6339: 
 6340: sub cstore {
 6341:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6342:     my $home='';
 6343: 
 6344:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6345: 
 6346:     $symb=&symbclean($symb);
 6347:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6348: 
 6349:     if (!$domain) { $domain=$env{'user.domain'}; }
 6350:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6351: 
 6352:     &devalidate($symb,$stuname,$domain);
 6353: 
 6354:     $symb=escape($symb);
 6355:     if (!$namespace) { 
 6356:        unless ($namespace=$env{'request.course.id'}) { 
 6357:           return ''; 
 6358:        } 
 6359:     }
 6360:     if (!$home) { $home=$env{'user.home'}; }
 6361: 
 6362:     $$storehash{'ip'}=&get_requestor_ip();
 6363:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6364: 
 6365:     my $namevalue='';
 6366:     foreach my $key (keys(%$storehash)) {
 6367:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6368:     }
 6369:     $namevalue=~s/\&$//;
 6370:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6371:     return critical
 6372:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6373: }
 6374: 
 6375: # --------------------------------------------------------------------- Restore
 6376: 
 6377: sub restore {
 6378:     my ($symb,$namespace,$domain,$stuname) = @_;
 6379:     my $home='';
 6380: 
 6381:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6382: 
 6383:     if (!$symb) {
 6384:         return if ($namespace eq 'courserequests');
 6385:         unless ($symb=escape(&symbread())) { return ''; }
 6386:     } else {
 6387:         unless ($namespace eq 'courserequests') {
 6388:             $symb=&escape(&symbclean($symb));
 6389:         }
 6390:     }
 6391:     if (!$namespace) { 
 6392:        unless ($namespace=$env{'request.course.id'}) { 
 6393:           return ''; 
 6394:        } 
 6395:     }
 6396:     if (!$domain) { $domain=$env{'user.domain'}; }
 6397:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6398:     if (!$home) { $home=$env{'user.home'}; }
 6399:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6400: 
 6401:     my %returnhash=();
 6402:     foreach my $line (split(/\&/,$answer)) {
 6403: 	my ($name,$value)=split(/\=/,$line);
 6404:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6405:     }
 6406:     my $version;
 6407:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6408:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6409:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6410:        }
 6411:     }
 6412:     return %returnhash;
 6413: }
 6414: 
 6415: # ---------------------------------------------------------- Course Description
 6416: #
 6417: #  
 6418: 
 6419: sub coursedescription {
 6420:     my ($courseid,$args)=@_;
 6421:     $courseid=~s/^\///;
 6422:     $courseid=~s/\_/\//g;
 6423:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6424:     my $chome=&homeserver($cnum,$cdomain);
 6425:     my $normalid=$cdomain.'_'.$cnum;
 6426:     # need to always cache even if we get errors otherwise we keep 
 6427:     # trying and trying and trying to get the course description.
 6428:     my %envhash=();
 6429:     my %returnhash=();
 6430:     
 6431:     my $expiretime=600;
 6432:     if ($env{'request.course.id'} eq $normalid) {
 6433: 	$expiretime=120;
 6434:     }
 6435: 
 6436:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6437:     if (!$args->{'freshen_cache'}
 6438: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6439: 	foreach my $key (keys(%env)) {
 6440: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6441: 	    my ($setting) = $1;
 6442: 	    $returnhash{$setting} = $env{$key};
 6443: 	}
 6444: 	return %returnhash;
 6445:     }
 6446: 
 6447:     # get the data again
 6448: 
 6449:     if (!$args->{'one_time'}) {
 6450: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6451:     }
 6452: 
 6453:     if ($chome ne 'no_host') {
 6454:        %returnhash=&dump('environment',$cdomain,$cnum);
 6455:        if (!exists($returnhash{'con_lost'})) {
 6456: 	   my $username = $env{'user.name'}; # Defult username
 6457: 	   if(defined $args->{'user'}) {
 6458: 	       $username = $args->{'user'};
 6459: 	   }
 6460:            $returnhash{'home'}= $chome;
 6461: 	   $returnhash{'domain'} = $cdomain;
 6462: 	   $returnhash{'num'} = $cnum;
 6463:            if (!defined($returnhash{'type'})) {
 6464:                $returnhash{'type'} = 'Course';
 6465:            }
 6466:            while (my ($name,$value) = each %returnhash) {
 6467:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6468:            }
 6469:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6470:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6471: 	       $username.'_'.$cdomain.'_'.$cnum;
 6472:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6473:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6474:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6475:        }
 6476:     }
 6477:     if (!$args->{'one_time'}) {
 6478: 	&appenv(\%envhash);
 6479:     }
 6480:     return %returnhash;
 6481: }
 6482: 
 6483: sub update_released_required {
 6484:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6485:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6486:         $cid = $env{'request.course.id'};
 6487:         $cdom = $env{'course.'.$cid.'.domain'};
 6488:         $cnum = $env{'course.'.$cid.'.num'};
 6489:         $chome = $env{'course.'.$cid.'.home'};
 6490:     }
 6491:     if ($needsrelease) {
 6492:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6493:         my $needsupdate;
 6494:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6495:             $needsupdate = 1;
 6496:         } else {
 6497:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6498:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6499:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6500:                 $needsupdate = 1;
 6501:             }
 6502:         }
 6503:         if ($needsupdate) {
 6504:             my %needshash = (
 6505:                              'internal.releaserequired' => $needsrelease,
 6506:                             );
 6507:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6508:             if ($putresult eq 'ok') {
 6509:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6510:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6511:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6512:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6513:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6514:                 }
 6515:             }
 6516:         }
 6517:     }
 6518:     return;
 6519: }
 6520: 
 6521: # -------------------------------------------------See if a user is privileged
 6522: 
 6523: sub privileged {
 6524:     my ($username,$domain,$possdomains,$possroles)=@_;
 6525:     my $now = time;
 6526:     my $roles;
 6527:     if (ref($possroles) eq 'ARRAY') {
 6528:         $roles = $possroles; 
 6529:     } else {
 6530:         $roles = ['dc','su'];
 6531:     }
 6532:     if (ref($possdomains) eq 'ARRAY') {
 6533:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6534:         foreach my $dom (@{$possdomains}) {
 6535:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6536:                 (ref($privileged{$dom}) eq 'HASH')) {
 6537:                 foreach my $role (@{$roles}) {
 6538:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6539:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6540:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6541:                             return 1 unless (($end && $end < $now) ||
 6542:                                              ($start && $start > $now));
 6543:                         }
 6544:                     }
 6545:                 }
 6546:             }
 6547:         }
 6548:     } else {
 6549:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6550:         my $now = time;
 6551: 
 6552:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6553:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6554:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6555:                 return 1 unless ($tend && $tend < $now) 
 6556:                         or ($tstart && $tstart > $now);
 6557:             }
 6558:         }
 6559:     }
 6560:     return 0;
 6561: }
 6562: 
 6563: sub privileged_by_domain {
 6564:     my ($domains,$roles) = @_;
 6565:     my %privileged = ();
 6566:     my $cachetime = 60*60*24;
 6567:     my $now = time;
 6568:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6569:         return %privileged;
 6570:     }
 6571:     foreach my $dom (@{$domains}) {
 6572:         next if (ref($privileged{$dom}) eq 'HASH');
 6573:         my $needroles;
 6574:         foreach my $role (@{$roles}) {
 6575:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6576:             if (defined($cached)) {
 6577:                 if (ref($result) eq 'HASH') {
 6578:                     $privileged{$dom}{$role} = $result;
 6579:                 }
 6580:             } else {
 6581:                 $needroles = 1;
 6582:             }
 6583:         }
 6584:         if ($needroles) {
 6585:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6586:             $privileged{$dom} = {};
 6587:             foreach my $server (keys(%dompersonnel)) {
 6588:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6589:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6590:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6591:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6592:                         next if ($end && $end < $now);
 6593:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6594:                             $dompersonnel{$server}{$item};
 6595:                     }
 6596:                 }
 6597:             }
 6598:             if (ref($privileged{$dom}) eq 'HASH') {
 6599:                 foreach my $role (@{$roles}) {
 6600:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6601:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6602:                     } else {
 6603:                         my %hash = ();
 6604:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6605:                     }
 6606:                 }
 6607:             }
 6608:         }
 6609:     }
 6610:     return %privileged;
 6611: }
 6612: 
 6613: # -------------------------------------------------------- Get user privileges
 6614: 
 6615: sub rolesinit {
 6616:     my ($domain, $username) = @_;
 6617:     my %userroles = ('user.login.time' => time);
 6618:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6619: 
 6620:     # firstaccess and timerinterval are related to timed maps/resources. 
 6621:     # also, blocking can be triggered by an activating timer
 6622:     # it's saved in the user's %env.
 6623:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6624:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6625:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6626:         %timerintchk, %timerintenv);
 6627: 
 6628:     foreach my $key (keys(%firstaccess)) {
 6629:         my ($cid, $rest) = split(/\0/, $key);
 6630:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6631:     }
 6632: 
 6633:     foreach my $key (keys(%timerinterval)) {
 6634:         my ($cid,$rest) = split(/\0/,$key);
 6635:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6636:     }
 6637: 
 6638:     my %allroles=();
 6639:     my %allgroups=();
 6640: 
 6641:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6642:         my $role = $rolesdump{$area};
 6643:         $area =~ s/\_\w\w$//;
 6644: 
 6645:         my ($trole, $tend, $tstart, $group_privs);
 6646: 
 6647:         if ($role =~ /^cr/) {
 6648:         # Custom role, defined by a user 
 6649:         # e.g., user.role.cr/msu/smith/mynewrole
 6650:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6651:                 $trole = $1;
 6652:                 ($tend, $tstart) = split('_', $2);
 6653:             } else {
 6654:                 $trole = $role;
 6655:             }
 6656:         } elsif ($role =~ m|^gr/|) {
 6657:         # Role of member in a group, defined within a course/community
 6658:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6659:             ($trole, $tend, $tstart) = split(/_/, $role);
 6660:             next if $tstart eq '-1';
 6661:             ($trole, $group_privs) = split(/\//, $trole);
 6662:             $group_privs = &unescape($group_privs);
 6663:         } else {
 6664:         # Just a normal role, defined in roles.tab
 6665:             ($trole, $tend, $tstart) = split(/_/,$role);
 6666:         }
 6667: 
 6668:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6669:                  $username);
 6670:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6671: 
 6672:         # role expired or not available yet?
 6673:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6674:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6675: 
 6676:         next if $area eq '' or $trole eq '';
 6677: 
 6678:         my $spec = "$trole.$area";
 6679:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6680: 
 6681:         if ($trole =~ /^cr\//) {
 6682:         # Custom role, defined by a user
 6683:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6684:         } elsif ($trole eq 'gr') {
 6685:         # Role of a member in a group, defined within a course/community
 6686:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6687:             next;
 6688:         } else {
 6689:         # Normal role, defined in roles.tab
 6690:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6691:         }
 6692: 
 6693:         my $cid = $tdomain.'_'.$trest;
 6694:         unless ($firstaccchk{$cid}) {
 6695:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6696:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6697:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6698:                         $coursetimerstarts{$cid}{$item}; 
 6699:                 }
 6700:             }
 6701:             $firstaccchk{$cid} = 1;
 6702:         }
 6703:         unless ($timerintchk{$cid}) {
 6704:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6705:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6706:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6707:                        $coursetimerintervals{$cid}{$item};
 6708:                 }
 6709:             }
 6710:             $timerintchk{$cid} = 1;
 6711:         }
 6712:     }
 6713: 
 6714:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6715:                                                           \%allroles, \%allgroups);
 6716:     $env{'user.adv'} = $userroles{'user.adv'};
 6717:     $env{'user.rar'} = $userroles{'user.rar'};
 6718: 
 6719:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6720: }
 6721: 
 6722: sub set_arearole {
 6723:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6724:     unless ($nolog) {
 6725: # log the associated role with the area
 6726:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6727:     }
 6728:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6729: }
 6730: 
 6731: sub custom_roleprivs {
 6732:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6733:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6734:     my $homsvr = &homeserver($rauthor,$rdomain);
 6735:     if (&hostname($homsvr) ne '') {
 6736:         my ($rdummy,$roledef)=
 6737:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6738:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6739:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6740:             if (defined($syspriv)) {
 6741:                 if ($trest =~ /^$match_community$/) {
 6742:                     $syspriv =~ s/bre\&S//; 
 6743:                 }
 6744:                 $$allroles{'cm./'}.=':'.$syspriv;
 6745:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6746:             }
 6747:             if ($tdomain ne '') {
 6748:                 if (defined($dompriv)) {
 6749:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6750:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6751:                 }
 6752:                 if (($trest ne '') && (defined($coursepriv))) {
 6753:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6754:                         my $rolename = $1;
 6755:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6756:                     }
 6757:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6758:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6759:                 }
 6760:             }
 6761:         }
 6762:     }
 6763: }
 6764: 
 6765: sub course_adhocrole_privs {
 6766:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6767:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6768:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6769:         my (%currprivs,%storeprivs);
 6770:         foreach my $item (split(/:/,$coursepriv)) {
 6771:             my ($priv,$restrict) = split(/\&/,$item);
 6772:             $currprivs{$priv} = $restrict;
 6773:         }
 6774:         my (%possadd,%possremove,%full);
 6775:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6776:             my ($priv,$restrict)=split(/\&/,$item);
 6777:             $full{$priv} = $restrict;
 6778:         }
 6779:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6780:              next if ($item eq '');
 6781:              my ($rule,$rest) = split(/=/,$item);
 6782:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6783:              foreach my $priv (split(/:/,$rest)) {
 6784:                  if ($priv ne '') {
 6785:                      if ($rule eq 'off') {
 6786:                          $possremove{$priv} = 1;
 6787:                      } else {
 6788:                          $possadd{$priv} = 1;
 6789:                      }
 6790:                  }
 6791:              }
 6792:          }
 6793:          foreach my $priv (sort(keys(%full))) {
 6794:              if (exists($currprivs{$priv})) {
 6795:                  unless (exists($possremove{$priv})) {
 6796:                      $storeprivs{$priv} = $currprivs{$priv};
 6797:                  }
 6798:              } elsif (exists($possadd{$priv})) {
 6799:                  $storeprivs{$priv} = $full{$priv};
 6800:              }
 6801:          }
 6802:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6803:      }
 6804:      return $coursepriv;
 6805: }
 6806: 
 6807: sub group_roleprivs {
 6808:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6809:     my $access = 1;
 6810:     my $now = time;
 6811:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6812:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6813:     if ($access) {
 6814:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6815:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6816:     }
 6817: }
 6818: 
 6819: sub standard_roleprivs {
 6820:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6821:     if (defined($pr{$trole.':s'})) {
 6822:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6823:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6824:     }
 6825:     if ($tdomain ne '') {
 6826:         if (defined($pr{$trole.':d'})) {
 6827:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6828:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6829:         }
 6830:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6831:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6832:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6833:         }
 6834:     }
 6835: }
 6836: 
 6837: sub set_userprivs {
 6838:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6839:     my $author=0;
 6840:     my $adv=0;
 6841:     my $rar=0;
 6842:     my %grouproles = ();
 6843:     if (keys(%{$allgroups}) > 0) {
 6844:         my @groupkeys; 
 6845:         foreach my $role (keys(%{$allroles})) {
 6846:             push(@groupkeys,$role);
 6847:         }
 6848:         if (ref($groups_roles) eq 'HASH') {
 6849:             foreach my $key (keys(%{$groups_roles})) {
 6850:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6851:                     push(@groupkeys,$key);
 6852:                 }
 6853:             }
 6854:         }
 6855:         if (@groupkeys > 0) {
 6856:             foreach my $role (@groupkeys) {
 6857:                 my ($trole,$area,$sec,$extendedarea);
 6858:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6859:                     $trole = $1;
 6860:                     $area = $2;
 6861:                     $sec = $3;
 6862:                     $extendedarea = $area.$sec;
 6863:                     if (exists($$allgroups{$area})) {
 6864:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6865:                             my $spec = $trole.'.'.$extendedarea;
 6866:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6867:                                                 $$allgroups{$area}{$group};
 6868:                         }
 6869:                     }
 6870:                 }
 6871:             }
 6872:         }
 6873:     }
 6874:     foreach my $group (keys(%grouproles)) {
 6875:         $$allroles{$group} = $grouproles{$group};
 6876:     }
 6877:     foreach my $role (keys(%{$allroles})) {
 6878:         my %thesepriv;
 6879:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6880:         foreach my $item (split(/:/,$$allroles{$role})) {
 6881:             if ($item ne '') {
 6882:                 my ($privilege,$restrictions)=split(/&/,$item);
 6883:                 if ($restrictions eq '') {
 6884:                     $thesepriv{$privilege}='F';
 6885:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6886:                     $thesepriv{$privilege}.=$restrictions;
 6887:                 }
 6888:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6889:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6890:             }
 6891:         }
 6892:         my $thesestr='';
 6893:         foreach my $priv (sort(keys(%thesepriv))) {
 6894: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6895: 	}
 6896:         $userroles->{'user.priv.'.$role} = $thesestr;
 6897:     }
 6898:     return ($author,$adv,$rar);
 6899: }
 6900: 
 6901: sub role_status {
 6902:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6903:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6904:         my ($one,$two) = split(m{\./},$rolekey,2);
 6905:         (undef,undef,$$role) = split(/\./,$one,3);
 6906:         unless (!defined($$role) || $$role eq '') {
 6907:             $$where = '/'.$two;
 6908:             $$trolecode=$$role.'.'.$$where;
 6909:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6910:             $$tstatus='is';
 6911:             if ($$tstart && $$tstart>$update) {
 6912:                 $$tstatus='future';
 6913:                 if ($$tstart<$now) {
 6914:                     if ($$tstart && $$tstart>$refresh) {
 6915:                         if (($$where ne '') && ($$role ne '')) {
 6916:                             my (%allroles,%allgroups,$group_privs,
 6917:                                 %groups_roles,@rolecodes);
 6918:                             my %userroles = (
 6919:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6920:                             );
 6921:                             @rolecodes = ('cm'); 
 6922:                             my $spec=$$role.'.'.$$where;
 6923:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6924:                             if ($$role =~ /^cr\//) {
 6925:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6926:                                 push(@rolecodes,'cr');
 6927:                             } elsif ($$role eq 'gr') {
 6928:                                 push(@rolecodes,$$role);
 6929:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6930:                                                     $env{'user.name'});
 6931:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6932:                                 (undef,my $group_privs) = split(/\//,$trole);
 6933:                                 $group_privs = &unescape($group_privs);
 6934:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6935:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6936:                                 &get_groups_roles($tdomain,$trest,
 6937:                                                   \%course_roles,\@rolecodes,
 6938:                                                   \%groups_roles);
 6939:                             } else {
 6940:                                 push(@rolecodes,$$role);
 6941:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6942:                             }
 6943:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6944:                                                                    \%groups_roles);
 6945:                             &appenv(\%userroles,\@rolecodes);
 6946:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6947:                         }
 6948:                     }
 6949:                     $$tstatus = 'is';
 6950:                 }
 6951:             }
 6952:             if ($$tend) {
 6953:                 if ($$tend<$update) {
 6954:                     $$tstatus='expired';
 6955:                 } elsif ($$tend<$now) {
 6956:                     $$tstatus='will_not';
 6957:                 }
 6958:             }
 6959:         }
 6960:     }
 6961: }
 6962: 
 6963: sub get_groups_roles {
 6964:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6965:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6966:                   (ref($rolecodes) eq 'ARRAY') && 
 6967:                   (ref($groups_roles) eq 'HASH')); 
 6968:     if (keys(%{$cdom_courseroles}) > 0) {
 6969:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6970:         if ($cdom ne '' && $cnum ne '') {
 6971:             foreach my $key (keys(%{$cdom_courseroles})) {
 6972:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6973:                     my $crsrole = $1;
 6974:                     my $crssec = $2;
 6975:                     if ($crsrole =~ /^cr/) {
 6976:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6977:                             push(@{$rolecodes},'cr');
 6978:                         }
 6979:                     } else {
 6980:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6981:                             push(@{$rolecodes},$crsrole);
 6982:                         }
 6983:                     }
 6984:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6985:                     if ($crssec ne '') {
 6986:                         $rolekey .= "/$crssec";
 6987:                     }
 6988:                     $rolekey .= './';
 6989:                     $groups_roles->{$rolekey} = $rolecodes;
 6990:                 }
 6991:             }
 6992:         }
 6993:     }
 6994:     return;
 6995: }
 6996: 
 6997: sub delete_env_groupprivs {
 6998:     my ($where,$courseroles,$possroles) = @_;
 6999:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7000:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7001:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7002:         %{$courseroles->{$udom}} =
 7003:             &get_my_roles('','','userroles',['active'],
 7004:                           $possroles,[$udom],1);
 7005:     }
 7006:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7007:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7008:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7009:             my $area = '/'.$cdom.'/'.$cnum;
 7010:             my $privkey = "user.priv.$crsrole.$area";
 7011:             if ($crssec ne '') {
 7012:                 $privkey .= '/'.$crssec;
 7013:             }
 7014:             $privkey .= ".$area/$group";
 7015:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7016:         }
 7017:     }
 7018:     return;
 7019: }
 7020: 
 7021: sub check_adhoc_privs {
 7022:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7023:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7024:     if ($sec) {
 7025:         $cckey .= '/'.$sec;
 7026:     } 
 7027:     my $setprivs;
 7028:     if ($env{$cckey}) {
 7029:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7030:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7031:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7032:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7033:             $setprivs = 1;
 7034:         }
 7035:     } else {
 7036:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7037:         $setprivs = 1;
 7038:     }
 7039:     return $setprivs;
 7040: }
 7041: 
 7042: sub set_adhoc_privileges {
 7043: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7044:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7045:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7046:     if ($sec ne '') {
 7047:         $area .= '/'.$sec;
 7048:     }
 7049:     my $spec = $role.'.'.$area;
 7050:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7051:                                   $env{'user.name'},1);
 7052:     my %rolehash = ();
 7053:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7054:         my $rolename = $1;
 7055:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7056:         my %domdef = &get_domain_defaults($dcdom);
 7057:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7058:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7059:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7060:             }
 7061:         }
 7062:     } else {
 7063:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7064:     }
 7065:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7066:     &appenv(\%userroles,[$role,'cm']);
 7067:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7068:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7069:             ($caller eq 'tiny')) {
 7070:         &appenv( {'request.role'        => $spec,
 7071:                   'request.role.domain' => $dcdom,
 7072:                   'request.course.sec'  => $sec,
 7073:                  }
 7074:                );
 7075:         my $tadv=0;
 7076:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7077:         &appenv({'request.role.adv'    => $tadv});
 7078:     }
 7079: }
 7080: 
 7081: # --------------------------------------------------------------- get interface
 7082: 
 7083: sub get {
 7084:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7085:    my $items='';
 7086:    foreach my $item (@$storearr) {
 7087:        $items.=&escape($item).'&';
 7088:    }
 7089:    $items=~s/\&$//;
 7090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7091:    if (!$uname) { $uname=$env{'user.name'}; }
 7092:    my $uhome=&homeserver($uname,$udomain);
 7093: 
 7094:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7095:    my @pairs=split(/\&/,$rep);
 7096:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7097:      return @pairs;
 7098:    }
 7099:    my %returnhash=();
 7100:    my $i=0;
 7101:    foreach my $item (@$storearr) {
 7102:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7103:       $i++;
 7104:    }
 7105:    return %returnhash;
 7106: }
 7107: 
 7108: # --------------------------------------------------------------- del interface
 7109: 
 7110: sub del {
 7111:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7112:    my $items='';
 7113:    foreach my $item (@$storearr) {
 7114:        $items.=&escape($item).'&';
 7115:    }
 7116: 
 7117:    $items=~s/\&$//;
 7118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7119:    if (!$uname) { $uname=$env{'user.name'}; }
 7120:    my $uhome=&homeserver($uname,$udomain);
 7121:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7122: }
 7123: 
 7124: # -------------------------------------------------------------- dump interface
 7125: 
 7126: sub unserialize {
 7127:     my ($rep, $escapedkeys) = @_;
 7128: 
 7129:     return {} if $rep =~ /^error/;
 7130: 
 7131:     my %returnhash=();
 7132: 	foreach my $item (split(/\&/,$rep)) {
 7133: 	    my ($key, $value) = split(/=/, $item, 2);
 7134: 	    $key = unescape($key) unless $escapedkeys;
 7135: 	    next if $key =~ /^error: 2 /;
 7136: 	    $returnhash{$key} = &thaw_unescape($value);
 7137: 	}
 7138:     #return %returnhash;
 7139:     return \%returnhash;
 7140: }        
 7141: 
 7142: # see Lond::dump_with_regexp
 7143: # if $escapedkeys hash keys won't get unescaped.
 7144: sub dump {
 7145:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7146:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7147:     if (!$uname) { $uname=$env{'user.name'}; }
 7148:     my $uhome=&homeserver($uname,$udomain);
 7149: 
 7150:     if ($regexp) {
 7151:         $regexp=&escape($regexp);
 7152:     } else {
 7153:         $regexp='.';
 7154:     }
 7155:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7156:         # user is hosted on this machine
 7157:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7158:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7159:         return %{unserialize($reply, $escapedkeys)};
 7160:     }
 7161:     my $rep;
 7162:     if ($encrypt) {
 7163:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7164:     } else {
 7165:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7166:     }
 7167:     my @pairs=split(/\&/,$rep);
 7168:     my %returnhash=();
 7169:     if (!($rep =~ /^error/ )) {
 7170: 	foreach my $item (@pairs) {
 7171: 	    my ($key,$value)=split(/=/,$item,2);
 7172:         $key = unescape($key) unless $escapedkeys;
 7173:         #$key = &unescape($key);
 7174: 	    next if ($key =~ /^error: 2 /);
 7175: 	    $returnhash{$key}=&thaw_unescape($value);
 7176: 	}
 7177:     }
 7178:     return %returnhash;
 7179: }
 7180: 
 7181: 
 7182: # --------------------------------------------------------- dumpstore interface
 7183: 
 7184: sub dumpstore {
 7185:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7186:    # same as dump but keys must be escaped. They may contain colon separated
 7187:    # lists of values that may themself contain colons (e.g. symbs).
 7188:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7189: }
 7190: 
 7191: # -------------------------------------------------------------- keys interface
 7192: 
 7193: sub getkeys {
 7194:    my ($namespace,$udomain,$uname)=@_;
 7195:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7196:    if (!$uname) { $uname=$env{'user.name'}; }
 7197:    my $uhome=&homeserver($uname,$udomain);
 7198:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7199:    my @keyarray=();
 7200:    foreach my $key (split(/\&/,$rep)) {
 7201:       next if ($key =~ /^error: 2 /);
 7202:       push(@keyarray,&unescape($key));
 7203:    }
 7204:    return @keyarray;
 7205: }
 7206: 
 7207: # --------------------------------------------------------------- currentdump
 7208: sub currentdump {
 7209:    my ($courseid,$sdom,$sname)=@_;
 7210:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7211:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7212:    $sname    = $env{'user.name'}         if (! defined($sname));
 7213:    my $uhome = &homeserver($sname,$sdom);
 7214:    my $rep;
 7215: 
 7216:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7217:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7218:                    $courseid)));
 7219:    } else {
 7220:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7221:    }
 7222: 
 7223:    return if ($rep =~ /^(error:|no_such_host)/);
 7224:    #
 7225:    my %returnhash=();
 7226:    #
 7227:    if ($rep eq 'unknown_cmd') {
 7228:        # an old lond will not know currentdump
 7229:        # Do a dump and make it look like a currentdump
 7230:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7231:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7232:        my %hash = @tmp;
 7233:        @tmp=();
 7234:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7235:    } else {
 7236:        my @pairs=split(/\&/,$rep);
 7237:        foreach my $pair (@pairs) {
 7238:            my ($key,$value)=split(/=/,$pair,2);
 7239:            my ($symb,$param) = split(/:/,$key);
 7240:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7241:                                                         &thaw_unescape($value);
 7242:        }
 7243:    }
 7244:    return %returnhash;
 7245: }
 7246: 
 7247: sub convert_dump_to_currentdump{
 7248:     my %hash = %{shift()};
 7249:     my %returnhash;
 7250:     # Code ripped from lond, essentially.  The only difference
 7251:     # here is the unescaping done by lonnet::dump().  Conceivably
 7252:     # we might run in to problems with parameter names =~ /^v\./
 7253:     while (my ($key,$value) = each(%hash)) {
 7254:         my ($v,$symb,$param) = split(/:/,$key);
 7255: 	$symb  = &unescape($symb);
 7256: 	$param = &unescape($param);
 7257:         next if ($v eq 'version' || $symb eq 'keys');
 7258:         next if (exists($returnhash{$symb}) &&
 7259:                  exists($returnhash{$symb}->{$param}) &&
 7260:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7261:         $returnhash{$symb}->{$param}=$value;
 7262:         $returnhash{$symb}->{'v.'.$param}=$v;
 7263:     }
 7264:     #
 7265:     # Remove all of the keys in the hashes which keep track of
 7266:     # the version of the parameter.
 7267:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7268:         # use a foreach because we are going to delete from the hash.
 7269:         foreach my $key (keys(%$param_hash)) {
 7270:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7271:         }
 7272:     }
 7273:     return \%returnhash;
 7274: }
 7275: 
 7276: # ------------------------------------------------------ critical inc interface
 7277: 
 7278: sub cinc {
 7279:     return &inc(@_,'critical');
 7280: }
 7281: 
 7282: # --------------------------------------------------------------- inc interface
 7283: 
 7284: sub inc {
 7285:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7286:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7287:     if (!$uname) { $uname=$env{'user.name'}; }
 7288:     my $uhome=&homeserver($uname,$udomain);
 7289:     my $items='';
 7290:     if (! ref($store)) {
 7291:         # got a single value, so use that instead
 7292:         $items = &escape($store).'=&';
 7293:     } elsif (ref($store) eq 'SCALAR') {
 7294:         $items = &escape($$store).'=&';        
 7295:     } elsif (ref($store) eq 'ARRAY') {
 7296:         $items = join('=&',map {&escape($_);} @{$store});
 7297:     } elsif (ref($store) eq 'HASH') {
 7298:         while (my($key,$value) = each(%{$store})) {
 7299:             $items.= &escape($key).'='.&escape($value).'&';
 7300:         }
 7301:     }
 7302:     $items=~s/\&$//;
 7303:     if ($critical) {
 7304: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7305:     } else {
 7306: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7307:     }
 7308: }
 7309: 
 7310: # --------------------------------------------------------------- put interface
 7311: 
 7312: sub put {
 7313:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7314:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7315:    if (!$uname) { $uname=$env{'user.name'}; }
 7316:    my $uhome=&homeserver($uname,$udomain);
 7317:    my $items='';
 7318:    foreach my $item (keys(%$storehash)) {
 7319:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7320:    }
 7321:    $items=~s/\&$//;
 7322:    if ($encrypt) {
 7323:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7324:    } else {
 7325:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7326:    }
 7327: }
 7328: 
 7329: # ------------------------------------------------------------ newput interface
 7330: 
 7331: sub newput {
 7332:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7333:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7334:    if (!$uname) { $uname=$env{'user.name'}; }
 7335:    my $uhome=&homeserver($uname,$udomain);
 7336:    my $items='';
 7337:    foreach my $key (keys(%$storehash)) {
 7338:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7339:    }
 7340:    $items=~s/\&$//;
 7341:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7342: }
 7343: 
 7344: # ---------------------------------------------------------  putstore interface
 7345: 
 7346: sub putstore {
 7347:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7349:    if (!$uname) { $uname=$env{'user.name'}; }
 7350:    my $uhome=&homeserver($uname,$udomain);
 7351:    my $items='';
 7352:    foreach my $key (keys(%$storehash)) {
 7353:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7354:    }
 7355:    $items=~s/\&$//;
 7356:    my $esc_symb=&escape($symb);
 7357:    my $esc_v=&escape($version);
 7358:    my $reply =
 7359:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7360: 	      $uhome);
 7361:    if (($tolog) && ($reply eq 'ok')) {
 7362:        my $namevalue='';
 7363:        foreach my $key (keys(%{$storehash})) {
 7364:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7365:        }
 7366:        my $ip = &get_requestor_ip();
 7367:        $namevalue .= 'ip='.&escape($ip).
 7368:                      '&host='.&escape($perlvar{'lonHostID'}).
 7369:                      '&version='.$esc_v.
 7370:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7371:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7372:    }
 7373:    if ($reply eq 'unknown_cmd') {
 7374:        # gfall back to way things use to be done
 7375:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7376: 			    $uname);
 7377:    }
 7378:    return $reply;
 7379: }
 7380: 
 7381: sub old_putstore {
 7382:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7383:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7384:     if (!$uname) { $uname=$env{'user.name'}; }
 7385:     my $uhome=&homeserver($uname,$udomain);
 7386:     my %newstorehash;
 7387:     foreach my $item (keys(%$storehash)) {
 7388: 	my $key = $version.':'.&escape($symb).':'.$item;
 7389: 	$newstorehash{$key} = $storehash->{$item};
 7390:     }
 7391:     my $items='';
 7392:     my %allitems = ();
 7393:     foreach my $item (keys(%newstorehash)) {
 7394: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7395: 	    my $key = $1.':keys:'.$2;
 7396: 	    $allitems{$key} .= $3.':';
 7397: 	}
 7398: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7399:     }
 7400:     foreach my $item (keys(%allitems)) {
 7401: 	$allitems{$item} =~ s/\:$//;
 7402: 	$items.= $item.'='.$allitems{$item}.'&';
 7403:     }
 7404:     $items=~s/\&$//;
 7405:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7406: }
 7407: 
 7408: # ------------------------------------------------------ critical put interface
 7409: 
 7410: sub cput {
 7411:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7412:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7413:    if (!$uname) { $uname=$env{'user.name'}; }
 7414:    my $uhome=&homeserver($uname,$udomain);
 7415:    my $items='';
 7416:    foreach my $item (keys(%$storehash)) {
 7417:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7418:    }
 7419:    $items=~s/\&$//;
 7420:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7421: }
 7422: 
 7423: # -------------------------------------------------------------- eget interface
 7424: 
 7425: sub eget {
 7426:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7427:    my $items='';
 7428:    foreach my $item (@$storearr) {
 7429:        $items.=&escape($item).'&';
 7430:    }
 7431:    $items=~s/\&$//;
 7432:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7433:    if (!$uname) { $uname=$env{'user.name'}; }
 7434:    my $uhome=&homeserver($uname,$udomain);
 7435:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7436:    my @pairs=split(/\&/,$rep);
 7437:    my %returnhash=();
 7438:    my $i=0;
 7439:    foreach my $item (@$storearr) {
 7440:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7441:       $i++;
 7442:    }
 7443:    return %returnhash;
 7444: }
 7445: 
 7446: # ------------------------------------------------------------ tmpput interface
 7447: sub tmpput {
 7448:     my ($storehash,$server,$context)=@_;
 7449:     my $items='';
 7450:     foreach my $item (keys(%$storehash)) {
 7451: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7452:     }
 7453:     $items=~s/\&$//;
 7454:     if (defined($context)) {
 7455:         $items .= ':'.&escape($context);
 7456:     }
 7457:     return &reply("tmpput:$items",$server);
 7458: }
 7459: 
 7460: # ------------------------------------------------------------ tmpget interface
 7461: sub tmpget {
 7462:     my ($token,$server)=@_;
 7463:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7464:     my $rep=&reply("tmpget:$token",$server);
 7465:     my %returnhash;
 7466:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7467:         return %returnhash;
 7468:     }
 7469:     foreach my $item (split(/\&/,$rep)) {
 7470: 	my ($key,$value)=split(/=/,$item);
 7471: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7472:     }
 7473:     return %returnhash;
 7474: }
 7475: 
 7476: # ------------------------------------------------------------ tmpdel interface
 7477: sub tmpdel {
 7478:     my ($token,$server)=@_;
 7479:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7480:     return &reply("tmpdel:$token",$server);
 7481: }
 7482: 
 7483: # ------------------------------------------------------------ get_timebased_id 
 7484: 
 7485: sub get_timebased_id {
 7486:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7487:         $maxtries) = @_;
 7488:     my ($newid,$error,$dellock);
 7489:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7490:         return ('','ok','invalid call to get suffix');
 7491:     }
 7492: 
 7493: # set defaults for any optional args for which values were not supplied
 7494:     if ($who eq '') {
 7495:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7496:     }
 7497:     if (!$locktries) {
 7498:         $locktries = 3;
 7499:     }
 7500:     if (!$maxtries) {
 7501:         $maxtries = 10;
 7502:     }
 7503:     
 7504:     if (($cdom eq '') || ($cnum eq '')) {
 7505:         if ($env{'request.course.id'}) {
 7506:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7507:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7508:         }
 7509:         if (($cdom eq '') || ($cnum eq '')) {
 7510:             return ('','ok','call to get suffix not in course context');
 7511:         }
 7512:     }
 7513: 
 7514: # construct locking item
 7515:     my $lockhash = {
 7516:                       $prefix."\0".'locked_'.$keyid => $who,
 7517:                    };
 7518:     my $tries = 0;
 7519: 
 7520: # attempt to get lock on nohist_$namespace file
 7521:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7522:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7523:         $tries ++;
 7524:         sleep 1;
 7525:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7526:     }
 7527: 
 7528: # attempt to get unique identifier, based on current timestamp
 7529:     if ($gotlock eq 'ok') {
 7530:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7531:         my $id = time;
 7532:         $newid = $id;
 7533:         if ($idtype eq 'addcode') {
 7534:             $newid .= &sixnum_code();
 7535:         }
 7536:         my $idtries = 0;
 7537:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7538:             if ($idtype eq 'concat') {
 7539:                 $newid = $id.$idtries;
 7540:             } elsif ($idtype eq 'addcode') {
 7541:                 $newid = $newid.&sixnum_code();
 7542:             } else {
 7543:                 $newid ++;
 7544:             }
 7545:             $idtries ++;
 7546:         }
 7547:         if (!exists($inuse{$prefix."\0".$newid})) {
 7548:             my %new_item =  (
 7549:                               $prefix."\0".$newid => $who,
 7550:                             );
 7551:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7552:                                                  $cdom,$cnum);
 7553:             if ($putresult ne 'ok') {
 7554:                 undef($newid);
 7555:                 $error = 'error saving new item: '.$putresult;
 7556:             }
 7557:         } else {
 7558:              undef($newid);
 7559:              $error = ('error: no unique suffix available for the new item ');
 7560:         }
 7561: #  remove lock
 7562:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7563:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7564:     } else {
 7565:         $error = "error: could not obtain lockfile\n";
 7566:         $dellock = 'ok';
 7567:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7568:             $dellock = 'nolock';
 7569:         }
 7570:     }
 7571:     return ($newid,$dellock,$error);
 7572: }
 7573: 
 7574: sub sixnum_code {
 7575:     my $code;
 7576:     for (0..6) {
 7577:         $code .= int( rand(9) );
 7578:     }
 7579:     return $code;
 7580: }
 7581: 
 7582: # -------------------------------------------------- portfolio access checking
 7583: 
 7584: sub portfolio_access {
 7585:     my ($requrl,$clientip) = @_;
 7586:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7587:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7588:     if ($result) {
 7589:         my %setters;
 7590:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7591:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7592:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7593:             if (($startblock && $endblock) || ($by_ip)) {
 7594:                 return 'B';
 7595:             }
 7596:         } else {
 7597:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7598:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7599:             if (($startblock && $endblock) || ($by_ip)) {
 7600:                 return 'B';
 7601:             }
 7602:         }
 7603:     }
 7604:     if ($result eq 'ok') {
 7605:        return 'F';
 7606:     } elsif ($result =~ /^[^:]+:guest_/) {
 7607:        return 'A';
 7608:     }
 7609:     return '';
 7610: }
 7611: 
 7612: sub get_portfolio_access {
 7613:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7614: 
 7615:     if (!ref($access_hash)) {
 7616: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7617: 	my %access_controls = &get_access_controls($current_perms,$group,
 7618: 						   $file_name);
 7619: 	$access_hash = $access_controls{$file_name};
 7620:     }
 7621: 
 7622:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7623:     my $now = time;
 7624:     if (ref($access_hash) eq 'HASH') {
 7625:         foreach my $key (keys(%{$access_hash})) {
 7626:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7627:             if ($start > $now) {
 7628:                 next;
 7629:             }
 7630:             if ($end && $end<$now) {
 7631:                 next;
 7632:             }
 7633:             if ($scope eq 'public') {
 7634:                 $public = $key;
 7635:                 last;
 7636:             } elsif ($scope eq 'guest') {
 7637:                 $guest = $key;
 7638:             } elsif ($scope eq 'domains') {
 7639:                 push(@domains,$key);
 7640:             } elsif ($scope eq 'users') {
 7641:                 push(@users,$key);
 7642:             } elsif ($scope eq 'course') {
 7643:                 push(@courses,$key);
 7644:             } elsif ($scope eq 'group') {
 7645:                 push(@groups,$key);
 7646:             } elsif ($scope eq 'ip') {
 7647:                 push(@ips,$key);
 7648:             }
 7649:         }
 7650:         if ($public) {
 7651:             return 'ok';
 7652:         } elsif (@ips > 0) {
 7653:             my $allowed;
 7654:             foreach my $ipkey (@ips) {
 7655:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7656:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7657:                         $allowed = 1;
 7658:                         last; 
 7659:                     }
 7660:                 }
 7661:             }
 7662:             if ($allowed) {
 7663:                 return 'ok';
 7664:             }
 7665:         }
 7666:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7667:             if ($guest) {
 7668:                 return $guest;
 7669:             }
 7670:         } else {
 7671:             if (@domains > 0) {
 7672:                 foreach my $domkey (@domains) {
 7673:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7674:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7675:                             return 'ok';
 7676:                         }
 7677:                     }
 7678:                 }
 7679:             }
 7680:             if (@users > 0) {
 7681:                 foreach my $userkey (@users) {
 7682:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7683:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7684:                             if (ref($item) eq 'HASH') {
 7685:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7686:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7687:                                     return 'ok';
 7688:                                 }
 7689:                             }
 7690:                         }
 7691:                     } 
 7692:                 }
 7693:             }
 7694:             my %roleshash;
 7695:             my @courses_and_groups = @courses;
 7696:             push(@courses_and_groups,@groups); 
 7697:             if (@courses_and_groups > 0) {
 7698:                 my (%allgroups,%allroles); 
 7699:                 my ($start,$end,$role,$sec,$group);
 7700:                 foreach my $envkey (%env) {
 7701:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7702:                         my $cid = $2.'_'.$3; 
 7703:                         if ($1 eq 'gr') {
 7704:                             $group = $4;
 7705:                             $allgroups{$cid}{$group} = $env{$envkey};
 7706:                         } else {
 7707:                             if ($4 eq '') {
 7708:                                 $sec = 'none';
 7709:                             } else {
 7710:                                 $sec = $4;
 7711:                             }
 7712:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7713:                         }
 7714:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7715:                         my $cid = $2.'_'.$3;
 7716:                         if ($4 eq '') {
 7717:                             $sec = 'none';
 7718:                         } else {
 7719:                             $sec = $4;
 7720:                         }
 7721:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7722:                     }
 7723:                 }
 7724:                 if (keys(%allroles) == 0) {
 7725:                     return;
 7726:                 }
 7727:                 foreach my $key (@courses_and_groups) {
 7728:                     my %content = %{$$access_hash{$key}};
 7729:                     my $cnum = $content{'number'};
 7730:                     my $cdom = $content{'domain'};
 7731:                     my $cid = $cdom.'_'.$cnum;
 7732:                     if (!exists($allroles{$cid})) {
 7733:                         next;
 7734:                     }    
 7735:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7736:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7737:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7738:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7739:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7740:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7741:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7742:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7743:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7744:                                         if (grep/^all$/,@sections) {
 7745:                                             return 'ok';
 7746:                                         } else {
 7747:                                             if (grep/^$sec$/,@sections) {
 7748:                                                 return 'ok';
 7749:                                             }
 7750:                                         }
 7751:                                     }
 7752:                                 }
 7753:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7754:                                     if (grep/^none$/,@groups) {
 7755:                                         return 'ok';
 7756:                                     }
 7757:                                 } else {
 7758:                                     if (grep/^all$/,@groups) {
 7759:                                         return 'ok';
 7760:                                     } 
 7761:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7762:                                         if (grep/^$group$/,@groups) {
 7763:                                             return 'ok';
 7764:                                         }
 7765:                                     }
 7766:                                 } 
 7767:                             }
 7768:                         }
 7769:                     }
 7770:                 }
 7771:             }
 7772:             if ($guest) {
 7773:                 return $guest;
 7774:             }
 7775:         }
 7776:     }
 7777:     return;
 7778: }
 7779: 
 7780: sub course_group_datechecker {
 7781:     my ($dates,$now,$status) = @_;
 7782:     my ($start,$end) = split(/\./,$dates);
 7783:     if (!$start && !$end) {
 7784:         return 'ok';
 7785:     }
 7786:     if (grep/^active$/,@{$status}) {
 7787:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7788:             return 'ok';
 7789:         }
 7790:     }
 7791:     if (grep/^previous$/,@{$status}) {
 7792:         if ($end > $now ) {
 7793:             return 'ok';
 7794:         }
 7795:     }
 7796:     if (grep/^future$/,@{$status}) {
 7797:         if ($start > $now) {
 7798:             return 'ok';
 7799:         }
 7800:     }
 7801:     return; 
 7802: }
 7803: 
 7804: sub parse_portfolio_url {
 7805:     my ($url) = @_;
 7806: 
 7807:     my ($type,$udom,$unum,$group,$file_name);
 7808:     
 7809:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7810: 	$type = 1;
 7811:         $udom = $1;
 7812:         $unum = $2;
 7813:         $file_name = $3;
 7814:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7815: 	$type = 2;
 7816:         $udom = $1;
 7817:         $unum = $2;
 7818:         $group = $3;
 7819:         $file_name = $3.'/'.$4;
 7820:     }
 7821:     if (wantarray) {
 7822: 	return ($type,$udom,$unum,$file_name,$group);
 7823:     }
 7824:     return $type;
 7825: }
 7826: 
 7827: sub is_portfolio_url {
 7828:     my ($url) = @_;
 7829:     return scalar(&parse_portfolio_url($url));
 7830: }
 7831: 
 7832: sub is_portfolio_file {
 7833:     my ($file) = @_;
 7834:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7835:         return 1;
 7836:     }
 7837:     return;
 7838: }
 7839: 
 7840: sub usertools_access {
 7841:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7842:     my ($access,%tools);
 7843:     if ($context eq '') {
 7844:         $context = 'tools';
 7845:     }
 7846:     if ($context eq 'requestcourses') {
 7847:         %tools = (
 7848:                       official   => 1,
 7849:                       unofficial => 1,
 7850:                       community  => 1,
 7851:                       textbook   => 1,
 7852:                       placement  => 1,
 7853:                       lti        => 1,
 7854:                  );
 7855:     } elsif ($context eq 'requestauthor') {
 7856:         %tools = (
 7857:                       requestauthor => 1,
 7858:                  );
 7859:     } else {
 7860:         %tools = (
 7861:                       aboutme   => 1,
 7862:                       blog      => 1,
 7863:                       webdav    => 1,
 7864:                       portfolio => 1,
 7865:                  );
 7866:     }
 7867:     return if (!defined($tools{$tool}));
 7868: 
 7869:     if (($udom eq '') || ($uname eq '')) {
 7870:         $udom = $env{'user.domain'};
 7871:         $uname = $env{'user.name'};
 7872:     }
 7873: 
 7874:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7875:         if ($action ne 'reload') {
 7876:             if ($context eq 'requestcourses') {
 7877:                 return $env{'environment.canrequest.'.$tool};
 7878:             } elsif ($context eq 'requestauthor') {
 7879:                 return $env{'environment.canrequest.author'};
 7880:             } else {
 7881:                 return $env{'environment.availabletools.'.$tool};
 7882:             }
 7883:         }
 7884:     }
 7885: 
 7886:     my ($toolstatus,$inststatus,$envkey);
 7887:     if ($context eq 'requestauthor') {
 7888:         $envkey = $context; 
 7889:     } else {
 7890:         $envkey = $context.'.'.$tool;
 7891:     }
 7892: 
 7893:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7894:          ($action ne 'reload')) {
 7895:         $toolstatus = $env{'environment.'.$envkey};
 7896:         $inststatus = $env{'environment.inststatus'};
 7897:     } else {
 7898:         if (ref($userenvref) eq 'HASH') {
 7899:             $toolstatus = $userenvref->{$envkey};
 7900:             $inststatus = $userenvref->{'inststatus'};
 7901:         } else {
 7902:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7903:             $toolstatus = $userenv{$envkey};
 7904:             $inststatus = $userenv{'inststatus'};
 7905:         }
 7906:     }
 7907: 
 7908:     if ($toolstatus ne '') {
 7909:         if ($toolstatus) {
 7910:             $access = 1;
 7911:         } else {
 7912:             $access = 0;
 7913:         }
 7914:         return $access;
 7915:     }
 7916: 
 7917:     my ($is_adv,%domdef);
 7918:     if (ref($is_advref) eq 'HASH') {
 7919:         $is_adv = $is_advref->{'is_adv'};
 7920:     } else {
 7921:         $is_adv = &is_advanced_user($udom,$uname);
 7922:     }
 7923:     if (ref($domdefref) eq 'HASH') {
 7924:         %domdef = %{$domdefref};
 7925:     } else {
 7926:         %domdef = &get_domain_defaults($udom);
 7927:     }
 7928:     if (ref($domdef{$tool}) eq 'HASH') {
 7929:         if ($is_adv) {
 7930:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7931:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7932:                     $access = 1;
 7933:                 } else {
 7934:                     $access = 0;
 7935:                 }
 7936:                 return $access;
 7937:             }
 7938:         }
 7939:         if ($inststatus ne '') {
 7940:             my ($hasaccess,$hasnoaccess);
 7941:             foreach my $affiliation (split(/:/,$inststatus)) {
 7942:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7943:                     if ($domdef{$tool}{$affiliation}) {
 7944:                         $hasaccess = 1;
 7945:                     } else {
 7946:                         $hasnoaccess = 1;
 7947:                     }
 7948:                 }
 7949:             }
 7950:             if ($hasaccess || $hasnoaccess) {
 7951:                 if ($hasaccess) {
 7952:                     $access = 1;
 7953:                 } elsif ($hasnoaccess) {
 7954:                     $access = 0; 
 7955:                 }
 7956:                 return $access;
 7957:             }
 7958:         } else {
 7959:             if ($domdef{$tool}{'default'} ne '') {
 7960:                 if ($domdef{$tool}{'default'}) {
 7961:                     $access = 1;
 7962:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7963:                     $access = 0;
 7964:                 }
 7965:                 return $access;
 7966:             }
 7967:         }
 7968:     } else {
 7969:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7970:             $access = 1;
 7971:         } else {
 7972:             $access = 0;
 7973:         }
 7974:         return $access;
 7975:     }
 7976: }
 7977: 
 7978: sub is_course_owner {
 7979:     my ($cdom,$cnum,$udom,$uname) = @_;
 7980:     if (($udom eq '') || ($uname eq '')) {
 7981:         $udom = $env{'user.domain'};
 7982:         $uname = $env{'user.name'};
 7983:     }
 7984:     unless (($udom eq '') || ($uname eq '')) {
 7985:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7986:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7987:                 return 1;
 7988:             } else {
 7989:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7990:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7991:                     return 1;
 7992:                 }
 7993:             }
 7994:         }
 7995:     }
 7996:     return;
 7997: }
 7998: 
 7999: sub is_advanced_user {
 8000:     my ($udom,$uname) = @_;
 8001:     if ($udom ne '' && $uname ne '') {
 8002:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8003:             if (wantarray) {
 8004:                 return ($env{'user.adv'},$env{'user.author'});
 8005:             } else {
 8006:                 return $env{'user.adv'};
 8007:             }
 8008:         }
 8009:     }
 8010:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8011:     my %allroles;
 8012:     my ($is_adv,$is_author);
 8013:     foreach my $role (keys(%roleshash)) {
 8014:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8015:         my $area = '/'.$tdomain.'/'.$trest;
 8016:         if ($sec ne '') {
 8017:             $area .= '/'.$sec;
 8018:         }
 8019:         if (($area ne '') && ($trole ne '')) {
 8020:             my $spec=$trole.'.'.$area;
 8021:             if ($trole =~ /^cr\//) {
 8022:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8023:             } elsif ($trole ne 'gr') {
 8024:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8025:             }
 8026:             if ($trole eq 'au') {
 8027:                 $is_author = 1;
 8028:             }
 8029:         }
 8030:     }
 8031:     foreach my $role (keys(%allroles)) {
 8032:         last if ($is_adv);
 8033:         foreach my $item (split(/:/,$allroles{$role})) {
 8034:             if ($item ne '') {
 8035:                 my ($privilege,$restrictions)=split(/&/,$item);
 8036:                 if ($privilege eq 'adv') {
 8037:                     $is_adv = 1;
 8038:                     last;
 8039:                 }
 8040:             }
 8041:         }
 8042:     }
 8043:     if (wantarray) {
 8044:         return ($is_adv,$is_author);
 8045:     }
 8046:     return $is_adv;
 8047: }
 8048: 
 8049: sub check_can_request {
 8050:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8051:     my $canreq = 0;
 8052:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8053:         $uname = $env{'user.name'};
 8054:         $udom = $env{'user.domain'};
 8055:     }
 8056:     my ($types,$typename) = &Apache::loncommon::course_types();
 8057:     my @options = ('approval','validate','autolimit');
 8058:     my $optregex = join('|',@options);
 8059:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8060:         foreach my $type (@{$types}) {
 8061:             if (&usertools_access($uname,$udom,$type,undef,
 8062:                                   'requestcourses')) {
 8063:                 $canreq ++;
 8064:                 if (ref($request_domains) eq 'HASH') {
 8065:                     push(@{$request_domains->{$type}},$udom);
 8066:                 }
 8067:                 if ($dom eq $udom) {
 8068:                     $can_request->{$type} = 1;
 8069:                 }
 8070:             }
 8071:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8072:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8073:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8074:                 if (@curr > 0) {
 8075:                     foreach my $item (@curr) {
 8076:                         if (ref($request_domains) eq 'HASH') {
 8077:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8078:                             if ($otherdom ne '') {
 8079:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8080:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8081:                                         push(@{$request_domains->{$type}},$otherdom);
 8082:                                     }
 8083:                                 } else {
 8084:                                     push(@{$request_domains->{$type}},$otherdom);
 8085:                                 }
 8086:                             }
 8087:                         }
 8088:                     }
 8089:                     unless ($dom eq $env{'user.domain'}) {
 8090:                         $canreq ++;
 8091:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8092:                             $can_request->{$type} = 1;
 8093:                         }
 8094:                     }
 8095:                 }
 8096:             }
 8097:         }
 8098:     }
 8099:     return $canreq;
 8100: }
 8101: 
 8102: # ---------------------------------------------- Custom access rule evaluation
 8103: 
 8104: sub customaccess {
 8105:     my ($priv,$uri)=@_;
 8106:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8107:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8108:     $udom = &LONCAPA::clean_domain($udom);
 8109:     $ucrs = &LONCAPA::clean_username($ucrs);
 8110:     my $access=0;
 8111:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8112: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8113: 	if ($type eq 'user') {
 8114: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8115: 		my ($tdom,$tuname)=split(m{/},$scope);
 8116: 		if ($tdom) {
 8117: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8118: 		}
 8119: 		if ($tuname) {
 8120: 		    if ($tuname ne $env{'user.name'}) { next; }
 8121: 		}
 8122: 		$access=($effect eq 'allow');
 8123: 		last;
 8124: 	    }
 8125: 	} else {
 8126: 	    if ($role) {
 8127: 		if ($role ne $urole) { next; }
 8128: 	    }
 8129: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8130: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8131: 		if ($tdom) {
 8132: 		    if ($tdom ne $udom) { next; }
 8133: 		}
 8134: 		if ($tcrs) {
 8135: 		    if ($tcrs ne $ucrs) { next; }
 8136: 		}
 8137: 		if ($tsec) {
 8138: 		    if ($tsec ne $usec) { next; }
 8139: 		}
 8140: 		$access=($effect eq 'allow');
 8141: 		last;
 8142: 	    }
 8143: 	    if ($realm eq '' && $role eq '') {
 8144: 		$access=($effect eq 'allow');
 8145: 	    }
 8146: 	}
 8147:     }
 8148:     return $access;
 8149: }
 8150: 
 8151: # ------------------------------------------------- Check for a user privilege
 8152: 
 8153: sub allowed {
 8154:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8155:     my $ver_orguri=$uri;
 8156:     $uri=&deversion($uri);
 8157:     my $orguri=$uri;
 8158:     $uri=&declutter($uri);
 8159: 
 8160:     if ($priv eq 'evb') {
 8161: # Evade communication block restrictions for specified role in a course or domain
 8162:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8163:             return $1;
 8164:         } else {
 8165:             return;
 8166:         }
 8167:     }
 8168: 
 8169:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8170: # Free bre access to adm and meta resources
 8171:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8172: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8173: 	&& ($priv eq 'bre')) {
 8174: 	return 'F';
 8175:     }
 8176: 
 8177: # Free bre access to user's own portfolio contents
 8178:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8179:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8180: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8181:         my %setters;
 8182:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8183:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8184:         if (($startblock && $endblock) || ($by_ip)) {
 8185:             return 'B';
 8186:         } else {
 8187:             return 'F';
 8188:         }
 8189:     }
 8190: 
 8191: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8192:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8193:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8194:         if (exists($env{'request.course.id'})) {
 8195:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8196:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8197:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8198:                 my $courseprivid=$env{'request.course.id'};
 8199:                 $courseprivid=~s/\_/\//;
 8200:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8201:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8202:                     return $1; 
 8203:                 } else {
 8204:                     if ($env{'request.course.sec'}) {
 8205:                         $courseprivid.='/'.$env{'request.course.sec'};
 8206:                     }
 8207:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8208:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8209:                         return $2;
 8210:                     }
 8211:                 }
 8212:             }
 8213:         }
 8214:     }
 8215: 
 8216: # Free bre to public access
 8217: 
 8218:     if ($priv eq 'bre') {
 8219:         my $copyright;
 8220:         unless ($uri =~ /ext\.tool/) {
 8221:             $copyright=&metadata($uri,'copyright');
 8222:         }
 8223: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8224:            return 'F'; 
 8225:         }
 8226:         if ($copyright eq 'priv') {
 8227:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8228: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8229: 		return '';
 8230:             }
 8231:         }
 8232:         if ($copyright eq 'domain') {
 8233:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8234: 	    unless (($env{'user.domain'} eq $1) ||
 8235:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8236: 		return '';
 8237:             }
 8238:         }
 8239:         if ($env{'request.role'}=~ /li\.\//) {
 8240:             # Library role, so allow browsing of resources in this domain.
 8241:             return 'F';
 8242:         }
 8243:         if ($copyright eq 'custom') {
 8244: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8245:         }
 8246:     }
 8247:     # Domain coordinator is trying to create a course
 8248:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8249:         # uri is the requested domain in this case.
 8250:         # comparison to 'request.role.domain' shows if the user has selected
 8251:         # a role of dc for the domain in question.
 8252:         return 'F' if ($uri eq $env{'request.role.domain'});
 8253:     }
 8254: 
 8255:     my $thisallowed='';
 8256:     my $statecond=0;
 8257:     my $courseprivid='';
 8258: 
 8259:     my $ownaccess;
 8260:     # Community Coordinator or Assistant Co-author browsing resource space.
 8261:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8262:         if ($uri eq '') {
 8263:             $ownaccess = 1;
 8264:         } else {
 8265:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8266:                 my $udom = $env{'user.domain'};
 8267:                 my $uname = $env{'user.name'};
 8268:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8269:                     $ownaccess = 1;
 8270:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8271:                     unless ($uri =~ m{\.\./}) {
 8272:                         $ownaccess = 1;
 8273:                     }
 8274:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8275:                     my $now = time;
 8276:                     if ($uri =~ m{^([^/]+)/?$}) {
 8277:                         my $adom = $1;
 8278:                         foreach my $key (keys(%env)) {
 8279:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8280:                                 my ($start,$end) = split(/\./,$env{$key});
 8281:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8282:                                     $ownaccess = 1;
 8283:                                     last;
 8284:                                 }
 8285:                             }
 8286:                         }
 8287:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8288:                         my $adom = $1;
 8289:                         my $aname = $2;
 8290:                         foreach my $role ('ca','aa') { 
 8291:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8292:                                 my ($start,$end) =
 8293:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8294:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8295:                                     $ownaccess = 1;
 8296:                                     last;
 8297:                                 }
 8298:                             }
 8299:                         }
 8300:                     }
 8301:                 }
 8302:             }
 8303:         }
 8304:     }
 8305: 
 8306: # Course
 8307: 
 8308:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8309:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8310:             $thisallowed.=$1;
 8311:         }
 8312:     }
 8313: 
 8314: # Domain
 8315: 
 8316:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8317:        =~/\Q$priv\E\&([^\:]*)/) {
 8318:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8319:             $thisallowed.=$1;
 8320:         }
 8321:     }
 8322: 
 8323: # User who is not author or co-author might still be able to edit
 8324: # resource of an author in the domain (e.g., if Domain Coordinator).
 8325:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8326:         (&allowed('mdc',$env{'request.course.id'}))) {
 8327:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8328:             $thisallowed.=$1;
 8329:         }
 8330:     }
 8331: 
 8332: # Course: uri itself is a course
 8333:     my $courseuri=$uri;
 8334:     $courseuri=~s/\_(\d)/\/$1/;
 8335:     $courseuri=~s/^([^\/])/\/$1/;
 8336: 
 8337:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8338:        =~/\Q$priv\E\&([^\:]*)/) {
 8339:         if ($priv eq 'mip') {
 8340:             my $rem = $1;
 8341:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8342:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8343:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8344:                 if ($cdom ne '') {
 8345:                     my %passwdconf = &get_passwdconf($cdom);
 8346:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8347:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8348:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8349:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8350:                                 unless (@inststatuses) {
 8351:                                     @inststatuses = ('default');
 8352:                                 }
 8353:                                 foreach my $status (@inststatuses) {
 8354:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8355:                                         $thisallowed.=$rem;
 8356:                                     }
 8357:                                 }
 8358:                             }
 8359:                         }
 8360:                     }
 8361:                 }
 8362:             }
 8363:         } else {
 8364:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8365:                 $thisallowed.=$1;
 8366:             }
 8367:         }
 8368:     }
 8369: 
 8370: # URI is an uploaded document for this course, default permissions don't matter
 8371: # not allowing 'edit' access (editupload) to uploaded course docs
 8372:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8373: 	$thisallowed='';
 8374:         my ($match)=&is_on_map($uri);
 8375:         if ($match) {
 8376:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8377:                   =~/\Q$priv\E\&([^\:]*)/) {
 8378:                 my $value = $1;
 8379:                 my $deeplinkblock;
 8380:                 unless ($nodeeplinkcheck) {
 8381:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8382:                 }
 8383:                 if ($deeplinkblock) {
 8384:                     $thisallowed='D';
 8385:                 } elsif ($noblockcheck) {
 8386:                     $thisallowed.=$value;
 8387:                 } else {
 8388:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8389:                     if (@blockers > 0) {
 8390:                         $thisallowed = 'B';
 8391:                     } else {
 8392:                         $thisallowed.=$value;
 8393:                     }
 8394:                 }
 8395:             }
 8396:         } else {
 8397:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8398:             if ($refuri) {
 8399:                 if ($refuri =~ m|^/adm/|) {
 8400:                     $thisallowed='F';
 8401:                 } else {
 8402:                     $refuri=&declutter($refuri);
 8403:                     my ($match) = &is_on_map($refuri);
 8404:                     if ($match) {
 8405:                         my $deeplinkblock;
 8406:                         unless ($nodeeplinkcheck) {
 8407:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8408:                         }
 8409:                         if ($deeplinkblock) {
 8410:                             $thisallowed='D';
 8411:                         } elsif ($noblockcheck) {
 8412:                             $thisallowed='F';
 8413:                         } else {
 8414:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8415:                             if (@blockers > 0) {
 8416:                                 $thisallowed = 'B';
 8417:                             } else {
 8418:                                 $thisallowed='F';
 8419:                             }
 8420:                         }
 8421:                     }
 8422:                 }
 8423:             }
 8424:         }
 8425:     }
 8426: 
 8427:     if ($priv eq 'bre'
 8428: 	&& $thisallowed ne 'F' 
 8429: 	&& $thisallowed ne '2'
 8430: 	&& &is_portfolio_url($uri)) {
 8431: 	$thisallowed = &portfolio_access($uri,$clientip);
 8432:     }
 8433: 
 8434: # Full access at system, domain or course-wide level? Exit.
 8435:     if ($thisallowed=~/F/) {
 8436: 	return 'F';
 8437:     }
 8438: 
 8439: # If this is generating or modifying users, exit with special codes
 8440: 
 8441:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8442: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8443: 	    my ($audom,$auname)=split('/',$uri);
 8444: # no author name given, so this just checks on the general right to make a co-author in this domain
 8445: 	    unless ($auname) { return $thisallowed; }
 8446: # an author name is given, so we are about to actually make a co-author for a certain account
 8447: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8448: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8449: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8450: 	}
 8451: 	return $thisallowed;
 8452:     }
 8453: #
 8454: # Gathered so far: system, domain and course wide privileges
 8455: #
 8456: # Course: See if uri or referer is an individual resource that is part of 
 8457: # the course
 8458: 
 8459:     if ($env{'request.course.id'}) {
 8460: 
 8461: # If this is modifying password (internal auth) domains must match for user and user's role.
 8462: 
 8463:         if ($priv eq 'mip') {
 8464:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8465:                 return $thisallowed;
 8466:             } else {
 8467:                 return '';
 8468:             }
 8469:         }
 8470: 
 8471:        $courseprivid=$env{'request.course.id'};
 8472:        if ($env{'request.course.sec'}) {
 8473:           $courseprivid.='/'.$env{'request.course.sec'};
 8474:        }
 8475:        $courseprivid=~s/\_/\//;
 8476:        my $checkreferer=1;
 8477:        my ($match,$cond)=&is_on_map($uri);
 8478:        if ($match) {
 8479:            $statecond=$cond;
 8480:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8481:                =~/\Q$priv\E\&([^\:]*)/) {
 8482:                my $value = $1;
 8483:                if ($priv eq 'bre') {
 8484:                    my $deeplinkblock;
 8485:                    unless ($nodeeplinkcheck) {
 8486:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8487:                    }
 8488:                    if ($deeplinkblock) {
 8489:                        $thisallowed = 'D';
 8490:                    } elsif ($noblockcheck) {
 8491:                        $thisallowed.=$value;
 8492:                    } else {
 8493:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8494:                        if (@blockers > 0) {
 8495:                            $thisallowed = 'B';
 8496:                        } else {
 8497:                            $thisallowed.=$value;
 8498:                        }
 8499:                    }
 8500:                } else {
 8501:                    $thisallowed.=$value;
 8502:                }
 8503:                $checkreferer=0;
 8504:            }
 8505:        }
 8506: 
 8507:        if ($checkreferer) {
 8508: 	  my $refuri=$env{'httpref.'.$orguri};
 8509:             unless ($refuri) {
 8510:                 foreach my $key (keys(%env)) {
 8511: 		    if ($key=~/^httpref\..*\*/) {
 8512: 			my $pattern=$key;
 8513:                         $pattern=~s/^httpref\.\/res\///;
 8514:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8515:                         $pattern=~s/\//\\\//g;
 8516:                         if ($orguri=~/$pattern/) {
 8517: 			    $refuri=$env{$key};
 8518:                         }
 8519:                     }
 8520:                 }
 8521:             }
 8522: 
 8523:          if ($refuri) { 
 8524: 	  $refuri=&declutter($refuri);
 8525:           my ($match,$cond)=&is_on_map($refuri);
 8526:             if ($match) {
 8527:               my $refstatecond=$cond;
 8528:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8529:                   =~/\Q$priv\E\&([^\:]*)/) {
 8530:                   my $value = $1;
 8531:                   if ($priv eq 'bre') {
 8532:                       my $deeplinkblock;
 8533:                       unless ($nodeeplinkcheck) {
 8534:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8535:                       }
 8536:                       if ($deeplinkblock) {
 8537:                           $thisallowed = 'D';
 8538:                       } elsif ($noblockcheck) {
 8539:                           $thisallowed.=$value;
 8540:                       } else {
 8541:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8542:                           if (@blockers > 0) {
 8543:                               $thisallowed = 'B';
 8544:                           } else {
 8545:                               $thisallowed.=$value;
 8546:                           }
 8547:                       }
 8548:                   } else {
 8549:                       $thisallowed.=$value;
 8550:                   }
 8551:                   $uri=$refuri;
 8552:                   $statecond=$refstatecond;
 8553:               }
 8554:           }
 8555:         }
 8556:        }
 8557:    }
 8558: 
 8559: #
 8560: # Gathered now: all privileges that could apply, and condition number
 8561: # 
 8562: #
 8563: # Full or no access?
 8564: #
 8565: 
 8566:     if ($thisallowed=~/F/) {
 8567: 	return 'F';
 8568:     }
 8569: 
 8570:     unless ($thisallowed) {
 8571:         return '';
 8572:     }
 8573: 
 8574: # Restrictions exist, deal with them
 8575: #
 8576: #   C:according to course preferences
 8577: #   R:according to resource settings
 8578: #   L:unless locked
 8579: #   X:according to user session state
 8580: #
 8581: 
 8582: # Possibly locked functionality, check all courses
 8583: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8584: # Locks might take effect only after 10 minutes cache expiration for other
 8585: # courses, and 2 minutes for current course, in which user has st or ta role
 8586: # which is neither expired nor a future role (unless current course).
 8587: 
 8588:     my ($needlockcheck,$now,$crsonly);
 8589:     if ($thisallowed=~/L/) {
 8590:         $now = time;
 8591:         if ($priv eq 'bre') {
 8592:             if ($uri ne '') {
 8593:                 if ($orguri =~ m{^/+res/}) {
 8594:                     if ($uri =~ m{^lib/templates/}) {
 8595:                         if ($env{'request.course.id'}) {
 8596:                             $crsonly = 1;
 8597:                             $needlockcheck = 1;
 8598:                         }
 8599:                     } else {
 8600:                         $needlockcheck = 1;
 8601:                     }
 8602:                 } elsif ($env{'request.course.id'}) {
 8603:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8604:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8605:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8606:                         $crsonly = 1;
 8607:                     }
 8608:                     $needlockcheck = 1;
 8609:                 }
 8610:             }
 8611:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8612:             $needlockcheck = 1;
 8613:         }
 8614:     }
 8615:     if ($needlockcheck) {
 8616:         foreach my $envkey (keys(%env)) {
 8617:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8618:                my $courseid=$2;
 8619:                my $roleid=$1.'.'.$2;
 8620:                $courseid=~s/^\///;
 8621:                unless ($env{'request.role'} eq $roleid) {
 8622:                    my ($start,$end) = split(/\./,$env{$envkey});
 8623:                    next unless (($now >= $start) && (!$end || $end > $now));
 8624:                }
 8625:                my $expiretime=600;
 8626:                if ($env{'request.role'} eq $roleid) {
 8627: 		  $expiretime=120;
 8628:                }
 8629: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8630:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8631:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8632: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8633:                }
 8634:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8635:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8636: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8637:                        &log($env{'user.domain'},$env{'user.name'},
 8638:                             $env{'user.home'},
 8639:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8640:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8641:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8642: 		       return '';
 8643:                    }
 8644:                }
 8645:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8646:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8647: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8648:                        &log($env{'user.domain'},$env{'user.name'},
 8649:                             $env{'user.home'},
 8650:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8651:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8652:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8653: 		       return '';
 8654:                    }
 8655:                }
 8656: 	   }
 8657:        }
 8658:     }
 8659: 
 8660: #
 8661: # Rest of the restrictions depend on selected course
 8662: #
 8663: 
 8664:     unless ($env{'request.course.id'}) {
 8665: 	if ($thisallowed eq 'A') {
 8666: 	    return 'A';
 8667:         } elsif ($thisallowed eq 'B') {
 8668:             return 'B';
 8669: 	} else {
 8670: 	    return '1';
 8671: 	}
 8672:     }
 8673: 
 8674: #
 8675: # Now user is definitely in a course
 8676: #
 8677: 
 8678: 
 8679: # Course preferences
 8680: 
 8681:    if ($thisallowed=~/C/) {
 8682:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8683:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8684:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8685: 	   =~/\Q$rolecode\E/) {
 8686: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8687: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8688: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8689: 			$env{'request.course.id'});
 8690: 	   }
 8691:            return '';
 8692:        }
 8693: 
 8694:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8695: 	   =~/\Q$unamedom\E/) {
 8696: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8697: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8698: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8699: 			$env{'request.course.id'});
 8700: 	   }
 8701:            return '';
 8702:        }
 8703:    }
 8704: 
 8705: # Resource preferences
 8706: 
 8707:    if ($thisallowed=~/R/) {
 8708:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8709:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8710: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8711: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8712: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8713: 	   }
 8714: 	   return '';
 8715:        }
 8716:    }
 8717: 
 8718: # Restricted for deeplinked session?
 8719: 
 8720:     if ($env{'request.deeplink.login'}) {
 8721:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8722:             if (!$symb) { $symb=&symbread($uri,1); }
 8723:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8724:                 return '';
 8725:             }
 8726:         }
 8727:     }
 8728: 
 8729: # Restricted by state or randomout?
 8730: 
 8731:    if ($thisallowed=~/X/) {
 8732:       if ($env{'acc.randomout'}) {
 8733: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8734:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8735:             return ''; 
 8736:          }
 8737:       }
 8738:       if (&condval($statecond)) {
 8739: 	 return '2';
 8740:       } else {
 8741:          return '';
 8742:       }
 8743:    }
 8744: 
 8745:     if ($thisallowed eq 'A') {
 8746: 	return 'A';
 8747:     } elsif ($thisallowed eq 'B') {
 8748:         return 'B';
 8749:     } elsif ($thisallowed eq 'D') {
 8750:         return 'D';
 8751:     }
 8752:    return 'F';
 8753: }
 8754: 
 8755: # ------------------------------------------- Check construction space access
 8756: 
 8757: sub constructaccess {
 8758:     my ($url,$setpriv)=@_;
 8759: 
 8760: # We do not allow editing of previous versions of files
 8761:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8762: 
 8763: # Get username and domain from URL
 8764:     my ($ownername,$ownerdomain,$ownerhome);
 8765: 
 8766:     ($ownerdomain,$ownername) =
 8767:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8768: 
 8769: # The URL does not really point to any authorspace, forget it
 8770:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8771: 
 8772: # Now we need to see if the user has access to the authorspace of
 8773: # $ownername at $ownerdomain
 8774: 
 8775:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8776: # Real author for this?
 8777:        $ownerhome = $env{'user.home'};
 8778:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8779:           return ($ownername,$ownerdomain,$ownerhome);
 8780:        }
 8781:     } else {
 8782: # Co-author for this?
 8783:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8784:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8785:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8786:             return ($ownername,$ownerdomain,$ownerhome);
 8787:         }
 8788:         if ($env{'request.course.id'}) {
 8789:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8790:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8791:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8792:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8793:                     return ($ownername,$ownerdomain,$ownerhome);
 8794:                 }
 8795:             }
 8796:         }
 8797:     }
 8798: 
 8799: # We don't have any access right now. If we are not possibly going to do anything about this,
 8800: # we might as well leave
 8801:    unless ($setpriv) { return ''; }
 8802: 
 8803: # Backdoor access?
 8804:     my $allowed=&allowed('eco',$ownerdomain);
 8805: # Nope
 8806:     unless ($allowed) { return ''; }
 8807: # Looks like we may have access, but could be locked by the owner of the construction space
 8808:     if ($allowed eq 'U') {
 8809:         my %blocked=&get('environment',['domcoord.author'],
 8810:                          $ownerdomain,$ownername);
 8811: # Is blocked by owner
 8812:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8813:     }
 8814:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8815: # Grant temporary access
 8816:         my $then=$env{'user.login.time'};
 8817:         my $update=$env{'user.update.time'};
 8818:         if (!$update) { $update = $then; }
 8819:         my $refresh=$env{'user.refresh.time'};
 8820:         if (!$refresh) { $refresh = $update; }
 8821:         my $now = time;
 8822:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8823:                            $now,'ca','constructaccess');
 8824:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8825:         return($ownername,$ownerdomain,$ownerhome);
 8826:     }
 8827: # No business here
 8828:     return '';
 8829: }
 8830: 
 8831: # ----------------------------------------------------------- Content Blocking
 8832: 
 8833: {
 8834: # Caches for faster Course Contents display where content blocking
 8835: # is in operation (i.e., interval param set) for timed quiz.
 8836: #
 8837: # User for whom data are being temporarily cached.
 8838: my $cacheduser='';
 8839: # Course for which data are being temporarily cached.
 8840: my $cachedcid='';
 8841: # Cached blockers for this user (a hash of blocking items). 
 8842: my %cachedblockers=();
 8843: # When the data were last cached.
 8844: my $cachedlast='';
 8845: 
 8846: sub load_all_blockers {
 8847:     my ($uname,$udom)=@_;
 8848:     if (($uname ne '') && ($udom ne '')) { 
 8849:         if (($cacheduser eq $uname.':'.$udom) &&
 8850:             ($cachedcid eq $env{'request.course.id'}) &&
 8851:             (abs($cachedlast-time)<5)) {
 8852:             return;
 8853:         }
 8854:     }
 8855:     $cachedlast=time;
 8856:     $cacheduser=$uname.':'.$udom;
 8857:     $cachedcid=$env{'request.course.id'};
 8858:     %cachedblockers = &get_commblock_resources();
 8859:     return;
 8860: }
 8861: 
 8862: sub get_comm_blocks {
 8863:     my ($cdom,$cnum) = @_;
 8864:     if ($cdom eq '' || $cnum eq '') {
 8865:         return unless ($env{'request.course.id'});
 8866:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8867:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8868:     }
 8869:     my %commblocks;
 8870:     my $hashid=$cdom.'_'.$cnum;
 8871:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8872:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8873:         %commblocks = %{$blocksref};
 8874:     } else {
 8875:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8876:         my $cachetime = 600;
 8877:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8878:     }
 8879:     return %commblocks;
 8880: }
 8881: 
 8882: sub get_commblock_resources {
 8883:     my ($blocks) = @_;
 8884:     my %blockers = ();
 8885:     return %blockers unless ($env{'request.course.id'});
 8886:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8887:     if ($env{'request.course.sec'}) {
 8888:         $courseurl .= '/'.$env{'request.course.sec'};
 8889:     }
 8890:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8891:     my %commblocks;
 8892:     if (ref($blocks) eq 'HASH') {
 8893:         %commblocks = %{$blocks};
 8894:     } else {
 8895:         %commblocks = &get_comm_blocks();
 8896:     }
 8897:     return %blockers unless (keys(%commblocks) > 0); 
 8898:     my $navmap = Apache::lonnavmaps::navmap->new();
 8899:     return %blockers unless (ref($navmap));
 8900:     my $now = time;
 8901:     foreach my $block (keys(%commblocks)) {
 8902:         if ($block =~ /^(\d+)____(\d+)$/) {
 8903:             my ($start,$end) = ($1,$2);
 8904:             if ($start <= $now && $end >= $now) {
 8905:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8906:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8907:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8908:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8909:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8910:                             }
 8911:                         }
 8912:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8913:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8914:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8915:                             }
 8916:                         }
 8917:                     }
 8918:                 }
 8919:             }
 8920:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8921:             my $item = $1;
 8922:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8923:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8924:                     my (@interval,$mapname);
 8925:                     my $type = 'map';
 8926:                     if ($item eq 'course') {
 8927:                         $type = 'course';
 8928:                         @interval=&EXT("resource.0.interval");
 8929:                     } else {
 8930:                         if ($item =~ /___\d+___/) {
 8931:                             $type = 'resource';
 8932:                             @interval=&EXT("resource.0.interval",$item);
 8933:                         } else {
 8934:                             $mapname = &deversion($item);
 8935:                             if (ref($navmap)) {
 8936:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 8937:                                 @interval = ($timelimit,'map');
 8938:                             }
 8939:                         }
 8940:                     }
 8941:                     if ($interval[0] =~ /^(\d+)/) {
 8942:                         my $timelimit = $1; 
 8943:                         my $first_access;
 8944:                         if ($type eq 'resource') {
 8945:                             $first_access=&get_first_access($interval[1],$item);
 8946:                         } elsif ($type eq 'map') {
 8947:                             $first_access=&get_first_access($interval[1],undef,$item);
 8948:                         } else {
 8949:                             $first_access=&get_first_access($interval[1]);
 8950:                         }
 8951:                         if ($first_access) {
 8952:                             my $timesup = $first_access+$timelimit;
 8953:                             if ($timesup > $now) {
 8954:                                 my $activeblock;
 8955:                                 if ($type eq 'resource') {
 8956:                                     if (ref($navmap)) {
 8957:                                         my $res = $navmap->getBySymb($item);
 8958:                                         if ($res->answerable()) {
 8959:                                             $activeblock = 1;
 8960:                                         }
 8961:                                     }
 8962:                                 } elsif ($type eq 'map') {
 8963:                                     my $mapsymb = &symbread($mapname,1);
 8964:                                     if (($mapsymb) && (ref($navmap))) {
 8965:                                         my $mapres = $navmap->getBySymb($mapsymb);
 8966:                                         if (ref($mapres)) {
 8967:                                             my $first = $mapres->map_start();
 8968:                                             my $finish = $mapres->map_finish();
 8969:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8970:                                             if (ref($it)) {
 8971:                                                 my $res;
 8972:                                                 while ($res = $it->next(undef,1)) {
 8973:                                                     next unless (ref($res));
 8974:                                                     my $symb = $res->symb();
 8975:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 8976:                                                     @interval=&EXT("resource.0.interval",$symb);
 8977:                                                     if ($interval[1] eq 'map') {
 8978:                                                         if ($res->answerable()) {
 8979:                                                             $activeblock = 1;
 8980:                                                             last;
 8981:                                                         }
 8982:                                                     }
 8983:                                                 }
 8984:                                             }
 8985:                                         }
 8986:                                     }
 8987:                                 }
 8988:                                 if ($activeblock) {
 8989:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8990:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8991:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8992:                                          }
 8993:                                     }
 8994:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8995:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8996:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8997:                                         }
 8998:                                     }
 8999:                                 }
 9000:                             }
 9001:                         }
 9002:                     }
 9003:                 }
 9004:             }
 9005:         }
 9006:     }
 9007:     return %blockers;
 9008: }
 9009: 
 9010: sub has_comm_blocking {
 9011:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9012:     my @blockers;
 9013:     return unless ($env{'request.course.id'});
 9014:     return unless ($priv eq 'bre');
 9015:     return if ($env{'request.state'} eq 'construct');
 9016:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9017:     if ($env{'request.course.sec'}) {
 9018:         $courseurl .= '/'.$env{'request.course.sec'};
 9019:     }
 9020:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9021:     my %blockinfo;
 9022:     if (ref($blocks) eq 'HASH') {
 9023:         %blockinfo = &get_commblock_resources($blocks);
 9024:     } else {
 9025:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9026:         %blockinfo = %cachedblockers;
 9027:     }
 9028:     return unless (keys(%blockinfo) > 0);
 9029:     my (%possibles,@symbs);
 9030:     if (!$symb) {
 9031:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9032:     }
 9033:     if ($symb) {
 9034:         @symbs = ($symb);
 9035:     } elsif (keys(%possibles)) { 
 9036:         @symbs = keys(%possibles);
 9037:     }
 9038:     my $noblock;
 9039:     foreach my $symb (@symbs) {
 9040:         last if ($noblock);
 9041:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9042:         foreach my $block (keys(%blockinfo)) {
 9043:             if ($block =~ /^firstaccess____(.+)$/) {
 9044:                 my $item = $1;
 9045:                 unless ($blocked) {
 9046:                     if (($item eq $map) || ($item eq $symb)) {
 9047:                         $noblock = 1;
 9048:                         last;
 9049:                     }
 9050:                 }
 9051:             }
 9052:             if (ref($blockinfo{$block}) eq 'HASH') {
 9053:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9054:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9055:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9056:                             push(@blockers,$block);
 9057:                         }
 9058:                     }
 9059:                 }
 9060:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9061:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9062:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9063:                             push(@blockers,$block);
 9064:                         }
 9065:                     }
 9066:                 }
 9067:             }
 9068:         }
 9069:     }
 9070:     unless ($noblock) { 
 9071:         return @blockers;
 9072:     }
 9073:     return;
 9074: }
 9075: }
 9076: 
 9077: sub deeplink_check {
 9078:     my ($priv,$symb,$uri) = @_;
 9079:     return unless ($env{'request.course.id'});
 9080:     return unless ($priv eq 'bre');
 9081:     return if ($env{'request.state'} eq 'construct');
 9082:     return if ($env{'request.role.adv'});
 9083:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9084:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9085:     my (%possibles,@symbs);
 9086:     if (!$symb) {
 9087:         $symb = &symbread($uri,1,1,1,\%possibles);
 9088:     }
 9089:     if ($symb) {
 9090:         @symbs = ($symb);
 9091:     } elsif (keys(%possibles)) {
 9092:         @symbs = keys(%possibles);
 9093:     }
 9094: 
 9095:     my ($deeplink_symb,$allow);
 9096:     if ($env{'request.deeplink.login'}) {
 9097:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9098:     }
 9099:     foreach my $symb (@symbs) {
 9100:         last if ($allow);
 9101:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9102:         if ($deeplink eq '') {
 9103:             $allow = 1;
 9104:         } else {
 9105:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9106:             if ($state ne 'only') {
 9107:                 $allow = 1;
 9108:             } else {
 9109:                 my $check_deeplink_entry;
 9110:                 if ($protect ne 'none') {
 9111:                     my ($acctype,$item) = split(/:/,$protect);
 9112:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9113:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9114:                             $check_deeplink_entry = 1
 9115:                         }
 9116:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9117:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9118:                             $check_deeplink_entry = 1;
 9119:                         }
 9120:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9121:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9122:                             $check_deeplink_entry = 1;
 9123:                         }
 9124:                     }
 9125:                 }
 9126:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9127:                     if ($scope eq 'res') {
 9128:                         if ($symb eq $deeplink_symb) {
 9129:                             $allow = 1;
 9130:                         }
 9131:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9132:                         my ($map_from_symb,$map_from_login);
 9133:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9134:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9135:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9136:                         } else {
 9137:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9138:                         }
 9139:                         if (($map_from_symb) && ($map_from_login)) {
 9140:                             if ($map_from_symb eq $map_from_login) {
 9141:                                 $allow = 1;
 9142:                             } elsif ($scope eq 'rec') {
 9143:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9144:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9145:                                     $allow = 1;
 9146:                                 }
 9147:                             }
 9148:                         }
 9149:                     }
 9150:                 }
 9151:             }
 9152:         }
 9153:     }
 9154:     return if ($allow);
 9155:     return 1;
 9156: }
 9157: 
 9158: # -------------------------------- Deversion and split uri into path an filename   
 9159: 
 9160: #
 9161: #   Removes the version from a URI and
 9162: #   splits it in to its filename and path to the filename.
 9163: #   Seems like File::Basename could have done this more clearly.
 9164: #   Parameters:
 9165: #      $uri   - input URI
 9166: #   Returns:
 9167: #     Two element list consisting of 
 9168: #     $pathname  - the URI up to and excluding the trailing /
 9169: #     $filename  - The part of the URI following the last /
 9170: #  NOTE:
 9171: #    Another realization of this is simply:
 9172: #    use File::Basename;
 9173: #    ...
 9174: #    $uri = shift;
 9175: #    $filename = basename($uri);
 9176: #    $path     = dirname($uri);
 9177: #    return ($filename, $path);
 9178: #
 9179: #     The implementation below is probably faster however.
 9180: #
 9181: sub split_uri_for_cond {
 9182:     my $uri=&deversion(&declutter(shift));
 9183:     my @uriparts=split(/\//,$uri);
 9184:     my $filename=pop(@uriparts);
 9185:     my $pathname=join('/',@uriparts);
 9186:     return ($pathname,$filename);
 9187: }
 9188: # --------------------------------------------------- Is a resource on the map?
 9189: 
 9190: sub is_on_map {
 9191:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9192:     #Trying to find the conditional for the file
 9193:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9194: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9195:     if ($match) {
 9196: 	return (1,$1);
 9197:     } else {
 9198: 	return (0,0);
 9199:     }
 9200: }
 9201: 
 9202: # --------------------------------------------------------- Get symb from alias
 9203: 
 9204: sub get_symb_from_alias {
 9205:     my $symb=shift;
 9206:     my ($map,$resid,$url)=&decode_symb($symb);
 9207: # Already is a symb
 9208:     if ($url) { return $symb; }
 9209: # Must be an alias
 9210:     my $aliassymb='';
 9211:     my %bighash;
 9212:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9213:                             &GDBM_READER(),0640)) {
 9214:         my $rid=$bighash{'mapalias_'.$symb};
 9215: 	if ($rid) {
 9216: 	    my ($mapid,$resid)=split(/\./,$rid);
 9217: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9218: 				    $resid,$bighash{'src_'.$rid});
 9219: 	}
 9220:         untie %bighash;
 9221:     }
 9222:     return $aliassymb;
 9223: }
 9224: 
 9225: # ----------------------------------------------------------------- Define Role
 9226: 
 9227: sub definerole {
 9228:   if (allowed('mcr','/')) {
 9229:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9230:     foreach my $role (split(':',$sysrole)) {
 9231: 	my ($crole,$cqual)=split(/\&/,$role);
 9232:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9233:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9234: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9235:                return "refused:s:$crole&$cqual"; 
 9236:             }
 9237:         }
 9238:     }
 9239:     foreach my $role (split(':',$domrole)) {
 9240: 	my ($crole,$cqual)=split(/\&/,$role);
 9241:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9242:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9243: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9244:                return "refused:d:$crole&$cqual"; 
 9245:             }
 9246:         }
 9247:     }
 9248:     foreach my $role (split(':',$courole)) {
 9249: 	my ($crole,$cqual)=split(/\&/,$role);
 9250:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9251:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9252: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9253:                return "refused:c:$crole&$cqual"; 
 9254:             }
 9255:         }
 9256:     }
 9257:     my $uhome;
 9258:     if (($uname ne '') && ($udom ne '')) {
 9259:         $uhome = &homeserver($uname,$udom);
 9260:         return $uhome if ($uhome eq 'no_host');
 9261:     } else {
 9262:         $uname = $env{'user.name'};
 9263:         $udom = $env{'user.domain'};
 9264:         $uhome = $env{'user.home'};
 9265:     }
 9266:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9267:                 "$udom:$uname:rolesdef_$rolename=".
 9268:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9269:     return reply($command,$uhome);
 9270:   } else {
 9271:     return 'refused';
 9272:   }
 9273: }
 9274: 
 9275: # ---------------- Make a metadata query against the network of library servers
 9276: 
 9277: sub metadata_query {
 9278:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9279:     my %rhash;
 9280:     my %libserv = &all_library();
 9281:     my @server_list = (defined($server_array) ? @$server_array
 9282:                                               : keys(%libserv) );
 9283:     for my $server (@server_list) {
 9284:         my $domains = ''; 
 9285:         if (ref($domains_hash) eq 'HASH') {
 9286:             $domains = $domains_hash->{$server}; 
 9287:         }
 9288: 	unless ($custom or $customshow) {
 9289: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9290: 	    $rhash{$server}=$reply;
 9291: 	}
 9292: 	else {
 9293: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9294: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9295: 			     $server);
 9296: 	    $rhash{$server}=$reply;
 9297: 	}
 9298:     }
 9299:     return \%rhash;
 9300: }
 9301: 
 9302: # ----------------------------------------- Send log queries and wait for reply
 9303: 
 9304: sub log_query {
 9305:     my ($uname,$udom,$query,%filters)=@_;
 9306:     my $uhome=&homeserver($uname,$udom);
 9307:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9308:     my $uhost=&hostname($uhome);
 9309:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9310:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9311:                        $uhome);
 9312:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9313:     return get_query_reply($queryid);
 9314: }
 9315: 
 9316: # -------------------------- Update MySQL table for portfolio file
 9317: 
 9318: sub update_portfolio_table {
 9319:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9320:     if ($group ne '') {
 9321:         $file_name =~s /^\Q$group\E//;
 9322:     }
 9323:     my $homeserver = &homeserver($uname,$udom);
 9324:     my $queryid=
 9325:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9326:                ':'.&escape($file_name).':'.$action,$homeserver);
 9327:     my $reply = &get_query_reply($queryid);
 9328:     return $reply;
 9329: }
 9330: 
 9331: # -------------------------- Update MySQL allusers table
 9332: 
 9333: sub update_allusers_table {
 9334:     my ($uname,$udom,$names) = @_;
 9335:     my $homeserver = &homeserver($uname,$udom);
 9336:     my $queryid=
 9337:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9338:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9339:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9340:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9341:                'generation='.&escape($names->{'generation'}).'%%'.
 9342:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9343:                'id='.&escape($names->{'id'}),$homeserver);
 9344:     return;
 9345: }
 9346: 
 9347: # ------- Request retrieval of institutional classlists for course(s)
 9348: 
 9349: sub fetch_enrollment_query {
 9350:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9351:     my ($homeserver,$sleep,$loopmax);
 9352:     my $maxtries = 1;
 9353:     if ($context eq 'automated') {
 9354:         $homeserver = $perlvar{'lonHostID'};
 9355:         $sleep = 2;
 9356:         $loopmax = 100;
 9357:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9358:     } else {
 9359:         $homeserver = &homeserver($cnum,$dom);
 9360:     }
 9361:     my $host=&hostname($homeserver);
 9362:     my $cmd = '';
 9363:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9364:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9365:     }
 9366:     $cmd =~ s/%%$//;
 9367:     $cmd = &escape($cmd);
 9368:     my $query = 'fetchenrollment';
 9369:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9370:     unless ($queryid=~/^\Q$host\E\_/) { 
 9371:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9372:         return 'error: '.$queryid;
 9373:     }
 9374:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9375:     my $tries = 1;
 9376:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9377:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9378:         $tries ++;
 9379:     }
 9380:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9381:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9382:     } else {
 9383:         my @responses = split(/:/,$reply);
 9384:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9385:             foreach my $line (@responses) {
 9386:                 my ($key,$value) = split(/=/,$line,2);
 9387:                 $$replyref{$key} = $value;
 9388:             }
 9389:         } else {
 9390:             my $pathname = LONCAPA::tempdir();
 9391:             foreach my $line (@responses) {
 9392:                 my ($key,$value) = split(/=/,$line);
 9393:                 $$replyref{$key} = $value;
 9394:                 if ($value > 0) {
 9395:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9396:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9397:                         my $destname = $pathname.'/'.$filename;
 9398:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9399:                         if ($xml_classlist =~ /^error/) {
 9400:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9401:                         } else {
 9402:                             if ( open(FILE,">",$destname) ) {
 9403:                                 print FILE &unescape($xml_classlist);
 9404:                                 close(FILE);
 9405:                             } else {
 9406:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9407:                             }
 9408:                         }
 9409:                     }
 9410:                 }
 9411:             }
 9412:         }
 9413:         return 'ok';
 9414:     }
 9415:     return 'error';
 9416: }
 9417: 
 9418: sub get_query_reply {
 9419:     my ($queryid,$sleep,$loopmax) = @_;
 9420:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9421:         $sleep = 0.2;
 9422:     }
 9423:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9424:         $loopmax = 100;
 9425:     }
 9426:     my $replyfile=LONCAPA::tempdir().$queryid;
 9427:     my $reply='';
 9428:     for (1..$loopmax) {
 9429: 	sleep($sleep);
 9430:         if (-e $replyfile.'.end') {
 9431: 	    if (open(my $fh,"<",$replyfile)) {
 9432: 		$reply = join('',<$fh>);
 9433: 		close($fh);
 9434: 	   } else { return 'error: reply_file_error'; }
 9435:            return &unescape($reply);
 9436: 	}
 9437:     }
 9438:     return 'timeout:'.$queryid;
 9439: }
 9440: 
 9441: sub courselog_query {
 9442: #
 9443: # possible filters:
 9444: # url: url or symb
 9445: # username
 9446: # domain
 9447: # action: view, submit, grade
 9448: # start: timestamp
 9449: # end: timestamp
 9450: #
 9451:     my (%filters)=@_;
 9452:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9453:     if ($filters{'url'}) {
 9454: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9455:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9456:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9457:     }
 9458:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9459:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9460:     return &log_query($cname,$cdom,'courselog',%filters);
 9461: }
 9462: 
 9463: sub userlog_query {
 9464: #
 9465: # possible filters:
 9466: # action: log check role
 9467: # start: timestamp
 9468: # end: timestamp
 9469: #
 9470:     my ($uname,$udom,%filters)=@_;
 9471:     return &log_query($uname,$udom,'userlog',%filters);
 9472: }
 9473: 
 9474: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9475: 
 9476: sub auto_run {
 9477:     my ($cnum,$cdom) = @_;
 9478:     my $response = 0;
 9479:     my $settings;
 9480:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9481:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9482:         $settings = $domconfig{'autoenroll'};
 9483:         if ($settings->{'run'} eq '1') {
 9484:             $response = 1;
 9485:         }
 9486:     } else {
 9487:         my $homeserver;
 9488:         if (&is_course($cdom,$cnum)) {
 9489:             $homeserver = &homeserver($cnum,$cdom);
 9490:         } else {
 9491:             $homeserver = &domain($cdom,'primary');
 9492:         }
 9493:         if ($homeserver ne 'no_host') {
 9494:             $response = &reply('autorun:'.$cdom,$homeserver);
 9495:         }
 9496:     }
 9497:     return $response;
 9498: }
 9499: 
 9500: sub auto_get_sections {
 9501:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9502:     my $homeserver;
 9503:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9504:         $homeserver = &homeserver($cnum,$cdom);
 9505:     }
 9506:     if (!defined($homeserver)) { 
 9507:         if ($cdom =~ /^$match_domain$/) {
 9508:             $homeserver = &domain($cdom,'primary');
 9509:         }
 9510:     }
 9511:     my @secs;
 9512:     if (defined($homeserver)) {
 9513:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9514:         unless ($response eq 'refused') {
 9515:             @secs = split(/:/,$response);
 9516:         }
 9517:     }
 9518:     return @secs;
 9519: }
 9520: 
 9521: sub auto_new_course {
 9522:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9523:     my $homeserver = &homeserver($cnum,$cdom);
 9524:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9525:     return $response;
 9526: }
 9527: 
 9528: sub auto_validate_courseID {
 9529:     my ($cnum,$cdom,$inst_course_id) = @_;
 9530:     my $homeserver = &homeserver($cnum,$cdom);
 9531:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9532:     return $response;
 9533: }
 9534: 
 9535: sub auto_validate_instcode {
 9536:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9537:     my ($homeserver,$response);
 9538:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9539:         $homeserver = &homeserver($cnum,$cdom);
 9540:     }
 9541:     if (!defined($homeserver)) {
 9542:         if ($cdom =~ /^$match_domain$/) {
 9543:             $homeserver = &domain($cdom,'primary');
 9544:         }
 9545:     }
 9546:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9547:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9548:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9549:     return ($outcome,$description,$defaultcredits);
 9550: }
 9551: 
 9552: sub auto_validate_inst_crosslist {
 9553:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9554:     my ($homeserver,$response);
 9555:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9556:         $homeserver = &homeserver($cnum,$cdom);
 9557:     }
 9558:     if (!defined($homeserver)) {
 9559:         if ($cdom =~ /^$match_domain$/) {
 9560:             $homeserver = &domain($cdom,'primary');
 9561:         }
 9562:     }
 9563:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9564:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9565:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9566:                          &escape($coowner),$homeserver);
 9567:     }
 9568:     return $response;
 9569: }
 9570: 
 9571: sub auto_create_password {
 9572:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9573:     my ($homeserver,$response);
 9574:     my $create_passwd = 0;
 9575:     my $authchk = '';
 9576:     if ($udom =~ /^$match_domain$/) {
 9577:         $homeserver = &domain($udom,'primary');
 9578:     }
 9579:     if ($homeserver eq '') {
 9580:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9581:             $homeserver = &homeserver($cnum,$cdom);
 9582:         }
 9583:     }
 9584:     if ($homeserver eq '') {
 9585:         $authchk = 'nodomain';
 9586:     } else {
 9587:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9588:         if ($response eq 'refused') {
 9589:             $authchk = 'refused';
 9590:         } else {
 9591:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9592:         }
 9593:     }
 9594:     return ($authparam,$create_passwd,$authchk);
 9595: }
 9596: 
 9597: sub auto_photo_permission {
 9598:     my ($cnum,$cdom,$students) = @_;
 9599:     my $homeserver = &homeserver($cnum,$cdom);
 9600:     my ($outcome,$perm_reqd,$conditions) = 
 9601: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9602:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9603: 	return (undef,undef);
 9604:     }
 9605:     return ($outcome,$perm_reqd,$conditions);
 9606: }
 9607: 
 9608: sub auto_checkphotos {
 9609:     my ($uname,$udom,$pid) = @_;
 9610:     my $homeserver = &homeserver($uname,$udom);
 9611:     my ($result,$resulttype);
 9612:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9613: 				   &escape($uname).':'.&escape($pid),
 9614: 				   $homeserver));
 9615:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9616: 	return (undef,undef);
 9617:     }
 9618:     if ($outcome) {
 9619:         ($result,$resulttype) = split(/:/,$outcome);
 9620:     } 
 9621:     return ($result,$resulttype);
 9622: }
 9623: 
 9624: sub auto_photochoice {
 9625:     my ($cnum,$cdom) = @_;
 9626:     my $homeserver = &homeserver($cnum,$cdom);
 9627:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9628: 						       &escape($cdom),
 9629: 						       $homeserver)));
 9630:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9631: 	return (undef,undef);
 9632:     }
 9633:     return ($update,$comment);
 9634: }
 9635: 
 9636: sub auto_photoupdate {
 9637:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9638:     my $homeserver = &homeserver($cnum,$dom);
 9639:     my $host=&hostname($homeserver);
 9640:     my $cmd = '';
 9641:     my $maxtries = 1;
 9642:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9643:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9644:     }
 9645:     $cmd =~ s/%%$//;
 9646:     $cmd = &escape($cmd);
 9647:     my $query = 'institutionalphotos';
 9648:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9649:     unless ($queryid=~/^\Q$host\E\_/) {
 9650:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9651:         return 'error: '.$queryid;
 9652:     }
 9653:     my $reply = &get_query_reply($queryid);
 9654:     my $tries = 1;
 9655:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9656:         $reply = &get_query_reply($queryid);
 9657:         $tries ++;
 9658:     }
 9659:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9660:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9661:     } else {
 9662:         my @responses = split(/:/,$reply);
 9663:         my $outcome = shift(@responses); 
 9664:         foreach my $item (@responses) {
 9665:             my ($key,$value) = split(/=/,$item);
 9666:             $$photo{$key} = $value;
 9667:         }
 9668:         return $outcome;
 9669:     }
 9670:     return 'error';
 9671: }
 9672: 
 9673: sub auto_instcode_format {
 9674:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9675: 	$cat_order) = @_;
 9676:     my $courses = '';
 9677:     my @homeservers;
 9678:     if ($caller eq 'global') {
 9679: 	my %servers = &get_servers($codedom,'library');
 9680: 	foreach my $tryserver (keys(%servers)) {
 9681: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9682: 		push(@homeservers,$tryserver);
 9683: 	    }
 9684:         }
 9685:     } elsif ($caller eq 'requests') {
 9686:         if ($codedom =~ /^$match_domain$/) {
 9687:             my $chome = &domain($codedom,'primary');
 9688:             unless ($chome eq 'no_host') {
 9689:                 push(@homeservers,$chome);
 9690:             }
 9691:         }
 9692:     } else {
 9693:         push(@homeservers,&homeserver($caller,$codedom));
 9694:     }
 9695:     foreach my $code (keys(%{$instcodes})) {
 9696:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9697:     }
 9698:     chop($courses);
 9699:     my $ok_response = 0;
 9700:     my $response;
 9701:     while (@homeservers > 0 && $ok_response == 0) {
 9702:         my $server = shift(@homeservers); 
 9703:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9704:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9705:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9706: 		split(/:/,$response);
 9707:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9708:             push(@{$codetitles},&str2array($codetitles_str));
 9709:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9710:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9711:             $ok_response = 1;
 9712:         }
 9713:     }
 9714:     if ($ok_response) {
 9715:         return 'ok';
 9716:     } else {
 9717:         return $response;
 9718:     }
 9719: }
 9720: 
 9721: sub auto_instcode_defaults {
 9722:     my ($domain,$returnhash,$code_order) = @_;
 9723:     my @homeservers;
 9724: 
 9725:     my %servers = &get_servers($domain,'library');
 9726:     foreach my $tryserver (keys(%servers)) {
 9727: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9728: 	    push(@homeservers,$tryserver);
 9729: 	}
 9730:     }
 9731: 
 9732:     my $response;
 9733:     foreach my $server (@homeservers) {
 9734:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9735:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9736: 	
 9737: 	foreach my $pair (split(/\&/,$response)) {
 9738: 	    my ($name,$value)=split(/\=/,$pair);
 9739: 	    if ($name eq 'code_order') {
 9740: 		@{$code_order} = split(/\&/,&unescape($value));
 9741: 	    } else {
 9742: 		$returnhash->{&unescape($name)}=&unescape($value);
 9743: 	    }
 9744: 	}
 9745: 	return 'ok';
 9746:     }
 9747: 
 9748:     return $response;
 9749: }
 9750: 
 9751: sub auto_possible_instcodes {
 9752:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9753:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9754:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9755:         return;
 9756:     }
 9757:     my (@homeservers,$uhome);
 9758:     if (defined(&domain($domain,'primary'))) {
 9759:         $uhome=&domain($domain,'primary');
 9760:         push(@homeservers,&domain($domain,'primary'));
 9761:     } else {
 9762:         my %servers = &get_servers($domain,'library');
 9763:         foreach my $tryserver (keys(%servers)) {
 9764:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9765:                 push(@homeservers,$tryserver);
 9766:             }
 9767:         }
 9768:     }
 9769:     my $response;
 9770:     foreach my $server (@homeservers) {
 9771:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9772:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9773:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9774:             split(':',$response);
 9775:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9776:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9777:         foreach my $item (split('&',$cat_title)) {   
 9778:             my ($name,$value)=split('=',$item);
 9779:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9780:         }
 9781:         foreach my $item (split('&',$cat_order)) {
 9782:             my ($name,$value)=split('=',$item);
 9783:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9784:         }
 9785:         return 'ok';
 9786:     }
 9787:     return $response;
 9788: }
 9789: 
 9790: sub auto_courserequest_checks {
 9791:     my ($dom) = @_;
 9792:     my ($homeserver,%validations);
 9793:     if ($dom =~ /^$match_domain$/) {
 9794:         $homeserver = &domain($dom,'primary');
 9795:     }
 9796:     unless ($homeserver eq 'no_host') {
 9797:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9798:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9799:             my @items = split(/&/,$response);
 9800:             foreach my $item (@items) {
 9801:                 my ($key,$value) = split('=',$item);
 9802:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9803:             }
 9804:         }
 9805:     }
 9806:     return %validations; 
 9807: }
 9808: 
 9809: sub auto_courserequest_validation {
 9810:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9811:     my ($homeserver,$response);
 9812:     if ($dom =~ /^$match_domain$/) {
 9813:         $homeserver = &domain($dom,'primary');
 9814:     }
 9815:     unless ($homeserver eq 'no_host') {
 9816:         my $customdata;
 9817:         if (ref($custominfo) eq 'HASH') {
 9818:             $customdata = &freeze_escape($custominfo);
 9819:         }
 9820:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9821:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9822:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9823:                                     $customdata,$homeserver));
 9824:     }
 9825:     return $response;
 9826: }
 9827: 
 9828: sub auto_validate_class_sec {
 9829:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9830:     my $homeserver = &homeserver($cnum,$cdom);
 9831:     my $ownerlist;
 9832:     if (ref($owners) eq 'ARRAY') {
 9833:         $ownerlist = join(',',@{$owners});
 9834:     } else {
 9835:         $ownerlist = $owners;
 9836:     }
 9837:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9838:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9839:     return $response;
 9840: }
 9841: 
 9842: sub auto_instsec_reformat {
 9843:     my ($cdom,$action,$instsecref) = @_;
 9844:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9845:     my @homeservers;
 9846:     if (defined(&domain($cdom,'primary'))) {
 9847:         push(@homeservers,&domain($cdom,'primary'));
 9848:     } else {
 9849:         my %servers = &get_servers($cdom,'library');
 9850:         foreach my $tryserver (keys(%servers)) {
 9851:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9852:                 push(@homeservers,$tryserver);
 9853:             }
 9854:         }
 9855:     }
 9856:     my $response;
 9857:     my %reformatted = %{$instsecref};
 9858:     foreach my $server (@homeservers) {
 9859:         if (ref($instsecref) eq 'HASH') {
 9860:             my $info = &freeze_escape($instsecref);
 9861:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9862:                                 $action.':'.$info,$server);
 9863:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9864:             my @items = split(/&/,$response);
 9865:             foreach my $item (@items) {
 9866:                 my ($key,$value) = split(/=/,$item);
 9867:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9868:             }
 9869:         }
 9870:     }
 9871:     return %reformatted;
 9872: }
 9873: 
 9874: sub auto_validate_instclasses {
 9875:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9876:     my ($homeserver,%validations);
 9877:     $homeserver = &homeserver($cnum,$cdom);
 9878:     unless ($homeserver eq 'no_host') {
 9879:         my $ownerlist;
 9880:         if (ref($owners) eq 'ARRAY') {
 9881:             $ownerlist = join(',',@{$owners});
 9882:         } else {
 9883:             $ownerlist = $owners;
 9884:         }
 9885:         if (ref($classesref) eq 'HASH') {
 9886:             my $classes = &freeze_escape($classesref);
 9887:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9888:                                 ':'.$cdom.':'.$classes,$homeserver);
 9889:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9890:                 my @items = split(/&/,$response);
 9891:                 foreach my $item (@items) {
 9892:                     my ($key,$value) = split('=',$item);
 9893:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9894:                 }
 9895:             }
 9896:         }
 9897:     }
 9898:     return %validations;
 9899: }
 9900: 
 9901: sub auto_crsreq_update {
 9902:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9903:         $code,$accessstart,$accessend,$inbound) = @_;
 9904:     my ($homeserver,%crsreqresponse);
 9905:     if ($cdom =~ /^$match_domain$/) {
 9906:         $homeserver = &domain($cdom,'primary');
 9907:     }
 9908:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9909:         my $info;
 9910:         if (ref($inbound) eq 'HASH') {
 9911:             $info = &freeze_escape($inbound);
 9912:         }
 9913:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9914:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9915:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9916:                             &escape($title).':'.&escape($code).':'.
 9917:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9918:                             $homeserver);
 9919:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9920:             my @items = split(/&/,$response);
 9921:             foreach my $item (@items) {
 9922:                 my ($key,$value) = split('=',$item);
 9923:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9924:             }
 9925:         }
 9926:     }
 9927:     return \%crsreqresponse;
 9928: }
 9929: 
 9930: sub auto_export_grades {
 9931:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9932:     my ($homeserver,%exportresponse);
 9933:     if ($cdom =~ /^$match_domain$/) {
 9934:         $homeserver = &domain($cdom,'primary');
 9935:     }
 9936:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9937:         my $info;
 9938:         if (ref($inforef) eq 'HASH') {
 9939:             $info = &freeze_escape($inforef);
 9940:         }
 9941:         if (ref($gradesref) eq 'HASH') {
 9942:             my $grades = &freeze_escape($gradesref);
 9943:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9944:                                 $info.':'.$grades,$homeserver);
 9945:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9946:                 my @items = split(/&/,$response);
 9947:                 foreach my $item (@items) {
 9948:                     my ($key,$value) = split('=',$item);
 9949:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9950:                 }
 9951:             }
 9952:         }
 9953:     }
 9954:     return \%exportresponse;
 9955: }
 9956: 
 9957: sub check_instcode_cloning {
 9958:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9959:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9960:         return;
 9961:     }
 9962:     my $canclone;
 9963:     if (@{$code_order} > 0) {
 9964:         my $instcoderegexp ='^';
 9965:         my @clonecodes = split(/\&/,$cloner);
 9966:         foreach my $item (@{$code_order}) {
 9967:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9968:                 foreach my $pair (@clonecodes) {
 9969:                     my ($key,$val) = split(/\=/,$pair,2);
 9970:                     $val = &unescape($val);
 9971:                     if ($key eq $item) {
 9972:                         $instcoderegexp .= '('.$val.')';
 9973:                         last;
 9974:                     }
 9975:                 }
 9976:             } else {
 9977:                 $instcoderegexp .= $codedefaults->{$item};
 9978:             }
 9979:         }
 9980:         $instcoderegexp .= '$';
 9981:         my (@from,@to);
 9982:         eval {
 9983:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9984:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9985:         };
 9986:         if ((@from > 0) && (@to > 0)) {
 9987:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9988:             if (!@diffs) {
 9989:                 $canclone = 1;
 9990:             }
 9991:         }
 9992:     }
 9993:     return $canclone;
 9994: }
 9995: 
 9996: sub default_instcode_cloning {
 9997:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9998:     my (%codedefaults,@code_order,$canclone);
 9999:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10000:         %codedefaults = %{$codedefaultsref};
10001:         @code_order = @{$codeorderref};
10002:     } elsif ($clonedom) {
10003:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10004:     }
10005:     if (($domdefclone) && (@code_order)) {
10006:         my @clonecodes = split(/\+/,$domdefclone);
10007:         my $instcoderegexp ='^';
10008:         foreach my $item (@code_order) {
10009:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10010:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10011:             } else {
10012:                 $instcoderegexp .= $codedefaults{$item};
10013:             }
10014:         }
10015:         $instcoderegexp .= '$';
10016:         my (@from,@to);
10017:         eval {
10018:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10019:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10020:         };
10021:         if ((@from > 0) && (@to > 0)) {
10022:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10023:             if (!@diffs) {
10024:                 $canclone = 1;
10025:             }
10026:         }
10027:     }
10028:     return $canclone;
10029: }
10030: 
10031: # ------------------------------------------------------- Course Group routines
10032: 
10033: sub get_coursegroups {
10034:     my ($cdom,$cnum,$group,$namespace) = @_;
10035:     return(&dump($namespace,$cdom,$cnum,$group));
10036: }
10037: 
10038: sub modify_coursegroup {
10039:     my ($cdom,$cnum,$groupsettings) = @_;
10040:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10041: }
10042: 
10043: sub toggle_coursegroup_status {
10044:     my ($cdom,$cnum,$group,$action) = @_;
10045:     my ($from_namespace,$to_namespace);
10046:     if ($action eq 'delete') {
10047:         $from_namespace = 'coursegroups';
10048:         $to_namespace = 'deleted_groups';
10049:     } else {
10050:         $from_namespace = 'deleted_groups';
10051:         $to_namespace = 'coursegroups';
10052:     }
10053:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10054:     if (my $tmp = &error(%curr_group)) {
10055:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10056:         return ('read error',$tmp);
10057:     } else {
10058:         my %savedsettings = %curr_group; 
10059:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10060:         my $deloutcome;
10061:         if ($result eq 'ok') {
10062:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10063:         } else {
10064:             return ('write error',$result);
10065:         }
10066:         if ($deloutcome eq 'ok') {
10067:             return 'ok';
10068:         } else {
10069:             return ('delete error',$deloutcome);
10070:         }
10071:     }
10072: }
10073: 
10074: sub modify_group_roles {
10075:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10076:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10077:     my $role = 'gr/'.&escape($userprivs);
10078:     my ($uname,$udom) = split(/:/,$user);
10079:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10080:     if ($result eq 'ok') {
10081:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10082:     }
10083:     return $result;
10084: }
10085: 
10086: sub modify_coursegroup_membership {
10087:     my ($cdom,$cnum,$membership) = @_;
10088:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10089:     return $result;
10090: }
10091: 
10092: sub get_active_groups {
10093:     my ($udom,$uname,$cdom,$cnum) = @_;
10094:     my $now = time;
10095:     my %groups = ();
10096:     foreach my $key (keys(%env)) {
10097:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10098:             my ($start,$end) = split(/\./,$env{$key});
10099:             if (($end!=0) && ($end<$now)) { next; }
10100:             if (($start!=0) && ($start>$now)) { next; }
10101:             if ($1 eq $cdom && $2 eq $cnum) {
10102:                 $groups{$3} = $env{$key} ;
10103:             }
10104:         }
10105:     }
10106:     return %groups;
10107: }
10108: 
10109: sub get_group_membership {
10110:     my ($cdom,$cnum,$group) = @_;
10111:     return(&dump('groupmembership',$cdom,$cnum,$group));
10112: }
10113: 
10114: sub get_users_groups {
10115:     my ($udom,$uname,$courseid) = @_;
10116:     my @usersgroups;
10117:     my $cachetime=1800;
10118: 
10119:     my $hashid="$udom:$uname:$courseid";
10120:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10121:     if (defined($cached)) {
10122:         @usersgroups = split(/:/,$grouplist);
10123:     } else {  
10124:         $grouplist = '';
10125:         my $courseurl = &courseid_to_courseurl($courseid);
10126:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10127:         my $access_end = $env{'course.'.$courseid.
10128:                               '.default_enrollment_end_date'};
10129:         my $now = time;
10130:         foreach my $key (keys(%roleshash)) {
10131:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10132:                 my $group = $1;
10133:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10134:                     my $start = $2;
10135:                     my $end = $1;
10136:                     if ($start == -1) { next; } # deleted from group
10137:                     if (($start!=0) && ($start>$now)) { next; }
10138:                     if (($end!=0) && ($end<$now)) {
10139:                         if ($access_end && $access_end < $now) {
10140:                             if ($access_end - $end < 86400) {
10141:                                 push(@usersgroups,$group);
10142:                             }
10143:                         }
10144:                         next;
10145:                     }
10146:                     push(@usersgroups,$group);
10147:                 }
10148:             }
10149:         }
10150:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10151:         $grouplist = join(':',@usersgroups);
10152:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10153:     }
10154:     return @usersgroups;
10155: }
10156: 
10157: sub devalidate_getgroups_cache {
10158:     my ($udom,$uname,$cdom,$cnum)=@_;
10159:     my $courseid = $cdom.'_'.$cnum;
10160: 
10161:     my $hashid="$udom:$uname:$courseid";
10162:     &devalidate_cache_new('getgroups',$hashid);
10163: }
10164: 
10165: # ------------------------------------------------------------------ Plain Text
10166: 
10167: sub plaintext {
10168:     my ($short,$type,$cid,$forcedefault) = @_;
10169:     if ($short =~ m{^cr/}) {
10170: 	return (split('/',$short))[-1];
10171:     }
10172:     if (!defined($cid)) {
10173:         $cid = $env{'request.course.id'};
10174:     }
10175:     my %rolenames = (
10176:                       Course    => 'std',
10177:                       Community => 'alt1',
10178:                       Placement => 'std',
10179:                     );
10180:     if ($cid ne '') {
10181:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10182:             unless ($forcedefault) {
10183:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10184:                 &Apache::lonlocal::mt_escape(\$roletext);
10185:                 return &Apache::lonlocal::mt($roletext);
10186:             }
10187:         }
10188:     }
10189:     if ((defined($type)) && (defined($rolenames{$type})) &&
10190:         (defined($rolenames{$type})) && 
10191:         (defined($prp{$short}{$rolenames{$type}}))) {
10192:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10193:     } elsif ($cid ne '') {
10194:         my $crstype = $env{'course.'.$cid.'.type'};
10195:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10196:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10197:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10198:         }
10199:     }
10200:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10201: }
10202: 
10203: # ----------------------------------------------------------------- Assign Role
10204: 
10205: sub assignrole {
10206:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10207:         $context)=@_;
10208:     my $mrole;
10209:     if ($role =~ /^cr\//) {
10210:         my $cwosec=$url;
10211:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10212: 	unless (&allowed('ccr',$cwosec)) {
10213:            my $refused = 1;
10214:            if ($context eq 'requestcourses') {
10215:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10216:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10217:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10218:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10219:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10220:                            if ($crsenv{'internal.courseowner'} eq
10221:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10222:                                $refused = '';
10223:                            }
10224:                        }
10225:                    }
10226:                }
10227:            }
10228:            if ($refused) {
10229:                &logthis('Refused custom assignrole: '.
10230:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10231:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10232:                return 'refused';
10233:            }
10234:         }
10235:         $mrole='cr';
10236:     } elsif ($role =~ /^gr\//) {
10237:         my $cwogrp=$url;
10238:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10239:         unless (&allowed('mdg',$cwogrp)) {
10240:             &logthis('Refused group assignrole: '.
10241:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10242:                     $env{'user.name'}.' at '.$env{'user.domain'});
10243:             return 'refused';
10244:         }
10245:         $mrole='gr';
10246:     } else {
10247:         my $cwosec=$url;
10248:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10249:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10250:             my $refused;
10251:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10252:                 if (!(&allowed('c'.$role,$url))) {
10253:                     $refused = 1;
10254:                 }
10255:             } else {
10256:                 $refused = 1;
10257:             }
10258:             if ($refused) {
10259:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10260:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10261:                     my %crsenv;
10262:                     if ($role eq 'cc' || $role eq 'co') {
10263:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10264:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10265:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10266:                                 if ($crsenv{'internal.courseowner'} eq 
10267:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10268:                                     $refused = '';
10269:                                 }
10270:                             }
10271:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10272:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10273:                                 if ($crsenv{'internal.courseowner'} eq 
10274:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10275:                                     $refused = '';
10276:                                 }
10277:                             }
10278:                         }
10279:                     }
10280:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10281:                     if ($role eq 'st') {
10282:                         $refused = '';
10283:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10284:                         $refused = '';
10285:                     }
10286:                 } elsif ($context eq 'requestcourses') {
10287:                     my @possroles = ('st','ta','ep','in','cc','co');
10288:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10289:                         my $wrongcc;
10290:                         if ($cnum =~ /^$match_community$/) {
10291:                             $wrongcc = 1 if ($role eq 'cc');
10292:                         } else {
10293:                             $wrongcc = 1 if ($role eq 'co');
10294:                         }
10295:                         unless ($wrongcc) {
10296:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10297:                             if ($crsenv{'internal.courseowner'} eq 
10298:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10299:                                 $refused = '';
10300:                             }
10301:                         }
10302:                     }
10303:                 } elsif ($context eq 'requestauthor') {
10304:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10305:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10306:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10307:                             $refused = '';
10308:                         } else {
10309:                             my %domdefaults = &get_domain_defaults($udom);
10310:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10311:                                 my $checkbystatus;
10312:                                 if ($env{'user.adv'}) { 
10313:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10314:                                     if ($disposition eq 'automatic') {
10315:                                         $refused = '';
10316:                                     } elsif ($disposition eq '') {
10317:                                         $checkbystatus = 1;
10318:                                     } 
10319:                                 } else {
10320:                                     $checkbystatus = 1;
10321:                                 }
10322:                                 if ($checkbystatus) {
10323:                                     if ($env{'environment.inststatus'}) {
10324:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10325:                                         foreach my $type (@inststatuses) {
10326:                                             if (($type ne '') &&
10327:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10328:                                                 $refused = '';
10329:                                             }
10330:                                         }
10331:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10332:                                         $refused = '';
10333:                                     }
10334:                                 }
10335:                             }
10336:                         }
10337:                     }
10338:                 }
10339:                 if ($refused) {
10340:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10341:                              ' '.$role.' '.$end.' '.$start.' by '.
10342: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10343:                     return 'refused';
10344:                 }
10345:             }
10346:         } elsif ($role eq 'au') {
10347:             if ($url ne '/'.$udom.'/') {
10348:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10349:                          ' to assign author role for '.$uname.':'.$udom.
10350:                          ' in domain: '.$url.' refused (wrong domain).');
10351:                 return 'refused';
10352:             }
10353:         }
10354:         $mrole=$role;
10355:     }
10356:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10357:                 "$udom:$uname:$url".'_'."$mrole=$role";
10358:     if ($end) { $command.='_'.$end; }
10359:     if ($start) {
10360: 	if ($end) { 
10361:            $command.='_'.$start; 
10362:         } else {
10363:            $command.='_0_'.$start;
10364:         }
10365:     }
10366:     my $origstart = $start;
10367:     my $origend = $end;
10368:     my $delflag;
10369: # actually delete
10370:     if ($deleteflag) {
10371: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10372: # modify command to delete the role
10373:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10374:                 "$udom:$uname:$url".'_'."$mrole";
10375: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10376: # set start and finish to negative values for userrolelog
10377:            $start=-1;
10378:            $end=-1;
10379:            $delflag = 1;
10380:         }
10381:     }
10382: # send command
10383:     my $answer=&reply($command,&homeserver($uname,$udom));
10384: # log new user role if status is ok
10385:     if ($answer eq 'ok') {
10386: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10387:         if (($role eq 'cc') || ($role eq 'in') ||
10388:             ($role eq 'ep') || ($role eq 'ad') ||
10389:             ($role eq 'ta') || ($role eq 'st') ||
10390:             ($role=~/^cr/) || ($role eq 'gr') ||
10391:             ($role eq 'co')) {
10392: # for course roles, perform group memberships changes triggered by role change.
10393:             unless ($role =~ /^gr/) {
10394:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10395:                                                  $origstart,$selfenroll,$context);
10396:             }
10397:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10398:                            $selfenroll,$context);
10399:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10400:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10401:                  ($role eq 'da')) {
10402:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10403:                            $context);
10404:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10405:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10406:                              $context); 
10407:         }
10408:         if ($role eq 'cc') {
10409:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10410:         }
10411:     }
10412:     return $answer;
10413: }
10414: 
10415: sub autoupdate_coowners {
10416:     my ($url,$end,$start,$uname,$udom) = @_;
10417:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10418:     if (($cdom ne '') && ($cnum ne '')) {
10419:         my $now = time;
10420:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10421:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10422:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10423:             my $instcode = $coursehash{'internal.coursecode'};
10424:             my $xlists = $coursehash{'internal.crosslistings'};
10425:             if ($instcode ne '') {
10426:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10427:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10428:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10429:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10430:                         unless ($result eq 'valid') {
10431:                             if ($xlists ne '') {
10432:                                 foreach my $xlist (split(',',$xlists)) {
10433:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10434:                                     $result =
10435:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10436:                                                                       $inst_crosslist,$uname.':'.$udom);
10437:                                     last if ($result eq 'valid');
10438:                                 }
10439:                             }
10440:                         }
10441:                         if ($result eq 'valid') {
10442:                             if ($coursehash{'internal.co-owners'}) {
10443:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10444:                                     push(@newcoowners,$coowner);
10445:                                 }
10446:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10447:                                     push(@newcoowners,$uname.':'.$udom);
10448:                                 }
10449:                                 @newcoowners = sort(@newcoowners);
10450:                             } else {
10451:                                 push(@newcoowners,$uname.':'.$udom);
10452:                             }
10453:                         } elsif ($coursehash{'internal.co-owners'}) {
10454:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10455:                                 unless ($coowner eq $uname.':'.$udom) {
10456:                                     push(@newcoowners,$coowner);
10457:                                 }
10458:                             }
10459:                             unless (@newcoowners > 0) {
10460:                                 $delcoowners = 1;
10461:                                 $coowners = '';
10462:                             }
10463:                         }
10464:                         if (@newcoowners || $delcoowners) {
10465:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10466:                                             $delcoowners,@newcoowners);
10467:                         }
10468:                     }
10469:                 }
10470:             }
10471:         }
10472:     }
10473: }
10474: 
10475: sub store_coowners {
10476:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10477:     my $cid = $cdom.'_'.$cnum;
10478:     my ($coowners,$delresult,$putresult);
10479:     if (@newcoowners) {
10480:         $coowners = join(',',@newcoowners);
10481:         my %coownershash = (
10482:                             'internal.co-owners' => $coowners,
10483:                            );
10484:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10485:         if ($putresult eq 'ok') {
10486:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10487:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10488:             }
10489:         }
10490:     }
10491:     if ($delcoowners) {
10492:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10493:         if ($delresult eq 'ok') {
10494:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10495:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10496:             }
10497:         }
10498:     }
10499:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10500:         my %crsinfo =
10501:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10502:         if (ref($crsinfo{$cid}) eq 'HASH') {
10503:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10504:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10505:         }
10506:     }
10507: }
10508: 
10509: # -------------------------------------------------- Modify user authentication
10510: # Overrides without validation
10511: 
10512: sub modifyuserauth {
10513:     my ($udom,$uname,$umode,$upass)=@_;
10514:     my $uhome=&homeserver($uname,$udom);
10515:     my $allowed;
10516:     if (&allowed('mau',$udom)) {
10517:         $allowed = 1;
10518:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10519:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10520:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10521:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10522:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10523:         if (($cdom ne '') && ($cnum ne '')) {
10524:             my $is_owner = &is_course_owner($cdom,$cnum);
10525:             if ($is_owner) {
10526:                 $allowed = 1;
10527:             }
10528:         }
10529:     }
10530:     unless ($allowed) { return 'refused'; }
10531:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10532:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10533:              ' in domain '.$env{'request.role.domain'});  
10534:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10535: 		     &escape($upass),$uhome);
10536:     my $ip = &get_requestor_ip();
10537:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10538:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10539:          '(Remote '.$ip.'): '.$reply);
10540:     &log($udom,,$uname,$uhome,
10541:         'Authentication changed by '.$env{'user.domain'}.', '.
10542:                                      $env{'user.name'}.', '.$umode.
10543:          '(Remote '.$ip.'): '.$reply);
10544:     unless ($reply eq 'ok') {
10545:         &logthis('Authentication mode error: '.$reply);
10546: 	return 'error: '.$reply;
10547:     }   
10548:     return 'ok';
10549: }
10550: 
10551: # --------------------------------------------------------------- Modify a user
10552: 
10553: sub modifyuser {
10554:     my ($udom,    $uname, $uid,
10555:         $umode,   $upass, $first,
10556:         $middle,  $last,  $gene,
10557:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10558:     $udom= &LONCAPA::clean_domain($udom);
10559:     $uname=&LONCAPA::clean_username($uname);
10560:     my $showcandelete = 'none';
10561:     if (ref($candelete) eq 'ARRAY') {
10562:         if (@{$candelete} > 0) {
10563:             $showcandelete = join(', ',@{$candelete});
10564:         }
10565:     }
10566:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10567:              $umode.', '.$first.', '.$middle.', '.
10568: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10569:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10570:                                      ' desiredhome not specified'). 
10571:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10572:              ' in domain '.$env{'request.role.domain'});
10573:     my $uhome=&homeserver($uname,$udom,'true');
10574:     my $newuser;
10575:     if ($uhome eq 'no_host') {
10576:         $newuser = 1;
10577:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10578:                 ($umode eq 'lti')) {
10579:             return 'error: more information needed to create new user';
10580:         }
10581:     }
10582: # ----------------------------------------------------------------- Create User
10583:     if (($uhome eq 'no_host') && 
10584: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10585:         my $unhome='';
10586:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10587:             $unhome = $desiredhome;
10588: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10589: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10590:         } else { # load balancing routine for determining $unhome
10591:             my $loadm=10000000;
10592: 	    my %servers = &get_servers($udom,'library');
10593: 	    foreach my $tryserver (keys(%servers)) {
10594: 		my $answer=reply('load',$tryserver);
10595: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10596: 		    $loadm=$answer;
10597: 		    $unhome=$tryserver;
10598: 		}
10599: 	    }
10600:         }
10601:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10602: 	    return 'error: unable to find a home server for '.$uname.
10603:                    ' in domain '.$udom;
10604:         }
10605:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10606:                          &escape($upass),$unhome);
10607: 	unless ($reply eq 'ok') {
10608:             return 'error: '.$reply;
10609:         }   
10610:         $uhome=&homeserver($uname,$udom,'true');
10611:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10612: 	    return 'error: unable verify users home machine.';
10613:         }
10614:     }   # End of creation of new user
10615: # ---------------------------------------------------------------------- Add ID
10616:     if ($uid) {
10617:        $uid=~tr/A-Z/a-z/;
10618:        my %uidhash=&idrget($udom,$uname);
10619:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10620:          && (!$forceid)) {
10621: 	  unless ($uid eq $uidhash{$uname}) {
10622: 	      return 'error: user id "'.$uid.'" does not match '.
10623:                   'current user id "'.$uidhash{$uname}.'".';
10624:           }
10625:        } else {
10626: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10627:        }
10628:     }
10629: # -------------------------------------------------------------- Add names, etc
10630:     my @tmp=&get('environment',
10631: 		   ['firstname','middlename','lastname','generation','id',
10632:                     'permanentemail','inststatus'],
10633: 		   $udom,$uname);
10634:     my (%names,%oldnames);
10635:     if ($tmp[0] =~ m/^error:.*/) { 
10636:         %names=(); 
10637:     } else {
10638:         %names = @tmp;
10639:         %oldnames = %names;
10640:     }
10641: #
10642: # If name, email and/or uid are blank (e.g., because an uploaded file
10643: # of users did not contain them), do not overwrite existing values
10644: # unless field is in $candelete array ref.  
10645: #
10646: 
10647:     my @fields = ('firstname','middlename','lastname','generation',
10648:                   'permanentemail','id');
10649:     my %newvalues;
10650:     if (ref($candelete) eq 'ARRAY') {
10651:         foreach my $field (@fields) {
10652:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10653:                 if ($field eq 'firstname') {
10654:                     $names{$field} = $first;
10655:                 } elsif ($field eq 'middlename') {
10656:                     $names{$field} = $middle;
10657:                 } elsif ($field eq 'lastname') {
10658:                     $names{$field} = $last;
10659:                 } elsif ($field eq 'generation') { 
10660:                     $names{$field} = $gene;
10661:                 } elsif ($field eq 'permanentemail') {
10662:                     $names{$field} = $email;
10663:                 } elsif ($field eq 'id') {
10664:                     $names{$field}  = $uid;
10665:                 }
10666:             }
10667:         }
10668:     }
10669:     if ($first)  { $names{'firstname'}  = $first; }
10670:     if (defined($middle)) { $names{'middlename'} = $middle; }
10671:     if ($last)   { $names{'lastname'}   = $last; }
10672:     if (defined($gene))   { $names{'generation'} = $gene; }
10673:     if ($email) {
10674:        $email=~s/[^\w\@\.\-\,]//gs;
10675:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10676:     }
10677:     if ($uid) { $names{'id'}  = $uid; }
10678:     if (defined($inststatus)) {
10679:         $names{'inststatus'} = '';
10680:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10681:         if (ref($usertypes) eq 'HASH') {
10682:             my @okstatuses; 
10683:             foreach my $item (split(/:/,$inststatus)) {
10684:                 if (defined($usertypes->{$item})) {
10685:                     push(@okstatuses,$item);  
10686:                 }
10687:             }
10688:             if (@okstatuses) {
10689:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10690:             }
10691:         }
10692:     }
10693:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10694:                  $umode.', '.$first.', '.$middle.', '.
10695:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10696:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10697:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10698:     } else {
10699:         $logmsg .= ' during self creation';
10700:     }
10701:     my $changed;
10702:     if ($newuser) {
10703:         $changed = 1;
10704:     } else {
10705:         foreach my $field (@fields) {
10706:             if ($names{$field} ne $oldnames{$field}) {
10707:                 $changed = 1;
10708:                 last;
10709:             }
10710:         }
10711:     }
10712:     unless ($changed) {
10713:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10714:         &logthis($logmsg);
10715:         return 'ok';
10716:     }
10717:     my $reply = &put('environment', \%names, $udom,$uname);
10718:     if ($reply ne 'ok') { 
10719:         return 'error: '.$reply;
10720:     }
10721:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10722:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10723:     }
10724:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10725:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10726:     $logmsg = 'Success modifying user '.$logmsg;
10727:     &logthis($logmsg);
10728:     return 'ok';
10729: }
10730: 
10731: # -------------------------------------------------------------- Modify student
10732: 
10733: sub modifystudent {
10734:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10735:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10736:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10737:     if (!$cid) {
10738: 	unless ($cid=$env{'request.course.id'}) {
10739: 	    return 'not_in_class';
10740: 	}
10741:     }
10742: # --------------------------------------------------------------- Make the user
10743:     my $reply=&modifyuser
10744: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10745:          $desiredhome,$email,$inststatus);
10746:     unless ($reply eq 'ok') { return $reply; }
10747:     # This will cause &modify_student_enrollment to get the uid from the
10748:     # student's environment
10749:     $uid = undef if (!$forceid);
10750:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10751:                                         $gene,$usec,$end,$start,$type,$locktype,
10752:                                         $cid,$selfenroll,$context,$credits,$instsec);
10753:     return $reply;
10754: }
10755: 
10756: sub modify_student_enrollment {
10757:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10758:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10759:     my ($cdom,$cnum,$chome);
10760:     if (!$cid) {
10761: 	unless ($cid=$env{'request.course.id'}) {
10762: 	    return 'not_in_class';
10763: 	}
10764: 	$cdom=$env{'course.'.$cid.'.domain'};
10765: 	$cnum=$env{'course.'.$cid.'.num'};
10766:     } else {
10767: 	($cdom,$cnum)=split(/_/,$cid);
10768:     }
10769:     $chome=$env{'course.'.$cid.'.home'};
10770:     if (!$chome) {
10771: 	$chome=&homeserver($cnum,$cdom);
10772:     }
10773:     if (!$chome) { return 'unknown_course'; }
10774:     # Make sure the user exists
10775:     my $uhome=&homeserver($uname,$udom);
10776:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10777: 	return 'error: no such user';
10778:     }
10779:     # Get student data if we were not given enough information
10780:     if (!defined($first)  || $first  eq '' || 
10781:         !defined($last)   || $last   eq '' || 
10782:         !defined($uid)    || $uid    eq '' || 
10783:         !defined($middle) || $middle eq '' || 
10784:         !defined($gene)   || $gene   eq '') {
10785:         # They did not supply us with enough data to enroll the student, so
10786:         # we need to pick up more information.
10787:         my %tmp = &get('environment',
10788:                        ['firstname','middlename','lastname', 'generation','id']
10789:                        ,$udom,$uname);
10790: 
10791:         #foreach my $key (keys(%tmp)) {
10792:         #    &logthis("key $key = ".$tmp{$key});
10793:         #}
10794:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10795:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10796:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10797:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10798:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10799:     }
10800:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10801:     my $user = "$uname:$udom";
10802:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10803:     my $reply=cput('classlist',
10804: 		   {$user => 
10805: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10806: 		   $cdom,$cnum);
10807:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10808:         &devalidate_getsection_cache($udom,$uname,$cid);
10809:     } else { 
10810: 	return 'error: '.$reply;
10811:     }
10812:     # Add student role to user
10813:     my $uurl='/'.$cid;
10814:     $uurl=~s/\_/\//g;
10815:     if ($usec) {
10816: 	$uurl.='/'.$usec;
10817:     }
10818:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10819:                              $selfenroll,$context);
10820:     if ($result ne 'ok') {
10821:         if ($old_entry{$user} ne '') {
10822:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10823:         } else {
10824:             $reply = &del('classlist',[$user],$cdom,$cnum);
10825:         }
10826:     }
10827:     return $result; 
10828: }
10829: 
10830: sub format_name {
10831:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10832:     my $name;
10833:     if ($first ne 'lastname') {
10834: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10835:     } else {
10836: 	if ($lastname=~/\S/) {
10837: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10838: 	    $name=~s/\s+,/,/;
10839: 	} else {
10840: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10841: 	}
10842:     }
10843:     $name=~s/^\s+//;
10844:     $name=~s/\s+$//;
10845:     $name=~s/\s+/ /g;
10846:     return $name;
10847: }
10848: 
10849: # ------------------------------------------------- Write to course preferences
10850: 
10851: sub writecoursepref {
10852:     my ($courseid,%prefs)=@_;
10853:     $courseid=~s/^\///;
10854:     $courseid=~s/\_/\//g;
10855:     my ($cdomain,$cnum)=split(/\//,$courseid);
10856:     my $chome=homeserver($cnum,$cdomain);
10857:     if (($chome eq '') || ($chome eq 'no_host')) { 
10858: 	return 'error: no such course';
10859:     }
10860:     my $cstring='';
10861:     foreach my $pref (keys(%prefs)) {
10862: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10863:     }
10864:     $cstring=~s/\&$//;
10865:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10866: }
10867: 
10868: # ---------------------------------------------------------- Make/modify course
10869: 
10870: sub createcourse {
10871:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10872:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10873:     $url=&declutter($url);
10874:     my $cid='';
10875:     if ($context eq 'requestcourses') {
10876:         my $can_create = 0;
10877:         my ($ownername,$ownerdom) = split(':',$course_owner);
10878:         if ($udom eq $ownerdom) {
10879:             my $reload;
10880:             if (($callercontext eq 'auto') &&
10881:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10882:                 $reload = 'reload';
10883:             }
10884:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10885:                                   $context)) {
10886:                 $can_create = 1;
10887:             }
10888:         } else {
10889:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10890:                                            $category);
10891:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10892:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10893:                 if (@curr > 0) {
10894:                     my @options = qw(approval validate autolimit);
10895:                     my $optregex = join('|',@options);
10896:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10897:                         $can_create = 1;
10898:                     }
10899:                 }
10900:             }
10901:         }
10902:         if ($can_create) {
10903:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10904:                 unless (&allowed('ccc',$udom)) {
10905:                     return 'refused'; 
10906:                 }
10907:             }
10908:         } else {
10909:             return 'refused';
10910:         }
10911:     } elsif (!&allowed('ccc',$udom)) {
10912:         return 'refused';
10913:     }
10914: # --------------------------------------------------------------- Get Unique ID
10915:     my $uname;
10916:     if ($cnum =~ /^$match_courseid$/) {
10917:         my $chome=&homeserver($cnum,$udom,'true');
10918:         if (($chome eq '') || ($chome eq 'no_host')) {
10919:             $uname = $cnum;
10920:         } else {
10921:             $uname = &generate_coursenum($udom,$crstype);
10922:         }
10923:     } else {
10924:         $uname = &generate_coursenum($udom,$crstype);
10925:     }
10926:     return $uname if ($uname =~ /^error/);
10927: # -------------------------------------------------- Check supplied server name
10928:     if (!defined($course_server)) {
10929:         if (defined(&domain($udom,'primary'))) {
10930:             $course_server = &domain($udom,'primary');
10931:         } else {
10932:             $course_server = $env{'user.home'}; 
10933:         }
10934:     }
10935:     my %host_servers =
10936:         &Apache::lonnet::get_servers($udom,'library');
10937:     unless ($host_servers{$course_server}) {
10938:         return 'error: invalid home server for course: '.$course_server;
10939:     }
10940: # ------------------------------------------------------------- Make the course
10941:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10942:                       $course_server);
10943:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10944:     my $uhome=&homeserver($uname,$udom,'true');
10945:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10946: 	return 'error: no such course';
10947:     }
10948: # ----------------------------------------------------------------- Course made
10949: # log existence
10950:     my $now = time;
10951:     my $newcourse = {
10952:                     $udom.'_'.$uname => {
10953:                                      description => $description,
10954:                                      inst_code   => $inst_code,
10955:                                      owner       => $course_owner,
10956:                                      type        => $crstype,
10957:                                      creator     => $env{'user.name'}.':'.
10958:                                                     $env{'user.domain'},
10959:                                      created     => $now,
10960:                                      context     => $context,
10961:                                                 },
10962:                     };
10963:     &courseidput($udom,$newcourse,$uhome,'notime');
10964: # set toplevel url
10965:     my $topurl=$url;
10966:     unless ($nonstandard) {
10967: # ------------------------------------------ For standard courses, make top url
10968:         my $mapurl=&clutter($url);
10969:         if ($mapurl eq '/res/') { $mapurl=''; }
10970:         $env{'form.initmap'}=(<<ENDINITMAP);
10971: <map>
10972: <resource id="1" type="start"></resource>
10973: <resource id="2" src="$mapurl"></resource>
10974: <resource id="3" type="finish"></resource>
10975: <link index="1" from="1" to="2"></link>
10976: <link index="2" from="2" to="3"></link>
10977: </map>
10978: ENDINITMAP
10979:         $topurl=&declutter(
10980:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10981:                           );
10982:     }
10983: # ----------------------------------------------------------- Write preferences
10984:     &writecoursepref($udom.'_'.$uname,
10985:                      ('description'              => $description,
10986:                       'url'                      => $topurl,
10987:                       'internal.creator'         => $env{'user.name'}.':'.
10988:                                                     $env{'user.domain'},
10989:                       'internal.created'         => $now,
10990:                       'internal.creationcontext' => $context)
10991:                     );
10992:     return '/'.$udom.'/'.$uname;
10993: }
10994: 
10995: # ------------------------------------------------------------------- Create ID
10996: sub generate_coursenum {
10997:     my ($udom,$crstype) = @_;
10998:     my $domdesc = &domain($udom);
10999:     return 'error: invalid domain' if ($domdesc eq '');
11000:     my $first;
11001:     if ($crstype eq 'Community') {
11002:         $first = '0';
11003:     } else {
11004:         $first = int(1+rand(9)); 
11005:     } 
11006:     my $uname=$first.
11007:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11008:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11009:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11010: # ----------------------------------------------- Make sure that does not exist
11011:     my $uhome=&homeserver($uname,$udom,'true');
11012:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11013:         if ($crstype eq 'Community') {
11014:             $first = '0';
11015:         } else {
11016:             $first = int(1+rand(9));
11017:         }
11018:         $uname=$first.
11019:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11020:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11021:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11022:         $uhome=&homeserver($uname,$udom,'true');
11023:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11024:             return 'error: unable to generate unique course-ID';
11025:         }
11026:     }
11027:     return $uname;
11028: }
11029: 
11030: sub is_course {
11031:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11032:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11033: 
11034:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11035:     my $uhome=&homeserver($cnum,$cdom);
11036:     my $iscourse;
11037:     if (grep { $_ eq $uhome } current_machine_ids()) {
11038:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11039:     } else {
11040:         my $hashid = $cdom.':'.$cnum;
11041:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11042:         unless (defined($cached)) {
11043:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11044:                                         $cnum,undef,undef,'.');
11045:             $iscourse = 0;
11046:             if (exists($courses{$cdom.'_'.$cnum})) {
11047:                 $iscourse = 1;
11048:             }
11049:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11050:         }
11051:     }
11052:     return unless ($iscourse);
11053:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11054: }
11055: 
11056: sub store_userdata {
11057:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11058:     my $result;
11059:     if ($datakey ne '') {
11060:         if (ref($storehash) eq 'HASH') {
11061:             if ($udom eq '' || $uname eq '') {
11062:                 $udom = $env{'user.domain'};
11063:                 $uname = $env{'user.name'};
11064:             }
11065:             my $uhome=&homeserver($uname,$udom);
11066:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11067:                 $result = 'error: no_host';
11068:             } else {
11069:                 $storehash->{'ip'} = &get_requestor_ip();
11070:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11071: 
11072:                 my $namevalue='';
11073:                 foreach my $key (keys(%{$storehash})) {
11074:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11075:                 }
11076:                 $namevalue=~s/\&$//;
11077:                 unless ($namespace eq 'courserequests') {
11078:                     $datakey = &escape($datakey);
11079:                 }
11080:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11081:                                   $namevalue,$uhome);
11082:             }
11083:         } else {
11084:             $result = 'error: data to store was not a hash reference'; 
11085:         }
11086:     } else {
11087:         $result= 'error: invalid requestkey'; 
11088:     }
11089:     return $result;
11090: }
11091: 
11092: # ---------------------------------------------------------- Assign Custom Role
11093: 
11094: sub assigncustomrole {
11095:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11096:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11097:                        $end,$start,$deleteflag,$selfenroll,$context);
11098: }
11099: 
11100: # ----------------------------------------------------------------- Revoke Role
11101: 
11102: sub revokerole {
11103:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11104:     my $now=time;
11105:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11106: }
11107: 
11108: # ---------------------------------------------------------- Revoke Custom Role
11109: 
11110: sub revokecustomrole {
11111:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11112:     my $now=time;
11113:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11114:            $deleteflag,$selfenroll,$context);
11115: }
11116: 
11117: # ------------------------------------------------------------ Disk usage
11118: sub diskusage {
11119:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11120:     $directorypath =~ s/\/$//;
11121:     my $listing=&reply('du2:'.&escape($directorypath).':'
11122:                        .&escape($getpropath).':'.&escape($uname).':'
11123:                        .&escape($udom),homeserver($uname,$udom));
11124:     if ($listing eq 'unknown_cmd') {
11125:         if ($getpropath) {
11126:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11127:         }
11128:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11129:     }
11130:     return $listing;
11131: }
11132: 
11133: sub is_locked {
11134:     my ($file_name, $domain, $user, $which) = @_;
11135:     my @check;
11136:     my $is_locked;
11137:     push (@check,$file_name);
11138:     my %locked = &get('file_permissions',\@check,
11139: 		      $env{'user.domain'},$env{'user.name'});
11140:     my ($tmp)=keys(%locked);
11141:     if ($tmp=~/^error:/) { undef(%locked); }
11142:     
11143:     if (ref($locked{$file_name}) eq 'ARRAY') {
11144:         $is_locked = 'false';
11145:         foreach my $entry (@{$locked{$file_name}}) {
11146:            if (ref($entry) eq 'ARRAY') {
11147:                $is_locked = 'true';
11148:                if (ref($which) eq 'ARRAY') {
11149:                    push(@{$which},$entry);
11150:                } else {
11151:                    last;
11152:                }
11153:            }
11154:        }
11155:     } else {
11156:         $is_locked = 'false';
11157:     }
11158:     return $is_locked;
11159: }
11160: 
11161: sub declutter_portfile {
11162:     my ($file) = @_;
11163:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11164:     return $file;
11165: }
11166: 
11167: # ------------------------------------------------------------- Mark as Read Only
11168: 
11169: sub mark_as_readonly {
11170:     my ($domain,$user,$files,$what) = @_;
11171:     my %current_permissions = &dump('file_permissions',$domain,$user);
11172:     my ($tmp)=keys(%current_permissions);
11173:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11174:     foreach my $file (@{$files}) {
11175: 	$file = &declutter_portfile($file);
11176:         push(@{$current_permissions{$file}},$what);
11177:     }
11178:     &put('file_permissions',\%current_permissions,$domain,$user);
11179:     return;
11180: }
11181: 
11182: # ------------------------------------------------------------Save Selected Files
11183: 
11184: sub save_selected_files {
11185:     my ($user, $path, @files) = @_;
11186:     my $filename = $user."savedfiles";
11187:     my @other_files = &files_not_in_path($user, $path);
11188:     open (OUT,'>',LONCAPA::tempdir().$filename);
11189:     foreach my $file (@files) {
11190:         print (OUT $env{'form.currentpath'}.$file."\n");
11191:     }
11192:     foreach my $file (@other_files) {
11193:         print (OUT $file."\n");
11194:     }
11195:     close (OUT);
11196:     return 'ok';
11197: }
11198: 
11199: sub clear_selected_files {
11200:     my ($user) = @_;
11201:     my $filename = $user."savedfiles";
11202:     open (OUT,'>',LONCAPA::tempdir().$filename);
11203:     print (OUT undef);
11204:     close (OUT);
11205:     return ("ok");    
11206: }
11207: 
11208: sub files_in_path {
11209:     my ($user, $path) = @_;
11210:     my $filename = $user."savedfiles";
11211:     my %return_files;
11212:     open (IN,'<',LONCAPA::tempdir().$filename);
11213:     while (my $line_in = <IN>) {
11214:         chomp ($line_in);
11215:         my @paths_and_file = split (m!/!, $line_in);
11216:         my $file_part = pop (@paths_and_file);
11217:         my $path_part = join ('/', @paths_and_file);
11218:         $path_part.='/';
11219:         my $path_and_file = $path_part.$file_part;
11220:         if ($path_part eq $path) {
11221:             $return_files{$file_part}= 'selected';
11222:         }
11223:     }
11224:     close (IN);
11225:     return (\%return_files);
11226: }
11227: 
11228: # called in portfolio select mode, to show files selected NOT in current directory
11229: sub files_not_in_path {
11230:     my ($user, $path) = @_;
11231:     my $filename = $user."savedfiles";
11232:     my @return_files;
11233:     my $path_part;
11234:     open(IN, '<',LONCAPA::tempdir().$filename);
11235:     while (my $line = <IN>) {
11236:         #ok, I know it's clunky, but I want it to work
11237:         my @paths_and_file = split(m|/|, $line);
11238:         my $file_part = pop(@paths_and_file);
11239:         chomp($file_part);
11240:         my $path_part = join('/', @paths_and_file);
11241:         $path_part .= '/';
11242:         my $path_and_file = $path_part.$file_part;
11243:         if ($path_part ne $path) {
11244:             push(@return_files, ($path_and_file));
11245:         }
11246:     }
11247:     close(OUT);
11248:     return (@return_files);
11249: }
11250: 
11251: #------------------------------Submitted/Handedback Portfolio Files Versioning
11252:  
11253: sub portfiles_versioning {
11254:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11255:     my $portfolio_root = '/userfiles/portfolio';
11256:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11257:     foreach my $file (@{$portfiles}) {
11258:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11259:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11260:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11261:         my $getpropath = 1;
11262:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11263:                                              $stu_name,$getpropath);
11264:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11265:         my $new_answer = 
11266:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11267:         if ($new_answer ne 'problem getting file') {
11268:             push(@{$versioned_portfiles}, $directory.$new_answer);
11269:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11270:                               [$symb,$env{'request.course.id'},'graded']);
11271:         }
11272:     }
11273: }
11274: 
11275: sub get_next_version {
11276:     my ($answer_name, $answer_ext, $dir_list) = @_;
11277:     my $version;
11278:     if (ref($dir_list) eq 'ARRAY') {
11279:         foreach my $row (@{$dir_list}) {
11280:             my ($file) = split(/\&/,$row,2);
11281:             my ($file_name,$file_version,$file_ext) =
11282:                 &file_name_version_ext($file);
11283:             if (($file_name eq $answer_name) &&
11284:                 ($file_ext eq $answer_ext)) {
11285:                      # gets here if filename and extension match,
11286:                      # regardless of version
11287:                 if ($file_version ne '') {
11288:                     # a versioned file is found  so save it for later
11289:                     if ($file_version > $version) {
11290:                         $version = $file_version;
11291:                     }
11292:                 }
11293:             }
11294:         }
11295:     }
11296:     $version ++;
11297:     return($version);
11298: }
11299: 
11300: sub version_selected_portfile {
11301:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11302:     my ($answer_name,$answer_ver,$answer_ext) =
11303:         &file_name_version_ext($file_name);
11304:     my $new_answer;
11305:     $env{'form.copy'} =
11306:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11307:     if($env{'form.copy'} eq '-1') {
11308:         $new_answer = 'problem getting file';
11309:     } else {
11310:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11311:         my $copy_result = 
11312:             &finishuserfileupload($stu_name,$domain,'copy',
11313:                                   '/portfolio'.$directory.$new_answer);
11314:     }
11315:     undef($env{'form.copy'});
11316:     return ($new_answer);
11317: }
11318: 
11319: sub file_name_version_ext {
11320:     my ($file)=@_;
11321:     my @file_parts = split(/\./, $file);
11322:     my ($name,$version,$ext);
11323:     if (@file_parts > 1) {
11324:         $ext=pop(@file_parts);
11325:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11326:             $version=pop(@file_parts);
11327:         }
11328:         $name=join('.',@file_parts);
11329:     } else {
11330:         $name=join('.',@file_parts);
11331:     }
11332:     return($name,$version,$ext);
11333: }
11334: 
11335: #----------------------------------------------Get portfolio file permissions
11336: 
11337: sub get_portfile_permissions {
11338:     my ($domain,$user) = @_;
11339:     my %current_permissions = &dump('file_permissions',$domain,$user);
11340:     my ($tmp)=keys(%current_permissions);
11341:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11342:     return \%current_permissions;
11343: }
11344: 
11345: #---------------------------------------------Get portfolio file access controls
11346: 
11347: sub get_access_controls {
11348:     my ($current_permissions,$group,$file) = @_;
11349:     my %access;
11350:     my $real_file = $file;
11351:     $file =~ s/\.meta$//;
11352:     if (defined($file)) {
11353:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11354:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11355:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11356:             }
11357:         }
11358:     } else {
11359:         foreach my $key (keys(%{$current_permissions})) {
11360:             if ($key =~ /\0accesscontrol$/) {
11361:                 if (defined($group)) {
11362:                     if ($key !~ m-^\Q$group\E/-) {
11363:                         next;
11364:                     }
11365:                 }
11366:                 my ($fullpath) = split(/\0/,$key);
11367:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11368:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11369:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11370:                     }
11371:                 }
11372:             }
11373:         }
11374:     }
11375:     return %access;
11376: }
11377: 
11378: sub modify_access_controls {
11379:     my ($file_name,$changes,$domain,$user)=@_;
11380:     my ($outcome,$deloutcome);
11381:     my %store_permissions;
11382:     my %new_values;
11383:     my %new_control;
11384:     my %translation;
11385:     my @deletions = ();
11386:     my $now = time;
11387:     if (exists($$changes{'activate'})) {
11388:         if (ref($$changes{'activate'}) eq 'HASH') {
11389:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11390:             my $numnew = scalar(@newitems);
11391:             for (my $i=0; $i<$numnew; $i++) {
11392:                 my $newkey = $newitems[$i];
11393:                 my $newid = &Apache::loncommon::get_cgi_id();
11394:                 if ($newkey =~ /^\d+:/) { 
11395:                     $newkey =~ s/^(\d+)/$newid/;
11396:                     $translation{$1} = $newid;
11397:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11398:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11399:                     $translation{$1} = $newid;
11400:                 }
11401:                 $new_values{$file_name."\0".$newkey} = 
11402:                                           $$changes{'activate'}{$newitems[$i]};
11403:                 $new_control{$newkey} = $now;
11404:             }
11405:         }
11406:     }
11407:     my %todelete;
11408:     my %changed_items;
11409:     foreach my $action ('delete','update') {
11410:         if (exists($$changes{$action})) {
11411:             if (ref($$changes{$action}) eq 'HASH') {
11412:                 foreach my $key (keys(%{$$changes{$action}})) {
11413:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11414:                     if ($action eq 'delete') { 
11415:                         $todelete{$itemnum} = 1;
11416:                     } else {
11417:                         $changed_items{$itemnum} = $key;
11418:                     }
11419:                 }
11420:             }
11421:         }
11422:     }
11423:     # get lock on access controls for file.
11424:     my $lockhash = {
11425:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11426:                                                        ':'.$env{'user.domain'},
11427:                    }; 
11428:     my $tries = 0;
11429:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11430:    
11431:     while (($gotlock ne 'ok') && $tries < 10) {
11432:         $tries ++;
11433:         sleep(0.1);
11434:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11435:     }
11436:     if ($gotlock eq 'ok') {
11437:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11438:         my ($tmp)=keys(%curr_permissions);
11439:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11440:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11441:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11442:             if (ref($curr_controls) eq 'HASH') {
11443:                 foreach my $control_item (keys(%{$curr_controls})) {
11444:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11445:                     if (defined($todelete{$itemnum})) {
11446:                         push(@deletions,$file_name."\0".$control_item);
11447:                     } else {
11448:                         if (defined($changed_items{$itemnum})) {
11449:                             $new_control{$changed_items{$itemnum}} = $now;
11450:                             push(@deletions,$file_name."\0".$control_item);
11451:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11452:                         } else {
11453:                             $new_control{$control_item} = $$curr_controls{$control_item};
11454:                         }
11455:                     }
11456:                 }
11457:             }
11458:         }
11459:         my ($group);
11460:         if (&is_course($domain,$user)) {
11461:             ($group,my $file) = split(/\//,$file_name,2);
11462:         }
11463:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11464:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11465:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11466:         #  remove lock
11467:         my @del_lock = ($file_name."\0".'locked_access_records');
11468:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11469:         my $sqlresult =
11470:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11471:                                     $group);
11472:     } else {
11473:         $outcome = "error: could not obtain lockfile\n";  
11474:     }
11475:     return ($outcome,$deloutcome,\%new_values,\%translation);
11476: }
11477: 
11478: sub make_public_indefinitely {
11479:     my (@requrl) = @_;
11480:     return &automated_portfile_access('public',\@requrl);
11481: }
11482: 
11483: sub automated_portfile_access {
11484:     my ($accesstype,$addsref,$delsref,$info) = @_;
11485:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11486:         return 'invalid';
11487:     }
11488:     my %urls;
11489:     if (ref($addsref) eq 'ARRAY') {
11490:         foreach my $requrl (@{$addsref}) {
11491:             if (&is_portfolio_url($requrl)) {
11492:                 unless (exists($urls{$requrl})) {
11493:                     $urls{$requrl} = 'add';
11494:                 }
11495:             }
11496:         }
11497:     }
11498:     if (ref($delsref) eq 'ARRAY') {
11499:         foreach my $requrl (@{$delsref}) { 
11500:             if (&is_portfolio_url($requrl)) {
11501:                 unless (exists($urls{$requrl})) {
11502:                     $urls{$requrl} = 'delete'; 
11503:                 }
11504:             }
11505:         }
11506:     }
11507:     unless (keys(%urls)) {
11508:         return 'invalid';
11509:     }
11510:     my $ip;
11511:     if ($accesstype eq 'ip') {
11512:         if (ref($info) eq 'HASH') {
11513:             if ($info->{'ip'} ne '') {
11514:                 $ip = $info->{'ip'};
11515:             }
11516:         }
11517:         if ($ip eq '') {
11518:             return 'invalid';
11519:         }
11520:     }
11521:     my $errors;
11522:     my $now = time;
11523:     my %current_perms;
11524:     foreach my $requrl (sort(keys(%urls))) {
11525:         my $action;
11526:         if ($urls{$requrl} eq 'add') {
11527:             $action = 'activate';
11528:         } else {
11529:             $action = 'none';
11530:         }
11531:         my $aclnum = 0;
11532:         my (undef,$udom,$unum,$file_name,$group) =
11533:             &parse_portfolio_url($requrl);
11534:         unless (exists($current_perms{$unum.':'.$udom})) {
11535:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11536:         }
11537:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11538:                                                    $group,$file_name);
11539:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11540:             my ($num,$scope,$end,$start) = 
11541:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11542:             if ($scope eq $accesstype) {
11543:                 if (($start <= $now) && ($end == 0)) {
11544:                     if ($accesstype eq 'ip') {
11545:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11546:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11547:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11548:                                     if ($urls{$requrl} eq 'add') {
11549:                                         $action = 'none';
11550:                                         last;
11551:                                     } else {
11552:                                         $action = 'delete';
11553:                                         $aclnum = $num;
11554:                                         last;
11555:                                     }
11556:                                 }
11557:                             }
11558:                         }
11559:                     } elsif ($accesstype eq 'public') {
11560:                         if ($urls{$requrl} eq 'add') {
11561:                             $action = 'none';
11562:                             last;
11563:                         } else {
11564:                             $action = 'delete';
11565:                             $aclnum = $num;
11566:                             last;
11567:                         }
11568:                     }
11569:                 } elsif ($accesstype eq 'public') {
11570:                     $action = 'update';
11571:                     $aclnum = $num;
11572:                     last;
11573:                 }
11574:             }
11575:         }
11576:         if ($action eq 'none') {
11577:             next;
11578:         } else {
11579:             my %changes;
11580:             my $newend = 0;
11581:             my $newstart = $now;
11582:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11583:             $changes{$action}{$newkey} = {
11584:                 type => $accesstype,
11585:                 time => {
11586:                     start => $newstart,
11587:                     end   => $newend,
11588:                 },
11589:             };
11590:             if ($accesstype eq 'ip') {
11591:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11592:             }
11593:             my ($outcome,$deloutcome,$new_values,$translation) =
11594:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11595:             unless ($outcome eq 'ok') {
11596:                 $errors .= $outcome.' ';
11597:             }
11598:         }
11599:     }
11600:     if ($errors) {
11601:         $errors =~ s/\s$//;
11602:         return $errors;
11603:     } else {
11604:         return 'ok';
11605:     }
11606: }
11607: 
11608: #------------------------------------------------------Get Marked as Read Only
11609: 
11610: sub get_marked_as_readonly {
11611:     my ($domain,$user,$what,$group) = @_;
11612:     my $current_permissions = &get_portfile_permissions($domain,$user);
11613:     my @readonly_files;
11614:     my $cmp1=$what;
11615:     if (ref($what)) { $cmp1=join('',@{$what}) };
11616:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11617:         if (defined($group)) {
11618:             if ($file_name !~ m-^\Q$group\E/-) {
11619:                 next;
11620:             }
11621:         }
11622:         if (ref($value) eq "ARRAY"){
11623:             foreach my $stored_what (@{$value}) {
11624:                 my $cmp2=$stored_what;
11625:                 if (ref($stored_what) eq 'ARRAY') {
11626:                     $cmp2=join('',@{$stored_what});
11627:                 }
11628:                 if ($cmp1 eq $cmp2) {
11629:                     push(@readonly_files, $file_name);
11630:                     last;
11631:                 } elsif (!defined($what)) {
11632:                     push(@readonly_files, $file_name);
11633:                     last;
11634:                 }
11635:             }
11636:         }
11637:     }
11638:     return @readonly_files;
11639: }
11640: #-----------------------------------------------------------Get Marked as Read Only Hash
11641: 
11642: sub get_marked_as_readonly_hash {
11643:     my ($current_permissions,$group,$what) = @_;
11644:     my %readonly_files;
11645:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11646:         if (defined($group)) {
11647:             if ($file_name !~ m-^\Q$group\E/-) {
11648:                 next;
11649:             }
11650:         }
11651:         if (ref($value) eq "ARRAY"){
11652:             foreach my $stored_what (@{$value}) {
11653:                 if (ref($stored_what) eq 'ARRAY') {
11654:                     foreach my $lock_descriptor(@{$stored_what}) {
11655:                         if ($lock_descriptor eq 'graded') {
11656:                             $readonly_files{$file_name} = 'graded';
11657:                         } elsif ($lock_descriptor eq 'handback') {
11658:                             $readonly_files{$file_name} = 'handback';
11659:                         } else {
11660:                             if (!exists($readonly_files{$file_name})) {
11661:                                 $readonly_files{$file_name} = 'locked';
11662:                             }
11663:                         }
11664:                     }
11665:                 } 
11666:             }
11667:         } 
11668:     }
11669:     return %readonly_files;
11670: }
11671: # ------------------------------------------------------------ Unmark as Read Only
11672: 
11673: sub unmark_as_readonly {
11674:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11675:     # for portfolio submissions, $what contains [$symb,$crsid] 
11676:     my ($domain,$user,$what,$file_name,$group) = @_;
11677:     $file_name = &declutter_portfile($file_name);
11678:     my $symb_crs = $what;
11679:     if (ref($what)) { $symb_crs=join('',@$what); }
11680:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11681:     my ($tmp)=keys(%current_permissions);
11682:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11683:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11684:     foreach my $file (@readonly_files) {
11685: 	my $clean_file = &declutter_portfile($file);
11686: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11687: 	my $current_locks = $current_permissions{$file};
11688:         my @new_locks;
11689:         my @del_keys;
11690:         if (ref($current_locks) eq "ARRAY"){
11691:             foreach my $locker (@{$current_locks}) {
11692:                 my $compare=$locker;
11693:                 if (ref($locker) eq 'ARRAY') {
11694:                     $compare=join('',@{$locker});
11695:                     if ($compare ne $symb_crs) {
11696:                         push(@new_locks, $locker);
11697:                     }
11698:                 }
11699:             }
11700:             if (scalar(@new_locks) > 0) {
11701:                 $current_permissions{$file} = \@new_locks;
11702:             } else {
11703:                 push(@del_keys, $file);
11704:                 &del('file_permissions',\@del_keys, $domain, $user);
11705:                 delete($current_permissions{$file});
11706:             }
11707:         }
11708:     }
11709:     &put('file_permissions',\%current_permissions,$domain,$user);
11710:     return;
11711: }
11712: 
11713: # ------------------------------------------------------------ Directory lister
11714: 
11715: sub dirlist {
11716:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11717:     $uri=~s/^\///;
11718:     $uri=~s/\/$//;
11719:     my ($udom, $uname);
11720:     if ($getuserdir) {
11721:         $udom = $userdomain;
11722:         $uname = $username;
11723:     } else {
11724:         (undef,$udom,$uname)=split(/\//,$uri);
11725:         if(defined($userdomain)) {
11726:             $udom = $userdomain;
11727:         }
11728:         if(defined($username)) {
11729:             $uname = $username;
11730:         }
11731:     }
11732:     my ($dirRoot,$listing,@listing_results);
11733: 
11734:     $dirRoot = $perlvar{'lonDocRoot'};
11735:     if (defined($getpropath)) {
11736:         $dirRoot = &propath($udom,$uname);
11737:         $dirRoot =~ s/\/$//;
11738:     } elsif (defined($getuserdir)) {
11739:         my $subdir=$uname.'__';
11740:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11741:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11742:                    ."/$udom/$subdir/$uname";
11743:     } elsif (defined($alternateRoot)) {
11744:         $dirRoot = $alternateRoot;
11745:     }
11746: 
11747:     if($udom) {
11748:         if($uname) {
11749:             my $uhome = &homeserver($uname,$udom);
11750:             if ($uhome eq 'no_host') {
11751:                 return ([],'no_host');
11752:             }
11753:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11754:                               .$getuserdir.':'.&escape($dirRoot)
11755:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11756:             if ($listing eq 'unknown_cmd') {
11757:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11758:             } else {
11759:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11760:             }
11761:             if ($listing eq 'unknown_cmd') {
11762:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11763:                 @listing_results = split(/:/,$listing);
11764:             } else {
11765:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11766:             }
11767:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11768:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11769:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11770:                 return ([],$listing);
11771:             } else {
11772:                 return (\@listing_results);
11773:             }
11774:         } elsif(!$alternateRoot) {
11775:             my (%allusers,%listerror);
11776: 	    my %servers = &get_servers($udom,'library');
11777:  	    foreach my $tryserver (keys(%servers)) {
11778:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11779:                                   &escape($udom),$tryserver);
11780:                 if ($listing eq 'unknown_cmd') {
11781: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11782: 				      $udom, $tryserver);
11783:                 } else {
11784:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11785:                 }
11786: 		if ($listing eq 'unknown_cmd') {
11787: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11788: 				      $udom, $tryserver);
11789: 		    @listing_results = split(/:/,$listing);
11790: 		} else {
11791: 		    @listing_results =
11792: 			map { &unescape($_); } split(/:/,$listing);
11793: 		}
11794:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11795:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11796:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11797:                     $listerror{$tryserver} = $listing;
11798:                 } else {
11799: 		    foreach my $line (@listing_results) {
11800: 			my ($entry) = split(/&/,$line,2);
11801: 			$allusers{$entry} = 1;
11802: 		    }
11803: 		}
11804:             }
11805:             my @alluserslist=();
11806:             foreach my $user (sort(keys(%allusers))) {
11807:                 push(@alluserslist,$user.'&user');
11808:             }
11809: 
11810:             if (!%listerror) {
11811:                 # no errors
11812:                 return (\@alluserslist);
11813:             } elsif (scalar(keys(%servers)) == 1) {
11814:                 # one library server, one error 
11815:                 my ($key) = keys(%listerror);
11816:                 return (\@alluserslist, $listerror{$key});
11817:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11818:                 # con_lost indicates that we might miss data from at least one
11819:                 # library server
11820:                 return (\@alluserslist, 'con_lost');
11821:             } else {
11822:                 # multiple library servers and no con_lost -> data should be
11823:                 # complete. 
11824:                 return (\@alluserslist);
11825:             }
11826: 
11827:         } else {
11828:             return ([],'missing username');
11829:         }
11830:     } elsif(!defined($getpropath)) {
11831:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11832:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11833:         return (\@all_domains);
11834:     } else {
11835:         return ([],'missing domain');
11836:     }
11837: }
11838: 
11839: # --------------------------------------------- GetFileTimestamp
11840: # This function utilizes dirlist and returns the date stamp for
11841: # when it was last modified.  It will also return an error of -1
11842: # if an error occurs
11843: 
11844: sub GetFileTimestamp {
11845:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11846:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11847:     $studentName   = &LONCAPA::clean_username($studentName);
11848:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11849:                                     undef,$getuserdir);
11850:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11851:         return -1;
11852:     }
11853:     if (ref($fileref) eq 'ARRAY') {
11854:         my @stats = split('&',$fileref->[0]);
11855:         # @stats contains first the filename, then the stat output
11856:         return $stats[10]; # so this is 10 instead of 9.
11857:     } else {
11858:         return -1;
11859:     }
11860: }
11861: 
11862: sub stat_file {
11863:     my ($uri) = @_;
11864:     $uri = &clutter_with_no_wrapper($uri);
11865: 
11866:     my ($udom,$uname,$file);
11867:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11868: 	($udom,$uname,$file) =
11869: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11870: 	$file = 'userfiles/'.$file;
11871:     }
11872:     if ($uri =~ m-^/res/-) {
11873: 	($udom,$uname) = 
11874: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11875: 	$file = $uri;
11876:     }
11877: 
11878:     if (!$udom || !$uname || !$file) {
11879: 	# unable to handle the uri
11880: 	return ();
11881:     }
11882:     my $getpropath;
11883:     if ($file =~ /^userfiles\//) {
11884:         $getpropath = 1;
11885:     }
11886:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11887:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11888:         return ();
11889:     } else {
11890:         if (ref($listref) eq 'ARRAY') {
11891:             my @stats = split('&',$listref->[0]);
11892: 	    shift(@stats); #filename is first
11893: 	    return @stats;
11894:         }
11895:     }
11896:     return ();
11897: }
11898: 
11899: # --------------------------------------------------------- recursedirs
11900: # Recursive function to traverse either a specific user's Authoring Space
11901: # or corresponding Published Resource Space, and populate the hash ref:
11902: # $dirhashref with URLs of all directories, and if $filehashref hash
11903: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11904: # or .rights files in resource space, and .meta, .save, .log, and .bak
11905: # files in Authoring Space.
11906: #
11907: # Inputs:
11908: #
11909: # $is_home - true if current server is home server for user's space
11910: # $context - either: priv, or res respectively for Authoring or Resource Space.
11911: # $docroot - Document root (i.e., /home/httpd/html
11912: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11913: # $relpath - Current path (relative to top level).
11914: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11915: # $filehashref - reference to hash to populate with URLs of files (Optional)
11916: #
11917: # Returns: nothing
11918: #
11919: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11920: #
11921: # Currently used by interface/londocs.pm to create linked select boxes for
11922: # directory and filename to import a Course "Author" resource into a course, and
11923: # also to create linked select boxes for Authoring Space and Directory to choose
11924: # save location for creation of a new "standard" problem from the Course Editor.
11925: #
11926: 
11927: sub recursedirs {
11928:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11929:     return unless (ref($dirhashref) eq 'HASH');
11930:     my $currpath = $docroot.$toppath;
11931:     if ($relpath) {
11932:         $currpath .= "/$relpath";
11933:     }
11934:     my $savefile;
11935:     if (ref($filehashref)) {
11936:         $savefile = 1;
11937:     }
11938:     if ($is_home) {
11939:         if (opendir(my $dirh,$currpath)) {
11940:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11941:                 next if ($item eq '');
11942:                 if (-d "$currpath/$item") {
11943:                     my $newpath;
11944:                     if ($relpath) {
11945:                         $newpath = "$relpath/$item";
11946:                     } else {
11947:                         $newpath = $item;
11948:                     }
11949:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11950:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11951:                 } elsif ($savefile) {
11952:                     if ($context eq 'priv') {
11953:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11954:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11955:                         }
11956:                     } else {
11957:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11958:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11959:                         }
11960:                     }
11961:                 }
11962:             }
11963:             closedir($dirh);
11964:         }
11965:     } else {
11966:         my ($dirlistref,$listerror) =
11967:             &dirlist($toppath.$relpath);
11968:         my @dir_lines;
11969:         my $dirptr=16384;
11970:         if (ref($dirlistref) eq 'ARRAY') {
11971:             foreach my $dir_line (sort
11972:                               {
11973:                                   my ($afile)=split('&',$a,2);
11974:                                   my ($bfile)=split('&',$b,2);
11975:                                   return (lc($afile) cmp lc($bfile));
11976:                               } (@{$dirlistref})) {
11977:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11978:                     split(/\&/,$dir_line,16);
11979:                 $item =~ s/\s+$//;
11980:                 next if (($item =~ /^\.\.?$/) || ($obs));
11981:                 if ($dirptr&$testdir) {
11982:                     my $newpath;
11983:                     if ($relpath) {
11984:                         $newpath = "$relpath/$item";
11985:                     } else {
11986:                         $relpath = '/';
11987:                         $newpath = $item;
11988:                     }
11989:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11990:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11991:                 } elsif ($savefile) {
11992:                     if ($context eq 'priv') {
11993:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11994:                             $filehashref->{$relpath}{$item} = 1;
11995:                         }
11996:                     } else {
11997:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11998:                             $filehashref->{$relpath}{$item} = 1;
11999:                         }
12000:                     }
12001:                 }
12002:             }
12003:         }
12004:     }
12005:     return;
12006: }
12007: 
12008: # -------------------------------------------------------- Value of a Condition
12009: 
12010: # gets the value of a specific preevaluated condition
12011: #    stored in the string  $env{user.state.<cid>}
12012: # or looks up a condition reference in the bighash and if if hasn't
12013: # already been evaluated recurses into docondval to get the value of
12014: # the condition, then memoizing it to 
12015: #   $env{user.state.<cid>.<condition>}
12016: sub directcondval {
12017:     my $number=shift;
12018:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12019: 	&Apache::lonuserstate::evalstate();
12020:     }
12021:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12022: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12023:     } elsif ($number =~ /^_/) {
12024: 	my $sub_condition;
12025: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12026: 		&GDBM_READER(),0640)) {
12027: 	    $sub_condition=$bighash{'conditions'.$number};
12028: 	    untie(%bighash);
12029: 	}
12030: 	my $value = &docondval($sub_condition);
12031: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12032: 	return $value;
12033:     }
12034:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12035:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12036:     } else {
12037:        return 2;
12038:     }
12039: }
12040: 
12041: # get the collection of conditions for this resource
12042: sub condval {
12043:     my $condidx=shift;
12044:     my $allpathcond='';
12045:     foreach my $cond (split(/\|/,$condidx)) {
12046: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12047: 	    $allpathcond.=
12048: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12049: 	}
12050:     }
12051:     $allpathcond=~s/\|$//;
12052:     return &docondval($allpathcond);
12053: }
12054: 
12055: #evaluates an expression of conditions
12056: sub docondval {
12057:     my ($allpathcond) = @_;
12058:     my $result=0;
12059:     if ($env{'request.course.id'}
12060: 	&& defined($allpathcond)) {
12061: 	my $operand='|';
12062: 	my @stack;
12063: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12064: 	    if ($chunk eq '(') {
12065: 		push @stack,($operand,$result);
12066: 	    } elsif ($chunk eq ')') {
12067: 		my $before=pop @stack;
12068: 		if (pop @stack eq '&') {
12069: 		    $result=$result>$before?$before:$result;
12070: 		} else {
12071: 		    $result=$result>$before?$result:$before;
12072: 		}
12073: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12074: 		$operand=$chunk;
12075: 	    } else {
12076: 		my $new=directcondval($chunk);
12077: 		if ($operand eq '&') {
12078: 		    $result=$result>$new?$new:$result;
12079: 		} else {
12080: 		    $result=$result>$new?$result:$new;
12081: 		}
12082: 	    }
12083: 	}
12084:     }
12085:     return $result;
12086: }
12087: 
12088: # ---------------------------------------------------- Devalidate courseresdata
12089: 
12090: sub devalidatecourseresdata {
12091:     my ($coursenum,$coursedomain)=@_;
12092:     my $hashid=$coursenum.':'.$coursedomain;
12093:     &devalidate_cache_new('courseres',$hashid);
12094: }
12095: 
12096: 
12097: # --------------------------------------------------- Course Resourcedata Query
12098: #
12099: #  Parameters:
12100: #      $coursenum    - Number of the course.
12101: #      $coursedomain - Domain at which the course was created.
12102: #  Returns:
12103: #     A hash of the course parameters along (I think) with timestamps
12104: #     and version info.
12105: 
12106: sub get_courseresdata {
12107:     my ($coursenum,$coursedomain)=@_;
12108:     my $coursehom=&homeserver($coursenum,$coursedomain);
12109:     my $hashid=$coursenum.':'.$coursedomain;
12110:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12111:     my %dumpreply;
12112:     unless (defined($cached)) {
12113: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12114: 	$result=\%dumpreply;
12115: 	my ($tmp) = keys(%dumpreply);
12116: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12117: 	    &do_cache_new('courseres',$hashid,$result,600);
12118: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12119: 	    return $tmp;
12120: 	} elsif ($tmp =~ /^(error)/) {
12121: 	    $result=undef;
12122: 	    &do_cache_new('courseres',$hashid,$result,600);
12123: 	}
12124:     }
12125:     return $result;
12126: }
12127: 
12128: sub devalidateuserresdata {
12129:     my ($uname,$udom)=@_;
12130:     my $hashid="$udom:$uname";
12131:     &devalidate_cache_new('userres',$hashid);
12132: }
12133: 
12134: sub get_userresdata {
12135:     my ($uname,$udom)=@_;
12136:     #most student don\'t have any data set, check if there is some data
12137:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12138: 
12139:     my $hashid="$udom:$uname";
12140:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12141:     if (!defined($cached)) {
12142: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12143: 	$result=\%resourcedata;
12144: 	&do_cache_new('userres',$hashid,$result,600);
12145:     }
12146:     my ($tmp)=keys(%$result);
12147:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12148: 	return $result;
12149:     }
12150:     #error 2 occurs when the .db doesn't exist
12151:     if ($tmp!~/error: 2 /) {
12152:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12153: 	    &logthis("<font color=\"blue\">WARNING:".
12154: 		     " Trying to get resource data for ".
12155: 		     $uname." at ".$udom.": ".
12156: 		     $tmp."</font>");
12157:         }
12158:     } elsif ($tmp=~/error: 2 /) {
12159: 	#&EXT_cache_set($udom,$uname);
12160: 	&do_cache_new('userres',$hashid,undef,600);
12161: 	undef($tmp); # not really an error so don't send it back
12162:     }
12163:     return $tmp;
12164: }
12165: #----------------------------------------------- resdata - return resource data
12166: #  Purpose:
12167: #    Return resource data for either users or for a course.
12168: #  Parameters:
12169: #     $name      - Course/user name.
12170: #     $domain    - Name of the domain the user/course is registered on.
12171: #     $type      - Type of thing $name is (must be 'course' or 'user')
12172: #     $mapp      - decluttered URL of enclosing map  
12173: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12174: #     $recurseup - Ref to array of map URLs, starting with map containing
12175: #                  $mapp up through hierarchy of nested maps to top level map.  
12176: #     $courseid  - CourseID (first part of param identifier).
12177: #     $modifier  - Middle part of param identifier.
12178: #     $what      - Last part of param identifier.
12179: #     @which     - Array of names of resources desired.
12180: #  Returns:
12181: #     The value of the first reasource in @which that is found in the
12182: #     resource hash.
12183: #  Exceptional Conditions:
12184: #     If the $type passed in is not valid (not the string 'course' or 
12185: #     'user', an undefined  reference is returned.
12186: #     If none of the resources are found, an undef is returned
12187: sub resdata {
12188:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12189:         $modifier,$what,@which)=@_;
12190:     my $result;
12191:     if ($type eq 'course') {
12192: 	$result=&get_courseresdata($name,$domain);
12193:     } elsif ($type eq 'user') {
12194: 	$result=&get_userresdata($name,$domain);
12195:     }
12196:     if (!ref($result)) { return $result; }    
12197:     foreach my $item (@which) {
12198:         if ($item->[1] eq 'course') {
12199:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12200:                 unless ($$recursed) {
12201:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12202:                     $$recursed = 1;
12203:                 }
12204:                 foreach my $item (@${recurseup}) {
12205:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12206:                     last if (defined($result->{$norecursechk}));
12207:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12208:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12209:                 }
12210:             }
12211:         }
12212:         if (defined($result->{$item->[0]})) {
12213: 	    return [$result->{$item->[0]},$item->[1]];
12214: 	}
12215:     }
12216:     return undef;
12217: }
12218: 
12219: sub get_domain_lti {
12220:     my ($cdom,$context) = @_;
12221:     my ($name,%lti);
12222:     if ($context eq 'consumer') {
12223:         $name = 'ltitools';
12224:     } elsif ($context eq 'provider') {
12225:         $name = 'lti';
12226:     } else {
12227:         return %lti;
12228:     }
12229:     my ($result,$cached)=&is_cached_new($name,$cdom);
12230:     if (defined($cached)) {
12231:         if (ref($result) eq 'HASH') {
12232:             %lti = %{$result};
12233:         }
12234:     } else {
12235:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12236:         if (ref($domconfig{$name}) eq 'HASH') {
12237:             %lti = %{$domconfig{$name}};
12238:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12239:             if (ref($encdomconfig{$name}) eq 'HASH') {
12240:                 foreach my $id (keys(%lti)) {
12241:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12242:                         foreach my $item ('key','secret') {
12243:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12244:                         }
12245:                     }
12246:                 }
12247:             }
12248:         }
12249:         my $cachetime = 24*60*60;
12250:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12251:     }
12252:     return %lti;
12253: }
12254: 
12255: sub get_course_lti {
12256:     my ($cnum,$cdom) = @_;
12257:     my $hashid=$cdom.'_'.$cnum;
12258:     my %courselti;
12259:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12260:     if (defined($cached)) {
12261:         if (ref($result) eq 'HASH') {
12262:             %courselti = %{$result};
12263:         }
12264:     } else {
12265:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12266:         my $cachetime = 24*60*60;
12267:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12268:     }
12269:     return %courselti;
12270: }
12271: 
12272: sub courselti_itemid {
12273:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12274:     my ($chome,$itemid);
12275:     $chome = &homeserver($cnum,$cdom);
12276:     return if ($chome eq 'no_host');
12277:     if (ref($params) eq 'HASH') {
12278:         my $items = &freeze_escape($params);
12279:         my $rep;
12280:         if (grep { $_ eq $chome } current_machine_ids()) {
12281:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12282:         } else {
12283:             my $escurl = &escape($url);
12284:             my $escmethod = &escape($method);
12285:             my $items = &freeze_escape($params);
12286:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12287:         }
12288:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12289:                 ($rep eq 'unknown_cmd')) {
12290:             $itemid = $rep;
12291:         }
12292:     }
12293:     return $itemid;
12294: }
12295: 
12296: sub domainlti_itemid {
12297:     my ($cdom,$url,$method,$params,$context) = @_;
12298:     my ($primary_id,$itemid);
12299:     $primary_id = &domain($cdom,'primary');
12300:     return if ($primary_id eq '');
12301:     if (ref($params) eq 'HASH') {
12302:         my $items = &freeze_escape($params);
12303:         my $rep;
12304:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12305:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12306:         } else {
12307:             my $cnum = '';
12308:             my $escurl = &escape($url);
12309:             my $escmethod = &escape($method);
12310:             my $items = &freeze_escape($params);
12311:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12312:         }
12313:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12314:                 ($rep eq 'unknown_cmd')) {
12315:             $itemid = $rep;
12316:         }
12317:     }
12318:     return $itemid;
12319: }
12320: 
12321: sub get_numsuppfiles {
12322:     my ($cnum,$cdom,$ignorecache)=@_;
12323:     my $hashid=$cnum.':'.$cdom;
12324:     my ($suppcount,$cached);
12325:     unless ($ignorecache) {
12326:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12327:     }
12328:     unless (defined($cached)) {
12329:         my $chome=&homeserver($cnum,$cdom);
12330:         unless ($chome eq 'no_host') {
12331:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12332:             my $suppmap = 'supplemental.sequence';
12333:             ($suppcount,$supptools,$errors) =
12334:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12335:                                                          $supptools,$errors);
12336:         }
12337:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12338:     }
12339:     return $suppcount;
12340: }
12341: 
12342: #
12343: # EXT resource caching routines
12344: #
12345: 
12346: {
12347: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12348: #
12349: # The course for which we cache
12350: my $cachedmapkey='';
12351: # The cached recursive maps for this course
12352: my %cachedmaps=();
12353: # When this was last done
12354: my $cachedmaptime='';
12355: 
12356: sub clear_EXT_cache_status {
12357:     &delenv('cache.EXT.');
12358: }
12359: 
12360: sub EXT_cache_status {
12361:     my ($target_domain,$target_user) = @_;
12362:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12363:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12364:         # We know already the user has no data
12365:         return 1;
12366:     } else {
12367:         return 0;
12368:     }
12369: }
12370: 
12371: sub EXT_cache_set {
12372:     my ($target_domain,$target_user) = @_;
12373:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12374:     #&appenv({$cachename => time});
12375: }
12376: 
12377: # --------------------------------------------------------- Value of a Variable
12378: sub EXT {
12379: 
12380:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12381:     unless ($varname) { return ''; }
12382:     #get real user name/domain, courseid and symb
12383:     my $courseid;
12384:     my $publicuser;
12385:     if ($symbparm) {
12386: 	$symbparm=&get_symb_from_alias($symbparm);
12387:     }
12388:     if (!($uname && $udom)) {
12389:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12390:       if (!$symbparm) {	$symbparm=$cursymb; }
12391:     } else {
12392: 	$courseid=$env{'request.course.id'};
12393:     }
12394:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12395:     my $rest;
12396:     if (defined($therest[0])) {
12397:        $rest=join('.',@therest);
12398:     } else {
12399:        $rest='';
12400:     }
12401: 
12402:     my $qualifierrest=$qualifier;
12403:     if ($rest) { $qualifierrest.='.'.$rest; }
12404:     my $spacequalifierrest=$space;
12405:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12406:     if ($realm eq 'user') {
12407: # --------------------------------------------------------------- user.resource
12408: 	if ($space eq 'resource') {
12409: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12410: 		  || defined($Apache::lonhomework::parsing_a_task))
12411: 		 &&
12412: 		 ($symbparm eq &symbread()) ) {
12413: 		# if we are in the middle of processing the resource the
12414: 		# get the value we are planning on committing
12415:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12416:                     return $Apache::lonhomework::results{$qualifierrest};
12417:                 } else {
12418:                     return $Apache::lonhomework::history{$qualifierrest};
12419:                 }
12420: 	    } else {
12421: 		my %restored;
12422: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12423: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12424: 		} else {
12425: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12426: 		}
12427: 		return $restored{$qualifierrest};
12428: 	    }
12429: # ----------------------------------------------------------------- user.access
12430:         } elsif ($space eq 'access') {
12431: 	    # FIXME - not supporting calls for a specific user
12432:             return &allowed($qualifier,$rest);
12433: # ------------------------------------------ user.preferences, user.environment
12434:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12435: 	    if (($uname eq $env{'user.name'}) &&
12436: 		($udom eq $env{'user.domain'})) {
12437: 		return $env{join('.',('environment',$qualifierrest))};
12438: 	    } else {
12439: 		my %returnhash;
12440: 		if (!$publicuser) {
12441: 		    %returnhash=&userenvironment($udom,$uname,
12442: 						 $qualifierrest);
12443: 		}
12444: 		return $returnhash{$qualifierrest};
12445: 	    }
12446: # ----------------------------------------------------------------- user.course
12447:         } elsif ($space eq 'course') {
12448: 	    # FIXME - not supporting calls for a specific user
12449:             return $env{join('.',('request.course',$qualifier))};
12450: # ------------------------------------------------------------------- user.role
12451:         } elsif ($space eq 'role') {
12452: 	    # FIXME - not supporting calls for a specific user
12453:             my ($role,$where)=split(/\./,$env{'request.role'});
12454:             if ($qualifier eq 'value') {
12455: 		return $role;
12456:             } elsif ($qualifier eq 'extent') {
12457:                 return $where;
12458:             }
12459: # ----------------------------------------------------------------- user.domain
12460:         } elsif ($space eq 'domain') {
12461:             return $udom;
12462: # ------------------------------------------------------------------- user.name
12463:         } elsif ($space eq 'name') {
12464:             return $uname;
12465: # ---------------------------------------------------- Any other user namespace
12466:         } else {
12467: 	    my %reply;
12468: 	    if (!$publicuser) {
12469: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12470: 	    }
12471: 	    return $reply{$qualifierrest};
12472:         }
12473:     } elsif ($realm eq 'query') {
12474: # ---------------------------------------------- pull stuff out of query string
12475:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12476: 						[$spacequalifierrest]);
12477: 	return $env{'form.'.$spacequalifierrest}; 
12478:    } elsif ($realm eq 'request') {
12479: # ------------------------------------------------------------- request.browser
12480:         if ($space eq 'browser') {
12481:             return $env{'browser.'.$qualifier};
12482: # ------------------------------------------------------------ request.filename
12483:         } else {
12484:             return $env{'request.'.$spacequalifierrest};
12485:         }
12486:     } elsif ($realm eq 'course') {
12487: # ---------------------------------------------------------- course.description
12488:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12489:     } elsif ($realm eq 'resource') {
12490: 
12491: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12492: 	    if (!$symbparm) { $symbparm=&symbread(); }
12493: 	}
12494: 
12495:         if ($qualifier eq '') {
12496: 	    if ($space eq 'title') {
12497: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12498: 	        return &gettitle($symbparm);
12499: 	    }
12500: 	
12501: 	    if ($space eq 'map') {
12502: 	        my ($map) = &decode_symb($symbparm);
12503: 	        return &symbread($map);
12504: 	    }
12505:             if ($space eq 'maptitle') {
12506:                 my ($map) = &decode_symb($symbparm);
12507:                 return &gettitle($map);
12508:             }
12509: 	    if ($space eq 'filename') {
12510: 	        if ($symbparm) {
12511: 		    return &clutter((&decode_symb($symbparm))[2]);
12512: 	        }
12513: 	        return &hreflocation('',$env{'request.filename'});
12514: 	    }
12515: 
12516:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12517:                 if ($space eq 'visibleparts') {
12518:                     my $navmap = Apache::lonnavmaps::navmap->new();
12519:                     my $item;
12520:                     if (ref($navmap)) {
12521:                         my $res = $navmap->getBySymb($symbparm);
12522:                         my $parts = $res->parts();
12523:                         if (ref($parts) eq 'ARRAY') {
12524:                             $item = join(',',@{$parts});
12525:                         }
12526:                         undef($navmap);
12527:                     }
12528:                     return $item;
12529:                 }
12530:             }
12531:         }
12532: 
12533: 	my ($section, $group, @groups, @recurseup, $recursed);
12534:         if (ref($recurseupref) eq 'ARRAY') {
12535:             @recurseup = @{$recurseupref};
12536:             $recursed = 1;
12537:         }
12538: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12539:         if (($courseid eq '') && ($cid)) {
12540:             $courseid = $cid;
12541:         }
12542: 	if (($symbparm && $courseid) && 
12543: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12544: 
12545: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12546: 
12547: # ----------------------------------------------------- Cascading lookup scheme
12548: 	    my $symbp=$symbparm;
12549: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12550: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12551:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12552: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12553: 	    if (($env{'user.name'} eq $uname) &&
12554: 		($env{'user.domain'} eq $udom)) {
12555: 		$section=$env{'request.course.sec'};
12556:                 @groups = split(/:/,$env{'request.course.groups'});  
12557:                 @groups=&sort_course_groups($courseid,@groups); 
12558: 	    } else {
12559: 		if (! defined($usection)) {
12560: 		    $section=&getsection($udom,$uname,$courseid);
12561: 		} else {
12562: 		    $section = $usection;
12563: 		}
12564:                 @groups = &get_users_groups($udom,$uname,$courseid);
12565: 	    }
12566: 
12567: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12568: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12569:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12570: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12571: 
12572: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12573: 	    my $courselevelr=$courseid.'.'.$symbparm;
12574:             $courseleveli=$courseid.'.'.$recurseparm;
12575: 	    $courselevelm=$courseid.'.'.$mapparm;
12576: 
12577: # ----------------------------------------------------------- first, check user
12578: 
12579: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12580:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12581: 				       ([$courselevelr,'resource'],
12582: 					[$courselevelm,'map'     ],
12583:                                         [$courseleveli,'map'     ],
12584: 					[$courselevel, 'course'  ]));
12585: 	    if (defined($userreply)) { return &get_reply($userreply); }
12586: 
12587: # ------------------------------------------------ second, check some of course
12588:             my $coursereply;
12589:             if (@groups > 0) {
12590:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12591:                                        $recurseparm,$mapparm,$spacequalifierrest,
12592:                                        $mapp,\$recursed,\@recurseup);
12593:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12594:             }
12595: 
12596: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12597: 				  $env{'course.'.$courseid.'.domain'},
12598: 				  'course',$mapp,\$recursed,\@recurseup,
12599:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12600: 				  ([$seclevelr,   'resource'],
12601: 				   [$seclevelm,   'map'     ],
12602:                                    [$secleveli,   'map'     ],
12603: 				   [$seclevel,    'course'  ],
12604: 				   [$courselevelr,'resource']));
12605: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12606: 
12607: # ------------------------------------------------------ third, check map parms
12608: 	    my %parmhash=();
12609: 	    my $thisparm='';
12610: 	    if (tie(%parmhash,'GDBM_File',
12611: 		    $env{'request.course.fn'}.'_parms.db',
12612: 		    &GDBM_READER(),0640)) {
12613: 		$thisparm=$parmhash{$symbparm};
12614: 		untie(%parmhash);
12615: 	    }
12616: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12617: 	}
12618: # ------------------------------------------ fourth, look in resource metadata
12619:  
12620:         my $what = $spacequalifierrest;
12621: 	$what=~s/\./\_/;
12622: 	my $filename;
12623: 	if (!$symbparm) { $symbparm=&symbread(); }
12624: 	if ($symbparm) {
12625: 	    $filename=(&decode_symb($symbparm))[2];
12626: 	} else {
12627: 	    $filename=$env{'request.filename'};
12628: 	}
12629:         my $toolsymb;
12630:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12631:             $toolsymb = $symbparm;
12632:         }
12633: 	my $metadata=&metadata($filename,$what,$toolsymb);
12634: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12635: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12636: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12637: 
12638: # ----------------------------------------------- fifth, look in rest of course
12639: 	if ($symbparm && defined($courseid) && 
12640: 	    $courseid eq $env{'request.course.id'}) {
12641: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12642: 				     $env{'course.'.$courseid.'.domain'},
12643: 				     'course',$mapp,\$recursed,\@recurseup,
12644:                                      $courseid,'.',$spacequalifierrest,
12645: 				     ([$courselevelm,'map'   ],
12646:                                       [$courseleveli,'map'   ],
12647: 				      [$courselevel, 'course']));
12648: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12649: 	}
12650: # ------------------------------------------------------------------ Cascade up
12651: 	unless ($space eq '0') {
12652: 	    my @parts=split(/_/,$space);
12653: 	    my $id=pop(@parts);
12654: 	    my $part=join('_',@parts);
12655: 	    if ($part eq '') { $part='0'; }
12656: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12657: 				 $symbparm,$udom,$uname,$section,1);
12658: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12659: 	}
12660: 	if ($recurse) { return undef; }
12661: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12662: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12663: # ---------------------------------------------------- Any other user namespace
12664:     } elsif ($realm eq 'environment') {
12665: # ----------------------------------------------------------------- environment
12666: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12667: 	    return $env{'environment.'.$spacequalifierrest};
12668: 	} else {
12669: 	    if ($uname eq 'anonymous' && $udom eq '') {
12670: 		return '';
12671: 	    }
12672: 	    my %returnhash=&userenvironment($udom,$uname,
12673: 					    $spacequalifierrest);
12674: 	    return $returnhash{$spacequalifierrest};
12675: 	}
12676:     } elsif ($realm eq 'system') {
12677: # ----------------------------------------------------------------- system.time
12678: 	if ($space eq 'time') {
12679: 	    return time;
12680:         }
12681:     } elsif ($realm eq 'server') {
12682: # ----------------------------------------------------------------- system.time
12683: 	if ($space eq 'name') {
12684: 	    return $ENV{'SERVER_NAME'};
12685:         }
12686:     } elsif ($realm eq 'client') {
12687:         if ($space eq 'remote_addr') {
12688:             return &get_requestor_ip();
12689:         }
12690:     }
12691:     return '';
12692: }
12693: 
12694: sub get_reply {
12695:     my ($reply_value) = @_;
12696:     if (ref($reply_value) eq 'ARRAY') {
12697:         if (wantarray) {
12698: 	    return @$reply_value;
12699:         }
12700:         return $reply_value->[0];
12701:     } else {
12702:         return $reply_value;
12703:     }
12704: }
12705: 
12706: sub check_group_parms {
12707:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12708:         $recursed,$recurseupref) = @_;
12709:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12710:                   [$what,'course']);
12711:     my $coursereply;
12712:     foreach my $group (@{$groups}) {
12713:         my @groupitems = ();
12714:         foreach my $level (@levels) {
12715:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12716:              push(@groupitems,[$item,$level->[1]]);
12717:         }
12718:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12719:                                    $env{'course.'.$courseid.'.domain'},
12720:                                    'course',$mapp,$recursed,$recurseupref,
12721:                                    $courseid,'.['.$group.'].',$what,
12722:                                    @groupitems);
12723:         last if (defined($coursereply));
12724:     }
12725:     return $coursereply;
12726: }
12727: 
12728: sub get_map_hierarchy {
12729:     my ($mapname,$courseid) = @_;
12730:     my @recurseup = ();
12731:     if ($mapname) {
12732:         if (($cachedmapkey eq $courseid) &&
12733:             (abs($cachedmaptime-time)<5)) {
12734:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12735:                 return @{$cachedmaps{$mapname}};
12736:             }
12737:         }
12738:         my $navmap = Apache::lonnavmaps::navmap->new();
12739:         if (ref($navmap)) {
12740:             @recurseup = $navmap->recurseup_maps($mapname);
12741:             undef($navmap);
12742:             $cachedmaps{$mapname} = \@recurseup;
12743:             $cachedmaptime=time;
12744:             $cachedmapkey=$courseid;
12745:         }
12746:     }
12747:     return @recurseup;
12748: }
12749: 
12750: }
12751: 
12752: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12753:     my ($courseid,@groups) = @_;
12754:     @groups = sort(@groups);
12755:     return @groups;
12756: }
12757: 
12758: sub packages_tab_default {
12759:     my ($uri,$varname,$toolsymb)=@_;
12760:     my (undef,$part,$name)=split(/\./,$varname);
12761: 
12762:     my (@extension,@specifics,$do_default);
12763:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12764: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12765: 	if ($pack_type eq 'default') {
12766: 	    $do_default=1;
12767: 	} elsif ($pack_type eq 'extension') {
12768: 	    push(@extension,[$package,$pack_type,$pack_part]);
12769: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12770: 	    # only look at packages defaults for packages that this id is
12771: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12772: 	}
12773:     }
12774:     # first look for a package that matches the requested part id
12775:     foreach my $package (@specifics) {
12776: 	my (undef,$pack_type,$pack_part)=@{$package};
12777: 	next if ($pack_part ne $part);
12778: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12779: 	    return $packagetab{"$pack_type&$name&default"};
12780: 	}
12781:     }
12782:     # look for any possible matching non extension_ package
12783:     foreach my $package (@specifics) {
12784: 	my (undef,$pack_type,$pack_part)=@{$package};
12785: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12786: 	    return $packagetab{"$pack_type&$name&default"};
12787: 	}
12788: 	if ($pack_type eq 'part') { $pack_part='0'; }
12789: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12790: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12791: 	}
12792:     }
12793:     # look for any posible extension_ match
12794:     foreach my $package (@extension) {
12795: 	my ($package,$pack_type)=@{$package};
12796: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12797: 	    return $packagetab{"$pack_type&$name&default"};
12798: 	}
12799: 	if (defined($packagetab{$package."&$name&default"})) {
12800: 	    return $packagetab{$package."&$name&default"};
12801: 	}
12802:     }
12803:     # look for a global default setting
12804:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12805: 	return $packagetab{"default&$name&default"};
12806:     }
12807:     return undef;
12808: }
12809: 
12810: sub add_prefix_and_part {
12811:     my ($prefix,$part)=@_;
12812:     my $keyroot;
12813:     if (defined($prefix) && $prefix !~ /^__/) {
12814: 	# prefix that has a part already
12815: 	$keyroot=$prefix;
12816:     } elsif (defined($prefix)) {
12817: 	# prefix that is missing a part
12818: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12819:     } else {
12820: 	# no prefix at all
12821: 	if (defined($part)) { $keyroot='_'.$part; }
12822:     }
12823:     return $keyroot;
12824: }
12825: 
12826: # ---------------------------------------------------------------- Get metadata
12827: 
12828: my %metaentry;
12829: my %importedpartids;
12830: my %importedrespids;
12831: sub metadata {
12832:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12833:     $uri=&declutter($uri);
12834:     # if it is a non metadata possible uri return quickly
12835:     if (($uri eq '') || 
12836: 	(($uri =~ m|^/*adm/|) && 
12837: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12838:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12839: 	return undef;
12840:     }
12841:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12842: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12843: 	return undef;
12844:     }
12845:     my $filename=$uri;
12846:     $uri=~s/\.meta$//;
12847: #
12848: # Is the metadata already cached?
12849: # Look at timestamp of caching
12850: # Everything is cached by the main uri, libraries are never directly cached
12851: #
12852:     if (!defined($liburi)) {
12853: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12854: 	if (defined($cached)) { return $result->{':'.$what}; }
12855:     }
12856: 
12857: #
12858: # If the uri is for an external tool the file from
12859: # which metadata should be retrieved depends on whether
12860: # the tool had been configured to be gradable (set in the Course
12861: # Editor or Resource Editor).
12862: #
12863: # If a valid symb has been included as the third arg in the call
12864: # to &metadata() that can be used to retrieve the value of
12865: # parameter_0_gradable set for the resource, and included in the
12866: # uploaded map containing the tool. The value is retrieved via
12867: # &EXT(), if a valid symb is available.  Otherwise the value of
12868: # gradable in the exttool_$marker.db file for the tool instance
12869: # is retrieved via &get().
12870: #
12871: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12872: # hiddenresource and encrypturl (during course initialization)
12873: # the map-level parameter for resource.0.gradable included in the 
12874: # uploaded map containing the tool will not yet have been stored
12875: # in the user_course_parms.db file for the user's session, so in 
12876: # this case fall back to retrieving gradable status from the
12877: # exttool_$marker.db file.
12878: #
12879: # In order to avoid an infinite loop, &metadata() will return
12880: # before a call to &EXT(), if the uri is for an external tool
12881: # and the $what for which metadata is being requested is
12882: # parameter_0_gradable or 0_gradable.
12883: #
12884: 
12885:     if ($uri =~ /ext\.tool$/) {
12886:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12887:             return;
12888:         } else {
12889:             my ($checked,$use_passback);
12890:             if ($toolsymb ne '') {
12891:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12892:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12893:                     $checked = 1;
12894:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12895:                         $use_passback = 1;
12896:                     }
12897:                 }
12898:             }
12899:             unless ($checked) {
12900:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12901:                 $marker=~s/\D//g;
12902:                 if ($marker) {
12903:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12904:                     $use_passback = $toolsettings{'gradable'};
12905:                 }
12906:             }
12907:             if ($use_passback) {
12908:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12909:             } else {
12910:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12911:             }
12912:         }
12913:     }
12914: 
12915:     {
12916: # Imported parts would go here
12917:         my @origfiletagids=();
12918:         my $importedparts=0;
12919: 
12920: # Imported responseids would go here
12921:         my $importedresponses=0;
12922: #
12923: # Is this a recursive call for a library?
12924: #
12925: #	if (! exists($metacache{$uri})) {
12926: #	    $metacache{$uri}={};
12927: #	}
12928: 	my $cachetime = 60*60;
12929:         if ($liburi) {
12930: 	    $liburi=&declutter($liburi);
12931:             $filename=$liburi;
12932:         } else {
12933: 	    &devalidate_cache_new('meta',$uri);
12934: 	    undef(%metaentry);
12935: 	}
12936:         my %metathesekeys=();
12937:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12938: 	my $metastring;
12939: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12940: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12941: 	    $metastring = 
12942: 		&Apache::lonnet::ssi_body($which,
12943: 					  ('grade_target' => 'meta'));
12944: 	    $cachetime = 1; # only want this cached in the child not long term
12945: 	} elsif (($uri !~ m -^(editupload)/-) && 
12946:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12947: 	    my $file=&filelocation('',&clutter($filename));
12948: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12949: 	    $metastring=&getfile($file);
12950: 	}
12951:         my $parser=HTML::LCParser->new(\$metastring);
12952:         my $token;
12953:         undef %metathesekeys;
12954:         while ($token=$parser->get_token) {
12955: 	    if ($token->[0] eq 'S') {
12956: 		if (defined($token->[2]->{'package'})) {
12957: #
12958: # This is a package - get package info
12959: #
12960: 		    my $package=$token->[2]->{'package'};
12961: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12962: 		    if (defined($token->[2]->{'id'})) { 
12963: 			$keyroot.='_'.$token->[2]->{'id'}; 
12964: 		    }
12965: 		    if ($metaentry{':packages'}) {
12966: 			$metaentry{':packages'}.=','.$package.$keyroot;
12967: 		    } else {
12968: 			$metaentry{':packages'}=$package.$keyroot;
12969: 		    }
12970: 		    foreach my $pack_entry (keys(%packagetab)) {
12971: 			my $part=$keyroot;
12972: 			$part=~s/^\_//;
12973: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12974: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12975: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12976: 			    # ignore package.tab specified default values
12977:                             # here &package_tab_default() will fetch those
12978: 			    if ($subp eq 'default') { next; }
12979: 			    my $value=$packagetab{$pack_entry};
12980: 			    my $unikey;
12981: 			    if ($pack =~ /_0$/) {
12982: 				$unikey='parameter_0_'.$name;
12983: 				$part=0;
12984: 			    } else {
12985: 				$unikey='parameter'.$keyroot.'_'.$name;
12986: 			    }
12987: 			    if ($subp eq 'display') {
12988: 				$value.=' [Part: '.$part.']';
12989: 			    }
12990: 			    $metaentry{':'.$unikey.'.part'}=$part;
12991: 			    $metathesekeys{$unikey}=1;
12992: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12993: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12994: 			    }
12995: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12996: 				$metaentry{':'.$unikey}=
12997: 				    $metaentry{':'.$unikey.'.default'};
12998: 			    }
12999: 			}
13000: 		    }
13001: 		} else {
13002: #
13003: # This is not a package - some other kind of start tag
13004: #
13005: 		    my $entry=$token->[1];
13006: 		    my $unikey='';
13007: 
13008: 		    if ($entry eq 'import') {
13009: #
13010: # Importing a library here
13011: #
13012:                         my $location=$parser->get_text('/import');
13013:                         my $dir=$filename;
13014:                         $dir=~s|[^/]*$||;
13015:                         $location=&filelocation($dir,$location);
13016: 
13017:                         my $importid=$token->[2]->{'id'};
13018:                         my $importmode=$token->[2]->{'importmode'};
13019: #
13020: # Check metadata for imported file to
13021: # see if it contained response items
13022: #
13023:                         my ($origfile,@libfilekeys);
13024:                         my %currmetaentry = %metaentry;
13025:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13026:                                                            $depthcount+1));
13027:                         if (grep(/^responseorder$/,@libfilekeys)) {
13028:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13029:                                                              undef,$depthcount+1);
13030:                             if ($libresponseorder ne '') {
13031:                                 if ($#origfiletagids<0) {
13032:                                     undef(%importedrespids);
13033:                                     undef(%importedpartids);
13034:                                 }
13035:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13036:                                 if (@respids) {
13037:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13038:                                 }
13039:                                 if ($importedrespids{$importid} ne '') {
13040:                                     $importedresponses = 1;
13041: # We need to get the original file and the imported file to get the response order correct
13042: # Load and inspect original file
13043:                                     if ($#origfiletagids<0) {
13044:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13045:                                         $origfile=&getfile($origfilelocation);
13046:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13047:                                     }
13048:                                 }
13049:                             }
13050:                         }
13051: # Do not overwrite contents of %metaentry hash for resource itself with 
13052: # hash populated for imported library file
13053:                         %metaentry = %currmetaentry;
13054:                         undef(%currmetaentry);
13055:                         if ($importmode eq 'part') {
13056: # Import as part(s)
13057:                            $importedparts=1;
13058: # We need to get the original file and the imported file to get the part order correct
13059: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13060: # Load and inspect original file if we didn't do that already
13061:                            if ($#origfiletagids<0) {
13062:                                undef(%importedrespids);
13063:                                undef(%importedpartids);
13064:                                if ($origfile eq '') {
13065:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13066:                                    $origfile=&getfile($origfilelocation);
13067:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13068:                                }
13069:                            }
13070:                            my @impfilepartids;
13071: # If <partorder> tag is included in metadata for the imported file
13072: # get the parts in the imported file from that.
13073:                            if (grep(/^partorder$/,@libfilekeys)) {
13074:                                %currmetaentry = %metaentry;
13075:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13076:                                                             $depthcount+1);
13077:                                %metaentry = %currmetaentry;
13078:                                undef(%currmetaentry);
13079:                                if ($libpartorder ne '') {
13080:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13081:                                }
13082:                            } else {
13083: # If no <partorder> tag available, load and inspect imported file
13084:                                my $impfile=&getfile($location);
13085:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13086:                            }
13087:                            if ($#impfilepartids>=0) {
13088: # This problem had parts
13089:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13090:                            } else {
13091: # Importing by turning a single problem into a problem part
13092: # It gets the import-tags ID as part-ID
13093:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13094:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13095:                            }
13096:                         } else {
13097: # Import as problem or as normal import
13098:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13099:                             unless ($importmode eq 'problem') {
13100: # Normal import
13101:                                 if (defined($token->[2]->{'id'})) {
13102:                                     $unikey.='_'.$token->[2]->{'id'};
13103:                                 }
13104:                             }
13105: # Check metadata for imported file to
13106: # see if it contained parts
13107:                             if (grep(/^partorder$/,@libfilekeys)) {
13108:                                 %currmetaentry = %metaentry;
13109:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13110:                                                              $depthcount+1);
13111:                                 %metaentry = %currmetaentry;
13112:                                 undef(%currmetaentry);
13113:                                 if ($libpartorder ne '') {
13114:                                     $importedparts = 1;
13115:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13116:                                 }
13117:                             }
13118:                         }
13119: 			if ($depthcount<20) {
13120: 			    my $metadata = 
13121: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13122: 					  $depthcount+1);
13123: 			    foreach my $meta (split(',',$metadata)) {
13124: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13125: 				$metathesekeys{$meta}=1;
13126: 			    }
13127:                         }
13128: 		    } else {
13129: #
13130: # Not importing, some other kind of non-package, non-library start tag
13131: # 
13132:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13133:                         if (defined($token->[2]->{'id'})) {
13134:                             $unikey.='_'.$token->[2]->{'id'};
13135:                         }
13136: 			if (defined($token->[2]->{'name'})) { 
13137: 			    $unikey.='_'.$token->[2]->{'name'}; 
13138: 			}
13139: 			$metathesekeys{$unikey}=1;
13140: 			foreach my $param (@{$token->[3]}) {
13141: 			    $metaentry{':'.$unikey.'.'.$param} =
13142: 				$token->[2]->{$param};
13143: 			}
13144: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13145: 			my $default=$metaentry{':'.$unikey.'.default'};
13146: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13147: 		 # only ws inside the tag, and not in default, so use default
13148: 		 # as value
13149: 			    $metaentry{':'.$unikey}=$default;
13150: 			} elsif ( $internaltext =~ /\S/ ) {
13151: 		  # something interesting inside the tag
13152: 			    $metaentry{':'.$unikey}=$internaltext;
13153: 			} else {
13154: 		  # no interesting values, don't set a default
13155: 			}
13156: # end of not-a-package not-a-library import
13157: 		    }
13158: # end of not-a-package start tag
13159: 		}
13160: # the next is the end of "start tag"
13161: 	    }
13162: 	}
13163: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13164: 	$extension = lc($extension);
13165: 	if ($extension eq 'htm') { $extension='html'; }
13166: 
13167: 	foreach my $key (keys(%packagetab)) {
13168: 	    #no specific packages #how's our extension
13169: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13170: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13171: 					 \%metathesekeys);
13172: 	}
13173: 
13174: 	if (!exists($metaentry{':packages'})
13175: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13176: 	    foreach my $key (keys(%packagetab)) {
13177: 		#no specific packages well let's get default then
13178: 		if ($key!~/^default&/) { next; }
13179: 		&metadata_create_package_def($uri,$key,'default',
13180: 					     \%metathesekeys);
13181: 	    }
13182: 	}
13183: # are there custom rights to evaluate
13184: 	if ($metaentry{':copyright'} eq 'custom') {
13185: 
13186:     #
13187:     # Importing a rights file here
13188:     #
13189: 	    unless ($depthcount) {
13190: 		my $location=$metaentry{':customdistributionfile'};
13191: 		my $dir=$filename;
13192: 		$dir=~s|[^/]*$||;
13193: 		$location=&filelocation($dir,$location);
13194: 		my $rights_metadata =
13195: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13196: 			      $depthcount+1);
13197: 		foreach my $rights (split(',',$rights_metadata)) {
13198: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13199: 		    $metathesekeys{$rights}=1;
13200: 		}
13201: 	    }
13202: 	}
13203: 	# uniqifiy package listing
13204: 	my %seen;
13205: 	my @uniq_packages =
13206: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13207: 	$metaentry{':packages'} = join(',',@uniq_packages);
13208: 
13209:         if (($importedresponses) || ($importedparts)) {
13210:             if ($importedparts) {
13211: # We had imported parts and need to rebuild partorder
13212:                 $metaentry{':partorder'}='';
13213:                 $metathesekeys{'partorder'}=1;
13214:             }
13215:             if ($importedresponses) {
13216: # We had imported responses and need to rebuil responseorder
13217:                 $metaentry{':responseorder'}='';
13218:                 $metathesekeys{'responseorder'}=1;
13219:             }
13220:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13221:                 my $origid = $origfiletagids[$index+1];
13222:                 if ($origfiletagids[$index] eq 'part') {
13223: # Original part, part of the problem
13224:                     if ($importedparts) {
13225:                         $metaentry{':partorder'}.=','.$origid;
13226:                     }
13227:                 } elsif ($origfiletagids[$index] eq 'import') {
13228:                     if ($importedparts) {
13229: # We have imported parts at this position
13230:                         if ($importedpartids{$origid} ne '') {
13231:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13232:                         }
13233:                     }
13234:                     if ($importedresponses) {
13235: # We have imported responses at this position
13236:                         if ($importedrespids{$origid} ne '') {
13237:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13238:                         }
13239:                     }
13240:                 } else {
13241: # Original response item, part of the problem
13242:                     if ($importedresponses) {
13243:                         $metaentry{':responseorder'}.=','.$origid;
13244:                     }
13245:                 }
13246:             }
13247:             if ($importedparts) {
13248:                 $metaentry{':partorder'}=~s/^\,//;
13249:             }
13250:             if ($importedresponses) {
13251:                 $metaentry{':responseorder'}=~s/^\,//;
13252:             }
13253:         }
13254: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13255: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13256: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13257:         unless ($liburi) {
13258: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13259:         }
13260: # this is the end of "was not already recently cached
13261:     }
13262:     return $metaentry{':'.$what};
13263: }
13264: 
13265: sub metadata_create_package_def {
13266:     my ($uri,$key,$package,$metathesekeys)=@_;
13267:     my ($pack,$name,$subp)=split(/\&/,$key);
13268:     if ($subp eq 'default') { next; }
13269:     
13270:     if (defined($metaentry{':packages'})) {
13271: 	$metaentry{':packages'}.=','.$package;
13272:     } else {
13273: 	$metaentry{':packages'}=$package;
13274:     }
13275:     my $value=$packagetab{$key};
13276:     my $unikey;
13277:     $unikey='parameter_0_'.$name;
13278:     $metaentry{':'.$unikey.'.part'}=0;
13279:     $$metathesekeys{$unikey}=1;
13280:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13281: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13282:     }
13283:     if (defined($metaentry{':'.$unikey.'.default'})) {
13284: 	$metaentry{':'.$unikey}=
13285: 	    $metaentry{':'.$unikey.'.default'};
13286:     }
13287: }
13288: 
13289: sub metadata_generate_part0 {
13290:     my ($metadata,$metacache,$uri) = @_;
13291:     my %allnames;
13292:     foreach my $metakey (keys(%$metadata)) {
13293: 	if ($metakey=~/^parameter\_(.*)/) {
13294: 	  my $part=$$metacache{':'.$metakey.'.part'};
13295: 	  my $name=$$metacache{':'.$metakey.'.name'};
13296: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13297: 	    $allnames{$name}=$part;
13298: 	  }
13299: 	}
13300:     }
13301:     foreach my $name (keys(%allnames)) {
13302:       $$metadata{"parameter_0_$name"}=1;
13303:       my $key=":parameter_0_$name";
13304:       $$metacache{"$key.part"}='0';
13305:       $$metacache{"$key.name"}=$name;
13306:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13307: 					   $allnames{$name}.'_'.$name.
13308: 					   '.type'};
13309:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13310: 			     '.display'};
13311:       my $expr='[Part: '.$allnames{$name}.']';
13312:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13313:       $$metacache{"$key.display"}=$olddis;
13314:     }
13315: }
13316: 
13317: # ------------------------------------------------------ Devalidate title cache
13318: 
13319: sub devalidate_title_cache {
13320:     my ($url)=@_;
13321:     if (!$env{'request.course.id'}) { return; }
13322:     my $symb=&symbread($url);
13323:     if (!$symb) { return; }
13324:     my $key=$env{'request.course.id'}."\0".$symb;
13325:     &devalidate_cache_new('title',$key);
13326: }
13327: 
13328: # ------------------------------------------------- Get the title of a course
13329: 
13330: sub current_course_title {
13331:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13332: }
13333: # ------------------------------------------------- Get the title of a resource
13334: 
13335: sub gettitle {
13336:     my $urlsymb=shift;
13337:     my $symb=&symbread($urlsymb);
13338:     if ($symb) {
13339: 	my $key=$env{'request.course.id'}."\0".$symb;
13340: 	my ($result,$cached)=&is_cached_new('title',$key);
13341: 	if (defined($cached)) { 
13342: 	    return $result;
13343: 	}
13344: 	my ($map,$resid,$url)=&decode_symb($symb);
13345: 	my $title='';
13346: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13347: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13348: 	} else {
13349: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13350: 		    &GDBM_READER(),0640)) {
13351: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13352: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13353: 		untie(%bighash);
13354: 	    }
13355: 	}
13356: 	$title=~s/\&colon\;/\:/gs;
13357: 	if ($title) {
13358: # Remember both $symb and $title for dynamic metadata
13359:             $accesshash{$symb.'___crstitle'}=$title;
13360:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13361: # Cache this title and then return it
13362: 	    return &do_cache_new('title',$key,$title,600);
13363: 	}
13364: 	$urlsymb=$url;
13365:     }
13366:     my $title=&metadata($urlsymb,'title');
13367:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13368:     return $title;
13369: }
13370: 
13371: sub get_slot {
13372:     my ($which,$cnum,$cdom)=@_;
13373:     if (!$cnum || !$cdom) {
13374: 	(undef,my $courseid)=&whichuser();
13375: 	$cdom=$env{'course.'.$courseid.'.domain'};
13376: 	$cnum=$env{'course.'.$courseid.'.num'};
13377:     }
13378:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13379:     my %slotinfo;
13380:     if (exists($remembered{$key})) {
13381: 	$slotinfo{$which} = $remembered{$key};
13382:     } else {
13383: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13384: 	&Apache::lonhomework::showhash(%slotinfo);
13385: 	my ($tmp)=keys(%slotinfo);
13386: 	if ($tmp=~/^error:/) { return (); }
13387: 	$remembered{$key} = $slotinfo{$which};
13388:     }
13389:     if (ref($slotinfo{$which}) eq 'HASH') {
13390: 	return %{$slotinfo{$which}};
13391:     }
13392:     return $slotinfo{$which};
13393: }
13394: 
13395: sub get_reservable_slots {
13396:     my ($cnum,$cdom,$uname,$udom) = @_;
13397:     my $now = time;
13398:     my $reservable_info;
13399:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13400:     if (exists($remembered{$key})) {
13401:         $reservable_info = $remembered{$key};
13402:     } else {
13403:         my %resv;
13404:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13405:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13406:         $reservable_info = \%resv;
13407:         $remembered{$key} = $reservable_info;
13408:     }
13409:     return $reservable_info;
13410: }
13411: 
13412: sub get_course_slots {
13413:     my ($cnum,$cdom) = @_;
13414:     my $hashid=$cnum.':'.$cdom;
13415:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13416:     if (defined($cached)) {
13417:         if (ref($result) eq 'HASH') {
13418:             return %{$result};
13419:         }
13420:     } else {
13421:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13422:         my ($tmp) = keys(%slots);
13423:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13424:             &do_cache_new('allslots',$hashid,\%slots,600);
13425:             return %slots;
13426:         }
13427:     }
13428:     return;
13429: }
13430: 
13431: sub devalidate_slots_cache {
13432:     my ($cnum,$cdom)=@_;
13433:     my $hashid=$cnum.':'.$cdom;
13434:     &devalidate_cache_new('allslots',$hashid);
13435: }
13436: 
13437: sub get_coursechange {
13438:     my ($cdom,$cnum) = @_;
13439:     if ($cdom eq '' || $cnum eq '') {
13440:         return unless ($env{'request.course.id'});
13441:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13442:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13443:     }
13444:     my $hashid=$cdom.'_'.$cnum;
13445:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13446:     if ((defined($cached)) && ($change ne '')) {
13447:         return $change;
13448:     } else {
13449:         my %crshash;
13450:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13451:         if ($crshash{'internal.contentchange'} eq '') {
13452:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13453:             if ($change eq '') {
13454:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13455:                 $change = $crshash{'internal.created'};
13456:             }
13457:         } else {
13458:             $change = $crshash{'internal.contentchange'};
13459:         }
13460:         my $cachetime = 600;
13461:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13462:     }
13463:     return $change;
13464: }
13465: 
13466: sub devalidate_coursechange_cache {
13467:     my ($cnum,$cdom)=@_;
13468:     my $hashid=$cnum.':'.$cdom;
13469:     &devalidate_cache_new('crschange',$hashid);
13470: }
13471: 
13472: # ------------------------------------------------- Update symbolic store links
13473: 
13474: sub symblist {
13475:     my ($mapname,%newhash)=@_;
13476:     $mapname=&deversion(&declutter($mapname));
13477:     my %hash;
13478:     if (($env{'request.course.fn'}) && (%newhash)) {
13479:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13480:                       &GDBM_WRCREAT(),0640)) {
13481: 	    foreach my $url (keys(%newhash)) {
13482: 		next if ($url eq 'last_known'
13483: 			 && $env{'form.no_update_last_known'});
13484: 		$hash{declutter($url)}=&encode_symb($mapname,
13485: 						    $newhash{$url}->[1],
13486: 						    $newhash{$url}->[0]);
13487:             }
13488:             if (untie(%hash)) {
13489: 		return 'ok';
13490:             }
13491:         }
13492:     }
13493:     return 'error';
13494: }
13495: 
13496: # --------------------------------------------------------------- Verify a symb
13497: 
13498: sub symbverify {
13499:     my ($symb,$thisurl,$encstate)=@_;
13500:     my $thisfn=$thisurl;
13501:     $thisfn=&declutter($thisfn);
13502: # direct jump to resource in page or to a sequence - will construct own symbs
13503:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13504: # check URL part
13505:     my ($map,$resid,$url)=&decode_symb($symb);
13506: 
13507:     unless ($url eq $thisfn) { return 0; }
13508: 
13509:     $symb=&symbclean($symb);
13510:     $thisurl=&deversion($thisurl);
13511:     $thisfn=&deversion($thisfn);
13512: 
13513:     my %bighash;
13514:     my $okay=0;
13515: 
13516:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13517:                             &GDBM_READER(),0640)) {
13518:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13519:             $thisurl =~ s/\?.+$//;
13520:             if ($map =~ m{^uploaded/.+\.page$}) {
13521:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13522:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13523:             }
13524:         }
13525:         my $ids;
13526:         if ($map =~ m{^uploaded/.+\.page$}) {
13527:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13528:         } else {
13529:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13530:         }
13531:         unless ($ids) {
13532:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13533:             $ids=$bighash{$idkey};
13534:         }
13535:         if ($ids) {
13536: # ------------------------------------------------------------------- Has ID(s)
13537:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13538:                 $symb =~ s/\?.+$//;
13539:             }
13540: 	    foreach my $id (split(/\,/,$ids)) {
13541: 	       my ($mapid,$resid)=split(/\./,$id);
13542:                if (
13543:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13544:    eq $symb) {
13545:                    if (ref($encstate)) {
13546:                        $$encstate = $bighash{'encrypted_'.$id};
13547:                    }
13548: 		   if (($env{'request.role.adv'}) ||
13549: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13550:                        ($thisurl eq '/adm/navmaps')) {
13551: 		       $okay=1;
13552:                        last;
13553: 		   }
13554: 	       }
13555: 	   }
13556:         }
13557: 	untie(%bighash);
13558:     }
13559:     return $okay;
13560: }
13561: 
13562: # --------------------------------------------------------------- Clean-up symb
13563: 
13564: sub symbclean {
13565:     my $symb=shift;
13566:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13567: # remove version from map
13568:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13569: 
13570: # remove version from URL
13571:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13572: 
13573: # remove wrapper
13574: 
13575:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13576:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13577:     return $symb;
13578: }
13579: 
13580: # ---------------------------------------------- Split symb to find map and url
13581: 
13582: sub encode_symb {
13583:     my ($map,$resid,$url)=@_;
13584:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13585: }
13586: 
13587: sub decode_symb {
13588:     my $symb=shift;
13589:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13590:     my ($map,$resid,$url)=split(/___/,$symb);
13591:     return (&fixversion($map),$resid,&fixversion($url));
13592: }
13593: 
13594: sub fixversion {
13595:     my $fn=shift;
13596:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13597:     my %bighash;
13598:     my $uri=&clutter($fn);
13599:     my $key=$env{'request.course.id'}.'_'.$uri;
13600: # is this cached?
13601:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13602:     if (defined($cached)) { return $result; }
13603: # unfortunately not cached, or expired
13604:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13605: 	    &GDBM_READER(),0640)) {
13606:  	if ($bighash{'version_'.$uri}) {
13607:  	    my $version=$bighash{'version_'.$uri};
13608:  	    unless (($version eq 'mostrecent') || 
13609: 		    ($version==&getversion($uri))) {
13610:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13611:  	    }
13612:  	}
13613:  	untie %bighash;
13614:     }
13615:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13616: }
13617: 
13618: sub deversion {
13619:     my $url=shift;
13620:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13621:     return $url;
13622: }
13623: 
13624: # ------------------------------------------------------ Return symb list entry
13625: 
13626: sub symbread {
13627:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13628:         $ignoresymbdb,$noenccheck)=@_;
13629:     my $cache_str='request.symbread.cached.'.$thisfn;
13630:     if (defined($env{$cache_str})) {
13631:         unless (ref($possibles) eq 'HASH') {
13632:             if ($ignorecachednull) {
13633:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13634:             } else {
13635:                 return $env{$cache_str};
13636:             }
13637:         }
13638:     }
13639: # no filename provided? try from environment
13640:     unless ($thisfn) {
13641:         if ($env{'request.symb'}) {
13642:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13643: 	}
13644: 	$thisfn=$env{'request.filename'};
13645:     }
13646:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13647: # is that filename actually a symb? Verify, clean, and return
13648:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13649: 	if (&symbverify($thisfn,$1)) {
13650: 	    return $env{$cache_str}=&symbclean($thisfn);
13651: 	}
13652:     }
13653:     $thisfn=declutter($thisfn);
13654:     my %hash;
13655:     my %bighash;
13656:     my $syval='';
13657:     if (($env{'request.course.fn'}) && ($thisfn)) {
13658:         my $targetfn = $thisfn;
13659:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13660:             $targetfn = 'adm/wrapper/'.$thisfn;
13661:         }
13662: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13663: 	    $targetfn=$1;
13664: 	}
13665:         unless ($ignoresymbdb) {
13666:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13667:                           &GDBM_READER(),0640)) {
13668: 	        $syval=$hash{$targetfn};
13669:                 untie(%hash);
13670:             }
13671:             if ($syval && $checkforblock) {
13672:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13673:                 if (@blockers) {
13674:                     $syval='';
13675:                 }
13676:             }
13677:         }
13678: # ---------------------------------------------------------- There was an entry
13679:         if ($syval) {
13680: 	    #unless ($syval=~/\_\d+$/) {
13681: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13682: 		    #&appenv({'request.ambiguous' => $thisfn});
13683: 		    #return $env{$cache_str}='';
13684: 		#}    
13685: 		#$syval.=$1;
13686: 	    #}
13687:         } else {
13688: # ------------------------------------------------------- Was not in symb table
13689:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13690:                             &GDBM_READER(),0640)) {
13691: # ---------------------------------------------- Get ID(s) for current resource
13692:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13693:               unless ($ids) { 
13694:                  $ids=$bighash{'ids_/'.$thisfn};
13695:               }
13696:               unless ($ids) {
13697: # alias?
13698: 		  $ids=$bighash{'mapalias_'.$thisfn};
13699:               }
13700:               if ($ids) {
13701: # ------------------------------------------------------------------- Has ID(s)
13702:                  my @possibilities=split(/\,/,$ids);
13703:                  if ($#possibilities==0) {
13704: # ----------------------------------------------- There is only one possibility
13705: 		     my ($mapid,$resid)=split(/\./,$ids);
13706: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13707: 						    $resid,$thisfn);
13708:                      if (ref($possibles) eq 'HASH') {
13709:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13710:                              $possibles->{$syval} = 1;
13711:                          }
13712:                      }
13713:                      if ($checkforblock) {
13714:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13715:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13716:                              if (@blockers) {
13717:                                  $syval = '';
13718:                                  untie(%bighash);
13719:                                  return $env{$cache_str}='';
13720:                              }
13721:                          }
13722:                      }
13723:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13724: # ------------------------------------------ There is more than one possibility
13725:                      my $realpossible=0;
13726:                      foreach my $id (@possibilities) {
13727: 			 my $file=$bighash{'src_'.$id};
13728:                          my $canaccess;
13729:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13730:                              $canaccess = 1;
13731:                          } else { 
13732:                              $canaccess = &allowed('bre',$file);
13733:                          }
13734:                          if ($canaccess) {
13735:          		     my ($mapid,$resid)=split(/\./,$id);
13736:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13737:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13738: 						             $resid,$thisfn);
13739:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13740:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13741:                                  if ($checkforblock) {
13742:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13743:                                      if (@blockers > 0) {
13744:                                          $syval = '';
13745:                                      } else {
13746:                                          $syval = $poss_syval;
13747:                                          $realpossible++;
13748:                                      }
13749:                                  } else {
13750:                                      $syval = $poss_syval;
13751:                                      $realpossible++;
13752:                                  }
13753:                                  if ($syval) {
13754:                                      if (ref($possibles) eq 'HASH') {
13755:                                          $possibles->{$syval} = 1;
13756:                                      }
13757:                                  }
13758:                              }
13759: 			 }
13760:                      }
13761: 		     if ($realpossible!=1) { $syval=''; }
13762:                  } else {
13763:                      $syval='';
13764:                  }
13765: 	      }
13766:               untie(%bighash);
13767:            }
13768:         }
13769:         if ($syval) {
13770: 	    return $env{$cache_str}=$syval;
13771:         }
13772:     }
13773:     &appenv({'request.ambiguous' => $thisfn});
13774:     return $env{$cache_str}='';
13775: }
13776: 
13777: # ---------------------------------------------------------- Return random seed
13778: 
13779: sub numval {
13780:     my $txt=shift;
13781:     $txt=~tr/A-J/0-9/;
13782:     $txt=~tr/a-j/0-9/;
13783:     $txt=~tr/K-T/0-9/;
13784:     $txt=~tr/k-t/0-9/;
13785:     $txt=~tr/U-Z/0-5/;
13786:     $txt=~tr/u-z/0-5/;
13787:     $txt=~s/\D//g;
13788:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13789:     return int($txt);
13790: }
13791: 
13792: sub numval2 {
13793:     my $txt=shift;
13794:     $txt=~tr/A-J/0-9/;
13795:     $txt=~tr/a-j/0-9/;
13796:     $txt=~tr/K-T/0-9/;
13797:     $txt=~tr/k-t/0-9/;
13798:     $txt=~tr/U-Z/0-5/;
13799:     $txt=~tr/u-z/0-5/;
13800:     $txt=~s/\D//g;
13801:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13802:     my $total;
13803:     foreach my $val (@txts) { $total+=$val; }
13804:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13805:     return int($total);
13806: }
13807: 
13808: sub numval3 {
13809:     use integer;
13810:     my $txt=shift;
13811:     $txt=~tr/A-J/0-9/;
13812:     $txt=~tr/a-j/0-9/;
13813:     $txt=~tr/K-T/0-9/;
13814:     $txt=~tr/k-t/0-9/;
13815:     $txt=~tr/U-Z/0-5/;
13816:     $txt=~tr/u-z/0-5/;
13817:     $txt=~s/\D//g;
13818:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13819:     my $total;
13820:     foreach my $val (@txts) { $total+=$val; }
13821:     if ($_64bit) { $total=(($total<<32)>>32); }
13822:     return $total;
13823: }
13824: 
13825: sub digest {
13826:     my ($data)=@_;
13827:     my $digest=&Digest::MD5::md5($data);
13828:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13829:     my ($e,$f);
13830:     {
13831:         use integer;
13832:         $e=($a+$b);
13833:         $f=($c+$d);
13834:         if ($_64bit) {
13835:             $e=(($e<<32)>>32);
13836:             $f=(($f<<32)>>32);
13837:         }
13838:     }
13839:     if (wantarray) {
13840: 	return ($e,$f);
13841:     } else {
13842: 	my $g;
13843: 	{
13844: 	    use integer;
13845: 	    $g=($e+$f);
13846: 	    if ($_64bit) {
13847: 		$g=(($g<<32)>>32);
13848: 	    }
13849: 	}
13850: 	return $g;
13851:     }
13852: }
13853: 
13854: sub latest_rnd_algorithm_id {
13855:     return '64bit5';
13856: }
13857: 
13858: sub get_rand_alg {
13859:     my ($courseid)=@_;
13860:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13861:     if ($courseid) {
13862: 	return $env{"course.$courseid.rndseed"};
13863:     }
13864:     return &latest_rnd_algorithm_id();
13865: }
13866: 
13867: sub validCODE {
13868:     my ($CODE)=@_;
13869:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13870:     return 0;
13871: }
13872: 
13873: sub getCODE {
13874:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13875:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13876: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13877: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13878: 	return $Apache::lonhomework::history{'resource.CODE'};
13879:     }
13880:     return undef;
13881: }
13882: #
13883: #  Determines the random seed for a specific context:
13884: #
13885: # parameters:
13886: #   symb      - in course context the symb for the seed.
13887: #   course_id - The course id of the form domain_coursenum.
13888: #   domain    - Domain for the user.
13889: #   course    - Course for the user.
13890: #   cenv      - environment of the course.
13891: #
13892: # NOTE:
13893: #   All parameters are picked out of the environment if missing
13894: #   or not defined.
13895: #   If a symb cannot be determined the current time is used instead.
13896: #
13897: #  For a given well defined symb, courside, domain, username,
13898: #  and course environment, the seed is reproducible.
13899: #
13900: sub rndseed {
13901:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13902:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13903:     if (!defined($symb)) {
13904: 	unless ($symb=$wsymb) { return time; }
13905:     }
13906:     if (!defined $courseid) { 
13907: 	$courseid=$wcourseid; 
13908:     }
13909:     if (!defined $domain) { $domain=$wdomain; }
13910:     if (!defined $username) { $username=$wusername }
13911: 
13912:     my $which;
13913:     if (defined($cenv->{'rndseed'})) {
13914: 	$which = $cenv->{'rndseed'};
13915:     } else {
13916: 	$which =&get_rand_alg($courseid);
13917:     }
13918:     if (defined(&getCODE())) {
13919: 
13920: 	if ($which eq '64bit5') {
13921: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13922: 	} elsif ($which eq '64bit4') {
13923: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13924: 	} else {
13925: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13926: 	}
13927:     } elsif ($which eq '64bit5') {
13928: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13929:     } elsif ($which eq '64bit4') {
13930: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13931:     } elsif ($which eq '64bit3') {
13932: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13933:     } elsif ($which eq '64bit2') {
13934: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13935:     } elsif ($which eq '64bit') {
13936: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13937:     }
13938:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13939: }
13940: 
13941: sub rndseed_32bit {
13942:     my ($symb,$courseid,$domain,$username)=@_;
13943:     {
13944: 	use integer;
13945: 	my $symbchck=unpack("%32C*",$symb) << 27;
13946: 	my $symbseed=numval($symb) << 22;
13947: 	my $namechck=unpack("%32C*",$username) << 17;
13948: 	my $nameseed=numval($username) << 12;
13949: 	my $domainseed=unpack("%32C*",$domain) << 7;
13950: 	my $courseseed=unpack("%32C*",$courseid);
13951: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13952: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13953: 	#&logthis("rndseed :$num:$symb");
13954: 	if ($_64bit) { $num=(($num<<32)>>32); }
13955: 	return $num;
13956:     }
13957: }
13958: 
13959: sub rndseed_64bit {
13960:     my ($symb,$courseid,$domain,$username)=@_;
13961:     {
13962: 	use integer;
13963: 	my $symbchck=unpack("%32S*",$symb) << 21;
13964: 	my $symbseed=numval($symb) << 10;
13965: 	my $namechck=unpack("%32S*",$username);
13966: 	
13967: 	my $nameseed=numval($username) << 21;
13968: 	my $domainseed=unpack("%32S*",$domain) << 10;
13969: 	my $courseseed=unpack("%32S*",$courseid);
13970: 	
13971: 	my $num1=$symbchck+$symbseed+$namechck;
13972: 	my $num2=$nameseed+$domainseed+$courseseed;
13973: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13974: 	#&logthis("rndseed :$num:$symb");
13975: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13976: 	return "$num1,$num2";
13977:     }
13978: }
13979: 
13980: sub rndseed_64bit2 {
13981:     my ($symb,$courseid,$domain,$username)=@_;
13982:     {
13983: 	use integer;
13984: 	# strings need to be an even # of cahracters long, it it is odd the
13985:         # last characters gets thrown away
13986: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13987: 	my $symbseed=numval($symb) << 10;
13988: 	my $namechck=unpack("%32S*",$username.' ');
13989: 	
13990: 	my $nameseed=numval($username) << 21;
13991: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13992: 	my $courseseed=unpack("%32S*",$courseid.' ');
13993: 	
13994: 	my $num1=$symbchck+$symbseed+$namechck;
13995: 	my $num2=$nameseed+$domainseed+$courseseed;
13996: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13997: 	#&logthis("rndseed :$num:$symb");
13998: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13999: 	return "$num1,$num2";
14000:     }
14001: }
14002: 
14003: sub rndseed_64bit3 {
14004:     my ($symb,$courseid,$domain,$username)=@_;
14005:     {
14006: 	use integer;
14007: 	# strings need to be an even # of cahracters long, it it is odd the
14008:         # last characters gets thrown away
14009: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14010: 	my $symbseed=numval2($symb) << 10;
14011: 	my $namechck=unpack("%32S*",$username.' ');
14012: 	
14013: 	my $nameseed=numval2($username) << 21;
14014: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14015: 	my $courseseed=unpack("%32S*",$courseid.' ');
14016: 	
14017: 	my $num1=$symbchck+$symbseed+$namechck;
14018: 	my $num2=$nameseed+$domainseed+$courseseed;
14019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14020: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14022: 	
14023: 	return "$num1:$num2";
14024:     }
14025: }
14026: 
14027: sub rndseed_64bit4 {
14028:     my ($symb,$courseid,$domain,$username)=@_;
14029:     {
14030: 	use integer;
14031: 	# strings need to be an even # of cahracters long, it it is odd the
14032:         # last characters gets thrown away
14033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14034: 	my $symbseed=numval3($symb) << 10;
14035: 	my $namechck=unpack("%32S*",$username.' ');
14036: 	
14037: 	my $nameseed=numval3($username) << 21;
14038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14039: 	my $courseseed=unpack("%32S*",$courseid.' ');
14040: 	
14041: 	my $num1=$symbchck+$symbseed+$namechck;
14042: 	my $num2=$nameseed+$domainseed+$courseseed;
14043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14044: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14046: 	
14047: 	return "$num1:$num2";
14048:     }
14049: }
14050: 
14051: sub rndseed_64bit5 {
14052:     my ($symb,$courseid,$domain,$username)=@_;
14053:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14054:     return "$num1:$num2";
14055: }
14056: 
14057: sub rndseed_CODE_64bit {
14058:     my ($symb,$courseid,$domain,$username)=@_;
14059:     {
14060: 	use integer;
14061: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14062: 	my $symbseed=numval2($symb);
14063: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14064: 	my $CODEseed=numval(&getCODE());
14065: 	my $courseseed=unpack("%32S*",$courseid.' ');
14066: 	my $num1=$symbseed+$CODEchck;
14067: 	my $num2=$CODEseed+$courseseed+$symbchck;
14068: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14069: 	#&logthis("rndseed :$num1:$num2:$symb");
14070: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14071: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14072: 	return "$num1:$num2";
14073:     }
14074: }
14075: 
14076: sub rndseed_CODE_64bit4 {
14077:     my ($symb,$courseid,$domain,$username)=@_;
14078:     {
14079: 	use integer;
14080: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14081: 	my $symbseed=numval3($symb);
14082: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14083: 	my $CODEseed=numval3(&getCODE());
14084: 	my $courseseed=unpack("%32S*",$courseid.' ');
14085: 	my $num1=$symbseed+$CODEchck;
14086: 	my $num2=$CODEseed+$courseseed+$symbchck;
14087: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14088: 	#&logthis("rndseed :$num1:$num2:$symb");
14089: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14090: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14091: 	return "$num1:$num2";
14092:     }
14093: }
14094: 
14095: sub rndseed_CODE_64bit5 {
14096:     my ($symb,$courseid,$domain,$username)=@_;
14097:     my $code = &getCODE();
14098:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14099:     return "$num1:$num2";
14100: }
14101: 
14102: sub setup_random_from_rndseed {
14103:     my ($rndseed)=@_;
14104:     if ($rndseed =~/([,:])/) {
14105:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14106:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14107:             &Math::Random::random_set_seed_from_phrase($rndseed);
14108:         } else {
14109:             &Math::Random::random_set_seed($num1,$num2);
14110:         }
14111:     } else {
14112: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14113:     }
14114: }
14115: 
14116: sub latest_receipt_algorithm_id {
14117:     return 'receipt3';
14118: }
14119: 
14120: sub recunique {
14121:     my $fucourseid=shift;
14122:     my $unique;
14123:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14124: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14125: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14126:     } else {
14127: 	$unique=$perlvar{'lonReceipt'};
14128:     }
14129:     return unpack("%32C*",$unique);
14130: }
14131: 
14132: sub recprefix {
14133:     my $fucourseid=shift;
14134:     my $prefix;
14135:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14136: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14137: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14138:     } else {
14139: 	$prefix=$perlvar{'lonHostID'};
14140:     }
14141:     return unpack("%32C*",$prefix);
14142: }
14143: 
14144: sub ireceipt {
14145:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14146: 
14147:     my $return =&recprefix($fucourseid).'-';
14148: 
14149:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14150: 	$env{'request.state'} eq 'construct') {
14151: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14152: 	return $return;
14153:     }
14154: 
14155:     my $cuname=unpack("%32C*",$funame);
14156:     my $cudom=unpack("%32C*",$fudom);
14157:     my $cucourseid=unpack("%32C*",$fucourseid);
14158:     my $cusymb=unpack("%32C*",$fusymb);
14159:     my $cunique=&recunique($fucourseid);
14160:     my $cpart=unpack("%32S*",$part);
14161:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14162: 
14163: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14164: 			       
14165: 	$return.= ($cunique%$cuname+
14166: 		   $cunique%$cudom+
14167: 		   $cusymb%$cuname+
14168: 		   $cusymb%$cudom+
14169: 		   $cucourseid%$cuname+
14170: 		   $cucourseid%$cudom+
14171: 		   $cpart%$cuname+
14172: 		   $cpart%$cudom);
14173:     } else {
14174: 	$return.= ($cunique%$cuname+
14175: 		   $cunique%$cudom+
14176: 		   $cusymb%$cuname+
14177: 		   $cusymb%$cudom+
14178: 		   $cucourseid%$cuname+
14179: 		   $cucourseid%$cudom);
14180:     }
14181:     return $return;
14182: }
14183: 
14184: sub receipt {
14185:     my ($part)=@_;
14186:     my ($symb,$courseid,$domain,$name) = &whichuser();
14187:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14188: }
14189: 
14190: sub whichuser {
14191:     my ($passedsymb)=@_;
14192:     my ($symb,$courseid,$domain,$name,$publicuser);
14193:     if (defined($env{'form.grade_symb'})) {
14194: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14195: 	my $allowed=&allowed('vgr',$tmp_courseid);
14196: 	if (!$allowed &&
14197: 	    exists($env{'request.course.sec'}) &&
14198: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14199: 	    $allowed=&allowed('vgr',$tmp_courseid.
14200: 			      '/'.$env{'request.course.sec'});
14201: 	}
14202: 	if ($allowed) {
14203: 	    ($symb)=&get_env_multiple('form.grade_symb');
14204: 	    $courseid=$tmp_courseid;
14205: 	    ($domain)=&get_env_multiple('form.grade_domain');
14206: 	    ($name)=&get_env_multiple('form.grade_username');
14207: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14208: 	}
14209:     }
14210:     if (!$passedsymb) {
14211: 	$symb=&symbread();
14212:     } else {
14213: 	$symb=$passedsymb;
14214:     }
14215:     $courseid=$env{'request.course.id'};
14216:     $domain=$env{'user.domain'};
14217:     $name=$env{'user.name'};
14218:     if ($name eq 'public' && $domain eq 'public') {
14219: 	if (!defined($env{'form.username'})) {
14220: 	    $env{'form.username'}.=time.rand(10000000);
14221: 	}
14222: 	$name.=$env{'form.username'};
14223:     }
14224:     return ($symb,$courseid,$domain,$name,$publicuser);
14225: 
14226: }
14227: 
14228: # ------------------------------------------------------------ Serves up a file
14229: # returns either the contents of the file or 
14230: # -1 if the file doesn't exist
14231: #
14232: # if the target is a file that was uploaded via DOCS, 
14233: # a check will be made to see if a current copy exists on the local server,
14234: # if it does this will be served, otherwise a copy will be retrieved from
14235: # the home server for the course and stored in /home/httpd/html/userfiles on
14236: # the local server.   
14237: 
14238: sub getfile {
14239:     my ($file) = @_;
14240:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14241:     &repcopy($file);
14242:     return &readfile($file);
14243: }
14244: 
14245: sub repcopy_userfile {
14246:     my ($file)=@_;
14247:     my $londocroot = $perlvar{'lonDocRoot'};
14248:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14249:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14250:     my ($cdom,$cnum,$filename) = 
14251: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14252:     my $uri="/uploaded/$cdom/$cnum/$filename";
14253:     if (-e "$file") {
14254: # we already have a local copy, check it out
14255: 	my @fileinfo = stat($file);
14256: 	my $rtncode;
14257: 	my $info;
14258: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14259: 	if ($lwpresp ne 'ok') {
14260: # there is no such file anymore, even though we had a local copy
14261: 	    if ($rtncode eq '404') {
14262: 		unlink($file);
14263: 	    }
14264: 	    return -1;
14265: 	}
14266: 	if ($info < $fileinfo[9]) {
14267: # nice, the file we have is up-to-date, just say okay
14268: 	    return 'ok';
14269: 	} else {
14270: # the file is outdated, get rid of it
14271: 	    unlink($file);
14272: 	}
14273:     }
14274: # one way or the other, at this point, we don't have the file
14275: # construct the correct path for the file
14276:     my @parts = ($cdom,$cnum); 
14277:     if ($filename =~ m|^(.+)/[^/]+$|) {
14278: 	push @parts, split(/\//,$1);
14279:     }
14280:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14281:     foreach my $part (@parts) {
14282: 	$path .= '/'.$part;
14283: 	if (!-e $path) {
14284: 	    mkdir($path,0770);
14285: 	}
14286:     }
14287: # now the path exists for sure
14288: # get a user agent
14289:     my $transferfile=$file.'.in.transfer';
14290: # FIXME: this should flock
14291:     if (-e $transferfile) { return 'ok'; }
14292:     my $request;
14293:     $uri=~s/^\///;
14294:     my $homeserver = &homeserver($cnum,$cdom);
14295:     my $hostname = &hostname($homeserver);
14296:     my $protocol = $protocol{$homeserver};
14297:     $protocol = 'http' if ($protocol ne 'https');
14298:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14299:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14300: # did it work?
14301:     if ($response->is_error()) {
14302: 	unlink($transferfile);
14303: 	&logthis("Userfile repcopy failed for $uri");
14304: 	return -1;
14305:     }
14306: # worked, rename the transfer file
14307:     rename($transferfile,$file);
14308:     return 'ok';
14309: }
14310: 
14311: sub tokenwrapper {
14312:     my $uri=shift;
14313:     $uri=~s|^https?\://([^/]+)||;
14314:     $uri=~s|^/||;
14315:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14316:     my $token=$1;
14317:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14318:     if ($udom && $uname && $file) {
14319: 	$file=~s|(\?\.*)*$||;
14320:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14321:         my $homeserver = &homeserver($uname,$udom);
14322:         my $hostname = &hostname($homeserver);
14323:         my $protocol = $protocol{$homeserver};
14324:         $protocol = 'http' if ($protocol ne 'https');
14325:         return $protocol.'://'.$hostname.'/'.$uri.
14326:                (($uri=~/\?/)?'&':'?').'token='.$token.
14327:                                '&tokenissued='.$perlvar{'lonHostID'};
14328:     } else {
14329:         return '/adm/notfound.html';
14330:     }
14331: }
14332: 
14333: # call with reqtype HEAD: get last modification time
14334: # call with reqtype GET: get the file contents
14335: # Do not call this with reqtype GET for large files! It loads everything into memory
14336: #
14337: sub getuploaded {
14338:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14339:     $uri=~s/^\///;
14340:     my $homeserver = &homeserver($cnum,$cdom);
14341:     my $hostname = &hostname($homeserver);
14342:     my $protocol = $protocol{$homeserver};
14343:     $protocol = 'http' if ($protocol ne 'https');
14344:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14345:     my $request=new HTTP::Request($reqtype,$uri);
14346:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14347:     $$rtncode = $response->code;
14348:     if (! $response->is_success()) {
14349: 	return 'failed';
14350:     }      
14351:     if ($reqtype eq 'HEAD') {
14352: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14353:     } elsif ($reqtype eq 'GET') {
14354: 	$$info = $response->content;
14355:     }
14356:     return 'ok';
14357: }
14358: 
14359: sub readfile {
14360:     my $file = shift;
14361:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14362:     my $fh;
14363:     open($fh,"<",$file);
14364:     my $a='';
14365:     while (my $line = <$fh>) { $a .= $line; }
14366:     return $a;
14367: }
14368: 
14369: sub filelocation {
14370:     my ($dir,$file) = @_;
14371:     my $location;
14372:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14373: 
14374:     if ($file =~ m-^/adm/-) {
14375: 	$file=~s-^/adm/wrapper/-/-;
14376: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14377:     }
14378: 
14379:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14380:         $location = $file;
14381:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14382:         my ($udom,$uname,$filename)=
14383:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14384:         my $home=&homeserver($uname,$udom);
14385:         my $is_me=0;
14386:         my @ids=&current_machine_ids();
14387:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14388:         if ($is_me) {
14389:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14390:         } else {
14391:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14392:   	      $udom.'/'.$uname.'/'.$filename;
14393:         }
14394:     } elsif ($file =~ m-^/adm/-) {
14395: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14396:     } else {
14397:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14398:         $file=~s:^/(res|priv)/:/:;
14399:         my $space=$1;
14400:         if ( !( $file =~ m:^/:) ) {
14401:             $location = $dir. '/'.$file;
14402:         } else {
14403:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14404:         }
14405:     }
14406:     $location=~s://+:/:g; # remove duplicate /
14407:     while ($location=~m{/\.\./}) {
14408: 	if ($location =~ m{/[^/]+/\.\./}) {
14409: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14410: 	} else {
14411: 	    $location=~ s{/\.\./}{/}g;
14412: 	}
14413:     } #remove dir/..
14414:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14415:     return $location;
14416: }
14417: 
14418: sub hreflocation {
14419:     my ($dir,$file)=@_;
14420:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14421: 	$file=filelocation($dir,$file);
14422:     } elsif ($file=~m-^/adm/-) {
14423: 	$file=~s-^/adm/wrapper/-/-;
14424: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14425:     }
14426:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14427: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14428:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14429: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14430: 	        {/uploaded/$1/$2/}x;
14431:     }
14432:     if ($file=~ m{^/userfiles/}) {
14433: 	$file =~ s{^/userfiles/}{/uploaded/};
14434:     }
14435:     return $file;
14436: }
14437: 
14438: 
14439: 
14440: 
14441: 
14442: sub current_machine_domains {
14443:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14444: }
14445: 
14446: sub machine_domains {
14447:     my ($hostname) = @_;
14448:     my @domains;
14449:     my %hostname = &all_hostnames();
14450:     while( my($id, $name) = each(%hostname)) {
14451: #	&logthis("-$id-$name-$hostname-");
14452: 	if ($hostname eq $name) {
14453: 	    push(@domains,&host_domain($id));
14454: 	}
14455:     }
14456:     return @domains;
14457: }
14458: 
14459: sub current_machine_ids {
14460:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14461: }
14462: 
14463: sub machine_ids {
14464:     my ($hostname) = @_;
14465:     $hostname ||= &hostname($perlvar{'lonHostID'});
14466:     my @ids;
14467:     my %name_to_host = &all_names();
14468:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14469: 	return @{ $name_to_host{$hostname} };
14470:     }
14471:     return;
14472: }
14473: 
14474: sub additional_machine_domains {
14475:     my @domains;
14476:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14477:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14478:             while (my $line = <$fh>) {
14479:                 chomp($line);           
14480:                 $line =~ s/\s//g;
14481:                 push(@domains,$line);
14482:             }
14483:             close($fh);
14484:         }
14485:     }
14486:     return @domains;
14487: }
14488: 
14489: sub default_login_domain {
14490:     my $domain = $perlvar{'lonDefDomain'};
14491:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14492:     foreach my $posdom (&current_machine_domains(),
14493:                         &additional_machine_domains()) {
14494:         if (lc($posdom) eq lc($testdomain)) {
14495:             $domain=$posdom;
14496:             last;
14497:         }
14498:     }
14499:     return $domain;
14500: }
14501: 
14502: sub shared_institution {
14503:     my ($dom,$lonhost) = @_;
14504:     if ($lonhost eq '') {
14505:         $lonhost = $perlvar{'lonHostID'};
14506:     }
14507:     my $same_intdom;
14508:     my $hostintdom = &internet_dom($lonhost);
14509:     if ($hostintdom ne '') {
14510:         my %iphost = &get_iphost();
14511:         my $primary_id = &domain($dom,'primary');
14512:         my $primary_ip = &get_host_ip($primary_id);
14513:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14514:             foreach my $id (@{$iphost{$primary_ip}}) {
14515:                 my $intdom = &internet_dom($id);
14516:                 if ($intdom eq $hostintdom) {
14517:                     $same_intdom = 1;
14518:                     last;
14519:                 }
14520:             }
14521:         }
14522:     }
14523:     return $same_intdom;
14524: }
14525: 
14526: sub uses_sts {
14527:     my ($ignore_cache) = @_;
14528:     my $lonhost = $perlvar{'lonHostID'};
14529:     my $hostname = &hostname($lonhost);
14530:     my $sts_on;
14531:     if ($protocol{$lonhost} eq 'https') {
14532:         my $cachetime = 12*3600;
14533:         if (!$ignore_cache) {
14534:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14535:             if (defined($cached)) {
14536:                 return $sts_on;
14537:             }
14538:         }
14539:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14540:         my $request=new HTTP::Request('HEAD',$url);
14541:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14542:         if ($response->is_success) {
14543:             my $has_sts = $response->header('Strict-Transport-Security');
14544:             if ($has_sts eq '') {
14545:                 $sts_on = 0;
14546:             } else {
14547:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14548:                     my $maxage = $1;
14549:                     if ($maxage) {
14550:                         $sts_on = 1;
14551:                     } else {
14552:                         $sts_on = 0;
14553:                     }
14554:                 } else {
14555:                     $sts_on = 0;
14556:                 }
14557:             }
14558:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14559:         }
14560:     }
14561:     return;
14562: }
14563: 
14564: sub waf_allssl {
14565:     my ($host_name) = @_;
14566:     my $alias = &get_proxy_alias();
14567:     if ($host_name eq '') {
14568:         $host_name = $ENV{'SERVER_NAME'};
14569:     }
14570:     if (($host_name ne '') && ($alias eq $host_name)) {
14571:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14572:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14573:         if ($defdomdefaults{'waf_sslopt'}) {
14574:             return $defdomdefaults{'waf_sslopt'};
14575:         }
14576:     }
14577:     return;
14578: }
14579: 
14580: sub get_requestor_ip {
14581:     my ($r,$nolookup,$noproxy) = @_;
14582:     my $from_ip;
14583:     if (ref($r)) {
14584:         if ($r->can('useragent_ip')) {
14585:             if ($noproxy && $r->can('client_ip')) {
14586:                 $from_ip = $r->client_ip();
14587:             } else {
14588:                 $from_ip = $r->useragent_ip();
14589:             }
14590:         } elsif ($r->connection->can('remote_ip')) {
14591:             $from_ip = $r->connection->remote_ip();
14592:         } else {
14593:             $from_ip = $r->get_remote_host($nolookup);
14594:         }
14595:     } else {
14596:         $from_ip = $ENV{'REMOTE_ADDR'};
14597:     }
14598:     return $from_ip if ($noproxy); 
14599:     # Who controls proxy settings for server
14600:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14601:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14602:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14603:         if ($proxyinfo->{'vpnint'}) {
14604:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14605:                 return $from_ip;
14606:             }
14607:         }
14608:         if ($proxyinfo->{'trusted'}) {
14609:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14610:                 my $ipheader = $proxyinfo->{'ipheader'};
14611:                 my ($ip,$xfor);
14612:                 if (ref($r)) {
14613:                     if ($ipheader) {
14614:                         $ip = $r->headers_in->{$ipheader};
14615:                     }
14616:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14617:                 } else {
14618:                     if ($ipheader) {
14619:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14620:                     }
14621:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14622:                 }
14623:                 if (($ip eq '') && ($xfor ne '')) {
14624:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14625:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14626:                             $ip = $poss_ip;
14627:                             last;
14628:                         }
14629:                     }
14630:                 }
14631:                 if ($ip ne '') {
14632:                     return $ip;
14633:                 }
14634:             }
14635:         }
14636:     }
14637:     return $from_ip;
14638: }
14639: 
14640: sub get_proxy_settings {
14641:     my ($dom_in_use) = @_;
14642:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14643:     my $proxyinfo = {
14644:                        ipheader => $domdefaults{'waf_ipheader'},
14645:                        trusted  => $domdefaults{'waf_trusted'},
14646:                        vpnint   => $domdefaults{'waf_vpnint'},
14647:                        vpnext   => $domdefaults{'waf_vpnext'},
14648:                        sslopt   => $domdefaults{'waf_sslopt'},
14649:                     };
14650:     return $proxyinfo;
14651: }
14652: 
14653: sub ip_match {
14654:     my ($ip,$pattern_str) = @_;
14655:     $ip=Net::CIDR::cidrvalidate($ip);
14656:     if ($ip) {
14657:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14658:     }
14659:     return;
14660: }
14661: 
14662: sub get_proxy_alias {
14663:     my ($lonid) = @_;
14664:     if ($lonid eq '') {
14665:         $lonid = $perlvar{'lonHostID'};
14666:     }
14667:     if (!defined(&hostname($lonid))) {
14668:         return;
14669:     }
14670:     if ($lonid ne '') {
14671:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14672:         if ($cached) {
14673:             return $alias;
14674:         }
14675:         my $dom = &Apache::lonnet::host_domain($lonid);
14676:         if ($dom ne '') {
14677:             my $cachetime = 60*60*24;
14678:             my %domconfig =
14679:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14680:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14681:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14682:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14683:                 }
14684:             }
14685:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14686:         }
14687:     }
14688:     return;
14689: }
14690: 
14691: sub use_proxy_alias {
14692:     my ($r,$lonid) = @_;
14693:     my $alias = &get_proxy_alias($lonid);
14694:     if ($alias) {
14695:         my $dom = &host_domain($lonid);
14696:         if ($dom ne '') {
14697:             my $proxyinfo = &get_proxy_settings($dom);
14698:             my ($vpnint,$remote_ip);
14699:             if (ref($proxyinfo) eq 'HASH') {
14700:                 $vpnint = $proxyinfo->{'vpnint'};
14701:                 if ($vpnint) {
14702:                     $remote_ip = &get_requestor_ip($r,1,1);
14703:                 }
14704:             }
14705:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14706:                 return $alias;
14707:             }
14708:         }
14709:     }
14710:     return;
14711: }
14712: 
14713: sub alias_sso {
14714:     my ($lonid) = @_;
14715:     if ($lonid eq '') {
14716:         $lonid = $perlvar{'lonHostID'};
14717:     }
14718:     if (!defined(&hostname($lonid))) {
14719:         return;
14720:     }
14721:     if ($lonid ne '') {
14722:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14723:         if ($cached) {
14724:             return $use_alias;
14725:         }
14726:         my $dom = &Apache::lonnet::host_domain($lonid);
14727:         if ($dom ne '') {
14728:             my $cachetime = 60*60*24;
14729:             my %domconfig =
14730:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14731:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14732:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14733:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14734:                 }
14735:             }
14736:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14737:         }
14738:     }
14739:     return;
14740: }
14741: 
14742: sub get_saml_landing {
14743:     my ($lonid) = @_;
14744:     if ($lonid eq '') {
14745:         my $defdom = &default_login_domain();
14746:         my @hosts = &current_machine_ids();
14747:         if (@hosts > 1) {
14748:             foreach my $hostid (@hosts) {
14749:                 if (&host_domain($hostid) eq $defdom) {
14750:                     $lonid = $hostid;
14751:                     last;
14752:                 }
14753:             }
14754:         } else {
14755:             $lonid = $perlvar{'lonHostID'};
14756:         }
14757:         if ($lonid) {
14758:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14759:                 return;
14760:             }
14761:         } else {
14762:             return;
14763:         }
14764:     } elsif (!defined(&hostname($lonid))) {
14765:         return;
14766:     }
14767:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14768:     if ($cached) {
14769:         return $landing;
14770:     }
14771:     my $dom = &Apache::lonnet::host_domain($lonid);
14772:     if ($dom ne '') {
14773:         my $cachetime = 60*60*24;
14774:         my %domconfig =
14775:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14776:         if (ref($domconfig{'login'}) eq 'HASH') {
14777:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14778:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14779:                     $landing = 1;
14780:                 }
14781:             }
14782:         }
14783:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14784:     }
14785:     return;
14786: }
14787: 
14788: # ------------------------------------------------------------- Declutters URLs
14789: 
14790: sub declutter {
14791:     my $thisfn=shift;
14792:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14793:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14794:         $thisfn=~s{^/home/httpd/html}{};
14795:     }
14796:     $thisfn=~s/^\///;
14797:     $thisfn=~s|^adm/wrapper/||;
14798:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14799:     $thisfn=~s/^res\///;
14800:     $thisfn=~s/^priv\///;
14801:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14802:         $thisfn=~s/\?.+$//;
14803:     }
14804:     return $thisfn;
14805: }
14806: 
14807: # ------------------------------------------------------------- Clutter up URLs
14808: 
14809: sub clutter {
14810:     my $thisfn='/'.&declutter(shift);
14811:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14812: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14813:        $thisfn='/res'.$thisfn; 
14814:     }
14815:     if ($thisfn !~m|^/adm|) {
14816: 	if ($thisfn =~ m|^/ext/|) {
14817: 	    $thisfn='/adm/wrapper'.$thisfn;
14818: 	} else {
14819: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14820: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14821: 	    if ($embstyle eq 'ssi'
14822: 		|| ($embstyle eq 'hdn')
14823: 		|| ($embstyle eq 'rat')
14824: 		|| ($embstyle eq 'prv')
14825: 		|| ($embstyle eq 'ign')) {
14826: 		#do nothing with these
14827: 	    } elsif (($embstyle eq 'img') 
14828: 		|| ($embstyle eq 'emb')
14829: 		|| ($embstyle eq 'wrp')) {
14830: 		$thisfn='/adm/wrapper'.$thisfn;
14831: 	    } elsif ($embstyle eq 'unk'
14832: 		     && $thisfn!~/\.(sequence|page)$/) {
14833: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14834: 	    } else {
14835: #		&logthis("Got a blank emb style");
14836: 	    }
14837: 	}
14838:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14839:         $thisfn='/adm/wrapper'.$thisfn;
14840:     }
14841:     return $thisfn;
14842: }
14843: 
14844: sub clutter_with_no_wrapper {
14845:     my $uri = &clutter(shift);
14846:     if ($uri =~ m-^/adm/-) {
14847: 	$uri =~ s-^/adm/wrapper/-/-;
14848: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14849:     }
14850:     return $uri;
14851: }
14852: 
14853: sub freeze_escape {
14854:     my ($value)=@_;
14855:     if (ref($value)) {
14856: 	$value=&nfreeze($value);
14857: 	return '__FROZEN__'.&escape($value);
14858:     }
14859:     return &escape($value);
14860: }
14861: 
14862: 
14863: sub thaw_unescape {
14864:     my ($value)=@_;
14865:     if ($value =~ /^__FROZEN__/) {
14866: 	substr($value,0,10,undef);
14867: 	$value=&unescape($value);
14868: 	return &thaw($value);
14869:     }
14870:     return &unescape($value);
14871: }
14872: 
14873: sub correct_line_ends {
14874:     my ($result)=@_;
14875:     $$result =~s/\r\n/\n/mg;
14876:     $$result =~s/\r/\n/mg;
14877: }
14878: # ================================================================ Main Program
14879: 
14880: sub goodbye {
14881:    &logthis("Starting Shut down");
14882: #not converted to using infrastruture and probably shouldn't be
14883:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14884: #converted
14885: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14886:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14887: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14888: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14889: #1.1 only
14890: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14891: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14892: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14893: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14894:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14895:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14896:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14897:    &flushcourselogs();
14898:    &logthis("Shutting down");
14899: }
14900: 
14901: sub get_dns {
14902:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14903:     if (!$ignore_cache) {
14904: 	my ($content,$cached)=
14905: 	    &Apache::lonnet::is_cached_new('dns',$url);
14906: 	if ($cached) {
14907: 	    &$func($content,$hashref);
14908: 	    return;
14909: 	}
14910:     }
14911: 
14912:     my %alldns;
14913:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14914:         foreach my $dns (<$config>) {
14915: 	    next if ($dns !~ /^\^(\S*)/x);
14916:             my $line = $1;
14917:             my ($host,$protocol) = split(/:/,$line);
14918:             if ($protocol ne 'https') {
14919:                 $protocol = 'http';
14920:             }
14921: 	    $alldns{$host} = $protocol;
14922:         }
14923:         close($config);
14924:     }
14925:     while (%alldns) {
14926: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14927:         my ($contents,@content);
14928:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14929:             my $command = (split('/',$url))[3];
14930:             my ($dir,$file) = &parse_getdns_url($command,$url);
14931:             delete($alldns{$dns});
14932:             next if (($dir eq '') || ($file eq ''));
14933:             if (open(my $config,'<',"$dir/$file")) {
14934:                 @content = <$config>;
14935:                 close($config);
14936:             }
14937:             if ($url eq '/adm/dns/loncapaCRL') {
14938:                 $contents = join('',@content);
14939:             }
14940:         } else {
14941: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14942:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14943:             delete($alldns{$dns});
14944: 	    next if ($response->is_error());
14945:             if ($url eq '/adm/dns/loncapaCRL') {
14946:                 $contents = $response->content;
14947:             } else {
14948:                 @content = split("\n",$response->content);
14949:             }
14950:         }
14951:         if ($url eq '/adm/dns/loncapaCRL') {
14952:             return &$func($contents);
14953:         } else {
14954: 	    unless ($nocache) {
14955: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14956: 	    }
14957: 	    &$func(\@content,$hashref);
14958:             return;
14959:         }
14960:     }
14961:     my $which = (split('/',$url,4))[3];
14962:     if ($which eq 'loncapaCRL') {
14963:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14964:         if (-e $diskfile) {
14965:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14966:         } else {
14967:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14968:         }
14969:     } else {
14970:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14971:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14972:             my @content = <$config>;
14973:             close($config);
14974:             &$func(\@content,$hashref);
14975:         }
14976:     }
14977:     return;
14978: }
14979: 
14980: # ------------------------------------------------------Get DNS checksums file
14981: sub parse_dns_checksums_tab {
14982:     my ($lines,$hashref) = @_;
14983:     my $lonhost = $perlvar{'lonHostID'};
14984:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14985:     my $loncaparev = &get_server_loncaparev($machine_dom);
14986:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14987:     my $webconfdir = '/etc/httpd/conf';
14988:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14989:         $webconfdir = '/etc/apache2';
14990:     } elsif ($distro =~ /^sles(\d+)$/) {
14991:         if ($1 >= 10) {
14992:             $webconfdir = '/etc/apache2';
14993:         }
14994:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14995:         if ($1 >= 10.0) {
14996:             $webconfdir = '/etc/apache2';
14997:         }
14998:     }
14999:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15000:     my (%chksum,%revnum);
15001:     if (ref($lines) eq 'ARRAY') {
15002:         chomp(@{$lines});
15003:         my $version = shift(@{$lines});
15004:         if ($version eq $release) {  
15005:             foreach my $line (@{$lines}) {
15006:                 my ($file,$version,$shasum) = split(/,/,$line);
15007:                 if ($file =~ m{^/etc/httpd/conf}) {
15008:                     if ($webconfdir eq '/etc/apache2') {
15009:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15010:                     }
15011:                 }
15012:                 $chksum{$file} = $shasum;
15013:                 $revnum{$file} = $version;
15014:             }
15015:             if (ref($hashref) eq 'HASH') {
15016:                 %{$hashref} = (
15017:                                 sums     => \%chksum,
15018:                                 versions => \%revnum,
15019:                               );
15020:             }
15021:         }
15022:     }
15023:     return;
15024: }
15025: 
15026: sub fetch_dns_checksums {
15027:     my %checksums;
15028:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
15029:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15030:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15031:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15032:              \%checksums);
15033:     return \%checksums;
15034: }
15035: 
15036: sub fetch_crl_pemfile {
15037:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15038: }
15039: 
15040: sub save_crl_pem {
15041:     my ($content) = @_;
15042:     my ($msg,$hadchanges);
15043:     if ($content ne '') {
15044:         my $now = time;
15045:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15046:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15047:         if (open(my $fh,'>',"$tmpcrl")) {
15048:             print $fh $content;
15049:             close($fh);
15050:             if (-e $lonca) {
15051:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15052:                     my $check = <PIPE>;
15053:                     close(PIPE);
15054:                     chomp($check);
15055:                     if ($check eq 'verify OK') {
15056:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15057:                         my $backup;
15058:                         if (-e $dest) {
15059:                             if (&File::Copy::move($dest,"$dest.bak")) {
15060:                                 $backup = 'ok';
15061:                             }
15062:                         }
15063:                         if (&File::Copy::move($tmpcrl,$dest)) {
15064:                             $msg = 'ok';
15065:                             if ($backup) {
15066:                                 my (%oldnums,%newnums);
15067:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15068:                                     while (<PIPE>) {
15069:                                         $oldnums{(split(/:/))[1]} = 1;
15070:                                     }
15071:                                     close(PIPE);
15072:                                 }
15073:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15074:                                     while(<PIPE>) {
15075:                                         $newnums{(split(/:/))[1]} = 1;
15076:                                     }
15077:                                     close(PIPE);
15078:                                 }
15079:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15080:                                     unless (exists($oldnums{$key})) {
15081:                                         $hadchanges = 1;
15082:                                         last;
15083:                                     }
15084:                                 }
15085:                                 unless ($hadchanges) {
15086:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15087:                                         unless (exists($newnums{$key})) {
15088:                                             $hadchanges = 1;
15089:                                             last;
15090:                                         }
15091:                                     }
15092:                                 }
15093:                             }
15094:                         }
15095:                     } else {
15096:                         unlink($tmpcrl);
15097:                     }
15098:                 } else {
15099:                     unlink($tmpcrl);
15100:                 }
15101:             } else {
15102:                 unlink($tmpcrl);
15103:             }
15104:         }
15105:     }
15106:     return ($msg,$hadchanges);
15107: }
15108: 
15109: sub parse_getdns_url {
15110:     my ($command,$url) = @_;
15111:     my $dir = $perlvar{'lonTabDir'};
15112:     my $file;
15113:     if ($command eq 'hosts') {
15114:         $file = 'dns_hosts.tab';
15115:     } elsif ($command eq 'domain') {
15116:         $file = 'dns_domain.tab';
15117:     } elsif ($command eq 'checksums') {
15118:         my $version = (split('/',$url))[4];
15119:         $file = "dns_checksums/$version.tab",
15120:     } elsif ($command eq 'loncapaCRL') {
15121:         $dir = $perlvar{'lonCertificateDirectory'};
15122:         $file = $perlvar{'lonnetCertRevocationList'};
15123:     }
15124:     return ($dir,$file);
15125: }
15126: 
15127: # ------------------------------------------------------------ Read domain file
15128: {
15129:     my $loaded;
15130:     my %domain;
15131: 
15132:     sub parse_domain_tab {
15133: 	my ($lines) = @_;
15134: 	foreach my $line (@$lines) {
15135: 	    next if ($line =~ /^(\#|\s*$ )/x);
15136: 
15137: 	    chomp($line);
15138: 	    my ($name,@elements) = split(/:/,$line,9);
15139: 	    my %this_domain;
15140: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15141: 			       'lang_def', 'city', 'longi', 'lati',
15142: 			       'primary') {
15143: 		$this_domain{$field} = shift(@elements);
15144: 	    }
15145: 	    $domain{$name} = \%this_domain;
15146: 	}
15147:     }
15148: 
15149:     sub reset_domain_info {
15150: 	undef($loaded);
15151: 	undef(%domain);
15152:     }
15153: 
15154:     sub load_domain_tab {
15155: 	my ($ignore_cache,$nocache) = @_;
15156: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15157: 	my $fh;
15158: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15159: 	    my @lines = <$fh>;
15160: 	    &parse_domain_tab(\@lines);
15161: 	}
15162: 	close($fh);
15163: 	$loaded = 1;
15164:     }
15165: 
15166:     sub domain {
15167: 	&load_domain_tab() if (!$loaded);
15168: 
15169: 	my ($name,$what) = @_;
15170: 	return if ( !exists($domain{$name}) );
15171: 
15172: 	if (!$what) {
15173: 	    return $domain{$name}{'description'};
15174: 	}
15175: 	return $domain{$name}{$what};
15176:     }
15177: 
15178:     sub domain_info {
15179:         &load_domain_tab() if (!$loaded);
15180:         return %domain;
15181:     }
15182: 
15183: }
15184: 
15185: 
15186: # ------------------------------------------------------------- Read hosts file
15187: {
15188:     my %hostname;
15189:     my %hostdom;
15190:     my %libserv;
15191:     my $loaded;
15192:     my %name_to_host;
15193:     my %internetdom;
15194:     my %LC_dns_serv;
15195: 
15196:     sub parse_hosts_tab {
15197: 	my ($file) = @_;
15198: 	foreach my $configline (@$file) {
15199: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15200:             chomp($configline);
15201: 	    if ($configline =~ /^\^/) {
15202:                 if ($configline =~ /^\^([\w.\-]+)/) {
15203:                     $LC_dns_serv{$1} = 1;
15204:                 }
15205:                 next;
15206:             }
15207: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15208: 	    $name=~s/\s//g;
15209: 	    if ($id && $domain && $role && $name) {
15210:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15211:                     my $curr = $hostname{$id};
15212:                     my $skip;
15213:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15214:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15215:                             $skip = 1;
15216:                         } else {
15217:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15218:                         }
15219:                     }
15220:                     unless ($skip) {
15221:                         push(@{$name_to_host{$name}},$id);
15222:                     }
15223:                 } else {
15224:                     push(@{$name_to_host{$name}},$id);
15225:                 }
15226: 		$hostname{$id}=$name;
15227: 		$hostdom{$id}=$domain;
15228: 		if ($role eq 'library') { $libserv{$id}=$name; }
15229:                 if (defined($protocol)) {
15230:                     if ($protocol eq 'https') {
15231:                         $protocol{$id} = $protocol;
15232:                     } else {
15233:                         $protocol{$id} = 'http'; 
15234:                     }
15235:                 } else {
15236:                     $protocol{$id} = 'http';
15237:                 }
15238:                 if (defined($intdom)) {
15239:                     $internetdom{$id} = $intdom;
15240:                 }
15241: 	    }
15242: 	}
15243:     }
15244:     
15245:     sub reset_hosts_info {
15246: 	&purge_remembered();
15247: 	&reset_domain_info();
15248: 	&reset_hosts_ip_info();
15249:         undef(%internetdom);
15250: 	undef(%name_to_host);
15251: 	undef(%hostname);
15252: 	undef(%hostdom);
15253: 	undef(%libserv);
15254: 	undef($loaded);
15255:     }
15256: 
15257:     sub load_hosts_tab {
15258: 	my ($ignore_cache,$nocache) = @_;
15259: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15260: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15261: 	my @config = <$config>;
15262: 	&parse_hosts_tab(\@config);
15263: 	close($config);
15264: 	$loaded=1;
15265:     }
15266: 
15267:     sub hostname {
15268: 	&load_hosts_tab() if (!$loaded);
15269: 
15270: 	my ($lonid) = @_;
15271: 	return $hostname{$lonid};
15272:     }
15273: 
15274:     sub all_hostnames {
15275: 	&load_hosts_tab() if (!$loaded);
15276: 
15277: 	return %hostname;
15278:     }
15279: 
15280:     sub all_names {
15281:         my ($ignore_cache,$nocache) = @_;
15282: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15283: 
15284: 	return %name_to_host;
15285:     }
15286: 
15287:     sub all_host_domain {
15288:         &load_hosts_tab() if (!$loaded);
15289:         return %hostdom;
15290:     }
15291: 
15292:     sub all_host_intdom {
15293:         &load_hosts_tab() if (!$loaded);
15294:         return %internetdom;
15295:     }
15296: 
15297:     sub is_library {
15298: 	&load_hosts_tab() if (!$loaded);
15299: 
15300: 	return exists($libserv{$_[0]});
15301:     }
15302: 
15303:     sub all_library {
15304: 	&load_hosts_tab() if (!$loaded);
15305: 
15306: 	return %libserv;
15307:     }
15308: 
15309:     sub unique_library {
15310: 	#2x reverse removes all hostnames that appear more than once
15311:         my %unique = reverse &all_library();
15312:         return reverse %unique;
15313:     }
15314: 
15315:     sub get_servers {
15316: 	&load_hosts_tab() if (!$loaded);
15317: 
15318: 	my ($domain,$type) = @_;
15319: 	my %possible_hosts = ($type eq 'library') ? %libserv
15320: 	                                          : %hostname;
15321: 	my %result;
15322: 	if (ref($domain) eq 'ARRAY') {
15323: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15324: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15325: 		    $result{$host} = $hostname;
15326: 		}
15327: 	    }
15328: 	} else {
15329: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15330: 		if ($hostdom{$host} eq $domain) {
15331: 		    $result{$host} = $hostname;
15332: 		}
15333: 	    }
15334: 	}
15335: 	return %result;
15336:     }
15337: 
15338:     sub get_unique_servers {
15339:         my %unique = reverse &get_servers(@_);
15340: 	return reverse %unique;
15341:     }
15342: 
15343:     sub host_domain {
15344: 	&load_hosts_tab() if (!$loaded);
15345: 
15346: 	my ($lonid) = @_;
15347: 	return $hostdom{$lonid};
15348:     }
15349: 
15350:     sub all_domains {
15351: 	&load_hosts_tab() if (!$loaded);
15352: 
15353: 	my %seen;
15354: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15355: 	return @uniq;
15356:     }
15357: 
15358:     sub internet_dom {
15359:         &load_hosts_tab() if (!$loaded);
15360: 
15361:         my ($lonid) = @_;
15362:         return $internetdom{$lonid};
15363:     }
15364: 
15365:     sub is_LC_dns {
15366:         &load_hosts_tab() if (!$loaded);
15367: 
15368:         my ($hostname) = @_;
15369:         return exists($LC_dns_serv{$hostname});
15370:     }
15371: 
15372: }
15373: 
15374: { 
15375:     my %iphost;
15376:     my %name_to_ip;
15377:     my %lonid_to_ip;
15378: 
15379:     sub get_hosts_from_ip {
15380: 	my ($ip) = @_;
15381: 	my %iphosts = &get_iphost();
15382: 	if (ref($iphosts{$ip})) {
15383: 	    return @{$iphosts{$ip}};
15384: 	}
15385: 	return;
15386:     }
15387:     
15388:     sub reset_hosts_ip_info {
15389: 	undef(%iphost);
15390: 	undef(%name_to_ip);
15391: 	undef(%lonid_to_ip);
15392:     }
15393: 
15394:     sub get_host_ip {
15395: 	my ($lonid) = @_;
15396: 	if (exists($lonid_to_ip{$lonid})) {
15397: 	    return $lonid_to_ip{$lonid};
15398: 	}
15399: 	my $name=&hostname($lonid);
15400:    	my $ip = gethostbyname($name);
15401: 	return if (!$ip || length($ip) ne 4);
15402: 	$ip=inet_ntoa($ip);
15403: 	$name_to_ip{$name}   = $ip;
15404: 	$lonid_to_ip{$lonid} = $ip;
15405: 	return $ip;
15406:     }
15407:     
15408:     sub get_iphost {
15409: 	my ($ignore_cache,$nocache) = @_;
15410: 
15411: 	if (!$ignore_cache) {
15412: 	    if (%iphost) {
15413: 		return %iphost;
15414: 	    }
15415: 	    my ($ip_info,$cached)=
15416: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15417: 	    if ($cached) {
15418: 		%iphost      = %{$ip_info->[0]};
15419: 		%name_to_ip  = %{$ip_info->[1]};
15420: 		%lonid_to_ip = %{$ip_info->[2]};
15421: 		return %iphost;
15422: 	    }
15423: 	}
15424: 
15425: 	# get yesterday's info for fallback
15426: 	my %old_name_to_ip;
15427: 	my ($ip_info,$cached)=
15428: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15429: 	if ($cached) {
15430: 	    %old_name_to_ip = %{$ip_info->[1]};
15431: 	}
15432: 
15433: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15434: 	foreach my $name (keys(%name_to_host)) {
15435: 	    my $ip;
15436: 	    if (!exists($name_to_ip{$name})) {
15437: 		$ip = gethostbyname($name);
15438: 		if (!$ip || length($ip) ne 4) {
15439: 		    if (defined($old_name_to_ip{$name})) {
15440: 			$ip = $old_name_to_ip{$name};
15441: 			&logthis("Can't find $name defaulting to old $ip");
15442: 		    } else {
15443: 			&logthis("Name $name no IP found");
15444: 			next;
15445: 		    }
15446: 		} else {
15447: 		    $ip=inet_ntoa($ip);
15448: 		}
15449: 		$name_to_ip{$name} = $ip;
15450: 	    } else {
15451: 		$ip = $name_to_ip{$name};
15452: 	    }
15453: 	    foreach my $id (@{ $name_to_host{$name} }) {
15454: 		$lonid_to_ip{$id} = $ip;
15455: 	    }
15456: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15457: 	}
15458:         unless ($nocache) {
15459: 	    &do_cache_new('iphost','iphost',
15460: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15461: 		          48*60*60);
15462:         }
15463: 
15464: 	return %iphost;
15465:     }
15466: 
15467:     #
15468:     #  Given a DNS returns the loncapa host name for that DNS 
15469:     # 
15470:     sub host_from_dns {
15471:         my ($dns) = @_;
15472:         my @hosts;
15473:         my $ip;
15474: 
15475:         if (exists($name_to_ip{$dns})) {
15476:             $ip = $name_to_ip{$dns};
15477:         }
15478:         if (!$ip) {
15479:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15480:             if (length($ip) == 4) { 
15481: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15482:             }
15483:         }
15484:         if ($ip) {
15485: 	    @hosts = get_hosts_from_ip($ip);
15486: 	    return $hosts[0];
15487:         }
15488:         return undef;
15489:     }
15490: 
15491:     sub get_internet_names {
15492:         my ($lonid) = @_;
15493:         return if ($lonid eq '');
15494:         my ($idnref,$cached)=
15495:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15496:         if ($cached) {
15497:             return $idnref;
15498:         }
15499:         my $ip = &get_host_ip($lonid);
15500:         my @hosts = &get_hosts_from_ip($ip);
15501:         my %iphost = &get_iphost();
15502:         my (@idns,%seen);
15503:         foreach my $id (@hosts) {
15504:             my $dom = &host_domain($id);
15505:             my $prim_id = &domain($dom,'primary');
15506:             my $prim_ip = &get_host_ip($prim_id);
15507:             next if ($seen{$prim_ip});
15508:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15509:                 foreach my $id (@{$iphost{$prim_ip}}) {
15510:                     my $intdom = &internet_dom($id);
15511:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15512:                         push(@idns,$intdom);
15513:                     }
15514:                 }
15515:             }
15516:             $seen{$prim_ip} = 1;
15517:         }
15518:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15519:     }
15520: 
15521: }
15522: 
15523: sub all_loncaparevs {
15524:     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);
15525: }
15526: 
15527: # ---------------------------------------------------------- Read loncaparev table
15528: {
15529:     sub load_loncaparevs { 
15530:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15531:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15532:                 while (my $configline=<$config>) {
15533:                     chomp($configline);
15534:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15535:                     $loncaparevs{$hostid}=$loncaparev;
15536:                 }
15537:                 close($config);
15538:             }
15539:         }
15540:     }
15541: }
15542: 
15543: # ---------------------------------------------------------- Read serverhostID table
15544: {
15545:     sub load_serverhomeIDs {
15546:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15547:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15548:                 while (my $configline=<$config>) {
15549:                     chomp($configline);
15550:                     my ($name,$id)=split(/:/,$configline);
15551:                     $serverhomeIDs{$name}=$id;
15552:                 }
15553:                 close($config);
15554:             }
15555:         }
15556:     }
15557: }
15558: 
15559: 
15560: BEGIN {
15561: 
15562: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15563:     unless ($readit) {
15564: {
15565:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15566:     %perlvar = (%perlvar,%{$configvars});
15567: }
15568: 
15569: 
15570: # ------------------------------------------------------ Read spare server file
15571: {
15572:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15573: 
15574:     while (my $configline=<$config>) {
15575:        chomp($configline);
15576:        if ($configline) {
15577: 	   my ($host,$type) = split(':',$configline,2);
15578: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15579: 	   push(@{ $spareid{$type} }, $host);
15580:        }
15581:     }
15582:     close($config);
15583: }
15584: # ------------------------------------------------------------ Read permissions
15585: {
15586:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15587: 
15588:     while (my $configline=<$config>) {
15589: 	chomp($configline);
15590: 	if ($configline) {
15591: 	    my ($role,$perm)=split(/ /,$configline);
15592: 	    if ($perm ne '') { $pr{$role}=$perm; }
15593: 	}
15594:     }
15595:     close($config);
15596: }
15597: 
15598: # -------------------------------------------- Read plain texts for permissions
15599: {
15600:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15601: 
15602:     while (my $configline=<$config>) {
15603: 	chomp($configline);
15604: 	if ($configline) {
15605: 	    my ($short,@plain)=split(/:/,$configline);
15606:             %{$prp{$short}} = ();
15607: 	    if (@plain > 0) {
15608:                 $prp{$short}{'std'} = $plain[0];
15609:                 for (my $i=1; $i<@plain; $i++) {
15610:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15611:                 }
15612:             }
15613: 	}
15614:     }
15615:     close($config);
15616: }
15617: 
15618: # ---------------------------------------------------------- Read package table
15619: {
15620:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15621: 
15622:     while (my $configline=<$config>) {
15623: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15624: 	chomp($configline);
15625: 	my ($short,$plain)=split(/:/,$configline);
15626: 	my ($pack,$name)=split(/\&/,$short);
15627: 	if ($plain ne '') {
15628: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15629: 	    $packagetab{$short}=$plain; 
15630: 	}
15631:     }
15632:     close($config);
15633: }
15634: 
15635: # ---------------------------------------------------------- Read loncaparev table
15636: 
15637: &load_loncaparevs();
15638: 
15639: # ---------------------------------------------------------- Read serverhostID table
15640: 
15641: &load_serverhomeIDs();
15642: 
15643: # ---------------------------------------------------------- Read releaseslist XML
15644: {
15645:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15646:     if (-e $file) {
15647:         my $parser = HTML::LCParser->new($file);
15648:         while (my $token = $parser->get_token()) {
15649:             if ($token->[0] eq 'S') {
15650:                 my $item = $token->[1];
15651:                 my $name = $token->[2]{'name'};
15652:                 my $value = $token->[2]{'value'};
15653:                 my $valuematch = $token->[2]{'valuematch'};
15654:                 my $namematch = $token->[2]{'namematch'};
15655:                 if ($item eq 'parameter') {
15656:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15657:                         my $release = $parser->get_text();
15658:                         $release =~ s/(^\s*|\s*$ )//gx;
15659:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15660:                     }
15661:                 } elsif ($item ne '' && $name ne '') {
15662:                     my $release = $parser->get_text();
15663:                     $release =~ s/(^\s*|\s*$ )//gx;
15664:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15665:                 }
15666:             }
15667:         }
15668:     }
15669: }
15670: 
15671: # ---------------------------------------------------------- Read managers table
15672: {
15673:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15674:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15675:             while (my $configline=<$config>) {
15676:                 chomp($configline);
15677:                 next if ($configline =~ /^\#/);
15678:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15679:                     $managerstab{$configline} = 1;
15680:                 }
15681:             }
15682:             close($config);
15683:         }
15684:     }
15685: }
15686: 
15687: # ------------- set up temporary directory
15688: {
15689:     $tmpdir = LONCAPA::tempdir();
15690: 
15691: }
15692: 
15693: # ------------- set default texengine (domain default overrides this)
15694: {
15695:     $deftex = LONCAPA::texengine();
15696: }
15697: 
15698: # ------------- set default minimum length for passwords for internal auth users
15699: {
15700:     $passwdmin = LONCAPA::passwd_min();
15701: }
15702: 
15703: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15704: 				'compress_threshold'=> 20_000,
15705:  			        });
15706: 
15707: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15708: $dumpcount=0;
15709: $locknum=0;
15710: 
15711: &logtouch();
15712: &logthis('<font color="yellow">INFO: Read configuration</font>');
15713: $readit=1;
15714:     {
15715: 	use integer;
15716: 	my $test=(2**32)+1;
15717: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15718: 	&logthis(" Detected 64bit platform ($_64bit)");
15719:     }
15720: }
15721: }
15722: 
15723: 1;
15724: __END__
15725: 
15726: =pod
15727: 
15728: =head1 NAME
15729: 
15730: Apache::lonnet - Subroutines to ask questions about things in the network.
15731: 
15732: =head1 SYNOPSIS
15733: 
15734: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15735: 
15736:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15737: 
15738: Common parameters:
15739: 
15740: =over 4
15741: 
15742: =item *
15743: 
15744: $uname : an internal username (if $cname expecting a course Id specifically)
15745: 
15746: =item *
15747: 
15748: $udom : a domain (if $cdom expecting a course's domain specifically)
15749: 
15750: =item *
15751: 
15752: $symb : a resource instance identifier
15753: 
15754: =item *
15755: 
15756: $namespace : the name of a .db file that contains the data needed or
15757: being set.
15758: 
15759: =back
15760: 
15761: =head1 OVERVIEW
15762: 
15763: lonnet provides subroutines which interact with the
15764: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15765: about classes, users, and resources.
15766: 
15767: For many of these objects you can also use this to store data about
15768: them or modify them in various ways.
15769: 
15770: =head2 Symbs
15771: 
15772: To identify a specific instance of a resource, LON-CAPA uses symbols
15773: or "symbs"X<symb>. These identifiers are built from the URL of the
15774: map, the resource number of the resource in the map, and the URL of
15775: the resource itself. The latter is somewhat redundant, but might help
15776: if maps change.
15777: 
15778: An example is
15779: 
15780:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15781: 
15782: The respective map entry is
15783: 
15784:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15785:   title="Problem 2">
15786:  </resource>
15787: 
15788: Symbs are used by the random number generator, as well as to store and
15789: restore data specific to a certain instance of for example a problem.
15790: 
15791: =head2 Storing And Retrieving Data
15792: 
15793: X<store()>X<cstore()>X<restore()>Three of the most important functions
15794: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15795: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15796: is is the non-critical message twin of cstore. These functions are for
15797: handlers to store a perl hash to a user's permanent data space in an
15798: easy manner, and to retrieve it again on another call. It is expected
15799: that a handler would use this once at the beginning to retrieve data,
15800: and then again once at the end to send only the new data back.
15801: 
15802: The data is stored in the user's data directory on the user's
15803: homeserver under the ID of the course.
15804: 
15805: The hash that is returned by restore will have all of the previous
15806: value for all of the elements of the hash.
15807: 
15808: Example:
15809: 
15810:  #creating a hash
15811:  my %hash;
15812:  $hash{'foo'}='bar';
15813: 
15814:  #storing it
15815:  &Apache::lonnet::cstore(\%hash);
15816: 
15817:  #changing a value
15818:  $hash{'foo'}='notbar';
15819: 
15820:  #adding a new value
15821:  $hash{'bar'}='foo';
15822:  &Apache::lonnet::cstore(\%hash);
15823: 
15824:  #retrieving the hash
15825:  my %history=&Apache::lonnet::restore();
15826: 
15827:  #print the hash
15828:  foreach my $key (sort(keys(%history))) {
15829:    print("\%history{$key} = $history{$key}");
15830:  }
15831: 
15832: Will print out:
15833: 
15834:  %history{1:foo} = bar
15835:  %history{1:keys} = foo:timestamp
15836:  %history{1:timestamp} = 990455579
15837:  %history{2:bar} = foo
15838:  %history{2:foo} = notbar
15839:  %history{2:keys} = foo:bar:timestamp
15840:  %history{2:timestamp} = 990455580
15841:  %history{bar} = foo
15842:  %history{foo} = notbar
15843:  %history{timestamp} = 990455580
15844:  %history{version} = 2
15845: 
15846: Note that the special hash entries C<keys>, C<version> and
15847: C<timestamp> were added to the hash. C<version> will be equal to the
15848: total number of versions of the data that have been stored. The
15849: C<timestamp> attribute will be the UNIX time the hash was
15850: stored. C<keys> is available in every historical section to list which
15851: keys were added or changed at a specific historical revision of a
15852: hash.
15853: 
15854: B<Warning>: do not store the hash that restore returns directly. This
15855: will cause a mess since it will restore the historical keys as if the
15856: were new keys. I.E. 1:foo will become 1:1:foo etc.
15857: 
15858: Calling convention:
15859: 
15860:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15861:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15862: 
15863: For more detailed information, see lonnet specific documentation.
15864: 
15865: =head1 RETURN MESSAGES
15866: 
15867: =over 4
15868: 
15869: =item * B<con_lost>: unable to contact remote host
15870: 
15871: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15872: when the connection is brought back up
15873: 
15874: =item * B<con_failed>: unable to contact remote host and unable to save message
15875: for later delivery
15876: 
15877: =item * B<error:>: an error a occurred, a description of the error follows the :
15878: 
15879: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15880: that was requested
15881: 
15882: =back
15883: 
15884: =head1 PUBLIC SUBROUTINES
15885: 
15886: =head2 Session Environment Functions
15887: 
15888: =over 4
15889: 
15890: =item * 
15891: X<appenv()>
15892: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15893: the user envirnoment file, and will be restored for each access this
15894: user makes during this session, also modifies the %env for the current
15895: process. Optional rolesarrayref - if defined contains a reference to an array
15896: of roles which are exempt from the restriction on modifying user.role entries 
15897: in the user's environment.db and in %env.    
15898: 
15899: =item *
15900: X<delenv()>
15901: B<delenv($delthis,$regexp)>: removes all items from the session
15902: environment file that begin with $delthis. If the 
15903: optional second arg - $regexp - is true, $delthis is treated as a 
15904: regular expression, otherwise \Q$delthis\E is used. 
15905: The values are also deleted from the current processes %env.
15906: 
15907: =item * get_env_multiple($name) 
15908: 
15909: gets $name from the %env hash, it seemlessly handles the cases where multiple
15910: values may be defined and end up as an array ref.
15911: 
15912: returns an array of values
15913: 
15914: =back
15915: 
15916: =head2 User Information
15917: 
15918: =over 4
15919: 
15920: =item *
15921: X<queryauthenticate()>
15922: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15923: authentication scheme
15924: 
15925: =item *
15926: X<authenticate()>
15927: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15928: authenticate user from domain's lib servers (first use the current
15929: one). C<$upass> should be the users password.
15930: $checkdefauth is optional (value is 1 if a check should be made to
15931:    authenticate user using default authentication method, and allow
15932:    account creation if username does not have account in the domain).
15933: $clientcancheckhost is optional (value is 1 if checking whether the
15934:    server can host will occur on the client side in lonauth.pm).   
15935: 
15936: =item *
15937: X<homeserver()>
15938: B<homeserver($uname,$udom)>: find the server which has
15939: the user's directory and files (there must be only one), this caches
15940: the answer, and also caches if there is a borken connection.
15941: 
15942: =item *
15943: X<idget()>
15944: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15945: a list of student/employee IDs or clicker IDs
15946: (student/employee IDs are a unique resource in a domain, there must be 
15947: only 1 ID per username, and only 1 username per ID in a specific domain).
15948: clickerIDs are not necessarily unique, as students might share clickers.
15949: (returns hash: id=>name,id=>name)
15950: 
15951: =item *
15952: X<idrget()>
15953: B<idrget($udom,@unames)>: find the IDs behind a list of
15954: usernames (returns hash: name=>id,name=>id)
15955: 
15956: =item *
15957: X<idput()>
15958: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15959: names and associated student/employee IDs or clicker IDs.
15960: 
15961: =item *
15962: X<iddel()>
15963: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15964: student/employee ID or clicker ID username look-ups from domain.
15965: The homeserver ($uhome) and namespace ($namespace) are optional.
15966: If no $uhome is provided, it will be determined usig &homeserver()
15967: for each user.  If no $namespace is provided, the default is ids.
15968: 
15969: =item *
15970: X<updateclickers()>
15971: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15972: clicker ID-to-username look-ups in clickers.db on library server.
15973: Permitted actions are add or del (i.e., add or delete). The 
15974: clickers.db contains clickerID as keys (escaped), and each corresponding
15975: value is an escaped comma-separated list of usernames (for whom the
15976: library server is the homeserver), who registered that particular ID.
15977: If $critical is true, the update will be sent via &critical, otherwise
15978: &reply() will be used.
15979: 
15980: =item *
15981: X<rolesinit()>
15982: B<rolesinit($udom,$username)>: get user privileges.
15983: returns user role, first access and timer interval hashes
15984: 
15985: =item *
15986: X<privileged()>
15987: B<privileged($username,$domain)>: returns a true if user has a
15988: privileged and active role (i.e. su or dc), false otherwise.
15989: 
15990: =item *
15991: X<getsection()>
15992: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15993: course $cname, return section name/number or '' for "not in course"
15994: and '-1' for "no section"
15995: 
15996: =item *
15997: X<userenvironment()>
15998: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15999: passed in @what from the requested user's environment, returns a hash
16000: 
16001: =item * 
16002: X<userlog_query()>
16003: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16004: activity.log file. %filters defines filters applied when parsing the
16005: log file. These can be start or end timestamps, or the type of action
16006: - log to look for Login or Logout events, check for Checkin or
16007: Checkout, role for role selection. The response is in the form
16008: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16009: escaped strings of the action recorded in the activity.log file.
16010: 
16011: =back
16012: 
16013: =head2 User Roles
16014: 
16015: =over 4
16016: 
16017: =item *
16018: 
16019: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16020: returns codes for allowed actions.
16021: 
16022: The first argument is required, all others are optional.
16023: 
16024: $priv is the privilege being checked.
16025: $uri contains additional information about what is being checked for access (e.g.,
16026: URL, course ID etc.). 
16027: $symb is the unique resource instance identifier in a course; if needed,
16028: but not provided, it will be retrieved via a call to &symbread(). 
16029: $role is the role for which a priv is being checked (only used if priv is evb). 
16030: $clientip is the user's IP address (only used when checking for access to portfolio 
16031: files).
16032: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16033: prevents recursive calls to &allowed.
16034: 
16035:  F: full access
16036:  U,I,K: authentication modes (cxx only)
16037:  '': forbidden
16038:  1: user needs to choose course
16039:  2: browse allowed
16040:  A: passphrase authentication needed
16041:  B: access temporarily blocked because of a blocking event in a course.
16042:  D: access blocked because access is required via session initiated via deep-link 
16043: 
16044: =item *
16045: 
16046: constructaccess($url,$setpriv) : check for access to construction space URL
16047: 
16048: See if the owner domain and name in the URL match those in the
16049: expected environment.  If so, return three element list
16050: ($ownername,$ownerdomain,$ownerhome).
16051: 
16052: Otherwise return the null string.
16053: 
16054: If second argument 'setpriv' is true, it assigns the privileges,
16055: and returns the same three element list, unless the owner has
16056: blocked "ad hoc" Domain Coordinator access to the Author Space,
16057: in which case the null string is returned.
16058: 
16059: =item *
16060: 
16061: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16062: define a custom role rolename set privileges in format of lonTabs/roles.tab
16063: for system, domain, and course level. $uname and $udom are optional (current
16064: user's username and domain will be used when either of $uname or $udom are absent.
16065: 
16066: =item *
16067: 
16068: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16069: (rolesplain.tab); plain text explanation of a user role term.
16070: $type is Course (default) or Community.
16071: If $forcedefault evaluates to true, text returned will be default 
16072: text for $type. Otherwise, if this is a course, the text returned 
16073: will be a custom name for the role (if defined in the course's 
16074: environment).  If no custom name is defined the default is returned.
16075:    
16076: =item *
16077: 
16078: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16079: All arguments are optional. Returns a hash of a roles, either for
16080: co-author/assistant author roles for a user's Construction Space
16081: (default), or if $context is 'userroles', roles for the user himself,
16082: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16083: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16084: For each key, value is set to colon-separated start and end times for
16085: the role.  If no username and domain are specified, will default to
16086: current user/domain. Types, roles, and roledoms are references to arrays
16087: of role statuses (active, future or previous), roles 
16088: (e.g., cc,in, st etc.) and domains of the roles which can be used
16089: to restrict the list of roles reported. If no array ref is 
16090: provided for types, will default to return only active roles.
16091: 
16092: =item *
16093: 
16094: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16095: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16096: 
16097: Additional optional arguments are: $type (if role checking is to be restricted 
16098: to certain user status types -- previous (expired roles), active (currently
16099: available roles) or future (roles available in the future), and
16100: $hideprivileged -- if true will not report course roles for users who
16101: have active Domain Coordinator role in course's domain or in additional
16102: domains (specified in 'Domains to check for privileged users' in course
16103: environment -- set via:  Course Settings -> Classlists and staff listing).
16104: 
16105: =item *
16106: 
16107: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16108: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16109: $possdomains and $possroles are optional array refs -- to domains to check and
16110: roles to check.  If $possdomains is not specified, a dump will be done of the
16111: users' roles.db to check for a dc or su role in any domain. This can be
16112: time consuming if &privileged is called repeatedly (e.g., when displaying a
16113: classlist), so in such cases, supplying a $possdomains array is preferred, as
16114: this then allows &privileged_by_domain() to be used, which caches the identity
16115: of privileged users, eliminating the need for repeated calls to &dump().
16116: 
16117: =item *
16118: 
16119: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16120: where the outer hash keys are domains specified in the $possdomains array ref,
16121: next inner hash keys are privileged roles specified in the $roles array ref,
16122: and the innermost hash contains key = value pairs for username:domain = end:start
16123: for active or future "privileged" users with that role in that domain. To avoid
16124: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16125: innerhash are cached using priv_$role and $dom as the identifiers.
16126: 
16127: =back
16128: 
16129: =head2 User Modification
16130: 
16131: =over 4
16132: 
16133: =item *
16134: 
16135: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16136: user for the level given by URL.  Optional start and end dates (leave empty
16137: string or zero for "no date")
16138: 
16139: =item *
16140: 
16141: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16142: change a users, password, possible return values are: ok,
16143: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16144: refused
16145: 
16146: =item *
16147: 
16148: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16149: 
16150: =item *
16151: 
16152: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16153:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16154: 
16155: will update user information (firstname,middlename,lastname,generation,
16156: permanentemail), and if forceid is true, student/employee ID also.
16157: A user's institutional affiliation(s) can also be updated.
16158: User information fields will not be overwritten with empty entries 
16159: unless the field is included in the $candelete array reference.
16160: This array is included when a single user is modified via "Manage Users",
16161: or when Autoupdate.pl is run by cron in a domain.
16162: 
16163: =item *
16164: 
16165: modifystudent
16166: 
16167: modify a student's enrollment and identification information.
16168: The course id is resolved based on the current user's environment.  
16169: This means the invoking user must be a course coordinator or otherwise
16170: associated with a course.
16171: 
16172: This call is essentially a wrapper for lonnet::modifyuser and
16173: lonnet::modify_student_enrollment
16174: 
16175: Inputs: 
16176: 
16177: =over 4
16178: 
16179: =item B<$udom> Student's loncapa domain
16180: 
16181: =item B<$uname> Student's loncapa login name
16182: 
16183: =item B<$uid> Student/Employee ID
16184: 
16185: =item B<$umode> Student's authentication mode
16186: 
16187: =item B<$upass> Student's password
16188: 
16189: =item B<$first> Student's first name
16190: 
16191: =item B<$middle> Student's middle name
16192: 
16193: =item B<$last> Student's last name
16194: 
16195: =item B<$gene> Student's generation
16196: 
16197: =item B<$usec> Student's section in course
16198: 
16199: =item B<$end> Unix time of the roles expiration
16200: 
16201: =item B<$start> Unix time of the roles start date
16202: 
16203: =item B<$forceid> If defined, allow $uid to be changed
16204: 
16205: =item B<$desiredhome> server to use as home server for student
16206: 
16207: =item B<$email> Student's permanent e-mail address
16208: 
16209: =item B<$type> Type of enrollment (auto or manual)
16210: 
16211: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16212: 
16213: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16214: 
16215: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16216: 
16217: =item B<$context> role change context (shown in User Management Logs display in a course)
16218: 
16219: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16220: 
16221: =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.
16222: 
16223: =back
16224: 
16225: =item *
16226: 
16227: modify_student_enrollment
16228: 
16229: Change a student's enrollment status in a class.  The environment variable
16230: 'role.request.course' must be defined for this function to proceed.
16231: 
16232: Inputs:
16233: 
16234: =over 4
16235: 
16236: =item $udom, student's domain
16237: 
16238: =item $uname, student's name
16239: 
16240: =item $uid, student's user id
16241: 
16242: =item $first, student's first name
16243: 
16244: =item $middle
16245: 
16246: =item $last
16247: 
16248: =item $gene
16249: 
16250: =item $usec
16251: 
16252: =item $end
16253: 
16254: =item $start
16255: 
16256: =item $type
16257: 
16258: =item $locktype
16259: 
16260: =item $cid
16261: 
16262: =item $selfenroll
16263: 
16264: =item $context
16265: 
16266: =item $credits, number of credits student will earn from this class
16267: 
16268: =item $instsec, institutional course section code for student
16269: 
16270: =back
16271: 
16272: 
16273: =item *
16274: 
16275: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16276: custom role; give a custom role to a user for the level given by URL.  Specify
16277: name and domain of role author, and role name
16278: 
16279: =item *
16280: 
16281: revokerole($udom,$uname,$url,$role) : revoke a role for url
16282: 
16283: =item *
16284: 
16285: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16286: 
16287: =back
16288: 
16289: =head2 Course Infomation
16290: 
16291: =over 4
16292: 
16293: =item *
16294: 
16295: coursedescription($courseid,$options) : returns a hash of information about the
16296: specified course id, including all environment settings for the
16297: course, the description of the course will be in the hash under the
16298: key 'description'
16299: 
16300: $options is an optional parameter that if supplied is a hash reference that controls
16301: what how this function works.  It has the following key/values:
16302: 
16303: =over 4
16304: 
16305: =item freshen_cache
16306: 
16307: If defined, and the environment cache for the course is valid, it is 
16308: returned in the returned hash.
16309: 
16310: =item one_time
16311: 
16312: If defined, the last cache time is set to _now_
16313: 
16314: =item user
16315: 
16316: If defined, the supplied username is used instead of the current user.
16317: 
16318: 
16319: =back
16320: 
16321: =item *
16322: 
16323: resdata($name,$domain,$type,@which) : request for current parameter
16324: setting for a specific $type, where $type is either 'course' or 'user',
16325: @what should be a list of parameters to ask about. This routine caches
16326: answers for 10 minutes.
16327: 
16328: =item *
16329: 
16330: get_courseresdata($courseid, $domain) : dump the entire course resource
16331: data base, returning a hash that is keyed by the resource name and has
16332: values that are the resource value.  I believe that the timestamps and
16333: versions are also returned.
16334: 
16335: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16336: supplemental content area. This routine caches the number of files for 
16337: 10 minutes.
16338: 
16339: =back
16340: 
16341: =head2 Course Modification
16342: 
16343: =over 4
16344: 
16345: =item *
16346: 
16347: writecoursepref($courseid,%prefs) : write preferences (environment
16348: database) for a course
16349: 
16350: =item *
16351: 
16352: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16353: 
16354: =item *
16355: 
16356: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16357: 
16358: =item *
16359: 
16360: is_course($courseid), is_course($cdom, $cnum)
16361: 
16362: Accepts either a combined $courseid (in the form of domain_courseid) or the
16363: two component version $cdom, $cnum. It checks if the specified course exists.
16364: 
16365: Returns:
16366:     undef if the course doesn't exist, otherwise
16367:     in scalar context the combined courseid.
16368:     in list context the two components of the course identifier, domain and 
16369:     courseid.    
16370: 
16371: =back
16372: 
16373: =head2 Bubblesheet Configuration
16374: 
16375: =over 4
16376: 
16377: =item *
16378: 
16379: get_scantron_config($which)
16380: 
16381: $which - the name of the configuration to parse from the file.
16382: 
16383: Parses and returns the bubblesheet configuration line selected as a
16384: hash of configuration file fields.
16385: 
16386: 
16387: Returns:
16388:     If the named configuration is not in the file, an empty
16389:     hash is returned.
16390: 
16391:     a hash with the fields
16392:       name         - internal name for the this configuration setup
16393:       description  - text to display to operator that describes this config
16394:       CODElocation - if 0 or the string 'none'
16395:                           - no CODE exists for this config
16396:                      if -1 || the string 'letter'
16397:                           - a CODE exists for this config and is
16398:                             a string of letters
16399:                      Unsupported value (but planned for future support)
16400:                           if a positive integer
16401:                                - The CODE exists as the first n items from
16402:                                  the question section of the form
16403:                           if the string 'number'
16404:                                - The CODE exists for this config and is
16405:                                  a string of numbers
16406:       CODEstart   - (only matter if a CODE exists) column in the line where
16407:                      the CODE starts
16408:       CODElength  - length of the CODE
16409:       IDstart     - column where the student/employee ID starts
16410:       IDlength    - length of the student/employee ID info
16411:       Qstart      - column where the information from the bubbled
16412:                     'questions' start
16413:       Qlength     - number of columns comprising a single bubble line from
16414:                     the sheet. (usually either 1 or 10)
16415:       Qon         - either a single character representing the character used
16416:                     to signal a bubble was chosen in the positional setup, or
16417:                     the string 'letter' if the letter of the chosen bubble is
16418:                     in the final, or 'number' if a number representing the
16419:                     chosen bubble is in the file (1->A 0->J)
16420:       Qoff        - the character used to represent that a bubble was
16421:                     left blank
16422:       PaperID     - if the scanning process generates a unique number for each
16423:                     sheet scanned the column that this ID number starts in
16424:       PaperIDlength - number of columns that comprise the unique ID number
16425:                       for the sheet of paper
16426:       FirstName   - column that the first name starts in
16427:       FirstNameLength - number of columns that the first name spans
16428:       LastName    - column that the last name starts in
16429:       LastNameLength - number of columns that the last name spans
16430:       BubblesPerRow - number of bubbles available in each row used to
16431:                       bubble an answer. (If not specified, 10 assumed).
16432: 
16433: 
16434: =item *
16435: 
16436: get_scantronformat_file($cdom)
16437: 
16438: $cdom - the course's domain (optional); if not supplied, uses
16439: domain for current $env{'request.course.id'}.
16440: 
16441: Returns an array containing lines from the scantron format file for
16442: the domain of the course.
16443: 
16444: If a url for a custom.tab file is listed in domain's configuration.db,
16445: lines are from this file.
16446: 
16447: Otherwise, if a default.tab has been published in RES space by the
16448: domainconfig user, lines are from this file.
16449: 
16450: Otherwise, fall back to getting lines from the legacy file on the
16451: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16452: 
16453: =back
16454: 
16455: =head2 Resource Subroutines
16456: 
16457: =over 4
16458: 
16459: =item *
16460: 
16461: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16462: 
16463: =item *
16464: 
16465: repcopy($filename) : subscribes to the requested file, and attempts to
16466: replicate from the owning library server, Might return
16467: 'unavailable', 'not_found', 'forbidden', 'ok', or
16468: 'bad_request', also attempts to grab the metadata for the
16469: resource. Expects the local filesystem pathname
16470: (/home/httpd/html/res/....)
16471: 
16472: =back
16473: 
16474: =head2 Resource Information
16475: 
16476: =over 4
16477: 
16478: =item *
16479: 
16480: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16481: and returns the value of a variety of different possible values,
16482: $varname should be a request string, and the other parameters can be
16483: used to specify who and what one is asking about. Ordinarily, $cid 
16484: does not need to be specified, as it is retrived from 
16485: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16486: within lonuserstate::loadmap() when initializing a course, before
16487: $env{'request.course.id'} has been set, so it needs to be provided
16488: in that one case.
16489: 
16490: Possible values for $varname are environment.lastname (or other item
16491: from the envirnment hash), user.name (or someother aspect about the
16492: user), resource.0.maxtries (or some other part and parameter of a
16493: resource)
16494: 
16495: =item *
16496: 
16497: directcondval($number) : get current value of a condition; reads from a state
16498: string
16499: 
16500: =item *
16501: 
16502: condval($condidx) : value of condition index based on state
16503: 
16504: =item *
16505: 
16506: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16507: resource's metadata, $what should be either a specific key, or either
16508: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16509: packages that this resource currently uses, the last 3 arguments are 
16510: only used internally for recursive metadata.
16511: 
16512: the toolsymb is only used where the uri is for an external tool (for which
16513: the uri as well as the symb are guaranteed to be unique).
16514: 
16515: this function automatically caches all requests except any made recursively
16516: to retrieve a list of metadata keys for an imported library file ($liburi is 
16517: defined).
16518: 
16519: =item *
16520: 
16521: metadata_query($query,$custom,$customshow) : make a metadata query against the
16522: network of library servers; returns file handle of where SQL and regex results
16523: will be stored for query
16524: 
16525: =item *
16526: 
16527: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16528: return symbolic list entry (all arguments optional). 
16529: 
16530: Args: filename is the filename (including path) for the file for which a symb 
16531: is required; donotrecurse, if true will prevent calls to allowed() being made 
16532: to check access status if more than one resource was found in the bighash 
16533: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16534: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16535: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16536: cause possible symbs to be checked to determine if they are subject to content
16537: blocking, if so they will not be included as possible symbs; possibles is a
16538: ref to a hash, which, as a side effect, will be populated with all possible 
16539: symbs (content blocking not tested).
16540:  
16541: returns the data handle
16542: 
16543: =item *
16544: 
16545: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16546: and is a possible symb for the URL in $thisfn, and if is an encrypted
16547: resource that the user accessed using /enc/ returns a 1 on success, 0
16548: on failure, user must be in a course, as it assumes the existence of
16549: the course initial hash, and uses $env('request.course.id'}.  The third
16550: arg is an optional reference to a scalar.  If this arg is passed in the 
16551: call to symbverify, it will be set to 1 if the symb has been set to be 
16552: encrypted; otherwise it will be null.  
16553: 
16554: =item *
16555: 
16556: symbclean($symb) : removes versions numbers from a symb, returns the
16557: cleaned symb
16558: 
16559: =item *
16560: 
16561: is_on_map($uri) : checks if the $uri is somewhere on the current
16562: course map, user must be in a course for it to work.
16563: 
16564: =item *
16565: 
16566: numval($salt) : return random seed value (addend for rndseed)
16567: 
16568: =item *
16569: 
16570: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16571: a random seed, all arguments are optional, if they aren't sent it uses the
16572: environment to derive them. Note: if symb isn't sent and it can't get one
16573: from &symbread it will use the current time as its return value
16574: 
16575: =item *
16576: 
16577: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16578: unfakeable, receipt
16579: 
16580: =item *
16581: 
16582: receipt() : API to ireceipt working off of env values; given out to users
16583: 
16584: =item *
16585: 
16586: countacc($url) : count the number of accesses to a given URL
16587: 
16588: =item *
16589: 
16590: 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
16591: 
16592: =item *
16593: 
16594: 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)
16595: 
16596: =item *
16597: 
16598: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16599: 
16600: =item *
16601: 
16602: devalidate($symb) : devalidate temporary spreadsheet calculations,
16603: forcing spreadsheet to reevaluate the resource scores next time.
16604: 
16605: =item * 
16606: 
16607: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16608: when viewing in course context.
16609: 
16610:  input: six args -- filename (decluttered), course number, course domain,
16611:                     url, symb (if registered) and group (if this is a 
16612:                     group item -- e.g., bulletin board, group page etc.).
16613: 
16614:  output: array of five scalars --
16615:          $cfile -- url for file editing if editable on current server
16616:          $home -- homeserver of resource (i.e., for author if published,
16617:                                           or course if uploaded.).
16618:          $switchserver --  1 if server switch will be needed.
16619:          $forceedit -- 1 if icon/link should be to go to edit mode 
16620:          $forceview -- 1 if icon/link should be to go to view mode
16621: 
16622: =item *
16623: 
16624: is_course_upload($file,$cnum,$cdom)
16625: 
16626: Used in course context to determine if current file was uploaded to 
16627: the course (i.e., would be found in /userfiles/docs on the course's 
16628: homeserver.
16629: 
16630:   input: 3 args -- filename (decluttered), course number and course domain.
16631:   output: boolean -- 1 if file was uploaded.
16632: 
16633: =back
16634: 
16635: =head2 Storing/Retreiving Data
16636: 
16637: =over 4
16638: 
16639: =item *
16640: 
16641: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16642: permanently for this url; hashref needs to be given and should be a \%hashname;
16643: the remaining args aren't required and if they aren't passed or are '' they will
16644: be derived from the env (with the exception of $laststore, which is an 
16645: optional arg used when a user's submission is stored in grading).
16646: $laststore is $version=$timestamp, where $version is the most recent version
16647: number retrieved for the corresponding $symb in the $namespace db file, and
16648: $timestamp is the timestamp for that transaction (UNIX time).
16649: $laststore is currently only passed when cstore() is called by 
16650: structuretags::finalize_storage().
16651: 
16652: =item *
16653: 
16654: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16655: but uses critical subroutine
16656: 
16657: =item *
16658: 
16659: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16660: all args are optional
16661: 
16662: =item *
16663: 
16664: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16665: dumps the complete (or key matching regexp) namespace into a hash
16666: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16667: normally &store()ed into
16668: 
16669: $range should be either an integer '100' (give me the first 100
16670:                                            matching records)
16671:               or be  two integers sperated by a - with no spaces
16672:                  '30-50' (give me the 30th through the 50th matching
16673:                           records)
16674: 
16675: 
16676: =item *
16677: 
16678: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16679: replaces a &store() version of data with a replacement set of data
16680: for a particular resource in a namespace passed in the $storehash hash 
16681: reference. If $tolog is true, the transaction is logged in the courselog
16682: with an action=PUTSTORE.
16683: 
16684: =item *
16685: 
16686: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16687: works very similar to store/cstore, but all data is stored in a
16688: temporary location and can be reset using tmpreset, $storehash should
16689: be a hash reference, returns nothing on success
16690: 
16691: =item *
16692: 
16693: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16694: similar to restore, but all data is stored in a temporary location and
16695: can be reset using tmpreset. Returns a hash of values on success,
16696: error string otherwise.
16697: 
16698: =item *
16699: 
16700: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16701: deltes all keys for $symb form the temporary storage hash.
16702: 
16703: =item *
16704: 
16705: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16706: reference filled in from namesp ($udom and $uname are optional)
16707: 
16708: =item *
16709: 
16710: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16711: namesp ($udom and $uname are optional)
16712: 
16713: =item *
16714: 
16715: dump($namespace,$udom,$uname,$regexp,$range) : 
16716: dumps the complete (or key matching regexp) namespace into a hash
16717: ($udom, $uname, $regexp, $range are optional)
16718: 
16719: $range should be either an integer '100' (give me the first 100
16720:                                            matching records)
16721:               or be  two integers sperated by a - with no spaces
16722:                  '30-50' (give me the 30th through the 50th matching
16723:                           records)
16724: =item *
16725: 
16726: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16727: $store can be a scalar, an array reference, or if the amount to be 
16728: incremented is > 1, a hash reference.
16729: 
16730: ($udom and $uname are optional)
16731: 
16732: =item *
16733: 
16734: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16735: ($udom and $uname are optional)
16736: 
16737: =item *
16738: 
16739: cput($namespace,$storehash,$udom,$uname) : critical put
16740: ($udom and $uname are optional)
16741: 
16742: =item *
16743: 
16744: newput($namespace,$storehash,$udom,$uname) :
16745: 
16746: Attempts to store the items in the $storehash, but only if they don't
16747: currently exist, if this succeeds you can be certain that you have 
16748: successfully created a new key value pair in the $namespace db.
16749: 
16750: 
16751: Args:
16752:  $namespace: name of database to store values to
16753:  $storehash: hashref to store to the db
16754:  $udom: (optional) domain of user containing the db
16755:  $uname: (optional) name of user caontaining the db
16756: 
16757: Returns:
16758:  'ok' -> succeeded in storing all keys of $storehash
16759:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16760:                         least <key> already existed in the db (other
16761:                         requested keys may also already exist)
16762:  'error: <msg>' -> unable to tie the DB or other error occurred
16763:  'con_lost' -> unable to contact request server
16764:  'refused' -> action was not allowed by remote machine
16765: 
16766: 
16767: =item *
16768: 
16769: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16770: reference filled in from namesp (encrypts the return communication)
16771: ($udom and $uname are optional)
16772: 
16773: =item *
16774: 
16775: log($udom,$name,$home,$message) : write to permanent log for user; use
16776: critical subroutine
16777: 
16778: =item *
16779: 
16780: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16781: array reference filled in from namespace found in domain level on either
16782: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16783: 
16784: =item *
16785: 
16786: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16787: domain level either on specified domain server ($uhome) or primary domain 
16788: server ($udom and $uhome are optional)
16789: 
16790: =item * 
16791: 
16792: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16793: for: authentication, language, quotas, timezone, date locale, and portal URL in
16794: the target domain.
16795: 
16796: May also include additional key => value pairs for the following groups:
16797: 
16798: =over
16799: 
16800: =item
16801: disk quotas (MB allocated by default to portfolios and authoring spaces).
16802: 
16803: =over
16804: 
16805: =item defaultquota, authorquota
16806: 
16807: =back
16808: 
16809: =item
16810: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16811: portfolio for users).
16812: 
16813: =over
16814: 
16815: =item
16816: aboutme, blog, webdav, portfolio
16817: 
16818: =back
16819: 
16820: =item
16821: requestcourses: ability to request courses, and how requests are processed.
16822: 
16823: =over
16824: 
16825: =item
16826: official, unofficial, community, textbook, placement
16827: 
16828: =back
16829: 
16830: =item
16831: inststatus: types of institutional affiliation, and order in which they are displayed.
16832: 
16833: =over
16834: 
16835: =item
16836: inststatustypes, inststatusorder, inststatusguest
16837: 
16838: =back
16839: 
16840: =item
16841: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16842: for course's uploaded content.
16843: 
16844: =over
16845: 
16846: =item
16847: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16848: communityquota, textbookquota, placementquota
16849: 
16850: =back
16851: 
16852: =item
16853: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16854: on your servers.
16855: 
16856: =over
16857: 
16858: =item 
16859: remotesessions, hostedsessions
16860: 
16861: =back
16862: 
16863: =back
16864: 
16865: In cases where a domain coordinator has never used the "Set Domain Configuration"
16866: utility to create a configuration.db file on a domain's primary library server 
16867: only the following domain defaults: auth_def, auth_arg_def, lang_def
16868: -- corresponding values are authentication type (internal, krb4, krb5,
16869: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16870: will be available. Values are retrieved from cache (if current), unless the
16871: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16872: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16873: 
16874: Typical usage:
16875: 
16876: %domdefaults = &get_domain_defaults($target_domain);
16877: 
16878: =back
16879: 
16880: =head2 Network Status Functions
16881: 
16882: =over 4
16883: 
16884: =item *
16885: 
16886: dirlist() : return directory list based on URI (first arg).
16887: 
16888: Inputs: 1 required, 5 optional.
16889: 
16890: =over
16891: 
16892: =item 
16893: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16894: 
16895: =item
16896: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16897: 
16898: =item
16899: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16900: 
16901: =item
16902: $getpropath - boolean: 1 if prepend path using &propath(). 
16903: 
16904: =item
16905: $getuserdir - boolean: 1 if prepend path for "userfiles".
16906: 
16907: =item 
16908: $alternateRoot - path to prepend in place of path from $uri.
16909: 
16910: =back
16911: 
16912: Returns: Array of up to two items.
16913: 
16914: =over
16915: 
16916: a reference to an array of files/subdirectories
16917: 
16918: =over
16919: 
16920: Each element in the array of files/subdirectories is a & separated list of
16921: item name and the result of running stat on the item.  If dirlist was requested
16922: for a file instead of a directory, the item name will be ''. For a directory 
16923: listing, if the item is a metadata file, the element will end &N&M 
16924: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16925: default copyright set (1).  
16926: 
16927: =back
16928: 
16929: a scalar containing error condition (if encountered).
16930: 
16931: =over
16932: 
16933: =item 
16934: no_host (no homeserver identified for $username:$domain).
16935: 
16936: =item 
16937: no_such_host (server contacted for listing not identified as valid host).
16938: 
16939: =item 
16940: con_lost (connection to remote server failed).
16941: 
16942: =item 
16943: refused (invalid $username:$domain received on lond side).
16944: 
16945: =item 
16946: no_such_dir (directory at specified path on lond side does not exist). 
16947: 
16948: =item 
16949: empty (directory at specified path on lond side is empty).
16950: 
16951: =over
16952: 
16953: This is currently not encountered because the &ls3, &ls2, 
16954: &ls (_handler) routines on the lond side do not filter out
16955: . and .. from a directory listing. 
16956: 
16957: =back
16958: 
16959: =back
16960: 
16961: =back
16962: 
16963: =item *
16964: 
16965: spareserver() : find server with least workload from spare.tab
16966: 
16967: 
16968: =item *
16969: 
16970: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16971: if there is no corresponding loncapa host.
16972: 
16973: =back
16974: 
16975: 
16976: =head2 Apache Request
16977: 
16978: =over 4
16979: 
16980: =item *
16981: 
16982: ssi($url,%hash) : server side include, does a complete request cycle on url to
16983: localhost, posts hash
16984: 
16985: =back
16986: 
16987: =head2 Data to String to Data
16988: 
16989: =over 4
16990: 
16991: =item *
16992: 
16993: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16994: and '&' separators, supports elements that are arrayrefs and hashrefs
16995: 
16996: =item *
16997: 
16998: hashref2str($hashref) : convert a hashref into a string complete with
16999: escaping and '=' and '&' separators, supports elements that are
17000: arrayrefs and hashrefs
17001: 
17002: =item *
17003: 
17004: arrayref2str($arrayref) : convert an arrayref into a string complete
17005: with escaping and '&' separators, supports elements that are arrayrefs
17006: and hashrefs
17007: 
17008: =item *
17009: 
17010: str2hash($string) : convert string to hash using unescaping and
17011: splitting on '=' and '&', supports elements that are arrayrefs and
17012: hashrefs
17013: 
17014: =item *
17015: 
17016: str2array($string) : convert string to hash using unescaping and
17017: splitting on '&', supports elements that are arrayrefs and hashrefs
17018: 
17019: =back
17020: 
17021: =head2 Logging Routines
17022: 
17023: 
17024: These routines allow one to make log messages in the lonnet.log and
17025: lonnet.perm logfiles.
17026: 
17027: =over 4
17028: 
17029: =item *
17030: 
17031: logtouch() : make sure the logfile, lonnet.log, exists
17032: 
17033: =item *
17034: 
17035: logthis() : append message to the normal lonnet.log file, it gets
17036: preiodically rolled over and deleted.
17037: 
17038: =item *
17039: 
17040: logperm() : append a permanent message to lonnet.perm.log, this log
17041: file never gets deleted by any automated portion of the system, only
17042: messages of critical importance should go in here.
17043: 
17044: 
17045: =back
17046: 
17047: =head2 General File Helper Routines
17048: 
17049: =over 4
17050: 
17051: =item *
17052: 
17053: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17054: (a) files in /uploaded
17055:   (i) If a local copy of the file exists - 
17056:       compares modification date of local copy with last-modified date for 
17057:       definitive version stored on home server for course. If local copy is 
17058:       stale, requests a new version from the home server and stores it. 
17059:       If the original has been removed from the home server, then local copy 
17060:       is unlinked.
17061:   (ii) If local copy does not exist -
17062:       requests the file from the home server and stores it. 
17063:   
17064:   If $caller is 'uploadrep':  
17065:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17066:     for request for files originally uploaded via DOCS. 
17067:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17068:   
17069:   Otherwise:
17070:      This indicates a call from the content generation phase of the request.
17071:      -  returns the entire contents of the file or -1.
17072:      
17073: (b) files in /res
17074:    - returns the entire contents of a file or -1; 
17075:    it properly subscribes to and replicates the file if neccessary.
17076: 
17077: 
17078: =item *
17079: 
17080: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17081:                   reference
17082: 
17083: returns either a stat() list of data about the file or an empty list
17084: if the file doesn't exist or couldn't find out about it (connection
17085: problems or user unknown)
17086: 
17087: =item *
17088: 
17089: filelocation($dir,$file) : returns file system location of a file
17090: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17091: directory that relative $file lookups are to looked in ($dir of /a/dir
17092: and a file of ../bob will become /a/bob)
17093: 
17094: =item *
17095: 
17096: hreflocation($dir,$file) : returns file system location or a URL; same as
17097: filelocation except for hrefs
17098: 
17099: =item *
17100: 
17101: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17102: also removes beginning /home/httpd/html unless /priv/ follows it.
17103: 
17104: =back
17105: 
17106: =head2 Usererfile file routines (/uploaded*)
17107: 
17108: =over 4
17109: 
17110: =item *
17111: 
17112: userfileupload(): main rotine for putting a file in a user or course's
17113:                   filespace, arguments are,
17114: 
17115:  formname - required - this is the name of the element in $env where the
17116:            filename, and the contents of the file to create/modifed exist
17117:            the filename is in $env{'form.'.$formname.'.filename'} and the
17118:            contents of the file is located in $env{'form.'.$formname}
17119:  context - if coursedoc, store the file in the course of the active role
17120:              of the current user; 
17121:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17122:            if 'canceloverwrite': delete file in tmp/overwrites directory
17123:  subdir - required - subdirectory to put the file in under ../userfiles/
17124:          if undefined, it will be placed in "unknown"
17125: 
17126:  (This routine calls clean_filename() to remove any dangerous
17127:  characters from the filename, and then calls finuserfileupload() to
17128:  complete the transaction)
17129: 
17130:  returns either the url of the uploaded file (/uploaded/....) if successful
17131:  and /adm/notfound.html if unsuccessful
17132: 
17133: =item *
17134: 
17135: clean_filename(): routine for cleaing a filename up for storage in
17136:                  userfile space, argument is:
17137: 
17138:  filename - proposed filename
17139: 
17140: returns: the new clean filename
17141: 
17142: =item *
17143: 
17144: finishuserfileupload(): routine that creates and sends the file to
17145: userspace, probably shouldn't be called directly
17146: 
17147:   docuname: username or courseid of destination for the file
17148:   docudom: domain of user/course of destination for the file
17149:   formname: same as for userfileupload()
17150:   fname: filename (including subdirectories) for the file
17151:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17152:           if hashref, and context is scantron, will convert csv format to standard format
17153:   allfiles: reference to hash used to store objects found by parser
17154:   codebase: reference to hash used for codebases of java objects found by parser
17155:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17156:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17157:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17158:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17159:   context: if 'overwrite', will move the uploaded file from its temporary location to
17160:             userfiles to facilitate overwriting a previously uploaded file with same name.
17161:   mimetype: reference to scalar to accommodate mime type determined
17162:             from File::MMagic if $parser = parse.
17163: 
17164:  returns either the url of the uploaded file (/uploaded/....) if successful
17165:  and /adm/notfound.html if unsuccessful (or an error message if context 
17166:  was 'overwrite').
17167:  
17168: 
17169: =item *
17170: 
17171: renameuserfile(): renames an existing userfile to a new name
17172: 
17173:   Args:
17174:    docuname: username or courseid of destination for the file
17175:    docudom: domain of user/course of destination for the file
17176:    old: current file name (including any subdirs under userfiles)
17177:    new: desired file name (including any subdirs under userfiles)
17178: 
17179: =item *
17180: 
17181: mkdiruserfile(): creates a directory is a userfiles dir
17182: 
17183:   Args:
17184:    docuname: username or courseid of destination for the file
17185:    docudom: domain of user/course of destination for the file
17186:    dir: dir to create (including any subdirs under userfiles)
17187: 
17188: =item *
17189: 
17190: removeuserfile(): removes a file that exists in userfiles
17191: 
17192:   Args:
17193:    docuname: username or courseid of destination for the file
17194:    docudom: domain of user/course of destination for the file
17195:    fname: filname to delete (including any subdirs under userfiles)
17196: 
17197: =item *
17198: 
17199: removeuploadedurl(): convience function for removeuserfile()
17200: 
17201:   Args:
17202:    url:  a full /uploaded/... url to delete
17203: 
17204: =item * 
17205: 
17206: get_portfile_permissions():
17207:   Args:
17208:     domain: domain of user or course contain the portfolio files
17209:     user: name of user or num of course contain the portfolio files
17210:   Returns:
17211:     hashref of a dump of the proper file_permissions.db
17212:    
17213: 
17214: =item * 
17215: 
17216: get_access_controls():
17217: 
17218: Args:
17219:   current_permissions: the hash ref returned from get_portfile_permissions()
17220:   group: (optional) the group you want the files associated with
17221:   file: (optional) the file you want access info on
17222: 
17223: Returns:
17224:     a hash (keys are file names) of hashes containing
17225:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17226:         values are XML containing access control settings (see below) 
17227: 
17228: Internal notes:
17229: 
17230:  access controls are stored in file_permissions.db as key=value pairs.
17231:     key -> path to file/file_name\0uniqueID:scope_end_start
17232:         where scope -> public,guest,course,group,domains or users.
17233:               end -> UNIX time for end of access (0 -> no end date)
17234:               start -> UNIX time for start of access
17235: 
17236:     value -> XML description of access control
17237:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17238:             <start></start>
17239:             <end></end>
17240: 
17241:             <password></password>  for scope type = guest
17242: 
17243:             <domain></domain>     for scope type = course or group
17244:             <number></number>
17245:             <roles id="">
17246:              <role></role>
17247:              <access></access>
17248:              <section></section>
17249:              <group></group>
17250:             </roles>
17251: 
17252:             <dom></dom>         for scope type = domains
17253: 
17254:             <users>             for scope type = users
17255:              <user>
17256:               <uname></uname>
17257:               <udom></udom>
17258:              </user>
17259:             </users>
17260:            </scope> 
17261:               
17262:  Access data is also aggregated for each file in an additional key=value pair:
17263:  key -> path to file/file_name\0accesscontrol 
17264:  value -> reference to hash
17265:           hash contains key = value pairs
17266:           where key = uniqueID:scope_end_start
17267:                 value = UNIX time record was last updated
17268: 
17269:           Used to improve speed of look-ups of access controls for each file.  
17270:  
17271:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17272: 
17273: =item *
17274: 
17275: modify_access_controls():
17276: 
17277: Modifies access controls for a portfolio file
17278: Args
17279: 1. file name
17280: 2. reference to hash of required changes,
17281: 3. domain
17282: 4. username
17283:   where domain,username are the domain of the portfolio owner 
17284:   (either a user or a course) 
17285: 
17286: Returns:
17287: 1. result of additions or updates ('ok' or 'error', with error message). 
17288: 2. result of deletions ('ok' or 'error', with error message).
17289: 3. reference to hash of any new or updated access controls.
17290: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17291:    key = integer (inbound ID)
17292:    value = uniqueID
17293: 
17294: =item *
17295: 
17296: get_timebased_id():
17297: 
17298: Attempts to get a unique timestamp-based suffix for use with items added to a 
17299: course via the Course Editor (e.g., folders, composite pages, 
17300: group bulletin boards).
17301: 
17302: Args: (first three required; six others optional)
17303: 
17304: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17305:    docssequence, or name of group
17306: 
17307: 2. keyid (alphanumeric): name of temporary locking key in hash,
17308:    e.g., num, boardids
17309: 
17310: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17311:    file will be named nohist_namespace.db
17312: 
17313: 4. cdom: domain of course; default is current course domain from %env
17314: 
17315: 5. cnum: course number; default is current course number from %env
17316: 
17317: 6. idtype: set to concat if an additional digit is to be appended to the 
17318:    unix timestamp to form the suffix, if the plain timestamp is already
17319:    in use.  Default is to not do this, but simply increment the unix 
17320:    timestamp by 1 until a unique key is obtained.
17321: 
17322: 7. who: holder of locking key; defaults to user:domain for user.
17323: 
17324: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17325:    retrying); default is 3.
17326: 
17327: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17328: 
17329: Returns:
17330: 
17331: 1. suffix obtained (numeric)
17332: 
17333: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17334: 
17335: 3. error: contains (localized) error message if an error occurred.
17336: 
17337: 
17338: =back
17339: 
17340: =head2 HTTP Helper Routines
17341: 
17342: =over 4
17343: 
17344: =item *
17345: 
17346: escape() : unpack non-word characters into CGI-compatible hex codes
17347: 
17348: =item *
17349: 
17350: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17351: 
17352: =back
17353: 
17354: =head1 PRIVATE SUBROUTINES
17355: 
17356: =head2 Underlying communication routines (Shouldn't call)
17357: 
17358: =over 4
17359: 
17360: =item *
17361: 
17362: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17363: 
17364: =item *
17365: 
17366: reply() : uses subreply to send a message to remote machine, logs all failures
17367: 
17368: =item *
17369: 
17370: critical() : passes a critical message to another server; if cannot
17371: get through then place message in connection buffer directory and
17372: returns con_delayed, if incapable of saving message, returns
17373: con_failed
17374: 
17375: =item *
17376: 
17377: reconlonc() : tries to reconnect lonc client processes.
17378: 
17379: =back
17380: 
17381: =head2 Resource Access Logging
17382: 
17383: =over 4
17384: 
17385: =item *
17386: 
17387: flushcourselogs() : flush (save) buffer logs and access logs
17388: 
17389: =item *
17390: 
17391: courselog($what) : save message for course in hash
17392: 
17393: =item *
17394: 
17395: courseacclog($what) : save message for course using &courselog().  Perform
17396: special processing for specific resource types (problems, exams, quizzes, etc).
17397: 
17398: =item *
17399: 
17400: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17401: as a PerlChildExitHandler
17402: 
17403: =back
17404: 
17405: =head2 Other
17406: 
17407: =over 4
17408: 
17409: =item *
17410: 
17411: symblist($mapname,%newhash) : update symbolic storage links
17412: 
17413: =back
17414: 
17415: =cut
17416: 

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