File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1478: download - view: text, annotated - select for diffs
Tue Feb 1 19:10:54 2022 UTC (2 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Update comment.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1478 2022/02/01 19:10:54 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:     }
 2704:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2705:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2706:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2707:         }
 2708:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2709:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2710:         }
 2711:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2712:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2713:         }
 2714:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2715:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2716:         }
 2717:     }
 2718:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2719:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2720:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2721:                             'approval','limit');
 2722:             foreach my $type (@coursetypes) {
 2723:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2724:                     my @mgrdc = ();
 2725:                     foreach my $item (@settings) {
 2726:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2727:                             push(@mgrdc,$item);
 2728:                         }
 2729:                     }
 2730:                     if (@mgrdc) {
 2731:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2732:                     }
 2733:                 }
 2734:             }
 2735:         }
 2736:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2737:             foreach my $type (@coursetypes) {
 2738:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2739:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2740:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2741:                     }
 2742:                 }
 2743:             }
 2744:         }
 2745:     }
 2746:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2747:         $domdefaults{'catauth'} = 'std';
 2748:         $domdefaults{'catunauth'} = 'std';
 2749:         if ($domconfig{'coursecategories'}{'auth'}) {
 2750:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2751:         }
 2752:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2753:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2754:         }
 2755:     }
 2756:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2757:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2758:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2759:         }
 2760:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2761:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2762:         }
 2763:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2764:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2765:         }
 2766:     }
 2767:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2768:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2769:         foreach my $prefix (@prefixes) {
 2770:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2771:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2772:             }
 2773:         }
 2774:     }
 2775:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2776:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2777:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2778:     }
 2779:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2780:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2781:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2782:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2783:         }
 2784:     }
 2785:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2786:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2787:             if ($domconfig{'wafproxy'}{$item}) {
 2788:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2789:             }
 2790:         }
 2791:     } 
 2792:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2793:     return %domdefaults;
 2794: }
 2795: 
 2796: sub get_dom_cats {
 2797:     my ($dom) = @_;
 2798:     return unless (&domain($dom));
 2799:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2800:     unless (defined($cached)) {
 2801:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2802:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2803:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2804:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2805:             } else {
 2806:                 $cats = {};
 2807:             }
 2808:         } else {
 2809:             $cats = {};
 2810:         }
 2811:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2812:     }
 2813:     return $cats;
 2814: }
 2815: 
 2816: sub get_dom_instcats {
 2817:     my ($dom) = @_;
 2818:     return unless (&domain($dom));
 2819:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2820:     unless (defined($cached)) {
 2821:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2822:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2823:         if ($totcodes > 0) {
 2824:             my $caller = 'global';
 2825:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2826:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2827:                 $instcats = {
 2828:                                 codes => \%codes,
 2829:                                 codetitles => \@codetitles,
 2830:                                 cat_titles => \%cat_titles,
 2831:                                 cat_order => \%cat_order,
 2832:                             };
 2833:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2834:             }
 2835:         }
 2836:     }
 2837:     return $instcats;
 2838: }
 2839: 
 2840: sub retrieve_instcodes {
 2841:     my ($coursecodes,$dom) = @_;
 2842:     my $totcodes;
 2843:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2844:     foreach my $course (keys(%courses)) {
 2845:         if (ref($courses{$course}) eq 'HASH') {
 2846:             if ($courses{$course}{'inst_code'} ne '') {
 2847:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2848:                 $totcodes ++;
 2849:             }
 2850:         }
 2851:     }
 2852:     return $totcodes;
 2853: }
 2854: 
 2855: sub course_portal_url {
 2856:     my ($cnum,$cdom,$r) = @_;
 2857:     my $chome = &homeserver($cnum,$cdom);
 2858:     my $hostname = &hostname($chome);
 2859:     my $protocol = $protocol{$chome};
 2860:     $protocol = 'http' if ($protocol ne 'https');
 2861:     my %domdefaults = &get_domain_defaults($cdom);
 2862:     my $firsturl;
 2863:     if ($domdefaults{'portal_def'}) {
 2864:         $firsturl = $domdefaults{'portal_def'};
 2865:     } else {
 2866:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2867:         $hostname = $alias if ($alias ne '');
 2868:         $firsturl = $protocol.'://'.$hostname;
 2869:     }
 2870:     return $firsturl;
 2871: }
 2872: 
 2873: # --------------------------------------------- Get domain config for passwords
 2874: 
 2875: sub get_passwdconf {
 2876:     my ($dom) = @_;
 2877:     my (%passwdconf,$gotconf,$lookup);
 2878:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2879:     if (defined($cached)) {
 2880:         if (ref($result) eq 'HASH') {
 2881:             %passwdconf = %{$result};
 2882:             $gotconf = 1;
 2883:         }
 2884:     }
 2885:     unless ($gotconf) {
 2886:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2887:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2888:             %passwdconf = %{$domconfig{'passwords'}};
 2889:         }
 2890:         my $cachetime = 24*60*60;
 2891:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2892:     }
 2893:     return %passwdconf;
 2894: }
 2895: 
 2896: # --------------------------------------------------- Assign a key to a student
 2897: 
 2898: sub assign_access_key {
 2899: #
 2900: # a valid key looks like uname:udom#comments
 2901: # comments are being appended
 2902: #
 2903:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2904:     $kdom=
 2905:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2906:     $knum=
 2907:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2908:     $cdom=
 2909:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2910:     $cnum=
 2911:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2912:     $udom=$env{'user.name'} unless (defined($udom));
 2913:     $uname=$env{'user.domain'} unless (defined($uname));
 2914:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2915:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2916:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2917:                                                   # assigned to this person
 2918:                                                   # - this should not happen,
 2919:                                                   # unless something went wrong
 2920:                                                   # the first time around
 2921: # ready to assign
 2922:         $logentry=$1.'; '.$logentry;
 2923:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2924:                                                  $kdom,$knum) eq 'ok') {
 2925: # key now belongs to user
 2926: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2927:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2928:                 &appenv({'environment.'.$envkey => $ckey});
 2929:                 return 'ok';
 2930:             } else {
 2931:                 return 
 2932:   'error: Count not permanently assign key, will need to be re-entered later.';
 2933: 	    }
 2934:         } else {
 2935:             return 'error: Could not assign key, try again later.';
 2936:         }
 2937:     } elsif (!$existing{$ckey}) {
 2938: # the key does not exist
 2939: 	return 'error: The key does not exist';
 2940:     } else {
 2941: # the key is somebody else's
 2942: 	return 'error: The key is already in use';
 2943:     }
 2944: }
 2945: 
 2946: # ------------------------------------------ put an additional comment on a key
 2947: 
 2948: sub comment_access_key {
 2949: #
 2950: # a valid key looks like uname:udom#comments
 2951: # comments are being appended
 2952: #
 2953:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2954:     $cdom=
 2955:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2956:     $cnum=
 2957:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2958:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2959:     if ($existing{$ckey}) {
 2960:         $existing{$ckey}.='; '.$logentry;
 2961: # ready to assign
 2962:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2963:                                                  $cdom,$cnum) eq 'ok') {
 2964: 	    return 'ok';
 2965:         } else {
 2966: 	    return 'error: Count not store comment.';
 2967:         }
 2968:     } else {
 2969: # the key does not exist
 2970: 	return 'error: The key does not exist';
 2971:     }
 2972: }
 2973: 
 2974: # ------------------------------------------------------ Generate a set of keys
 2975: 
 2976: sub generate_access_keys {
 2977:     my ($number,$cdom,$cnum,$logentry)=@_;
 2978:     $cdom=
 2979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2980:     $cnum=
 2981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2982:     unless (&allowed('mky',$cdom)) { return 0; }
 2983:     unless (($cdom) && ($cnum)) { return 0; }
 2984:     if ($number>10000) { return 0; }
 2985:     sleep(2); # make sure don't get same seed twice
 2986:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2987:     my $total=0;
 2988:     for (my $i=1;$i<=$number;$i++) {
 2989:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2990:                   sprintf("%lx",int(100000*rand)).'-'.
 2991:                   sprintf("%lx",int(100000*rand));
 2992:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2993:        $newkey=~s/0/h/g; # and also 0 and O
 2994:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2995:        if ($existing{$newkey}) {
 2996:            $i--;
 2997:        } else {
 2998: 	  if (&put('accesskeys',
 2999:               { $newkey => '# generated '.localtime().
 3000:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3001:                            '; '.$logentry },
 3002: 		   $cdom,$cnum) eq 'ok') {
 3003:               $total++;
 3004: 	  }
 3005:        }
 3006:     }
 3007:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3008:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3009:     return $total;
 3010: }
 3011: 
 3012: # ------------------------------------------------------- Validate an accesskey
 3013: 
 3014: sub validate_access_key {
 3015:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3016:     $cdom=
 3017:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3018:     $cnum=
 3019:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3020:     $udom=$env{'user.domain'} unless (defined($udom));
 3021:     $uname=$env{'user.name'} unless (defined($uname));
 3022:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3023:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3024: }
 3025: 
 3026: # ------------------------------------- Find the section of student in a course
 3027: sub devalidate_getsection_cache {
 3028:     my ($udom,$unam,$courseid)=@_;
 3029:     my $hashid="$udom:$unam:$courseid";
 3030:     &devalidate_cache_new('getsection',$hashid);
 3031: }
 3032: 
 3033: sub courseid_to_courseurl {
 3034:     my ($courseid) = @_;
 3035:     #already url style courseid
 3036:     return $courseid if ($courseid =~ m{^/});
 3037: 
 3038:     if (exists($env{'course.'.$courseid.'.num'})) {
 3039: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3040: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3041: 	return "/$cdom/$cnum";
 3042:     }
 3043: 
 3044:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3045:     if (exists($courseinfo{'num'})) {
 3046: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3047:     }
 3048: 
 3049:     return undef;
 3050: }
 3051: 
 3052: sub getsection {
 3053:     my ($udom,$unam,$courseid)=@_;
 3054:     my $cachetime=1800;
 3055: 
 3056:     my $hashid="$udom:$unam:$courseid";
 3057:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3058:     if (defined($cached)) { return $result; }
 3059: 
 3060:     my %Pending; 
 3061:     my %Expired;
 3062:     #
 3063:     # Each role can either have not started yet (pending), be active, 
 3064:     #    or have expired.
 3065:     #
 3066:     # If there is an active role, we are done.
 3067:     #
 3068:     # If there is more than one role which has not started yet, 
 3069:     #     choose the one which will start sooner
 3070:     # If there is one role which has not started yet, return it.
 3071:     #
 3072:     # If there is more than one expired role, choose the one which ended last.
 3073:     # If there is a role which has expired, return it.
 3074:     #
 3075:     $courseid = &courseid_to_courseurl($courseid);
 3076:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3077:     foreach my $key (keys(%roleshash)) {
 3078:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3079:         my $section=$1;
 3080:         if ($key eq $courseid.'_st') { $section=''; }
 3081:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3082:         my $now=time;
 3083:         if (defined($end) && $end && ($now > $end)) {
 3084:             $Expired{$end}=$section;
 3085:             next;
 3086:         }
 3087:         if (defined($start) && $start && ($now < $start)) {
 3088:             $Pending{$start}=$section;
 3089:             next;
 3090:         }
 3091:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3092:     }
 3093:     #
 3094:     # Presumedly there will be few matching roles from the above
 3095:     # loop and the sorting time will be negligible.
 3096:     if (scalar(keys(%Pending))) {
 3097:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3098:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3099:     } 
 3100:     if (scalar(keys(%Expired))) {
 3101:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3102:         my $time = pop(@sorted);
 3103:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3104:     }
 3105:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3106: }
 3107: 
 3108: sub save_cache {
 3109:     &purge_remembered();
 3110:     #&Apache::loncommon::validate_page();
 3111:     undef(%env);
 3112:     undef($env_loaded);
 3113: }
 3114: 
 3115: my $to_remember=-1;
 3116: my %remembered;
 3117: my %accessed;
 3118: my $kicks=0;
 3119: my $hits=0;
 3120: sub make_key {
 3121:     my ($name,$id) = @_;
 3122:     if (length($id) > 65 
 3123: 	&& length(&escape($id)) > 200) {
 3124: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3125:     }
 3126:     return &escape($name.':'.$id);
 3127: }
 3128: 
 3129: sub devalidate_cache_new {
 3130:     my ($name,$id,$debug) = @_;
 3131:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3132:     my $remembered_id=$name.':'.$id;
 3133:     $id=&make_key($name,$id);
 3134:     $memcache->delete($id);
 3135:     delete($remembered{$remembered_id});
 3136:     delete($accessed{$remembered_id});
 3137: }
 3138: 
 3139: sub is_cached_new {
 3140:     my ($name,$id,$debug) = @_;
 3141:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3142:     if (exists($remembered{$remembered_id})) {
 3143: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3144: 	$accessed{$remembered_id}=[&gettimeofday()];
 3145: 	$hits++;
 3146: 	return ($remembered{$remembered_id},1);
 3147:     }
 3148:     $id=&make_key($name,$id);
 3149:     my $value = $memcache->get($id);
 3150:     if (!(defined($value))) {
 3151: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3152: 	return (undef,undef);
 3153:     }
 3154:     if ($value eq '__undef__') {
 3155: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3156: 	$value=undef;
 3157:     }
 3158:     &make_room($remembered_id,$value,$debug);
 3159:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3160:     return ($value,1);
 3161: }
 3162: 
 3163: sub do_cache_new {
 3164:     my ($name,$id,$value,$time,$debug) = @_;
 3165:     my $remembered_id=$name.':'.$id;
 3166:     $id=&make_key($name,$id);
 3167:     my $setvalue=$value;
 3168:     if (!defined($setvalue)) {
 3169: 	$setvalue='__undef__';
 3170:     }
 3171:     if (!defined($time) ) {
 3172: 	$time=600;
 3173:     }
 3174:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3175:     my $result = $memcache->set($id,$setvalue,$time);
 3176:     if (! $result) {
 3177: 	&logthis("caching of id -> $id  failed");
 3178: 	$memcache->disconnect_all();
 3179:     }
 3180:     # need to make a copy of $value
 3181:     &make_room($remembered_id,$value,$debug);
 3182:     return $value;
 3183: }
 3184: 
 3185: sub make_room {
 3186:     my ($remembered_id,$value,$debug)=@_;
 3187: 
 3188:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3189:                                     : $value;
 3190:     if ($to_remember<0) { return; }
 3191:     $accessed{$remembered_id}=[&gettimeofday()];
 3192:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3193:     my $to_kick;
 3194:     my $max_time=0;
 3195:     foreach my $other (keys(%accessed)) {
 3196: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3197: 	    $to_kick=$other;
 3198: 	    $max_time=&tv_interval($accessed{$other});
 3199: 	}
 3200:     }
 3201:     delete($remembered{$to_kick});
 3202:     delete($accessed{$to_kick});
 3203:     $kicks++;
 3204:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3205:     return;
 3206: }
 3207: 
 3208: sub purge_remembered {
 3209:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3210:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3211:     undef(%remembered);
 3212:     undef(%accessed);
 3213: }
 3214: # ------------------------------------- Read an entry from a user's environment
 3215: 
 3216: sub userenvironment {
 3217:     my ($udom,$unam,@what)=@_;
 3218:     my $items;
 3219:     foreach my $item (@what) {
 3220:         $items.=&escape($item).'&';
 3221:     }
 3222:     $items=~s/\&$//;
 3223:     my %returnhash=();
 3224:     my $uhome = &homeserver($unam,$udom);
 3225:     unless ($uhome eq 'no_host') {
 3226:         my @answer=split(/\&/, 
 3227:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3228:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3229:             return %returnhash;
 3230:         }
 3231:         my $i;
 3232:         for ($i=0;$i<=$#what;$i++) {
 3233: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3234:         }
 3235:     }
 3236:     return %returnhash;
 3237: }
 3238: 
 3239: # ---------------------------------------------------------- Get a studentphoto
 3240: sub studentphoto {
 3241:     my ($udom,$unam,$ext) = @_;
 3242:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3243:     if (defined($env{'request.course.id'})) {
 3244:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3245:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3246:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3247:             } else {
 3248:                 my ($result,$perm_reqd)=
 3249: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3250:                 if ($result eq 'ok') {
 3251:                     if (!($perm_reqd eq 'yes')) {
 3252:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3253:                     }
 3254:                 }
 3255:             }
 3256:         }
 3257:     } else {
 3258:         my ($result,$perm_reqd) = 
 3259: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3260:         if ($result eq 'ok') {
 3261:             if (!($perm_reqd eq 'yes')) {
 3262:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3263:             }
 3264:         }
 3265:     }
 3266:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3267: }
 3268: 
 3269: sub retrievestudentphoto {
 3270:     my ($udom,$unam,$ext,$type) = @_;
 3271:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3272:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3273:     if ($ret eq 'ok') {
 3274:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3275:         if ($type eq 'thumbnail') {
 3276:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3277:         }
 3278:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3279:         return $tokenurl;
 3280:     } else {
 3281:         if ($type eq 'thumbnail') {
 3282:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3283:         } else { 
 3284:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3285:         }
 3286:     }
 3287: }
 3288: 
 3289: # -------------------------------------------------------------------- New chat
 3290: 
 3291: sub chatsend {
 3292:     my ($newentry,$anon,$group)=@_;
 3293:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3294:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3295:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3296:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3297: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3298: 		   &escape($newentry)).':'.$group,$chome);
 3299: }
 3300: 
 3301: # ------------------------------------------ Find current version of a resource
 3302: 
 3303: sub getversion {
 3304:     my $fname=&clutter(shift);
 3305:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3306:     return &currentversion(&filelocation('',$fname));
 3307: }
 3308: 
 3309: sub currentversion {
 3310:     my $fname=shift;
 3311:     my $author=$fname;
 3312:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3313:     my ($udom,$uname)=split(/\//,$author);
 3314:     my $home=&homeserver($uname,$udom);
 3315:     if ($home eq 'no_host') { 
 3316:         return -1; 
 3317:     }
 3318:     my $answer=&reply("currentversion:$fname",$home);
 3319:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3320: 	return -1;
 3321:     }
 3322:     return $answer;
 3323: }
 3324: 
 3325: #
 3326: # Return special version number of resource if set by override, empty otherwise
 3327: #
 3328: sub usedversion {
 3329:     my $fname=shift;
 3330:     unless ($fname) { $fname=$env{'request.uri'}; }
 3331:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3332:     if ($urlversion) { return $urlversion; }
 3333:     return '';
 3334: }
 3335: 
 3336: # ----------------------------- Subscribe to a resource, return URL if possible
 3337: 
 3338: sub subscribe {
 3339:     my $fname=shift;
 3340:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3341:     $fname=~s/[\n\r]//g;
 3342:     my $author=$fname;
 3343:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3344:     my ($udom,$uname)=split(/\//,$author);
 3345:     my $home=homeserver($uname,$udom);
 3346:     if ($home eq 'no_host') {
 3347:         return 'not_found';
 3348:     }
 3349:     my $answer=reply("sub:$fname",$home);
 3350:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3351: 	$answer.=' by '.$home;
 3352:     }
 3353:     return $answer;
 3354: }
 3355:     
 3356: # -------------------------------------------------------------- Replicate file
 3357: 
 3358: sub repcopy {
 3359:     my $filename=shift;
 3360:     $filename=~s/\/+/\//g;
 3361:     my $londocroot = $perlvar{'lonDocRoot'};
 3362:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3363:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3364:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3365: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3366: 	return &repcopy_userfile($filename);
 3367:     }
 3368:     $filename=~s/[\n\r]//g;
 3369:     my $transname="$filename.in.transfer";
 3370: # FIXME: this should flock
 3371:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3372:     my $remoteurl=subscribe($filename);
 3373:     if ($remoteurl =~ /^con_lost by/) {
 3374: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3375:            return 'unavailable';
 3376:     } elsif ($remoteurl eq 'not_found') {
 3377: 	   #&logthis("Subscribe returned not_found: $filename");
 3378: 	   return 'not_found';
 3379:     } elsif ($remoteurl =~ /^rejected by/) {
 3380: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3381:            return 'forbidden';
 3382:     } elsif ($remoteurl eq 'directory') {
 3383:            return 'ok';
 3384:     } else {
 3385:         my $author=$filename;
 3386:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3387:         my ($udom,$uname)=split(/\//,$author);
 3388:         my $home=homeserver($uname,$udom);
 3389:         unless ($home eq $perlvar{'lonHostID'}) {
 3390:            my @parts=split(/\//,$filename);
 3391:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3392:            if ($path ne "$londocroot/res") {
 3393:                &logthis("Malconfiguration for replication: $filename");
 3394: 	       return 'bad_request';
 3395:            }
 3396:            my $count;
 3397:            for ($count=5;$count<$#parts;$count++) {
 3398:                $path.="/$parts[$count]";
 3399:                if ((-e $path)!=1) {
 3400: 		   mkdir($path,0777);
 3401:                }
 3402:            }
 3403:            my $request=new HTTP::Request('GET',"$remoteurl");
 3404:            my $response;
 3405:            if ($remoteurl =~ m{/raw/}) {
 3406:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3407:            } else {
 3408:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3409:            }
 3410:            if ($response->is_error()) {
 3411: 	       unlink($transname);
 3412:                my $message=$response->status_line;
 3413:                &logthis("<font color=\"blue\">WARNING:"
 3414:                        ." LWP get: $message: $filename</font>");
 3415:                return 'unavailable';
 3416:            } else {
 3417: 	       if ($remoteurl!~/\.meta$/) {
 3418:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3419:                   my $mresponse;
 3420:                   if ($remoteurl =~ m{/raw/}) {
 3421:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3422:                   } else {
 3423:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3424:                   }
 3425:                   if ($mresponse->is_error()) {
 3426: 		      unlink($filename.'.meta');
 3427:                       &logthis(
 3428:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3429:                   }
 3430: 	       }
 3431:                rename($transname,$filename);
 3432:                return 'ok';
 3433:            }
 3434:        }
 3435:     }
 3436: }
 3437: 
 3438: # ------------------------------------------------- Unsubscribe from a resource
 3439: 
 3440: sub unsubscribe {
 3441:     my ($fname) = @_;
 3442:     my $answer;
 3443:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3444:     $fname=~s/[\n\r]//g;
 3445:     my $author=$fname;
 3446:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3447:     my ($udom,$uname)=split(/\//,$author);
 3448:     my $home=homeserver($uname,$udom);
 3449:     if ($home eq 'no_host') {
 3450:         $answer = 'no_host';
 3451:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3452:         $answer = 'home';
 3453:     } else {
 3454:         my $defdom = $perlvar{'lonDefDomain'};
 3455:         if (&will_trust('content',$defdom,$udom)) {
 3456:             $answer = reply("unsub:$fname",$home);
 3457:         } else {
 3458:             $answer = 'untrusted';
 3459:         }
 3460:     }
 3461:     return $answer;
 3462: }
 3463: 
 3464: # ------------------------------------------------ Get server side include body
 3465: sub ssi_body {
 3466:     my ($filelink,%form)=@_;
 3467:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3468:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3469:     }
 3470:     my $output='';
 3471:     my $response;
 3472:     if ($filelink=~/^https?\:/) {
 3473:        ($output,$response)=&externalssi($filelink);
 3474:     } else {
 3475:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3476:        $filelink .= 'inhibitmenu=yes';
 3477:        ($output,$response)=&ssi($filelink,%form);
 3478:     }
 3479:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3480:     $output=~s/^.*?\<body[^\>]*\>//si;
 3481:     $output=~s/\<\/body\s*\>.*?$//si;
 3482:     if (wantarray) {
 3483:         return ($output, $response);
 3484:     } else {
 3485:         return $output;
 3486:     }
 3487: }
 3488: 
 3489: # --------------------------------------------------------- Server Side Include
 3490: 
 3491: sub absolute_url {
 3492:     my ($host_name,$unalias,$keep_proto) = @_;
 3493:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3494:     if ($host_name eq '') {
 3495: 	$host_name = $ENV{'SERVER_NAME'};
 3496:     }
 3497:     if ($unalias) {
 3498:         my $alias = &get_proxy_alias();
 3499:         if ($alias eq $host_name) {
 3500:             my $lonhost = $perlvar{'lonHostID'};
 3501:             my $hostname = &hostname($lonhost);
 3502:             my $lcproto; 
 3503:             if (($keep_proto) || ($hostname eq '')) {
 3504:                 $lcproto = $protocol;
 3505:             } else {
 3506:                 $lcproto = $protocol{$lonhost};
 3507:                 $lcproto = 'http' if ($lcproto ne 'https');
 3508:                 $lcproto .= '://';
 3509:             }
 3510:             unless ($hostname eq '') {
 3511:                 return $lcproto.$hostname;
 3512:             }
 3513:         }
 3514:     }
 3515:     return $protocol.$host_name;
 3516: }
 3517: 
 3518: #
 3519: #   Server side include.
 3520: # Parameters:
 3521: #  fn     Possibly encrypted resource name/id.
 3522: #  form   Hash that describes how the rendering should be done
 3523: #         and other things.
 3524: # Returns:
 3525: #   Scalar context: The content of the response.
 3526: #   Array context:  2 element list of the content and the full response object.
 3527: #     
 3528: sub ssi {
 3529: 
 3530:     my ($fn,%form)=@_;
 3531:     my ($host,$request,$response);
 3532:     $host = &absolute_url('',1);
 3533: 
 3534:     $form{'no_update_last_known'}=1;
 3535:     &Apache::lonenc::check_encrypt(\$fn);
 3536:     if (%form) {
 3537:       $request=new HTTP::Request('POST',$host.$fn);
 3538:       $request->content(join('&',map { 
 3539:             my $name = escape($_);
 3540:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3541:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3542:             : &escape($form{$_}) );    
 3543:         } keys(%form)));
 3544:     } else {
 3545:       $request=new HTTP::Request('GET',$host.$fn);
 3546:     }
 3547: 
 3548:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3549:     my $lonhost = $perlvar{'lonHostID'};
 3550:     my $islocal;
 3551:     if (($env{'request.course.id'}) &&
 3552:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3553:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3554:         ($form{'grade_symb'} ne '') &&
 3555:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3556:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3557:         $islocal = 1;
 3558:     }
 3559:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3560:                                              '','','',$islocal);
 3561: 
 3562:     if (wantarray) {
 3563: 	return ($response->content, $response);
 3564:     } else {
 3565: 	return $response->content;
 3566:     }
 3567: }
 3568: 
 3569: sub externalssi {
 3570:     my ($url)=@_;
 3571:     my $request=new HTTP::Request('GET',$url);
 3572:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3573:     if (wantarray) {
 3574:         return ($response->content, $response);
 3575:     } else {
 3576:         return $response->content;
 3577:     }
 3578: }
 3579: 
 3580: 
 3581: # If the local copy of a replicated resource is outdated, trigger a  
 3582: # connection from the homeserver to flush the delayed queue. If no update 
 3583: # happens, remove local copies of outdated resource (and corresponding
 3584: # metadata file).
 3585: 
 3586: sub remove_stale_resfile {
 3587:     my ($url) = @_;
 3588:     my $removed;
 3589:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3590:         my $audom = $1;
 3591:         my $auname = $2;
 3592:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3593:             my $homeserver = &homeserver($auname,$audom);
 3594:             unless (($homeserver eq 'no_host') ||
 3595:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3596:                 my $fname = &filelocation('',$url);
 3597:                 if (-e $fname) {
 3598:                     my $hostname = &hostname($homeserver);
 3599:                     if ($hostname) {
 3600:                         my $protocol = $protocol{$homeserver};
 3601:                         $protocol = 'http' if ($protocol ne 'https');
 3602:                         my $uri = &declutter($url);
 3603:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3604:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3605:                         if ($response->is_success()) {
 3606:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3607:                             my $locmodtime = (stat($fname))[9];
 3608:                             if ($locmodtime < $remmodtime) {
 3609:                                 my $stale;
 3610:                                 my $answer = &reply('pong',$homeserver);
 3611:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3612:                                     sleep(0.2);
 3613:                                     $locmodtime = (stat($fname))[9];
 3614:                                     if ($locmodtime < $remmodtime) {
 3615:                                         my $posstransfer = $fname.'.in.transfer';
 3616:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3617:                                             $removed = 1;
 3618:                                         } else {
 3619:                                             $stale = 1;
 3620:                                         }
 3621:                                     } else {
 3622:                                         $removed = 1;
 3623:                                     }
 3624:                                 } else {
 3625:                                     $stale = 1;
 3626:                                 }
 3627:                                 if ($stale) {
 3628:                                     if (unlink($fname)) {
 3629:                                         if ($uri!~/\.meta$/) {
 3630:                                             if (-e $fname.'.meta') {
 3631:                                                 unlink($fname.'.meta');
 3632:                                             }
 3633:                                         }
 3634:                                         my $unsubresult = &unsubscribe($fname);
 3635:                                         unless ($unsubresult eq 'ok') {
 3636:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3637:                                         }
 3638:                                         $removed = 1;
 3639:                                     }
 3640:                                 }
 3641:                             }
 3642:                         }
 3643:                     }
 3644:                 }
 3645:             }
 3646:         }
 3647:     }
 3648:     return $removed;
 3649: }
 3650: 
 3651: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3652: 
 3653: sub allowuploaded {
 3654:     my ($srcurl,$url)=@_;
 3655:     $url=&clutter(&declutter($url));
 3656:     my $dir=$url;
 3657:     $dir=~s/\/[^\/]+$//;
 3658:     my %httpref=();
 3659:     my $httpurl=&hreflocation('',$url);
 3660:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3661:     &Apache::lonnet::appenv(\%httpref);
 3662: }
 3663: 
 3664: #
 3665: # Determine if the current user should be able to edit a particular resource,
 3666: # when viewing in course context.
 3667: # (a) When viewing resource used to determine if "Edit" item is included in 
 3668: #     Functions.
 3669: # (b) When displaying folder contents in course editor, used to determine if
 3670: #     "Edit" link will be displayed alongside resource.
 3671: #
 3672: #  input: six args -- filename (decluttered), course number, course domain,
 3673: #                   url, symb (if registered) and group (if this is a group
 3674: #                   item -- e.g., bulletin board, group page etc.).
 3675: #  output: array of five scalars -- 
 3676: #          $cfile -- url for file editing if editable on current server
 3677: #          $home -- homeserver of resource (i.e., for author if published,
 3678: #                                           or course if uploaded.).
 3679: #          $switchserver --  1 if server switch will be needed.
 3680: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3681: #          $forceview -- 1 if icon/link should be to go to view mode
 3682: #
 3683: 
 3684: sub can_edit_resource {
 3685:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3686:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3687: #
 3688: # For aboutme pages user can only edit his/her own.
 3689: #
 3690:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3691:         my ($sdom,$sname) = ($1,$2);
 3692:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3693:             $home = $env{'user.home'};
 3694:             $cfile = $resurl;
 3695:             if ($env{'form.forceedit'}) {
 3696:                 $forceview = 1;
 3697:             } else {
 3698:                 $forceedit = 1;
 3699:             }
 3700:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3701:         } else {
 3702:             return;
 3703:         }
 3704:     }
 3705: 
 3706:     if ($env{'request.course.id'}) {
 3707:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3708:         if ($group ne '') {
 3709: # if this is a group homepage or group bulletin board, check group privs
 3710:             my $allowed = 0;
 3711:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3712:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3713:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3714:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3715:                     $allowed = 1;
 3716:                 }
 3717:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3718:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3719:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3720:                     $allowed = 1;
 3721:                 }
 3722:             }
 3723:             if ($allowed) {
 3724:                 $home=&homeserver($cnum,$cdom);
 3725:                 if ($env{'form.forceedit'}) {
 3726:                     $forceview = 1;
 3727:                 } else {
 3728:                     $forceedit = 1;
 3729:                 }
 3730:                 $cfile = $resurl;
 3731:             } else {
 3732:                 return;
 3733:             }
 3734:         } else {
 3735:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3736:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3737:                     return;
 3738:                 }
 3739:             } elsif (!$crsedit) {
 3740: #
 3741: # No edit allowed where CC has switched to student role.
 3742: #
 3743:                 return;
 3744:             }
 3745:         }
 3746:     }
 3747: 
 3748:     if ($file ne '') {
 3749:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3750:             if (&is_course_upload($file,$cnum,$cdom)) {
 3751:                 $uploaded = 1;
 3752:                 $incourse = 1;
 3753:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3754:                     $cfile = &hreflocation('',$file);
 3755:                     if ($env{'form.forceedit'}) {
 3756:                         $forceview = 1;
 3757:                     } else {
 3758:                         $forceedit = 1;
 3759:                     }
 3760:                 }
 3761:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3762:                 $incourse = 1;
 3763:                 if ($env{'form.forceedit'}) {
 3764:                     $forceview = 1;
 3765:                 } else {
 3766:                     $forceedit = 1;
 3767:                 }
 3768:                 $cfile = $resurl;
 3769:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3770:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3771:                     $incourse = 1;
 3772:                     if ($env{'form.forceedit'}) {
 3773:                         $forceview = 1;
 3774:                     } else {
 3775:                         $forceedit = 1;
 3776:                     }
 3777:                     $cfile = $resurl;
 3778:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3779:                     $incourse = 1;
 3780:                     $cfile = $resurl.'/smpedit';
 3781:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3782:                     $incourse = 1;
 3783:                     if ($env{'form.forceedit'}) {
 3784:                         $forceview = 1;
 3785:                     } else {
 3786:                         $forceedit = 1;
 3787:                     }
 3788:                     $cfile = $resurl;
 3789:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3790:                     my ($map,$id,$res) = &decode_symb($symb);
 3791:                     if ($map =~ /\.page$/) {
 3792:                         $incourse = 1;
 3793:                         if ($env{'form.forceedit'}) {
 3794:                             $forceview = 1;
 3795:                             $cfile = $map;
 3796:                         } else {
 3797:                             $forceedit = 1;
 3798:                             $cfile =  '/adm/wrapper'.$resurl;
 3799:                         }
 3800:                     }
 3801:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3802:                     $incourse = 1;
 3803:                     if ($env{'form.forceedit'}) {
 3804:                         $forceview = 1;
 3805:                     } else {
 3806:                         $forceedit = 1;
 3807:                     }
 3808:                     $cfile = $resurl;
 3809:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3810:                     $incourse = 1;
 3811:                     if ($env{'form.forceedit'}) {
 3812:                         $forceview = 1;
 3813:                     } else {
 3814:                         $forceedit = 1;
 3815:                     }
 3816:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3817:                 }
 3818:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3819:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3820:                 if (&is_on_map($template)) { 
 3821:                     $incourse = 1;
 3822:                     $forceview = 1;
 3823:                     $cfile = $template;
 3824:                 }
 3825:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3826:                 $incourse = 1;
 3827:                 if ($env{'form.forceedit'}) {
 3828:                     $forceview = 1;
 3829:                 } else {
 3830:                     $forceedit = 1;
 3831:                 }
 3832:                 $cfile = $resurl;
 3833:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3834:                 $incourse = 1;
 3835:                 if ($env{'form.forceedit'}) {
 3836:                     $forceview = 1;
 3837:                 } else {
 3838:                     $forceedit = 1;
 3839:                 }
 3840:                 $cfile = $resurl;
 3841:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3842:                 $incourse = 1;
 3843:                 $forceview = 1;
 3844:                 if ($symb) {
 3845:                     my ($map,$id,$res)=&decode_symb($symb);
 3846:                     $env{'request.symb'} = $symb;
 3847:                     $cfile = &clutter($res);
 3848:                 } else {
 3849:                     $cfile = $env{'form.suppurl'};
 3850:                     my $escfile = &unescape($cfile);
 3851:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3852:                         $cfile = '/adm/wrapper'.$escfile;
 3853:                     } else {
 3854:                         $escfile =~ s{^http://}{};
 3855:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3856:                     }
 3857:                 }
 3858:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3859:                 if ($env{'form.forceedit'}) {
 3860:                     $forceview = 1;
 3861:                 } else {
 3862:                     $forceedit = 1;
 3863:                 }
 3864:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3865:             }
 3866:         }
 3867:         if ($uploaded || $incourse) {
 3868:             $home=&homeserver($cnum,$cdom);
 3869:         } elsif ($file !~ m{/$}) {
 3870:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3871:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3872:             # Check that the user has permission to edit this resource
 3873:             my $setpriv = 1;
 3874:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3875:             if (defined($cfudom)) {
 3876:                 $home=&homeserver($cfuname,$cfudom);
 3877:                 $cfile=$file;
 3878:             }
 3879:         }
 3880:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3881:             (($home ne '') && ($home ne 'no_host'))) {
 3882:             my @ids=&current_machine_ids();
 3883:             unless (grep(/^\Q$home\E$/,@ids)) {
 3884:                 $switchserver=1;
 3885:             }
 3886:         }
 3887:     }
 3888:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3889: }
 3890: 
 3891: sub is_course_upload {
 3892:     my ($file,$cnum,$cdom) = @_;
 3893:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3894:     $uploadpath =~ s{^\/}{};
 3895:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3896:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3897:         return 1;
 3898:     }
 3899:     return;
 3900: }
 3901: 
 3902: sub in_course {
 3903:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3904:     if ($hideprivileged) {
 3905:         my $skipuser;
 3906:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3907:         my @possdoms = ($cdom);  
 3908:         if ($coursehash{'checkforpriv'}) { 
 3909:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3910:         }
 3911:         if (&privileged($uname,$udom,\@possdoms)) {
 3912:             $skipuser = 1;
 3913:             if ($coursehash{'nothideprivileged'}) {
 3914:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3915:                     my $user;
 3916:                     if ($item =~ /:/) {
 3917:                         $user = $item;
 3918:                     } else {
 3919:                         $user = join(':',split(/[\@]/,$item));
 3920:                     }
 3921:                     if ($user eq $uname.':'.$udom) {
 3922:                         undef($skipuser);
 3923:                         last;
 3924:                     }
 3925:                 }
 3926:             }
 3927:             if ($skipuser) {
 3928:                 return 0;
 3929:             }
 3930:         }
 3931:     }
 3932:     $type ||= 'any';
 3933:     if (!defined($cdom) || !defined($cnum)) {
 3934:         my $cid  = $env{'request.course.id'};
 3935:         $cdom = $env{'course.'.$cid.'.domain'};
 3936:         $cnum = $env{'course.'.$cid.'.num'};
 3937:     }
 3938:     my $typesref;
 3939:     if (($type eq 'any') || ($type eq 'all')) {
 3940:         $typesref = ['active','previous','future'];
 3941:     } elsif ($type eq 'previous' || $type eq 'future') {
 3942:         $typesref = [$type];
 3943:     }
 3944:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3945:                               $typesref,undef,[$cdom]);
 3946:     my ($tmp) = keys(%roles);
 3947:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3948:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3949:     if (@course_roles > 0) {
 3950:         return 1;
 3951:     }
 3952:     return 0;
 3953: }
 3954: 
 3955: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3956: # input: action, courseID, current domain, intended
 3957: #        path to file, source of file, instruction to parse file for objects,
 3958: #        ref to hash for embedded objects,
 3959: #        ref to hash for codebase of java objects.
 3960: #        reference to scalar to accommodate mime type determined
 3961: #          from File::MMagic if $parser = parse.
 3962: #
 3963: # output: url to file (if action was uploaddoc), 
 3964: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3965: #
 3966: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3967: # course.
 3968: #
 3969: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3970: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3971: #          course's home server.
 3972: #
 3973: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3974: #          be copied from $source (current location) to 
 3975: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3976: #         and will then be copied to
 3977: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3978: #         course's home server.
 3979: #
 3980: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3981: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3982: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3983: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3984: #         in course's home server.
 3985: #
 3986: 
 3987: sub process_coursefile {
 3988:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3989:         $mimetype)=@_;
 3990:     my $fetchresult;
 3991:     my $home=&homeserver($docuname,$docudom);
 3992:     if ($action eq 'propagate') {
 3993:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3994: 			     $home);
 3995:     } else {
 3996:         my $fpath = '';
 3997:         my $fname = $file;
 3998:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3999:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4000:         my $filepath = &build_filepath($fpath);
 4001:         if ($action eq 'copy') {
 4002:             if ($source eq '') {
 4003:                 $fetchresult = 'no source file';
 4004:                 return $fetchresult;
 4005:             } else {
 4006:                 my $destination = $filepath.'/'.$fname;
 4007:                 rename($source,$destination);
 4008:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4009:                                  $home);
 4010:             }
 4011:         } elsif ($action eq 'uploaddoc') {
 4012:             open(my $fh,'>',$filepath.'/'.$fname);
 4013:             print $fh $env{'form.'.$source};
 4014:             close($fh);
 4015:             if ($parser eq 'parse') {
 4016:                 my $mm = new File::MMagic;
 4017:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4018:                 if ($type eq 'text/html') {
 4019:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4020:                     unless ($parse_result eq 'ok') {
 4021:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4022:                     }
 4023:                 }
 4024:                 if (ref($mimetype)) {
 4025:                     $$mimetype = $type;
 4026:                 } 
 4027:             }
 4028:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4029:                                  $home);
 4030:             if ($fetchresult eq 'ok') {
 4031:                 return '/uploaded/'.$fpath.'/'.$fname;
 4032:             } else {
 4033:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4034:                         ' to host '.$home.': '.$fetchresult);
 4035:                 return '/adm/notfound.html';
 4036:             }
 4037:         }
 4038:     }
 4039:     unless ( $fetchresult eq 'ok') {
 4040:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4041:              ' to host '.$home.': '.$fetchresult);
 4042:     }
 4043:     return $fetchresult;
 4044: }
 4045: 
 4046: sub build_filepath {
 4047:     my ($fpath) = @_;
 4048:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4049:     unless ($fpath eq '') {
 4050:         my @parts=split('/',$fpath);
 4051:         foreach my $part (@parts) {
 4052:             $filepath.= '/'.$part;
 4053:             if ((-e $filepath)!=1) {
 4054:                 mkdir($filepath,0777);
 4055:             }
 4056:         }
 4057:     }
 4058:     return $filepath;
 4059: }
 4060: 
 4061: sub store_edited_file {
 4062:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4063:     my $file = $primary_url;
 4064:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4065:     my $fpath = '';
 4066:     my $fname = $file;
 4067:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4068:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4069:     my $filepath = &build_filepath($fpath);
 4070:     open(my $fh,'>',$filepath.'/'.$fname);
 4071:     print $fh $content;
 4072:     close($fh);
 4073:     my $home=&homeserver($docuname,$docudom);
 4074:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4075: 			  $home);
 4076:     if ($$fetchresult eq 'ok') {
 4077:         return '/uploaded/'.$fpath.'/'.$fname;
 4078:     } else {
 4079:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4080: 		 ' to host '.$home.': '.$$fetchresult);
 4081:         return '/adm/notfound.html';
 4082:     }
 4083: }
 4084: 
 4085: sub clean_filename {
 4086:     my ($fname,$args)=@_;
 4087: # Replace Windows backslashes by forward slashes
 4088:     $fname=~s/\\/\//g;
 4089:     if (!$args->{'keep_path'}) {
 4090:         # Get rid of everything but the actual filename
 4091: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4092:     }
 4093: # Replace spaces by underscores
 4094:     $fname=~s/\s+/\_/g;
 4095: # Transliterate non-ascii text to ascii
 4096:     my $lang = &Apache::lonlocal::current_language();
 4097:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4098: # Replace all other weird characters by nothing
 4099:     $fname=~s{[^/\w\.\-]}{}g;
 4100: # Replace all .\d. sequences with _\d. so they no longer look like version
 4101: # numbers
 4102:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4103: # Replace three or more adjacent underscores with one for consistency 
 4104: # with loncfile::filename_check() so complete url can be extracted by
 4105: # lonnet::decode_symb()
 4106:     $fname=~s/_{3,}/_/g;
 4107:     return $fname;
 4108: }
 4109: 
 4110: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4111: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4112: # image with the same aspect ratio as the original, but with dimensions which do 
 4113: # not exceed $resizewidth and $resizeheight.
 4114:  
 4115: sub resizeImage {
 4116:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4117:     my $ima = Image::Magick->new;
 4118:     my $resized;
 4119:     if (-e $img_path) {
 4120:         $ima->Read($img_path);
 4121:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4122:             my $width = $ima->Get('width');
 4123:             my $height = $ima->Get('height');
 4124:             if ($width > $resizewidth) {
 4125: 	        my $factor = $width/$resizewidth;
 4126:                 my $newheight = $height/$factor;
 4127:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4128:                 $resized = 1;
 4129:             }
 4130:         }
 4131:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4132:             my $width = $ima->Get('width');
 4133:             my $height = $ima->Get('height');
 4134:             if ($height > $resizeheight) {
 4135:                 my $factor = $height/$resizeheight;
 4136:                 my $newwidth = $width/$factor;
 4137:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4138:                 $resized = 1;
 4139:             }
 4140:         }
 4141:         if ($resized) {
 4142:             $ima->Write($img_path);
 4143:         }
 4144:     }
 4145:     return;
 4146: }
 4147: 
 4148: # --------------- Take an uploaded file and put it into the userfiles directory
 4149: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4150: #                    the desired filename is in $env{"form.$formname.filename"}
 4151: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4152: #                                    canceloverwrite, scantron or ''.
 4153: #                   if 'coursedoc': upload to the current course
 4154: #                   if 'existingfile': write file to tmp/overwrites directory 
 4155: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4156: #                   $context is passed as argument to &finishuserfileupload
 4157: #        $subdir - directory in userfile to store the file into
 4158: #        $parser - instruction to parse file for objects ($parser = parse) or
 4159: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4160: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4161: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4162: #        $allfiles - reference to hash for embedded objects
 4163: #        $codebase - reference to hash for codebase of java objects
 4164: #        $desuname - username for permanent storage of uploaded file
 4165: #        $dsetudom - domain for permanaent storage of uploaded file
 4166: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4167: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4168: #        $resizewidth - width (pixels) to which to resize uploaded image
 4169: #        $resizeheight - height (pixels) to which to resize uploaded image
 4170: #        $mimetype - reference to scalar to accommodate mime type determined
 4171: #                    from File::MMagic.
 4172: # 
 4173: # output: url of file in userspace, or error: <message> 
 4174: #             or /adm/notfound.html if failure to upload occurse
 4175: 
 4176: sub userfileupload {
 4177:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4178:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4179:     if (!defined($subdir)) { $subdir='unknown'; }
 4180:     my $fname=$env{'form.'.$formname.'.filename'};
 4181:     $fname=&clean_filename($fname);
 4182:     # See if there is anything left
 4183:     unless ($fname) { return 'error: no uploaded file'; }
 4184:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4185:     if ($fname =~ /^\./) {
 4186:         my ($s,$usec) = &gettimeofday();
 4187:         while (length($usec) < 6) {
 4188:             $usec = '0'.$usec;
 4189:         }
 4190:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4191:     }
 4192:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4193:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4194:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4195:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4196:         my $now = time;
 4197:         my $filepath;
 4198:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4199:              $filepath = 'tmp/helprequests/'.$now;
 4200:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4201:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4202:                          '_'.$env{'user.domain'}.'/pending';
 4203:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4204:             my ($docuname,$docudom);
 4205:             if ($destudom =~ /^$match_domain$/) {
 4206:                 $docudom = $destudom;
 4207:             } else {
 4208:                 $docudom = $env{'user.domain'};
 4209:             }
 4210:             if ($destuname =~ /^$match_username$/) {
 4211:                 $docuname = $destuname;
 4212:             } else {
 4213:                 $docuname = $env{'user.name'};
 4214:             }
 4215:             if (exists($env{'form.group'})) {
 4216:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4217:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4218:             }
 4219:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4220:             if ($context eq 'canceloverwrite') {
 4221:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4222:                 if (-e  $tempfile) {
 4223:                     my @info = stat($tempfile);
 4224:                     if ($info[9] eq $env{'form.timestamp'}) {
 4225:                         unlink($tempfile);
 4226:                     }
 4227:                 }
 4228:                 return;
 4229:             }
 4230:         }
 4231:         # Create the directory if not present
 4232:         my @parts=split(/\//,$filepath);
 4233:         my $fullpath = $perlvar{'lonDaemons'};
 4234:         for (my $i=0;$i<@parts;$i++) {
 4235:             $fullpath .= '/'.$parts[$i];
 4236:             if ((-e $fullpath)!=1) {
 4237:                 mkdir($fullpath,0777);
 4238:             }
 4239:         }
 4240:         open(my $fh,'>',$fullpath.'/'.$fname);
 4241:         print $fh $env{'form.'.$formname};
 4242:         close($fh);
 4243:         if ($context eq 'existingfile') {
 4244:             my @info = stat($fullpath.'/'.$fname);
 4245:             return ($fullpath.'/'.$fname,$info[9]);
 4246:         } else {
 4247:             return $fullpath.'/'.$fname;
 4248:         }
 4249:     }
 4250:     if ($subdir eq 'scantron') {
 4251:         $fname = 'scantron_orig_'.$fname;
 4252:     } else {
 4253:         $fname="$subdir/$fname";
 4254:     }
 4255:     if ($context eq 'coursedoc') {
 4256: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4257: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4258:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4259:             return &finishuserfileupload($docuname,$docudom,
 4260: 					 $formname,$fname,$parser,$allfiles,
 4261: 					 $codebase,$thumbwidth,$thumbheight,
 4262:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4263:         } else {
 4264:             if ($env{'form.folder'}) {
 4265:                 $fname=$env{'form.folder'}.'/'.$fname;
 4266:             }
 4267:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4268: 				       $fname,$formname,$parser,
 4269: 				       $allfiles,$codebase,$mimetype);
 4270:         }
 4271:     } elsif (defined($destuname)) {
 4272:         my $docuname=$destuname;
 4273:         my $docudom=$destudom;
 4274: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4275: 				     $parser,$allfiles,$codebase,
 4276:                                      $thumbwidth,$thumbheight,
 4277:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4278:     } else {
 4279:         my $docuname=$env{'user.name'};
 4280:         my $docudom=$env{'user.domain'};
 4281:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4282:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4283:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4284:         }
 4285: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4286: 				     $parser,$allfiles,$codebase,
 4287:                                      $thumbwidth,$thumbheight,
 4288:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4289:     }
 4290: }
 4291: 
 4292: sub finishuserfileupload {
 4293:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4294:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4295:     my $path=$docudom.'/'.$docuname.'/';
 4296:     my $filepath=$perlvar{'lonDocRoot'};
 4297:   
 4298:     my ($fnamepath,$file,$fetchthumb);
 4299:     $file=$fname;
 4300:     if ($fname=~m|/|) {
 4301:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4302: 	$path.=$fnamepath.'/';
 4303:     }
 4304:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4305:     my $count;
 4306:     for ($count=4;$count<=$#parts;$count++) {
 4307:         $filepath.="/$parts[$count]";
 4308:         if ((-e $filepath)!=1) {
 4309: 	    mkdir($filepath,0777);
 4310:         }
 4311:     }
 4312: 
 4313: # Save the file
 4314:     {
 4315: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4316: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4317: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4318: 	    return '/adm/notfound.html';
 4319: 	}
 4320:         if ($context eq 'overwrite') {
 4321:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4322:             my $target = $filepath.'/'.$file;
 4323:             if (-e $source) {
 4324:                 my @info = stat($source);
 4325:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4326:                     unless (&File::Copy::move($source,$target)) {
 4327:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4328:                         return "Moving from $source failed";
 4329:                     }
 4330:                 } else {
 4331:                     return "Temporary file: $source had unexpected date/time for last modification";
 4332:                 }
 4333:             } else {
 4334:                 return "Temporary file: $source missing";
 4335:             }
 4336:         } elsif (!print FH ($env{'form.'.$formname})) {
 4337: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4338: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4339: 	    return '/adm/notfound.html';
 4340: 	}
 4341: 	close(FH);
 4342:         if ($resizewidth && $resizeheight) {
 4343:             my $mm = new File::MMagic;
 4344:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4345:             if ($mime_type =~ m{^image/}) {
 4346: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4347:             }  
 4348: 	}
 4349:     }
 4350:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4351:         if (ref($mimetype)) {
 4352:             if ($$mimetype eq '') {
 4353:                 my $mm = new File::MMagic;
 4354:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4355:                 $$mimetype = $type;
 4356:             }
 4357:         }
 4358:     }
 4359:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4360:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4361:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4362:                                                        $allfiles,$codebase);
 4363:             unless ($parse_result eq 'ok') {
 4364:                 &logthis('Failed to parse '.$filepath.$file.
 4365: 	   	         ' for embedded media: '.$parse_result); 
 4366:             }
 4367:         }
 4368:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4369:         my $format = $env{'form.scantron_format'};
 4370:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4371:     }
 4372:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4373:         my $input = $filepath.'/'.$file;
 4374:         my $output = $filepath.'/'.'tn-'.$file;
 4375:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4376:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4377:         system({$args[0]} @args);
 4378:         if (-e $filepath.'/'.'tn-'.$file) {
 4379:             $fetchthumb  = 1; 
 4380:         }
 4381:     }
 4382:  
 4383: # Notify homeserver to grep it
 4384: #
 4385:     my $docuhome=&homeserver($docuname,$docudom);	
 4386:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4387:     if ($fetchresult eq 'ok') {
 4388:         if ($fetchthumb) {
 4389:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4390:             if ($thumbresult ne 'ok') {
 4391:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4392:                          $docuhome.': '.$thumbresult);
 4393:             }
 4394:         }
 4395: #
 4396: # Return the URL to it
 4397:         return '/uploaded/'.$path.$file;
 4398:     } else {
 4399:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4400: 		 ': '.$fetchresult);
 4401:         return '/adm/notfound.html';
 4402:     }
 4403: }
 4404: 
 4405: sub extract_embedded_items {
 4406:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4407:     my @state = ();
 4408:     my (%lastids,%related,%shockwave,%flashvars);
 4409:     my %javafiles = (
 4410:                       codebase => '',
 4411:                       code => '',
 4412:                       archive => ''
 4413:                     );
 4414:     my %mediafiles = (
 4415:                       src => '',
 4416:                       movie => '',
 4417:                      );
 4418:     my $p;
 4419:     if ($content) {
 4420:         $p = HTML::LCParser->new($content);
 4421:     } else {
 4422:         $p = HTML::LCParser->new($fullpath);
 4423:     }
 4424:     while (my $t=$p->get_token()) {
 4425: 	if ($t->[0] eq 'S') {
 4426: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4427: 	    push(@state, $tagname);
 4428:             if (lc($tagname) eq 'allow') {
 4429:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4430:             }
 4431: 	    if (lc($tagname) eq 'img') {
 4432: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4433: 	    }
 4434: 	    if (lc($tagname) eq 'a') {
 4435:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4436:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4437:                 }
 4438: 	    }
 4439:             if (lc($tagname) eq 'script') {
 4440:                 my $src;
 4441:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4442:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4443:                 } else {
 4444:                     if ($attr->{'src'} ne '') {
 4445:                         $src = $attr->{'src'};
 4446:                         &add_filetype($allfiles,$src,'src');
 4447:                     }
 4448:                 }
 4449:                 my $text = $p->get_trimmed_text();
 4450:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4451:                     my @swfargs = split(/,/,$1);
 4452:                     foreach my $item (@swfargs) {
 4453:                         $item =~ s/["']//g;
 4454:                         $item =~ s/^\s+//;
 4455:                         $item =~ s/\s+$//;
 4456:                     }
 4457:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4458:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4459:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4460:                         } else {
 4461:                             $related{$swfargs[0]} = [$swfargs[2]];
 4462:                         }
 4463:                     }
 4464:                 }
 4465:             }
 4466:             if (lc($tagname) eq 'link') {
 4467:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4468:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4469:                 }
 4470:             }
 4471: 	    if (lc($tagname) eq 'object' ||
 4472: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4473: 		foreach my $item (keys(%javafiles)) {
 4474: 		    $javafiles{$item} = '';
 4475: 		}
 4476:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4477:                     $lastids{lc($tagname)} = $attr->{'id'};
 4478:                 }
 4479: 	    }
 4480: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4481: 		my $name = lc($attr->{'name'});
 4482: 		foreach my $item (keys(%javafiles)) {
 4483: 		    if ($name eq $item) {
 4484: 			$javafiles{$item} = $attr->{'value'};
 4485: 			last;
 4486: 		    }
 4487: 		}
 4488:                 my $pathfrom;
 4489: 		foreach my $item (keys(%mediafiles)) {
 4490: 		    if ($name eq $item) {
 4491:                         $pathfrom = $attr->{'value'};
 4492:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4493: 			&add_filetype($allfiles,$pathfrom,$name);
 4494: 			last;
 4495: 		    }
 4496: 		}
 4497:                 if ($name eq 'flashvars') {
 4498:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4499:                 }
 4500:                 if ($pathfrom ne '') {
 4501:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4502:                                          $pathfrom);
 4503:                 }
 4504: 	    }
 4505: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4506: 		foreach my $item (keys(%javafiles)) {
 4507: 		    if ($attr->{$item}) {
 4508: 			$javafiles{$item} = $attr->{$item};
 4509: 			last;
 4510: 		    }
 4511: 		}
 4512: 		foreach my $item (keys(%mediafiles)) {
 4513: 		    if ($attr->{$item}) {
 4514: 			&add_filetype($allfiles,$attr->{$item},$item);
 4515: 			last;
 4516: 		    }
 4517: 		}
 4518:                 if (lc($tagname) eq 'embed') {
 4519:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4520:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4521:                                              $attr->{'src'});
 4522:                     }
 4523:                 }
 4524: 	    }
 4525:             if (lc($tagname) eq 'iframe') {
 4526:                 my $src = $attr->{'src'} ;
 4527:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4528:                     &add_filetype($allfiles,$src,'src');
 4529:                 } elsif ($src =~ m{^/}) {
 4530:                     if ($env{'request.course.id'}) {
 4531:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4532:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4533:                         my $url = &hreflocation('',$fullpath);
 4534:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4535:                             my $relpath = $1;
 4536:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4537:                                 &add_filetype($allfiles,$1,'src');
 4538:                             }
 4539:                         }
 4540:                     }
 4541:                 }
 4542:             }
 4543:             if ($t->[4] =~ m{/>$}) {
 4544:                 pop(@state);
 4545:             }
 4546: 	} elsif ($t->[0] eq 'E') {
 4547: 	    my ($tagname) = ($t->[1]);
 4548: 	    if ($javafiles{'codebase'} ne '') {
 4549: 		$javafiles{'codebase'} .= '/';
 4550: 	    }  
 4551: 	    if (lc($tagname) eq 'applet' ||
 4552: 		lc($tagname) eq 'object' ||
 4553: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4554: 		) {
 4555: 		foreach my $item (keys(%javafiles)) {
 4556: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4557: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4558: 			&add_filetype($allfiles,$file,$item);
 4559: 		    }
 4560: 		}
 4561: 	    } 
 4562: 	    pop @state;
 4563: 	}
 4564:     }
 4565:     foreach my $id (sort(keys(%flashvars))) {
 4566:         if ($shockwave{$id} ne '') {
 4567:             my @pairs = split(/\&/,$flashvars{$id});
 4568:             foreach my $pair (@pairs) {
 4569:                 my ($key,$value) = split(/\=/,$pair);
 4570:                 if ($key eq 'thumb') {
 4571:                     &add_filetype($allfiles,$value,$key);
 4572:                 } elsif ($key eq 'content') {
 4573:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4574:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4575:                     if ($ext ne '') {
 4576:                         &add_filetype($allfiles,$path.$value,$ext);
 4577:                     }
 4578:                 }
 4579:             }
 4580:         }
 4581:     }
 4582:     return 'ok';
 4583: }
 4584: 
 4585: sub add_filetype {
 4586:     my ($allfiles,$file,$type)=@_;
 4587:     if (exists($allfiles->{$file})) {
 4588: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4589: 	    push(@{$allfiles->{$file}}, &escape($type));
 4590: 	}
 4591:     } else {
 4592: 	@{$allfiles->{$file}} = (&escape($type));
 4593:     }
 4594: }
 4595: 
 4596: sub embedded_dependency {
 4597:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4598:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4599:         if (($identifier ne '') &&
 4600:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4601:             ($pathfrom ne '')) {
 4602:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4603:             foreach my $dep (@{$related->{$identifier}}) {
 4604:                 &add_filetype($allfiles,$path.$dep,'object');
 4605:             }
 4606:         }
 4607:     }
 4608:     return;
 4609: }
 4610: 
 4611: sub bubblesheet_converter {
 4612:     my ($cdom,$fullpath,$config,$format) = @_;
 4613:     if ((&domain($cdom) ne '') &&
 4614:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4615:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4616:         my (%csvcols,%csvoptions);
 4617:         if (ref($config->{'fields'}) eq 'HASH') {  
 4618:             %csvcols = %{$config->{'fields'}};
 4619:         }
 4620:         if (ref($config->{'options'}) eq 'HASH') {
 4621:             %csvoptions = %{$config->{'options'}};
 4622:         }
 4623:         my %csvbynum = reverse(%csvcols);
 4624:         my %scantronconf = &get_scantron_config($format,$cdom);
 4625:         if (keys(%scantronconf)) {
 4626:             my %bynum = (
 4627:                           $scantronconf{CODEstart} => 'CODEstart',
 4628:                           $scantronconf{IDstart}   => 'IDstart',
 4629:                           $scantronconf{PaperID}   => 'PaperID',
 4630:                           $scantronconf{FirstName} => 'FirstName',
 4631:                           $scantronconf{LastName}  => 'LastName',
 4632:                           $scantronconf{Qstart}    => 'Qstart',
 4633:                         );
 4634:             my @ordered;
 4635:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4636:                 push(@ordered,$bynum{$item});
 4637:             }
 4638:             my %mapstart = (
 4639:                               CODEstart => 'CODE',
 4640:                               IDstart   => 'ID',
 4641:                               PaperID   => 'PaperID',
 4642:                               FirstName => 'FirstName',
 4643:                               LastName  => 'LastName',
 4644:                               Qstart    => 'FirstQuestion',
 4645:                            );
 4646:             my %maplength = (
 4647:                               CODEstart => 'CODElength',
 4648:                               IDstart   => 'IDlength',
 4649:                               PaperID   => 'PaperIDlength',
 4650:                               FirstName => 'FirstNamelength',
 4651:                               LastName  => 'LastNamelength',
 4652:             );
 4653:             if (open(my $fh,'<',$fullpath)) {
 4654:                 my $output;
 4655:                 my %lettdig = &letter_to_digits();
 4656:                 my %diglett = reverse(%lettdig);
 4657:                 my $numletts = scalar(keys(%lettdig));
 4658:                 my $num = 0;
 4659:                 while (my $line=<$fh>) {
 4660:                     $num ++;
 4661:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4662:                     $line =~ s{[\r\n]+$}{};
 4663:                     my %found;
 4664:                     my @values = split(/,/,$line,-1);
 4665:                     my ($qstart,$record);
 4666:                     for (my $i=0; $i<@values; $i++) {
 4667:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4668:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4669:                             if ($values[$i] eq '') {
 4670:                                 $values[$i] = $scantronconf{'Qoff'};
 4671:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4672:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4673:                                     $values[$i] = $lettdig{uc($values[$i])};
 4674:                                 }
 4675:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4676:                                 if ($values[$i] =~ /^[0-9]$/) {
 4677:                                     $values[$i] = $diglett{$values[$i]};
 4678:                                 }
 4679:                             } else {
 4680:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4681:                                     my $digit;
 4682:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4683:                                         $digit = $lettdig{uc($values[$i])}-1;
 4684:                                         if ($values[$i] eq 'J') {
 4685:                                             $digit += $numletts;
 4686:                                         }
 4687:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4688:                                         $digit = $values[$i]-1;
 4689:                                         if ($values[$i] eq '0') {
 4690:                                             $digit += $numletts;
 4691:                                         }
 4692:                                     }
 4693:                                     my $qval='';
 4694:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4695:                                         if ($j == $digit) {
 4696:                                             $qval .= $scantronconf{'Qon'};
 4697:                                         } else {
 4698:                                             $qval .= $scantronconf{'Qoff'};
 4699:                                         }
 4700:                                     }
 4701:                                     $values[$i] = $qval;
 4702:                                 }
 4703:                             }
 4704:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4705:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4706:                             }
 4707:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4708:                             if ($numblank > 0) {
 4709:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4710:                             }
 4711:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4712:                                 $qstart = $i;
 4713:                                 $found{$csvbynum{$i}} = $values[$i];
 4714:                             } else {
 4715:                                 $found{'FirstQuestion'} .= $values[$i];
 4716:                             }
 4717:                         } elsif (exists($csvbynum{$i})) {
 4718:                             if ($csvoptions{'rem'}) {
 4719:                                 $values[$i] =~ s/^\s+//;
 4720:                             }
 4721:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4722:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4723:                                     $values[$i] = '0'.$values[$i];
 4724:                                 }
 4725:                             }
 4726:                             $found{$csvbynum{$i}} = $values[$i];
 4727:                         }
 4728:                     }
 4729:                     foreach my $item (@ordered) {
 4730:                         my $currlength = 1+length($record);
 4731:                         my $numspaces = $scantronconf{$item} - $currlength;
 4732:                         if ($numspaces > 0) {
 4733:                             $record .= (' ' x $numspaces);
 4734:                         }
 4735:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4736:                             unless ($item eq 'Qstart') {
 4737:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4738:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4739:                                 }
 4740:                             }
 4741:                             $record .= $found{$mapstart{$item}};
 4742:                         }
 4743:                     }
 4744:                     $output .= "$record\n";
 4745:                 }
 4746:                 close($fh);
 4747:                 if ($output) {
 4748:                     if (open(my $fh,'>',$fullpath)) {
 4749:                         print $fh $output;
 4750:                         close($fh);
 4751:                     }
 4752:                 }
 4753:             }
 4754:         }
 4755:         return;
 4756:     }
 4757: }
 4758: 
 4759: sub letter_to_digits {
 4760:     my %lettdig = (
 4761:                     A => 1,
 4762:                     B => 2,
 4763:                     C => 3,
 4764:                     D => 4,
 4765:                     E => 5,
 4766:                     F => 6,
 4767:                     G => 7,
 4768:                     H => 8,
 4769:                     I => 9,
 4770:                     J => 0,
 4771:                   );
 4772:     return %lettdig;
 4773: }
 4774: 
 4775: sub get_scantron_config {
 4776:     my ($which,$cdom) = @_;
 4777:     my @lines = &get_scantronformat_file($cdom);
 4778:     my %config;
 4779:     #FIXME probably should move to XML it has already gotten a bit much now
 4780:     foreach my $line (@lines) {
 4781:         my ($name,$descrip)=split(/:/,$line);
 4782:         if ($name ne $which ) { next; }
 4783:         chomp($line);
 4784:         my @config=split(/:/,$line);
 4785:         $config{'name'}=$config[0];
 4786:         $config{'description'}=$config[1];
 4787:         $config{'CODElocation'}=$config[2];
 4788:         $config{'CODEstart'}=$config[3];
 4789:         $config{'CODElength'}=$config[4];
 4790:         $config{'IDstart'}=$config[5];
 4791:         $config{'IDlength'}=$config[6];
 4792:         $config{'Qstart'}=$config[7];
 4793:         $config{'Qlength'}=$config[8];
 4794:         $config{'Qoff'}=$config[9];
 4795:         $config{'Qon'}=$config[10];
 4796:         $config{'PaperID'}=$config[11];
 4797:         $config{'PaperIDlength'}=$config[12];
 4798:         $config{'FirstName'}=$config[13];
 4799:         $config{'FirstNamelength'}=$config[14];
 4800:         $config{'LastName'}=$config[15];
 4801:         $config{'LastNamelength'}=$config[16];
 4802:         $config{'BubblesPerRow'}=$config[17];
 4803:         last;
 4804:     }
 4805:     return %config;
 4806: }
 4807: 
 4808: sub get_scantronformat_file {
 4809:     my ($cdom) = @_;
 4810:     if ($cdom eq '') {
 4811:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4812:     }
 4813:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4814:     my $gottab = 0;
 4815:     my @lines;
 4816:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4817:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4818:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4819:             if ($formatfile ne '-1') {
 4820:                 @lines = split("\n",$formatfile,-1);
 4821:                 $gottab = 1;
 4822:             }
 4823:         }
 4824:     }
 4825:     if (!$gottab) {
 4826:         my $confname = $cdom.'-domainconfig';
 4827:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4828:         my $formatfile = &getfile($default);
 4829:         if ($formatfile ne '-1') {
 4830:             @lines = split("\n",$formatfile,-1);
 4831:             $gottab = 1;
 4832:         }
 4833:     }
 4834:     if (!$gottab) {
 4835:         my @domains = &current_machine_domains();
 4836:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4837:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4838:                 @lines = <$fh>;
 4839:                 close($fh);
 4840:             }
 4841:         } else {
 4842:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4843:                 @lines = <$fh>;
 4844:                 close($fh);
 4845:             }
 4846:         }
 4847:     }
 4848:     return @lines;
 4849: }
 4850: 
 4851: sub removeuploadedurl {
 4852:     my ($url)=@_;	
 4853:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4854:     return &removeuserfile($uname,$udom,$fname);
 4855: }
 4856: 
 4857: sub removeuserfile {
 4858:     my ($docuname,$docudom,$fname)=@_;
 4859:     my $home=&homeserver($docuname,$docudom);    
 4860:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4861:     if ($result eq 'ok') {	
 4862:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4863:             my $metafile = $fname.'.meta';
 4864:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4865: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4866:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4867:             my $sqlresult = 
 4868:                 &update_portfolio_table($docuname,$docudom,$file,
 4869:                                         'portfolio_metadata',$group,
 4870:                                         'delete');
 4871:         }
 4872:     }
 4873:     return $result;
 4874: }
 4875: 
 4876: sub mkdiruserfile {
 4877:     my ($docuname,$docudom,$dir)=@_;
 4878:     my $home=&homeserver($docuname,$docudom);
 4879:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4880: }
 4881: 
 4882: sub renameuserfile {
 4883:     my ($docuname,$docudom,$old,$new)=@_;
 4884:     my $home=&homeserver($docuname,$docudom);
 4885:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4886:                         &escape("$old").':'.&escape("$new"),$home);
 4887:     if ($result eq 'ok') {
 4888:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4889:             my $oldmeta = $old.'.meta';
 4890:             my $newmeta = $new.'.meta';
 4891:             my $metaresult = 
 4892:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4893: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4894:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4895:             my $sqlresult = 
 4896:                 &update_portfolio_table($docuname,$docudom,$file,
 4897:                                         'portfolio_metadata',$group,
 4898:                                         'delete');
 4899:         }
 4900:     }
 4901:     return $result;
 4902: }
 4903: 
 4904: # ------------------------------------------------------------------------- Log
 4905: 
 4906: sub log {
 4907:     my ($dom,$nam,$hom,$what)=@_;
 4908:     return critical("log:$dom:$nam:$what",$hom);
 4909: }
 4910: 
 4911: # ------------------------------------------------------------------ Course Log
 4912: #
 4913: # This routine flushes several buffers of non-mission-critical nature
 4914: #
 4915: 
 4916: sub flushcourselogs {
 4917:     &logthis('Flushing log buffers');
 4918: #
 4919: # course logs
 4920: # This is a log of all transactions in a course, which can be used
 4921: # for data mining purposes
 4922: #
 4923: # It also collects the courseid database, which lists last transaction
 4924: # times and course titles for all courseids
 4925: #
 4926:     my %courseidbuffer=();
 4927:     foreach my $crsid (keys(%courselogs)) {
 4928:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4929: 		          &escape($courselogs{$crsid}),
 4930: 		          $coursehombuf{$crsid}) eq 'ok') {
 4931: 	    delete $courselogs{$crsid};
 4932:         } else {
 4933:             &logthis('Failed to flush log buffer for '.$crsid);
 4934:             if (length($courselogs{$crsid})>40000) {
 4935:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4936:                         " exceeded maximum size, deleting.</font>");
 4937:                delete $courselogs{$crsid};
 4938:             }
 4939:         }
 4940:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4941:             'description' => $coursedescrbuf{$crsid},
 4942:             'inst_code'    => $courseinstcodebuf{$crsid},
 4943:             'type'        => $coursetypebuf{$crsid},
 4944:             'owner'       => $courseownerbuf{$crsid},
 4945:         };
 4946:     }
 4947: #
 4948: # Write course id database (reverse lookup) to homeserver of courses 
 4949: # Is used in pickcourse
 4950: #
 4951:     foreach my $crs_home (keys(%courseidbuffer)) {
 4952:         my $response = &courseidput(&host_domain($crs_home),
 4953:                                     $courseidbuffer{$crs_home},
 4954:                                     $crs_home,'timeonly');
 4955:     }
 4956: #
 4957: # File accesses
 4958: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4959: #
 4960:     foreach my $entry (keys(%accesshash)) {
 4961:         if ($entry =~ /___count$/) {
 4962:             my ($dom,$name);
 4963:             ($dom,$name,undef)=
 4964: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4965:             if (! defined($dom) || $dom eq '' || 
 4966:                 ! defined($name) || $name eq '') {
 4967:                 my $cid = $env{'request.course.id'};
 4968: #
 4969: # FIXME 11/29/2021
 4970: # Typo in rev. 1.458 (2003/12/09)??
 4971: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 4972: #
 4973: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 4974: # $dom and $name will always be null, so the &inc() call will default to storing this data
 4975: # in a nohist_accesscount.db file for the user rather than the course.
 4976: #
 4977: # That said there is a lot of noise in the data being stored.
 4978: # So counts for prtspool/  and adm/ etc. are recorded.
 4979: #
 4980: # A review of which items ending '___count' are written to %accesshash should likely be 
 4981: # made before deciding whether to set these to 'course.' instead of 'request.'
 4982: #
 4983: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 4984: # accesses for things which are not published resources, regardless of course, and
 4985: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 4986: # anyone in the course for things which are not published resources.
 4987: #
 4988: # For an author, nohist_accesscount.db ends up having records for other items
 4989: # mixed up with the legitimate access counts for the author's published resources.
 4990: #
 4991:                 $dom  = $env{'request.'.$cid.'.domain'};
 4992:                 $name = $env{'request.'.$cid.'.num'};
 4993:             }
 4994:             my $value = $accesshash{$entry};
 4995:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4996:             my %temphash=($url => $value);
 4997:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4998:             if ($result eq 'ok') {
 4999:                 delete $accesshash{$entry};
 5000:             }
 5001:         } else {
 5002:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5003:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5004:             my %temphash=($entry => $accesshash{$entry});
 5005:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5006:                 delete $accesshash{$entry};
 5007:             }
 5008:         }
 5009:     }
 5010: #
 5011: # Roles
 5012: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5013: #
 5014:     foreach my $entry (keys(%userrolehash)) {
 5015:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5016: 	    split(/\:/,$entry);
 5017:         if (&Apache::lonnet::put('nohist_userroles',
 5018:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5019:                 $rudom,$runame) eq 'ok') {
 5020: 	    delete $userrolehash{$entry};
 5021:         }
 5022:     }
 5023: #
 5024: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5025: #
 5026:     my %domrolebuffer = ();
 5027:     foreach my $entry (keys(%domainrolehash)) {
 5028:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5029:         if ($domrolebuffer{$rudom}) {
 5030:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5031:                       '='.&escape($domainrolehash{$entry});
 5032:         } else {
 5033:             $domrolebuffer{$rudom}.=&escape($entry).
 5034:                       '='.&escape($domainrolehash{$entry});
 5035:         }
 5036:         delete $domainrolehash{$entry};
 5037:     }
 5038:     foreach my $dom (keys(%domrolebuffer)) {
 5039: 	my %servers;
 5040: 	if (defined(&domain($dom,'primary'))) {
 5041: 	    my $primary=&domain($dom,'primary');
 5042: 	    my $hostname=&hostname($primary);
 5043: 	    $servers{$primary} = $hostname;
 5044: 	} else { 
 5045: 	    %servers = &get_servers($dom,'library');
 5046: 	}
 5047: 	foreach my $tryserver (keys(%servers)) {
 5048: 	    if (&reply('domroleput:'.$dom.':'.
 5049: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5050: 		last;
 5051: 	    } else {  
 5052: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5053: 	    }
 5054:         }
 5055:     }
 5056:     $dumpcount++;
 5057: }
 5058: 
 5059: sub courselog {
 5060:     my $what=shift;
 5061:     $what=time.':'.$what;
 5062:     unless ($env{'request.course.id'}) { return ''; }
 5063:     $coursedombuf{$env{'request.course.id'}}=
 5064:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5065:     $coursenumbuf{$env{'request.course.id'}}=
 5066:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5067:     $coursehombuf{$env{'request.course.id'}}=
 5068:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5069:     $coursedescrbuf{$env{'request.course.id'}}=
 5070:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5071:     $courseinstcodebuf{$env{'request.course.id'}}=
 5072:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5073:     $courseownerbuf{$env{'request.course.id'}}=
 5074:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5075:     $coursetypebuf{$env{'request.course.id'}}=
 5076:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5077:     if (defined $courselogs{$env{'request.course.id'}}) {
 5078: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5079:     } else {
 5080: 	$courselogs{$env{'request.course.id'}}.=$what;
 5081:     }
 5082:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5083: 	&flushcourselogs();
 5084:     }
 5085: }
 5086: 
 5087: sub courseacclog {
 5088:     my $fnsymb=shift;
 5089:     unless ($env{'request.course.id'}) { return ''; }
 5090:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5091:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5092:         $what.=':POST';
 5093:         # FIXME: Probably ought to escape things....
 5094: 	foreach my $key (keys(%env)) {
 5095:             if ($key=~/^form\.(.*)/) {
 5096:                 my $formitem = $1;
 5097:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5098:                     $what.=':'.$formitem.'='.$env{$key};
 5099:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5100:                     if ($formitem eq 'proctorpassword') {
 5101:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5102:                     } else {
 5103:                         $what.=':'.$formitem.'='.$env{$key};
 5104:                     }
 5105:                 }
 5106:             }
 5107:         }
 5108:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5109:         # FIXME: We should not be depending on a form parameter that someone
 5110:         # editing lonsearchcat.pm might change in the future.
 5111:         if ($env{'form.phase'} eq 'course_search') {
 5112:             $what.= ':POST';
 5113:             # FIXME: Probably ought to escape things....
 5114:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5115:                                  'crsdiscuss') {
 5116:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5117:             }
 5118:         }
 5119:     }
 5120:     &courselog($what);
 5121: }
 5122: 
 5123: sub countacc {
 5124:     my $url=&declutter(shift);
 5125:     return if (! defined($url) || $url eq '');
 5126:     unless ($env{'request.course.id'}) { return ''; }
 5127: #
 5128: # Mark that this url was used in this course
 5129: #
 5130:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5131: #
 5132: # Increase the access count for this resource in this child process
 5133: #
 5134:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5135:     $accesshash{$key}++;
 5136: }
 5137: 
 5138: sub linklog {
 5139:     my ($from,$to)=@_;
 5140:     $from=&declutter($from);
 5141:     $to=&declutter($to);
 5142:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5143:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5144: }
 5145: 
 5146: sub statslog {
 5147:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5148:     if ($users<2) { return; }
 5149:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5150:             'course'       => $env{'request.course.id'},
 5151:             'sections'     => '"all"',
 5152:             'num_students' => $users,
 5153:             'part'         => $part,
 5154:             'symb'         => $symb,
 5155:             'mean_tries'   => $av_attempts,
 5156:             'deg_of_diff'  => $degdiff});
 5157:     foreach my $key (keys(%dynstore)) {
 5158:         $accesshash{$key}=$dynstore{$key};
 5159:     }
 5160: }
 5161:   
 5162: sub userrolelog {
 5163:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5164:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5165:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5166:        $userrolehash
 5167:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5168:                     =$tend.':'.$tstart;
 5169:     }
 5170:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5171:        $userrolehash
 5172:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5173:                     =$tend.':'.$tstart;
 5174:     }
 5175:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5176:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5177:        $domainrolehash
 5178:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5179:                     = $tend.':'.$tstart;
 5180:     }
 5181: }
 5182: 
 5183: sub courserolelog {
 5184:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5185:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5186:         my $cdom = $1;
 5187:         my $cnum = $2;
 5188:         my $sec = $3;
 5189:         my $namespace = 'rolelog';
 5190:         my %storehash = (
 5191:                            role    => $trole,
 5192:                            start   => $tstart,
 5193:                            end     => $tend,
 5194:                            selfenroll => $selfenroll,
 5195:                            context    => $context,
 5196:                         );
 5197:         if ($trole eq 'gr') {
 5198:             $namespace = 'groupslog';
 5199:             $storehash{'group'} = $sec;
 5200:         } else {
 5201:             $storehash{'section'} = $sec;
 5202:         }
 5203:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5204:                    $domain,$cnum,$cdom);
 5205:         if (($trole ne 'st') || ($sec ne '')) {
 5206:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5207:         }
 5208:     }
 5209:     return;
 5210: }
 5211: 
 5212: sub domainrolelog {
 5213:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5214:     if ($area =~ m{^/($match_domain)/$}) {
 5215:         my $cdom = $1;
 5216:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5217:         my $namespace = 'rolelog';
 5218:         my %storehash = (
 5219:                            role    => $trole,
 5220:                            start   => $tstart,
 5221:                            end     => $tend,
 5222:                            context => $context,
 5223:                         );
 5224:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5225:                    $domain,$domconfiguser,$cdom);
 5226:     }
 5227:     return;
 5228: 
 5229: }
 5230: 
 5231: sub coauthorrolelog {
 5232:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5233:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5234:         my $audom = $1;
 5235:         my $auname = $2;
 5236:         my $namespace = 'rolelog';
 5237:         my %storehash = (
 5238:                            role    => $trole,
 5239:                            start   => $tstart,
 5240:                            end     => $tend,
 5241:                            context => $context,
 5242:                         );
 5243:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5244:                    $domain,$auname,$audom);
 5245:     }
 5246:     return;
 5247: }
 5248: 
 5249: sub get_course_adv_roles {
 5250:     my ($cid,$codes) = @_;
 5251:     $cid=$env{'request.course.id'} unless (defined($cid));
 5252:     my %coursehash=&coursedescription($cid);
 5253:     my $crstype = &Apache::loncommon::course_type($cid);
 5254:     my %nothide=();
 5255:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5256:         if ($user !~ /:/) {
 5257: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5258:         } else {
 5259:             $nothide{$user}=1;
 5260:         }
 5261:     }
 5262:     my @possdoms = ($coursehash{'domain'});
 5263:     if ($coursehash{'checkforpriv'}) {
 5264:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5265:     }
 5266:     my %returnhash=();
 5267:     my %dumphash=
 5268:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5269:     my $now=time;
 5270:     my %privileged;
 5271:     foreach my $entry (keys(%dumphash)) {
 5272: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5273:         if (($tstart) && ($tstart<0)) { next; }
 5274:         if (($tend) && ($tend<$now)) { next; }
 5275:         if (($tstart) && ($now<$tstart)) { next; }
 5276:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5277: 	if ($username eq '' || $domain eq '') { next; }
 5278:         if ((&privileged($username,$domain,\@possdoms)) &&
 5279:             (!$nothide{$username.':'.$domain})) { next; }
 5280: 	if ($role eq 'cr') { next; }
 5281:         if ($codes) {
 5282:             if ($section) { $role .= ':'.$section; }
 5283:             if ($returnhash{$role}) {
 5284:                 $returnhash{$role}.=','.$username.':'.$domain;
 5285:             } else {
 5286:                 $returnhash{$role}=$username.':'.$domain;
 5287:             }
 5288:         } else {
 5289:             my $key=&plaintext($role,$crstype);
 5290:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5291:             if ($returnhash{$key}) {
 5292: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5293:             } else {
 5294:                 $returnhash{$key}=$username.':'.$domain;
 5295:             }
 5296:         }
 5297:     }
 5298:     return %returnhash;
 5299: }
 5300: 
 5301: sub get_my_roles {
 5302:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5303:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5304:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5305:     my (%dumphash,%nothide);
 5306:     if ($context eq 'userroles') {
 5307:         %dumphash = &dump('roles',$udom,$uname);
 5308:     } else {
 5309:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5310:         if ($hidepriv) {
 5311:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5312:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5313:                 if ($user !~ /:/) {
 5314:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5315:                 } else {
 5316:                     $nothide{$user} = 1;
 5317:                 }
 5318:             }
 5319:         }
 5320:     }
 5321:     my %returnhash=();
 5322:     my $now=time;
 5323:     my %privileged;
 5324:     foreach my $entry (keys(%dumphash)) {
 5325:         my ($role,$tend,$tstart);
 5326:         if ($context eq 'userroles') {
 5327:             next if ($entry =~ /^rolesdef/);
 5328: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5329:         } else {
 5330:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5331:         }
 5332:         if (($tstart) && ($tstart<0)) { next; }
 5333:         my $status = 'active';
 5334:         if (($tend) && ($tend<=$now)) {
 5335:             $status = 'previous';
 5336:         } 
 5337:         if (($tstart) && ($now<$tstart)) {
 5338:             $status = 'future';
 5339:         }
 5340:         if (ref($types) eq 'ARRAY') {
 5341:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5342:                 next;
 5343:             } 
 5344:         } else {
 5345:             if ($status ne 'active') {
 5346:                 next;
 5347:             }
 5348:         }
 5349:         my ($rolecode,$username,$domain,$section,$area);
 5350:         if ($context eq 'userroles') {
 5351:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5352:             (undef,$domain,$username,$section) = split(/\//,$area);
 5353:         } else {
 5354:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5355:         }
 5356:         if (ref($roledoms) eq 'ARRAY') {
 5357:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5358:                 next;
 5359:             }
 5360:         }
 5361:         if (ref($roles) eq 'ARRAY') {
 5362:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5363:                 if ($role =~ /^cr\//) {
 5364:                     if (!grep(/^cr$/,@{$roles})) {
 5365:                         next;
 5366:                     }
 5367:                 } elsif ($role =~ /^gr\//) {
 5368:                     if (!grep(/^gr$/,@{$roles})) {
 5369:                         next;
 5370:                     }
 5371:                 } else {
 5372:                     next;
 5373:                 }
 5374:             }
 5375:         }
 5376:         if ($hidepriv) {
 5377:             my @privroles = ('dc','su');
 5378:             if ($context eq 'userroles') {
 5379:                 next if (grep(/^\Q$role\E$/,@privroles));
 5380:             } else {
 5381:                 my $possdoms = [$domain];
 5382:                 if (ref($roledoms) eq 'ARRAY') {
 5383:                    push(@{$possdoms},@{$roledoms}); 
 5384:                 }
 5385:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5386:                     if (!$nothide{$username.':'.$domain}) {
 5387:                         next;
 5388:                     }
 5389:                 }
 5390:             }
 5391:         }
 5392:         if ($withsec) {
 5393:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5394:                 $tstart.':'.$tend;
 5395:         } else {
 5396:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5397:         }
 5398:     }
 5399:     return %returnhash;
 5400: }
 5401: 
 5402: sub get_all_adhocroles {
 5403:     my ($dom) = @_;
 5404:     my @roles_by_num = ();
 5405:     my %domdefaults = &get_domain_defaults($dom);
 5406:     my (%description,%access_in_dom,%access_info);
 5407:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5408:         my $count = 0;
 5409:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5410:         my %ordered;
 5411:         foreach my $role (sort(keys(%domcurrent))) {
 5412:             my ($order,$desc,$access_in_dom);
 5413:             if (ref($domcurrent{$role}) eq 'HASH') {
 5414:                 $order = $domcurrent{$role}{'order'};
 5415:                 $desc = $domcurrent{$role}{'desc'};
 5416:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5417:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5418:             }
 5419:             if ($order eq '') {
 5420:                 $order = $count;
 5421:             }
 5422:             $ordered{$order} = $role;
 5423:             if ($desc ne '') {
 5424:                 $description{$role} = $desc;
 5425:             } else {
 5426:                 $description{$role}= $role;
 5427:             }
 5428:             $count++;
 5429:         }
 5430:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5431:             push(@roles_by_num,$ordered{$item});
 5432:         }
 5433:     }
 5434:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5435: }
 5436: 
 5437: sub get_my_adhocroles {
 5438:     my ($cid,$checkreg) = @_;
 5439:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5440:     if ($env{'request.course.id'} eq $cid) {
 5441:         $cdom = $env{'course.'.$cid.'.domain'};
 5442:         $cnum = $env{'course.'.$cid.'.num'};
 5443:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5444:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5445:         $cdom = $1;
 5446:         $cnum = $2;
 5447:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5448:                                      $cdom,$cnum);
 5449:     }
 5450:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5451:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5452:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5453:         if ($rosterhash{$user} ne '') {
 5454:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5455:             return ([],{}) if ($type eq 'auto');
 5456:         }
 5457:     }
 5458:     if (($cdom ne '') && ($cnum ne ''))  {
 5459:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5460:             my $then=$env{'user.login.time'};
 5461:             my $update=$env{'user.update.time'};
 5462:             if (!$update) {
 5463:                 $update = $then;
 5464:             }
 5465:             my @liveroles;
 5466:             foreach my $role ('dh','da') {
 5467:                 if ($env{"user.role.$role./$cdom/"}) {
 5468:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5469:                     my $limit = $update;
 5470:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5471:                         $limit = $then;
 5472:                     }
 5473:                     my $activerole = 1;
 5474:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5475:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5476:                     if ($activerole) {
 5477:                         push(@liveroles,$role);
 5478:                     }
 5479:                 }
 5480:             }
 5481:             if (@liveroles) {
 5482:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5483:                     my ($accessref,$accessinfo,%access_in_dom);
 5484:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5485:                     if (ref($roles_by_num) eq 'ARRAY') {
 5486:                         if (@{$roles_by_num}) {
 5487:                             my %settings;
 5488:                             if ($env{'request.course.id'} eq $cid) {
 5489:                                 foreach my $envkey (keys(%env)) {
 5490:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5491:                                         $settings{$1} = $env{$envkey};
 5492:                                     }
 5493:                                 }
 5494:                             } else {
 5495:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5496:                             }
 5497:                             my %setincrs;
 5498:                             if ($settings{'internal.adhocaccess'}) {
 5499:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5500:                             }
 5501:                             my @statuses;
 5502:                             if ($env{'environment.inststatus'}) {
 5503:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5504:                             }
 5505:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5506:                             if (ref($accessref) eq 'HASH') {
 5507:                                 %access_in_dom = %{$accessref};
 5508:                             }
 5509:                             foreach my $role (@{$roles_by_num}) {
 5510:                                 my ($curraccess,@okstatus,@personnel);
 5511:                                 if ($setincrs{$role}) {
 5512:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5513:                                     if ($curraccess eq 'status') {
 5514:                                         @okstatus = split(/\&/,$rest);
 5515:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5516:                                         @personnel = split(/\&/,$rest);
 5517:                                     }
 5518:                                 } else {
 5519:                                     $curraccess = $access_in_dom{$role};
 5520:                                     if (ref($accessinfo) eq 'HASH') {
 5521:                                         if ($curraccess eq 'status') {
 5522:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5523:                                                 @okstatus = @{$accessinfo->{$role}};
 5524:                                             }
 5525:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5526:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5527:                                                 @personnel = @{$accessinfo->{$role}};
 5528:                                             }
 5529:                                         }
 5530:                                     }
 5531:                                 }
 5532:                                 if ($curraccess eq 'none') {
 5533:                                     next;
 5534:                                 } elsif ($curraccess eq 'all') {
 5535:                                     push(@possroles,$role);
 5536:                                 } elsif ($curraccess eq 'dh') {
 5537:                                     if (grep(/^dh$/,@liveroles)) {
 5538:                                         push(@possroles,$role);
 5539:                                     } else {
 5540:                                         next;
 5541:                                     }
 5542:                                 } elsif ($curraccess eq 'da') {
 5543:                                     if (grep(/^da$/,@liveroles)) {
 5544:                                         push(@possroles,$role);
 5545:                                     } else {
 5546:                                         next;
 5547:                                     }
 5548:                                 } elsif ($curraccess eq 'status') {
 5549:                                     if (@okstatus) {
 5550:                                         if (!@statuses) {
 5551:                                             if (grep(/^default$/,@okstatus)) {
 5552:                                                 push(@possroles,$role);
 5553:                                             }
 5554:                                         } else {
 5555:                                             foreach my $status (@okstatus) {
 5556:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5557:                                                     push(@possroles,$role);
 5558:                                                     last;
 5559:                                                 }
 5560:                                             }
 5561:                                         }
 5562:                                     }
 5563:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5564:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5565:                                         if ($curraccess eq 'exc') {
 5566:                                             push(@possroles,$role);
 5567:                                         }
 5568:                                     } elsif ($curraccess eq 'inc') {
 5569:                                         push(@possroles,$role);
 5570:                                     }
 5571:                                 }
 5572:                             }
 5573:                         }
 5574:                     }
 5575:                 }
 5576:             }
 5577:         }
 5578:     }
 5579:     unless (ref($description) eq 'HASH') {
 5580:         if (ref($roles_by_num) eq 'ARRAY') {
 5581:             my %desc;
 5582:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5583:             $description = \%desc;
 5584:         } else {
 5585:             $description = {};
 5586:         }
 5587:     }
 5588:     return (\@possroles,$description);
 5589: }
 5590: 
 5591: # ----------------------------------------------------- Frontpage Announcements
 5592: #
 5593: #
 5594: 
 5595: sub postannounce {
 5596:     my ($server,$text)=@_;
 5597:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5598:     unless ($text=~/\w/) { $text=''; }
 5599:     return &reply('setannounce:'.&escape($text),$server);
 5600: }
 5601: 
 5602: sub getannounce {
 5603: 
 5604:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5605: 	my $announcement='';
 5606: 	while (my $line = <$fh>) { $announcement .= $line; }
 5607: 	close($fh);
 5608: 	if ($announcement=~/\w/) { 
 5609: 	    return 
 5610:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5611:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5612: 	} else {
 5613: 	    return '';
 5614: 	}
 5615:     } else {
 5616: 	return '';
 5617:     }
 5618: }
 5619: 
 5620: # ---------------------------------------------------------- Course ID routines
 5621: # Deal with domain's nohist_courseid.db files
 5622: #
 5623: 
 5624: sub courseidput {
 5625:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5626:     return unless (ref($storehash) eq 'HASH');
 5627:     my $outcome;
 5628:     if ($caller eq 'timeonly') {
 5629:         my $cids = '';
 5630:         foreach my $item (keys(%$storehash)) {
 5631:             $cids.=&escape($item).'&';
 5632:         }
 5633:         $cids=~s/\&$//;
 5634:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5635:                           $coursehome);       
 5636:     } else {
 5637:         my $items = '';
 5638:         foreach my $item (keys(%$storehash)) {
 5639:             $items.= &escape($item).'='.
 5640:                      &freeze_escape($$storehash{$item}).'&';
 5641:         }
 5642:         $items=~s/\&$//;
 5643:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5644:                           $coursehome);
 5645:     }
 5646:     if ($outcome eq 'unknown_cmd') {
 5647:         my $what;
 5648:         foreach my $cid (keys(%$storehash)) {
 5649:             $what .= &escape($cid).'=';
 5650:             foreach my $item ('description','inst_code','owner','type') {
 5651:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5652:             }
 5653:             $what =~ s/\:$/&/;
 5654:         }
 5655:         $what =~ s/\&$//;  
 5656:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5657:     } else {
 5658:         return $outcome;
 5659:     }
 5660: }
 5661: 
 5662: sub courseiddump {
 5663:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5664:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5665:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5666:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5667:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5668:     my $as_hash = 1;
 5669:     my %returnhash;
 5670:     if (!$domfilter) { $domfilter=''; }
 5671:     my %libserv = &all_library();
 5672:     foreach my $tryserver (keys(%libserv)) {
 5673:         if ( (  $hostidflag == 1 
 5674: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5675: 	     || (!defined($hostidflag)) ) {
 5676: 
 5677: 	    if (($domfilter eq '') ||
 5678: 		(&host_domain($tryserver) eq $domfilter)) {
 5679:                 my $rep;
 5680:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5681:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5682:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5683:                                 &escape($descfilter), &escape($instcodefilter), 
 5684:                                 &escape($ownerfilter), &escape($coursefilter),
 5685:                                 &escape($typefilter), &escape($regexp_ok), 
 5686:                                 $as_hash, &escape($selfenrollonly), 
 5687:                                 &escape($catfilter), $showhidden, $caller, 
 5688:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5689:                                 &escape($createdbefore), &escape($createdafter), 
 5690:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5691:                                 $reqcrsdom,&escape($reqinstcode))));
 5692:                 } else {
 5693:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5694:                              $sincefilter.':'.&escape($descfilter).':'.
 5695:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5696:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5697:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5698:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5699:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5700:                              &escape($cc_clone).':'.$cloneonly.':'.
 5701:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5702:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5703:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5704:                 }
 5705:                      
 5706:                 my @pairs=split(/\&/,$rep);
 5707:                 foreach my $item (@pairs) {
 5708:                     my ($key,$value)=split(/\=/,$item,2);
 5709:                     $key = &unescape($key);
 5710:                     next if ($key =~ /^error: 2 /);
 5711:                     my $result = &thaw_unescape($value);
 5712:                     if (ref($result) eq 'HASH') {
 5713:                         $returnhash{$key}=$result;
 5714:                     } else {
 5715:                         my @responses = split(/:/,$value);
 5716:                         my @items = ('description','inst_code','owner','type');
 5717:                         for (my $i=0; $i<@responses; $i++) {
 5718:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5719:                         }
 5720:                     }
 5721:                 }
 5722:             }
 5723:         }
 5724:     }
 5725:     return %returnhash;
 5726: }
 5727: 
 5728: sub courselastaccess {
 5729:     my ($cdom,$cnum,$hostidref) = @_;
 5730:     my %returnhash;
 5731:     if ($cdom && $cnum) {
 5732:         my $chome = &homeserver($cnum,$cdom);
 5733:         if ($chome ne 'no_host') {
 5734:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5735:             &extract_lastaccess(\%returnhash,$rep);
 5736:         }
 5737:     } else {
 5738:         if (!$cdom) { $cdom=''; }
 5739:         my %libserv = &all_library();
 5740:         foreach my $tryserver (keys(%libserv)) {
 5741:             if (ref($hostidref) eq 'ARRAY') {
 5742:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5743:             } 
 5744:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5745:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5746:                 &extract_lastaccess(\%returnhash,$rep);
 5747:             }
 5748:         }
 5749:     }
 5750:     return %returnhash;
 5751: }
 5752: 
 5753: sub extract_lastaccess {
 5754:     my ($returnhash,$rep) = @_;
 5755:     if (ref($returnhash) eq 'HASH') {
 5756:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5757:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5758:                  $rep eq '') {
 5759:             my @pairs=split(/\&/,$rep);
 5760:             foreach my $item (@pairs) {
 5761:                 my ($key,$value)=split(/\=/,$item,2);
 5762:                 $key = &unescape($key);
 5763:                 next if ($key =~ /^error: 2 /);
 5764:                 $returnhash->{$key} = &thaw_unescape($value);
 5765:             }
 5766:         }
 5767:     }
 5768:     return;
 5769: }
 5770: 
 5771: # ---------------------------------------------------------- DC e-mail
 5772: 
 5773: sub dcmailput {
 5774:     my ($domain,$msgid,$message,$server)=@_;
 5775:     my $status = &Apache::lonnet::critical(
 5776:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5777:        &escape($message),$server);
 5778:     return $status;
 5779: }
 5780: 
 5781: sub dcmaildump {
 5782:     my ($dom,$startdate,$enddate,$senders) = @_;
 5783:     my %returnhash=();
 5784: 
 5785:     if (defined(&domain($dom,'primary'))) {
 5786:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5787:                                                          &escape($enddate).':';
 5788: 	my @esc_senders=map { &escape($_)} @$senders;
 5789: 	$cmd.=&escape(join('&',@esc_senders));
 5790: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5791:             my ($key,$value) = split(/\=/,$line,2);
 5792:             if (($key) && ($value)) {
 5793:                 $returnhash{&unescape($key)} = &unescape($value);
 5794:             }
 5795:         }
 5796:     }
 5797:     return %returnhash;
 5798: }
 5799: # ---------------------------------------------------------- Domain roles
 5800: 
 5801: sub get_domain_roles {
 5802:     my ($dom,$roles,$startdate,$enddate)=@_;
 5803:     if ((!defined($startdate)) || ($startdate eq '')) {
 5804:         $startdate = '.';
 5805:     }
 5806:     if ((!defined($enddate)) || ($enddate eq '')) {
 5807:         $enddate = '.';
 5808:     }
 5809:     my $rolelist;
 5810:     if (ref($roles) eq 'ARRAY') {
 5811:         $rolelist = join('&',@{$roles});
 5812:     }
 5813:     my %personnel = ();
 5814: 
 5815:     my %servers = &get_servers($dom,'library');
 5816:     foreach my $tryserver (keys(%servers)) {
 5817: 	%{$personnel{$tryserver}}=();
 5818: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5819: 					    &escape($startdate).':'.
 5820: 					    &escape($enddate).':'.
 5821: 					    &escape($rolelist), $tryserver))) {
 5822: 	    my ($key,$value) = split(/\=/,$line,2);
 5823: 	    if (($key) && ($value)) {
 5824: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5825: 	    }
 5826: 	}
 5827:     }
 5828:     return %personnel;
 5829: }
 5830: 
 5831: sub get_active_domroles {
 5832:     my ($dom,$roles) = @_;
 5833:     return () unless (ref($roles) eq 'ARRAY');
 5834:     my $now = time;
 5835:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5836:     my %domroles;
 5837:     foreach my $server (keys(%dompersonnel)) {
 5838:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5839:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5840:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5841:         }
 5842:     }
 5843:     return %domroles;
 5844: }
 5845: 
 5846: # ----------------------------------------------------------- Interval timing 
 5847: 
 5848: {
 5849: # Caches needed for speedup of navmaps
 5850: # We don't want to cache this for very long at all (5 seconds at most)
 5851: # 
 5852: # The user for whom we cache
 5853: my $cachedkey='';
 5854: # The cached times for this user
 5855: my %cachedtimes=();
 5856: # When this was last done
 5857: my $cachedtime='';
 5858: 
 5859: sub load_all_first_access {
 5860:     my ($uname,$udom,$ignorecache)=@_;
 5861:     if (($cachedkey eq $uname.':'.$udom) &&
 5862:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5863:         (!$ignorecache)) {
 5864:         return;
 5865:     }
 5866:     $cachedtime=time;
 5867:     $cachedkey=$uname.':'.$udom;
 5868:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5869: }
 5870: 
 5871: sub get_first_access {
 5872:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5873:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5874:     if ($argsymb) { $symb=$argsymb; }
 5875:     my ($map,$id,$res)=&decode_symb($symb);
 5876:     if ($argmap) { $map = $argmap; }
 5877:     if ($type eq 'course') {
 5878: 	$res='course';
 5879:     } elsif ($type eq 'map') {
 5880: 	$res=&symbread($map);
 5881:     } else {
 5882: 	$res=$symb;
 5883:     }
 5884:     &load_all_first_access($uname,$udom,$ignorecache);
 5885:     return $cachedtimes{"$courseid\0$res"};
 5886: }
 5887: 
 5888: sub set_first_access {
 5889:     my ($type,$interval)=@_;
 5890:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5891:     my ($map,$id,$res)=&decode_symb($symb);
 5892:     if ($type eq 'course') {
 5893: 	$res='course';
 5894:     } elsif ($type eq 'map') {
 5895: 	$res=&symbread($map);
 5896:     } else {
 5897: 	$res=$symb;
 5898:     }
 5899:     $cachedkey='';
 5900:     my $firstaccess=&get_first_access($type,$symb,$map);
 5901:     if ($firstaccess) {
 5902:         &logthis("First access time already set ($firstaccess) when attempting ".
 5903:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5904:                  "in $courseid");
 5905:         return 'already_set';
 5906:     } else {
 5907:         my $start = time;
 5908: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5909:                           $udom,$uname);
 5910:         if ($putres eq 'ok') {
 5911:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5912:                  $udom,$uname); 
 5913:             &appenv(
 5914:                      {
 5915:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5916:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5917:                      }
 5918:                   );
 5919:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5920:                 $cachedtimes{"$courseid\0$res"} = $start;
 5921:             }
 5922:         } elsif ($putres ne 'refused') {
 5923:             &logthis("Result: $putres when attempting to set first access time ".
 5924:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5925:         }
 5926:         return $putres;
 5927:     }
 5928:     return 'already_set';
 5929: }
 5930: }
 5931: 
 5932: # --------------------------------------------- Set Expire Date for Spreadsheet
 5933: 
 5934: sub expirespread {
 5935:     my ($uname,$udom,$stype,$usymb)=@_;
 5936:     my $cid=$env{'request.course.id'}; 
 5937:     if ($cid) {
 5938:        my $now=time;
 5939:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5940:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5941:                             $env{'course.'.$cid.'.num'}.
 5942: 	        	    ':nohist_expirationdates:'.
 5943:                             &escape($key).'='.$now,
 5944:                             $env{'course.'.$cid.'.home'})
 5945:     }
 5946:     return 'ok';
 5947: }
 5948: 
 5949: # ----------------------------------------------------- Devalidate Spreadsheets
 5950: 
 5951: sub devalidate {
 5952:     my ($symb,$uname,$udom)=@_;
 5953:     my $cid=$env{'request.course.id'}; 
 5954:     if ($cid) {
 5955:         # delete the stored spreadsheets for
 5956:         # - the student level sheet of this user in course's homespace
 5957:         # - the assessment level sheet for this resource 
 5958:         #   for this user in user's homespace
 5959: 	# - current conditional state info
 5960: 	my $key=$uname.':'.$udom.':';
 5961:         my $status=
 5962: 	    &del('nohist_calculatedsheets',
 5963: 		 [$key.'studentcalc:'],
 5964: 		 $env{'course.'.$cid.'.domain'},
 5965: 		 $env{'course.'.$cid.'.num'})
 5966: 		.' '.
 5967: 	    &del('nohist_calculatedsheets_'.$cid,
 5968: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5969:         unless ($status eq 'ok ok') {
 5970:            &logthis('Could not devalidate spreadsheet '.
 5971:                     $uname.' at '.$udom.' for '.
 5972: 		    $symb.': '.$status);
 5973:         }
 5974: 	&delenv('user.state.'.$cid);
 5975:     }
 5976: }
 5977: 
 5978: sub get_scalar {
 5979:     my ($string,$end) = @_;
 5980:     my $value;
 5981:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5982: 	$value = $1;
 5983:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5984: 	$value = $1;
 5985:     }
 5986:     return &unescape($value);
 5987: }
 5988: 
 5989: sub array2str {
 5990:   my (@array) = @_;
 5991:   my $result=&arrayref2str(\@array);
 5992:   $result=~s/^__ARRAY_REF__//;
 5993:   $result=~s/__END_ARRAY_REF__$//;
 5994:   return $result;
 5995: }
 5996: 
 5997: sub arrayref2str {
 5998:   my ($arrayref) = @_;
 5999:   my $result='__ARRAY_REF__';
 6000:   foreach my $elem (@$arrayref) {
 6001:     if(ref($elem) eq 'ARRAY') {
 6002:       $result.=&arrayref2str($elem).'&';
 6003:     } elsif(ref($elem) eq 'HASH') {
 6004:       $result.=&hashref2str($elem).'&';
 6005:     } elsif(ref($elem)) {
 6006:       #print("Got a ref of ".(ref($elem))." skipping.");
 6007:     } else {
 6008:       $result.=&escape($elem).'&';
 6009:     }
 6010:   }
 6011:   $result=~s/\&$//;
 6012:   $result .= '__END_ARRAY_REF__';
 6013:   return $result;
 6014: }
 6015: 
 6016: sub hash2str {
 6017:   my (%hash) = @_;
 6018:   my $result=&hashref2str(\%hash);
 6019:   $result=~s/^__HASH_REF__//;
 6020:   $result=~s/__END_HASH_REF__$//;
 6021:   return $result;
 6022: }
 6023: 
 6024: sub hashref2str {
 6025:   my ($hashref)=@_;
 6026:   my $result='__HASH_REF__';
 6027:   foreach my $key (sort(keys(%$hashref))) {
 6028:     if (ref($key) eq 'ARRAY') {
 6029:       $result.=&arrayref2str($key).'=';
 6030:     } elsif (ref($key) eq 'HASH') {
 6031:       $result.=&hashref2str($key).'=';
 6032:     } elsif (ref($key)) {
 6033:       $result.='=';
 6034:       #print("Got a ref of ".(ref($key))." skipping.");
 6035:     } else {
 6036: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6037:     }
 6038: 
 6039:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6040:       $result.=&arrayref2str($hashref->{$key}).'&';
 6041:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6042:       $result.=&hashref2str($hashref->{$key}).'&';
 6043:     } elsif(ref($hashref->{$key})) {
 6044:        $result.='&';
 6045:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6046:     } else {
 6047:       $result.=&escape($hashref->{$key}).'&';
 6048:     }
 6049:   }
 6050:   $result=~s/\&$//;
 6051:   $result .= '__END_HASH_REF__';
 6052:   return $result;
 6053: }
 6054: 
 6055: sub str2hash {
 6056:     my ($string)=@_;
 6057:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6058:     return %$hash;
 6059: }
 6060: 
 6061: sub str2hashref {
 6062:   my ($string) = @_;
 6063: 
 6064:   my %hash;
 6065: 
 6066:   if($string !~ /^__HASH_REF__/) {
 6067:       if (! ($string eq '' || !defined($string))) {
 6068: 	  $hash{'error'}='Not hash reference';
 6069:       }
 6070:       return (\%hash, $string);
 6071:   }
 6072: 
 6073:   $string =~ s/^__HASH_REF__//;
 6074: 
 6075:   while($string !~ /^__END_HASH_REF__/) {
 6076:       #key
 6077:       my $key='';
 6078:       if($string =~ /^__HASH_REF__/) {
 6079:           ($key, $string)=&str2hashref($string);
 6080:           if(defined($key->{'error'})) {
 6081:               $hash{'error'}='Bad data';
 6082:               return (\%hash, $string);
 6083:           }
 6084:       } elsif($string =~ /^__ARRAY_REF__/) {
 6085:           ($key, $string)=&str2arrayref($string);
 6086:           if($key->[0] eq 'Array reference error') {
 6087:               $hash{'error'}='Bad data';
 6088:               return (\%hash, $string);
 6089:           }
 6090:       } else {
 6091:           $string =~ s/^(.*?)=//;
 6092: 	  $key=&unescape($1);
 6093:       }
 6094:       $string =~ s/^=//;
 6095: 
 6096:       #value
 6097:       my $value='';
 6098:       if($string =~ /^__HASH_REF__/) {
 6099:           ($value, $string)=&str2hashref($string);
 6100:           if(defined($value->{'error'})) {
 6101:               $hash{'error'}='Bad data';
 6102:               return (\%hash, $string);
 6103:           }
 6104:       } elsif($string =~ /^__ARRAY_REF__/) {
 6105:           ($value, $string)=&str2arrayref($string);
 6106:           if($value->[0] eq 'Array reference error') {
 6107:               $hash{'error'}='Bad data';
 6108:               return (\%hash, $string);
 6109:           }
 6110:       } else {
 6111: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6112:       }
 6113:       $string =~ s/^&//;
 6114: 
 6115:       $hash{$key}=$value;
 6116:   }
 6117: 
 6118:   $string =~ s/^__END_HASH_REF__//;
 6119: 
 6120:   return (\%hash, $string);
 6121: }
 6122: 
 6123: sub str2array {
 6124:     my ($string)=@_;
 6125:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6126:     return @$array;
 6127: }
 6128: 
 6129: sub str2arrayref {
 6130:   my ($string) = @_;
 6131:   my @array;
 6132: 
 6133:   if($string !~ /^__ARRAY_REF__/) {
 6134:       if (! ($string eq '' || !defined($string))) {
 6135: 	  $array[0]='Array reference error';
 6136:       }
 6137:       return (\@array, $string);
 6138:   }
 6139: 
 6140:   $string =~ s/^__ARRAY_REF__//;
 6141: 
 6142:   while($string !~ /^__END_ARRAY_REF__/) {
 6143:       my $value='';
 6144:       if($string =~ /^__HASH_REF__/) {
 6145:           ($value, $string)=&str2hashref($string);
 6146:           if(defined($value->{'error'})) {
 6147:               $array[0] ='Array reference error';
 6148:               return (\@array, $string);
 6149:           }
 6150:       } elsif($string =~ /^__ARRAY_REF__/) {
 6151:           ($value, $string)=&str2arrayref($string);
 6152:           if($value->[0] eq 'Array reference error') {
 6153:               $array[0] ='Array reference error';
 6154:               return (\@array, $string);
 6155:           }
 6156:       } else {
 6157: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6158:       }
 6159:       $string =~ s/^&//;
 6160: 
 6161:       push(@array, $value);
 6162:   }
 6163: 
 6164:   $string =~ s/^__END_ARRAY_REF__//;
 6165: 
 6166:   return (\@array, $string);
 6167: }
 6168: 
 6169: # -------------------------------------------------------------------Temp Store
 6170: 
 6171: sub tmpreset {
 6172:   my ($symb,$namespace,$domain,$stuname) = @_;
 6173:   if (!$symb) {
 6174:     $symb=&symbread();
 6175:     if (!$symb) { $symb= $env{'request.url'}; }
 6176:   }
 6177:   $symb=escape($symb);
 6178: 
 6179:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6180:   $namespace=~s/\//\_/g;
 6181:   $namespace=~s/\W//g;
 6182: 
 6183:   if (!$domain) { $domain=$env{'user.domain'}; }
 6184:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6185:   if ($domain eq 'public' && $stuname eq 'public') {
 6186:       $stuname=&get_requestor_ip();
 6187:   }
 6188:   my $path=LONCAPA::tempdir();
 6189:   my %hash;
 6190:   if (tie(%hash,'GDBM_File',
 6191: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6192: 	  &GDBM_WRCREAT(),0640)) {
 6193:     foreach my $key (keys(%hash)) {
 6194:       if ($key=~ /:$symb/) {
 6195: 	delete($hash{$key});
 6196:       }
 6197:     }
 6198:   }
 6199: }
 6200: 
 6201: sub tmpstore {
 6202:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6203: 
 6204:   if (!$symb) {
 6205:     $symb=&symbread();
 6206:     if (!$symb) { $symb= $env{'request.url'}; }
 6207:   }
 6208:   $symb=escape($symb);
 6209: 
 6210:   if (!$namespace) {
 6211:     # I don't think we would ever want to store this for a course.
 6212:     # it seems this will only be used if we don't have a course.
 6213:     #$namespace=$env{'request.course.id'};
 6214:     #if (!$namespace) {
 6215:       $namespace=$env{'request.state'};
 6216:     #}
 6217:   }
 6218:   $namespace=~s/\//\_/g;
 6219:   $namespace=~s/\W//g;
 6220:   if (!$domain) { $domain=$env{'user.domain'}; }
 6221:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6222:   if ($domain eq 'public' && $stuname eq 'public') {
 6223:       $stuname=&get_requestor_ip();
 6224:   }
 6225:   my $now=time;
 6226:   my %hash;
 6227:   my $path=LONCAPA::tempdir();
 6228:   if (tie(%hash,'GDBM_File',
 6229: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6230: 	  &GDBM_WRCREAT(),0640)) {
 6231:     $hash{"version:$symb"}++;
 6232:     my $version=$hash{"version:$symb"};
 6233:     my $allkeys=''; 
 6234:     foreach my $key (keys(%$storehash)) {
 6235:       $allkeys.=$key.':';
 6236:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6237:     }
 6238:     $hash{"$version:$symb:timestamp"}=$now;
 6239:     $allkeys.='timestamp';
 6240:     $hash{"$version:keys:$symb"}=$allkeys;
 6241:     if (untie(%hash)) {
 6242:       return 'ok';
 6243:     } else {
 6244:       return "error:$!";
 6245:     }
 6246:   } else {
 6247:     return "error:$!";
 6248:   }
 6249: }
 6250: 
 6251: # -----------------------------------------------------------------Temp Restore
 6252: 
 6253: sub tmprestore {
 6254:   my ($symb,$namespace,$domain,$stuname) = @_;
 6255: 
 6256:   if (!$symb) {
 6257:     $symb=&symbread();
 6258:     if (!$symb) { $symb= $env{'request.url'}; }
 6259:   }
 6260:   $symb=escape($symb);
 6261: 
 6262:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6263: 
 6264:   if (!$domain) { $domain=$env{'user.domain'}; }
 6265:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6266:   if ($domain eq 'public' && $stuname eq 'public') {
 6267:       $stuname=&get_requestor_ip();
 6268:   }
 6269:   my %returnhash;
 6270:   $namespace=~s/\//\_/g;
 6271:   $namespace=~s/\W//g;
 6272:   my %hash;
 6273:   my $path=LONCAPA::tempdir();
 6274:   if (tie(%hash,'GDBM_File',
 6275: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6276: 	  &GDBM_READER(),0640)) {
 6277:     my $version=$hash{"version:$symb"};
 6278:     $returnhash{'version'}=$version;
 6279:     my $scope;
 6280:     for ($scope=1;$scope<=$version;$scope++) {
 6281:       my $vkeys=$hash{"$scope:keys:$symb"};
 6282:       my @keys=split(/:/,$vkeys);
 6283:       my $key;
 6284:       $returnhash{"$scope:keys"}=$vkeys;
 6285:       foreach $key (@keys) {
 6286: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6287: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6288:       }
 6289:     }
 6290:     if (!(untie(%hash))) {
 6291:       return "error:$!";
 6292:     }
 6293:   } else {
 6294:     return "error:$!";
 6295:   }
 6296:   return %returnhash;
 6297: }
 6298: 
 6299: # ----------------------------------------------------------------------- Store
 6300: 
 6301: sub store {
 6302:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6303:     my $home='';
 6304: 
 6305:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6306: 
 6307:     $symb=&symbclean($symb);
 6308:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6309: 
 6310:     if (!$domain) { $domain=$env{'user.domain'}; }
 6311:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6312: 
 6313:     &devalidate($symb,$stuname,$domain);
 6314: 
 6315:     $symb=escape($symb);
 6316:     if (!$namespace) { 
 6317:        unless ($namespace=$env{'request.course.id'}) { 
 6318:           return ''; 
 6319:        } 
 6320:     }
 6321:     if (!$home) { $home=$env{'user.home'}; }
 6322: 
 6323:     $$storehash{'ip'}=&get_requestor_ip();
 6324:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6325: 
 6326:     my $namevalue='';
 6327:     foreach my $key (keys(%$storehash)) {
 6328:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6329:     }
 6330:     $namevalue=~s/\&$//;
 6331:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6332:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6333: }
 6334: 
 6335: # -------------------------------------------------------------- Critical Store
 6336: 
 6337: sub cstore {
 6338:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6339:     my $home='';
 6340: 
 6341:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6342: 
 6343:     $symb=&symbclean($symb);
 6344:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6345: 
 6346:     if (!$domain) { $domain=$env{'user.domain'}; }
 6347:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6348: 
 6349:     &devalidate($symb,$stuname,$domain);
 6350: 
 6351:     $symb=escape($symb);
 6352:     if (!$namespace) { 
 6353:        unless ($namespace=$env{'request.course.id'}) { 
 6354:           return ''; 
 6355:        } 
 6356:     }
 6357:     if (!$home) { $home=$env{'user.home'}; }
 6358: 
 6359:     $$storehash{'ip'}=&get_requestor_ip();
 6360:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6361: 
 6362:     my $namevalue='';
 6363:     foreach my $key (keys(%$storehash)) {
 6364:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6365:     }
 6366:     $namevalue=~s/\&$//;
 6367:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6368:     return critical
 6369:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6370: }
 6371: 
 6372: # --------------------------------------------------------------------- Restore
 6373: 
 6374: sub restore {
 6375:     my ($symb,$namespace,$domain,$stuname) = @_;
 6376:     my $home='';
 6377: 
 6378:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6379: 
 6380:     if (!$symb) {
 6381:         return if ($namespace eq 'courserequests');
 6382:         unless ($symb=escape(&symbread())) { return ''; }
 6383:     } else {
 6384:         unless ($namespace eq 'courserequests') {
 6385:             $symb=&escape(&symbclean($symb));
 6386:         }
 6387:     }
 6388:     if (!$namespace) { 
 6389:        unless ($namespace=$env{'request.course.id'}) { 
 6390:           return ''; 
 6391:        } 
 6392:     }
 6393:     if (!$domain) { $domain=$env{'user.domain'}; }
 6394:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6395:     if (!$home) { $home=$env{'user.home'}; }
 6396:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6397: 
 6398:     my %returnhash=();
 6399:     foreach my $line (split(/\&/,$answer)) {
 6400: 	my ($name,$value)=split(/\=/,$line);
 6401:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6402:     }
 6403:     my $version;
 6404:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6405:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6406:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6407:        }
 6408:     }
 6409:     return %returnhash;
 6410: }
 6411: 
 6412: # ---------------------------------------------------------- Course Description
 6413: #
 6414: #  
 6415: 
 6416: sub coursedescription {
 6417:     my ($courseid,$args)=@_;
 6418:     $courseid=~s/^\///;
 6419:     $courseid=~s/\_/\//g;
 6420:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6421:     my $chome=&homeserver($cnum,$cdomain);
 6422:     my $normalid=$cdomain.'_'.$cnum;
 6423:     # need to always cache even if we get errors otherwise we keep 
 6424:     # trying and trying and trying to get the course description.
 6425:     my %envhash=();
 6426:     my %returnhash=();
 6427:     
 6428:     my $expiretime=600;
 6429:     if ($env{'request.course.id'} eq $normalid) {
 6430: 	$expiretime=120;
 6431:     }
 6432: 
 6433:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6434:     if (!$args->{'freshen_cache'}
 6435: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6436: 	foreach my $key (keys(%env)) {
 6437: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6438: 	    my ($setting) = $1;
 6439: 	    $returnhash{$setting} = $env{$key};
 6440: 	}
 6441: 	return %returnhash;
 6442:     }
 6443: 
 6444:     # get the data again
 6445: 
 6446:     if (!$args->{'one_time'}) {
 6447: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6448:     }
 6449: 
 6450:     if ($chome ne 'no_host') {
 6451:        %returnhash=&dump('environment',$cdomain,$cnum);
 6452:        if (!exists($returnhash{'con_lost'})) {
 6453: 	   my $username = $env{'user.name'}; # Defult username
 6454: 	   if(defined $args->{'user'}) {
 6455: 	       $username = $args->{'user'};
 6456: 	   }
 6457:            $returnhash{'home'}= $chome;
 6458: 	   $returnhash{'domain'} = $cdomain;
 6459: 	   $returnhash{'num'} = $cnum;
 6460:            if (!defined($returnhash{'type'})) {
 6461:                $returnhash{'type'} = 'Course';
 6462:            }
 6463:            while (my ($name,$value) = each %returnhash) {
 6464:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6465:            }
 6466:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6467:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6468: 	       $username.'_'.$cdomain.'_'.$cnum;
 6469:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6470:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6471:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6472:        }
 6473:     }
 6474:     if (!$args->{'one_time'}) {
 6475: 	&appenv(\%envhash);
 6476:     }
 6477:     return %returnhash;
 6478: }
 6479: 
 6480: sub update_released_required {
 6481:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6482:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6483:         $cid = $env{'request.course.id'};
 6484:         $cdom = $env{'course.'.$cid.'.domain'};
 6485:         $cnum = $env{'course.'.$cid.'.num'};
 6486:         $chome = $env{'course.'.$cid.'.home'};
 6487:     }
 6488:     if ($needsrelease) {
 6489:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6490:         my $needsupdate;
 6491:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6492:             $needsupdate = 1;
 6493:         } else {
 6494:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6495:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6496:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6497:                 $needsupdate = 1;
 6498:             }
 6499:         }
 6500:         if ($needsupdate) {
 6501:             my %needshash = (
 6502:                              'internal.releaserequired' => $needsrelease,
 6503:                             );
 6504:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6505:             if ($putresult eq 'ok') {
 6506:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6507:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6508:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6509:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6510:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6511:                 }
 6512:             }
 6513:         }
 6514:     }
 6515:     return;
 6516: }
 6517: 
 6518: # -------------------------------------------------See if a user is privileged
 6519: 
 6520: sub privileged {
 6521:     my ($username,$domain,$possdomains,$possroles)=@_;
 6522:     my $now = time;
 6523:     my $roles;
 6524:     if (ref($possroles) eq 'ARRAY') {
 6525:         $roles = $possroles; 
 6526:     } else {
 6527:         $roles = ['dc','su'];
 6528:     }
 6529:     if (ref($possdomains) eq 'ARRAY') {
 6530:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6531:         foreach my $dom (@{$possdomains}) {
 6532:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6533:                 (ref($privileged{$dom}) eq 'HASH')) {
 6534:                 foreach my $role (@{$roles}) {
 6535:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6536:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6537:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6538:                             return 1 unless (($end && $end < $now) ||
 6539:                                              ($start && $start > $now));
 6540:                         }
 6541:                     }
 6542:                 }
 6543:             }
 6544:         }
 6545:     } else {
 6546:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6547:         my $now = time;
 6548: 
 6549:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6550:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6551:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6552:                 return 1 unless ($tend && $tend < $now) 
 6553:                         or ($tstart && $tstart > $now);
 6554:             }
 6555:         }
 6556:     }
 6557:     return 0;
 6558: }
 6559: 
 6560: sub privileged_by_domain {
 6561:     my ($domains,$roles) = @_;
 6562:     my %privileged = ();
 6563:     my $cachetime = 60*60*24;
 6564:     my $now = time;
 6565:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6566:         return %privileged;
 6567:     }
 6568:     foreach my $dom (@{$domains}) {
 6569:         next if (ref($privileged{$dom}) eq 'HASH');
 6570:         my $needroles;
 6571:         foreach my $role (@{$roles}) {
 6572:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6573:             if (defined($cached)) {
 6574:                 if (ref($result) eq 'HASH') {
 6575:                     $privileged{$dom}{$role} = $result;
 6576:                 }
 6577:             } else {
 6578:                 $needroles = 1;
 6579:             }
 6580:         }
 6581:         if ($needroles) {
 6582:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6583:             $privileged{$dom} = {};
 6584:             foreach my $server (keys(%dompersonnel)) {
 6585:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6586:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6587:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6588:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6589:                         next if ($end && $end < $now);
 6590:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6591:                             $dompersonnel{$server}{$item};
 6592:                     }
 6593:                 }
 6594:             }
 6595:             if (ref($privileged{$dom}) eq 'HASH') {
 6596:                 foreach my $role (@{$roles}) {
 6597:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6598:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6599:                     } else {
 6600:                         my %hash = ();
 6601:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6602:                     }
 6603:                 }
 6604:             }
 6605:         }
 6606:     }
 6607:     return %privileged;
 6608: }
 6609: 
 6610: # -------------------------------------------------------- Get user privileges
 6611: 
 6612: sub rolesinit {
 6613:     my ($domain, $username) = @_;
 6614:     my %userroles = ('user.login.time' => time);
 6615:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6616: 
 6617:     # firstaccess and timerinterval are related to timed maps/resources. 
 6618:     # also, blocking can be triggered by an activating timer
 6619:     # it's saved in the user's %env.
 6620:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6621:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6622:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6623:         %timerintchk, %timerintenv);
 6624: 
 6625:     foreach my $key (keys(%firstaccess)) {
 6626:         my ($cid, $rest) = split(/\0/, $key);
 6627:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6628:     }
 6629: 
 6630:     foreach my $key (keys(%timerinterval)) {
 6631:         my ($cid,$rest) = split(/\0/,$key);
 6632:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6633:     }
 6634: 
 6635:     my %allroles=();
 6636:     my %allgroups=();
 6637: 
 6638:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6639:         my $role = $rolesdump{$area};
 6640:         $area =~ s/\_\w\w$//;
 6641: 
 6642:         my ($trole, $tend, $tstart, $group_privs);
 6643: 
 6644:         if ($role =~ /^cr/) {
 6645:         # Custom role, defined by a user 
 6646:         # e.g., user.role.cr/msu/smith/mynewrole
 6647:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6648:                 $trole = $1;
 6649:                 ($tend, $tstart) = split('_', $2);
 6650:             } else {
 6651:                 $trole = $role;
 6652:             }
 6653:         } elsif ($role =~ m|^gr/|) {
 6654:         # Role of member in a group, defined within a course/community
 6655:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6656:             ($trole, $tend, $tstart) = split(/_/, $role);
 6657:             next if $tstart eq '-1';
 6658:             ($trole, $group_privs) = split(/\//, $trole);
 6659:             $group_privs = &unescape($group_privs);
 6660:         } else {
 6661:         # Just a normal role, defined in roles.tab
 6662:             ($trole, $tend, $tstart) = split(/_/,$role);
 6663:         }
 6664: 
 6665:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6666:                  $username);
 6667:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6668: 
 6669:         # role expired or not available yet?
 6670:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6671:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6672: 
 6673:         next if $area eq '' or $trole eq '';
 6674: 
 6675:         my $spec = "$trole.$area";
 6676:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6677: 
 6678:         if ($trole =~ /^cr\//) {
 6679:         # Custom role, defined by a user
 6680:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6681:         } elsif ($trole eq 'gr') {
 6682:         # Role of a member in a group, defined within a course/community
 6683:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6684:             next;
 6685:         } else {
 6686:         # Normal role, defined in roles.tab
 6687:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6688:         }
 6689: 
 6690:         my $cid = $tdomain.'_'.$trest;
 6691:         unless ($firstaccchk{$cid}) {
 6692:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6693:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6694:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6695:                         $coursetimerstarts{$cid}{$item}; 
 6696:                 }
 6697:             }
 6698:             $firstaccchk{$cid} = 1;
 6699:         }
 6700:         unless ($timerintchk{$cid}) {
 6701:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6702:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6703:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6704:                        $coursetimerintervals{$cid}{$item};
 6705:                 }
 6706:             }
 6707:             $timerintchk{$cid} = 1;
 6708:         }
 6709:     }
 6710: 
 6711:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6712:                                                           \%allroles, \%allgroups);
 6713:     $env{'user.adv'} = $userroles{'user.adv'};
 6714:     $env{'user.rar'} = $userroles{'user.rar'};
 6715: 
 6716:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6717: }
 6718: 
 6719: sub set_arearole {
 6720:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6721:     unless ($nolog) {
 6722: # log the associated role with the area
 6723:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6724:     }
 6725:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6726: }
 6727: 
 6728: sub custom_roleprivs {
 6729:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6730:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6731:     my $homsvr = &homeserver($rauthor,$rdomain);
 6732:     if (&hostname($homsvr) ne '') {
 6733:         my ($rdummy,$roledef)=
 6734:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6735:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6736:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6737:             if (defined($syspriv)) {
 6738:                 if ($trest =~ /^$match_community$/) {
 6739:                     $syspriv =~ s/bre\&S//; 
 6740:                 }
 6741:                 $$allroles{'cm./'}.=':'.$syspriv;
 6742:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6743:             }
 6744:             if ($tdomain ne '') {
 6745:                 if (defined($dompriv)) {
 6746:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6747:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6748:                 }
 6749:                 if (($trest ne '') && (defined($coursepriv))) {
 6750:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6751:                         my $rolename = $1;
 6752:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6753:                     }
 6754:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6755:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6756:                 }
 6757:             }
 6758:         }
 6759:     }
 6760: }
 6761: 
 6762: sub course_adhocrole_privs {
 6763:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6764:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6765:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6766:         my (%currprivs,%storeprivs);
 6767:         foreach my $item (split(/:/,$coursepriv)) {
 6768:             my ($priv,$restrict) = split(/\&/,$item);
 6769:             $currprivs{$priv} = $restrict;
 6770:         }
 6771:         my (%possadd,%possremove,%full);
 6772:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6773:             my ($priv,$restrict)=split(/\&/,$item);
 6774:             $full{$priv} = $restrict;
 6775:         }
 6776:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6777:              next if ($item eq '');
 6778:              my ($rule,$rest) = split(/=/,$item);
 6779:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6780:              foreach my $priv (split(/:/,$rest)) {
 6781:                  if ($priv ne '') {
 6782:                      if ($rule eq 'off') {
 6783:                          $possremove{$priv} = 1;
 6784:                      } else {
 6785:                          $possadd{$priv} = 1;
 6786:                      }
 6787:                  }
 6788:              }
 6789:          }
 6790:          foreach my $priv (sort(keys(%full))) {
 6791:              if (exists($currprivs{$priv})) {
 6792:                  unless (exists($possremove{$priv})) {
 6793:                      $storeprivs{$priv} = $currprivs{$priv};
 6794:                  }
 6795:              } elsif (exists($possadd{$priv})) {
 6796:                  $storeprivs{$priv} = $full{$priv};
 6797:              }
 6798:          }
 6799:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6800:      }
 6801:      return $coursepriv;
 6802: }
 6803: 
 6804: sub group_roleprivs {
 6805:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6806:     my $access = 1;
 6807:     my $now = time;
 6808:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6809:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6810:     if ($access) {
 6811:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6812:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6813:     }
 6814: }
 6815: 
 6816: sub standard_roleprivs {
 6817:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6818:     if (defined($pr{$trole.':s'})) {
 6819:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6820:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6821:     }
 6822:     if ($tdomain ne '') {
 6823:         if (defined($pr{$trole.':d'})) {
 6824:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6825:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6826:         }
 6827:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6828:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6829:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6830:         }
 6831:     }
 6832: }
 6833: 
 6834: sub set_userprivs {
 6835:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6836:     my $author=0;
 6837:     my $adv=0;
 6838:     my $rar=0;
 6839:     my %grouproles = ();
 6840:     if (keys(%{$allgroups}) > 0) {
 6841:         my @groupkeys; 
 6842:         foreach my $role (keys(%{$allroles})) {
 6843:             push(@groupkeys,$role);
 6844:         }
 6845:         if (ref($groups_roles) eq 'HASH') {
 6846:             foreach my $key (keys(%{$groups_roles})) {
 6847:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6848:                     push(@groupkeys,$key);
 6849:                 }
 6850:             }
 6851:         }
 6852:         if (@groupkeys > 0) {
 6853:             foreach my $role (@groupkeys) {
 6854:                 my ($trole,$area,$sec,$extendedarea);
 6855:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6856:                     $trole = $1;
 6857:                     $area = $2;
 6858:                     $sec = $3;
 6859:                     $extendedarea = $area.$sec;
 6860:                     if (exists($$allgroups{$area})) {
 6861:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6862:                             my $spec = $trole.'.'.$extendedarea;
 6863:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6864:                                                 $$allgroups{$area}{$group};
 6865:                         }
 6866:                     }
 6867:                 }
 6868:             }
 6869:         }
 6870:     }
 6871:     foreach my $group (keys(%grouproles)) {
 6872:         $$allroles{$group} = $grouproles{$group};
 6873:     }
 6874:     foreach my $role (keys(%{$allroles})) {
 6875:         my %thesepriv;
 6876:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6877:         foreach my $item (split(/:/,$$allroles{$role})) {
 6878:             if ($item ne '') {
 6879:                 my ($privilege,$restrictions)=split(/&/,$item);
 6880:                 if ($restrictions eq '') {
 6881:                     $thesepriv{$privilege}='F';
 6882:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6883:                     $thesepriv{$privilege}.=$restrictions;
 6884:                 }
 6885:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6886:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6887:             }
 6888:         }
 6889:         my $thesestr='';
 6890:         foreach my $priv (sort(keys(%thesepriv))) {
 6891: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6892: 	}
 6893:         $userroles->{'user.priv.'.$role} = $thesestr;
 6894:     }
 6895:     return ($author,$adv,$rar);
 6896: }
 6897: 
 6898: sub role_status {
 6899:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6900:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6901:         my ($one,$two) = split(m{\./},$rolekey,2);
 6902:         (undef,undef,$$role) = split(/\./,$one,3);
 6903:         unless (!defined($$role) || $$role eq '') {
 6904:             $$where = '/'.$two;
 6905:             $$trolecode=$$role.'.'.$$where;
 6906:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6907:             $$tstatus='is';
 6908:             if ($$tstart && $$tstart>$update) {
 6909:                 $$tstatus='future';
 6910:                 if ($$tstart<$now) {
 6911:                     if ($$tstart && $$tstart>$refresh) {
 6912:                         if (($$where ne '') && ($$role ne '')) {
 6913:                             my (%allroles,%allgroups,$group_privs,
 6914:                                 %groups_roles,@rolecodes);
 6915:                             my %userroles = (
 6916:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6917:                             );
 6918:                             @rolecodes = ('cm'); 
 6919:                             my $spec=$$role.'.'.$$where;
 6920:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6921:                             if ($$role =~ /^cr\//) {
 6922:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6923:                                 push(@rolecodes,'cr');
 6924:                             } elsif ($$role eq 'gr') {
 6925:                                 push(@rolecodes,$$role);
 6926:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6927:                                                     $env{'user.name'});
 6928:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6929:                                 (undef,my $group_privs) = split(/\//,$trole);
 6930:                                 $group_privs = &unescape($group_privs);
 6931:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6932:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6933:                                 &get_groups_roles($tdomain,$trest,
 6934:                                                   \%course_roles,\@rolecodes,
 6935:                                                   \%groups_roles);
 6936:                             } else {
 6937:                                 push(@rolecodes,$$role);
 6938:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6939:                             }
 6940:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6941:                                                                    \%groups_roles);
 6942:                             &appenv(\%userroles,\@rolecodes);
 6943:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6944:                         }
 6945:                     }
 6946:                     $$tstatus = 'is';
 6947:                 }
 6948:             }
 6949:             if ($$tend) {
 6950:                 if ($$tend<$update) {
 6951:                     $$tstatus='expired';
 6952:                 } elsif ($$tend<$now) {
 6953:                     $$tstatus='will_not';
 6954:                 }
 6955:             }
 6956:         }
 6957:     }
 6958: }
 6959: 
 6960: sub get_groups_roles {
 6961:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6962:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6963:                   (ref($rolecodes) eq 'ARRAY') && 
 6964:                   (ref($groups_roles) eq 'HASH')); 
 6965:     if (keys(%{$cdom_courseroles}) > 0) {
 6966:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6967:         if ($cdom ne '' && $cnum ne '') {
 6968:             foreach my $key (keys(%{$cdom_courseroles})) {
 6969:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6970:                     my $crsrole = $1;
 6971:                     my $crssec = $2;
 6972:                     if ($crsrole =~ /^cr/) {
 6973:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6974:                             push(@{$rolecodes},'cr');
 6975:                         }
 6976:                     } else {
 6977:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6978:                             push(@{$rolecodes},$crsrole);
 6979:                         }
 6980:                     }
 6981:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6982:                     if ($crssec ne '') {
 6983:                         $rolekey .= "/$crssec";
 6984:                     }
 6985:                     $rolekey .= './';
 6986:                     $groups_roles->{$rolekey} = $rolecodes;
 6987:                 }
 6988:             }
 6989:         }
 6990:     }
 6991:     return;
 6992: }
 6993: 
 6994: sub delete_env_groupprivs {
 6995:     my ($where,$courseroles,$possroles) = @_;
 6996:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6997:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6998:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6999:         %{$courseroles->{$udom}} =
 7000:             &get_my_roles('','','userroles',['active'],
 7001:                           $possroles,[$udom],1);
 7002:     }
 7003:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7004:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7005:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7006:             my $area = '/'.$cdom.'/'.$cnum;
 7007:             my $privkey = "user.priv.$crsrole.$area";
 7008:             if ($crssec ne '') {
 7009:                 $privkey .= '/'.$crssec;
 7010:             }
 7011:             $privkey .= ".$area/$group";
 7012:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7013:         }
 7014:     }
 7015:     return;
 7016: }
 7017: 
 7018: sub check_adhoc_privs {
 7019:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7020:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7021:     if ($sec) {
 7022:         $cckey .= '/'.$sec;
 7023:     } 
 7024:     my $setprivs;
 7025:     if ($env{$cckey}) {
 7026:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7027:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7028:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7029:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7030:             $setprivs = 1;
 7031:         }
 7032:     } else {
 7033:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7034:         $setprivs = 1;
 7035:     }
 7036:     return $setprivs;
 7037: }
 7038: 
 7039: sub set_adhoc_privileges {
 7040: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7041:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7042:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7043:     if ($sec ne '') {
 7044:         $area .= '/'.$sec;
 7045:     }
 7046:     my $spec = $role.'.'.$area;
 7047:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7048:                                   $env{'user.name'},1);
 7049:     my %rolehash = ();
 7050:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7051:         my $rolename = $1;
 7052:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7053:         my %domdef = &get_domain_defaults($dcdom);
 7054:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7055:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7056:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7057:             }
 7058:         }
 7059:     } else {
 7060:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7061:     }
 7062:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7063:     &appenv(\%userroles,[$role,'cm']);
 7064:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7065:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7066:             ($caller eq 'tiny')) {
 7067:         &appenv( {'request.role'        => $spec,
 7068:                   'request.role.domain' => $dcdom,
 7069:                   'request.course.sec'  => $sec,
 7070:                  }
 7071:                );
 7072:         my $tadv=0;
 7073:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7074:         &appenv({'request.role.adv'    => $tadv});
 7075:     }
 7076: }
 7077: 
 7078: # --------------------------------------------------------------- get interface
 7079: 
 7080: sub get {
 7081:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7082:    my $items='';
 7083:    foreach my $item (@$storearr) {
 7084:        $items.=&escape($item).'&';
 7085:    }
 7086:    $items=~s/\&$//;
 7087:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7088:    if (!$uname) { $uname=$env{'user.name'}; }
 7089:    my $uhome=&homeserver($uname,$udomain);
 7090: 
 7091:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7092:    my @pairs=split(/\&/,$rep);
 7093:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7094:      return @pairs;
 7095:    }
 7096:    my %returnhash=();
 7097:    my $i=0;
 7098:    foreach my $item (@$storearr) {
 7099:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7100:       $i++;
 7101:    }
 7102:    return %returnhash;
 7103: }
 7104: 
 7105: # --------------------------------------------------------------- del interface
 7106: 
 7107: sub del {
 7108:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7109:    my $items='';
 7110:    foreach my $item (@$storearr) {
 7111:        $items.=&escape($item).'&';
 7112:    }
 7113: 
 7114:    $items=~s/\&$//;
 7115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7116:    if (!$uname) { $uname=$env{'user.name'}; }
 7117:    my $uhome=&homeserver($uname,$udomain);
 7118:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7119: }
 7120: 
 7121: # -------------------------------------------------------------- dump interface
 7122: 
 7123: sub unserialize {
 7124:     my ($rep, $escapedkeys) = @_;
 7125: 
 7126:     return {} if $rep =~ /^error/;
 7127: 
 7128:     my %returnhash=();
 7129: 	foreach my $item (split(/\&/,$rep)) {
 7130: 	    my ($key, $value) = split(/=/, $item, 2);
 7131: 	    $key = unescape($key) unless $escapedkeys;
 7132: 	    next if $key =~ /^error: 2 /;
 7133: 	    $returnhash{$key} = &thaw_unescape($value);
 7134: 	}
 7135:     #return %returnhash;
 7136:     return \%returnhash;
 7137: }        
 7138: 
 7139: # see Lond::dump_with_regexp
 7140: # if $escapedkeys hash keys won't get unescaped.
 7141: sub dump {
 7142:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7143:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7144:     if (!$uname) { $uname=$env{'user.name'}; }
 7145:     my $uhome=&homeserver($uname,$udomain);
 7146: 
 7147:     if ($regexp) {
 7148:         $regexp=&escape($regexp);
 7149:     } else {
 7150:         $regexp='.';
 7151:     }
 7152:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7153:         # user is hosted on this machine
 7154:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7155:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7156:         return %{unserialize($reply, $escapedkeys)};
 7157:     }
 7158:     my $rep;
 7159:     if ($encrypt) {
 7160:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7161:     } else {
 7162:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7163:     }
 7164:     my @pairs=split(/\&/,$rep);
 7165:     my %returnhash=();
 7166:     if (!($rep =~ /^error/ )) {
 7167: 	foreach my $item (@pairs) {
 7168: 	    my ($key,$value)=split(/=/,$item,2);
 7169:         $key = unescape($key) unless $escapedkeys;
 7170:         #$key = &unescape($key);
 7171: 	    next if ($key =~ /^error: 2 /);
 7172: 	    $returnhash{$key}=&thaw_unescape($value);
 7173: 	}
 7174:     }
 7175:     return %returnhash;
 7176: }
 7177: 
 7178: 
 7179: # --------------------------------------------------------- dumpstore interface
 7180: 
 7181: sub dumpstore {
 7182:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7183:    # same as dump but keys must be escaped. They may contain colon separated
 7184:    # lists of values that may themself contain colons (e.g. symbs).
 7185:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7186: }
 7187: 
 7188: # -------------------------------------------------------------- keys interface
 7189: 
 7190: sub getkeys {
 7191:    my ($namespace,$udomain,$uname)=@_;
 7192:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7193:    if (!$uname) { $uname=$env{'user.name'}; }
 7194:    my $uhome=&homeserver($uname,$udomain);
 7195:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7196:    my @keyarray=();
 7197:    foreach my $key (split(/\&/,$rep)) {
 7198:       next if ($key =~ /^error: 2 /);
 7199:       push(@keyarray,&unescape($key));
 7200:    }
 7201:    return @keyarray;
 7202: }
 7203: 
 7204: # --------------------------------------------------------------- currentdump
 7205: sub currentdump {
 7206:    my ($courseid,$sdom,$sname)=@_;
 7207:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7208:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7209:    $sname    = $env{'user.name'}         if (! defined($sname));
 7210:    my $uhome = &homeserver($sname,$sdom);
 7211:    my $rep;
 7212: 
 7213:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7214:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7215:                    $courseid)));
 7216:    } else {
 7217:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7218:    }
 7219: 
 7220:    return if ($rep =~ /^(error:|no_such_host)/);
 7221:    #
 7222:    my %returnhash=();
 7223:    #
 7224:    if ($rep eq 'unknown_cmd') {
 7225:        # an old lond will not know currentdump
 7226:        # Do a dump and make it look like a currentdump
 7227:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7228:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7229:        my %hash = @tmp;
 7230:        @tmp=();
 7231:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7232:    } else {
 7233:        my @pairs=split(/\&/,$rep);
 7234:        foreach my $pair (@pairs) {
 7235:            my ($key,$value)=split(/=/,$pair,2);
 7236:            my ($symb,$param) = split(/:/,$key);
 7237:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7238:                                                         &thaw_unescape($value);
 7239:        }
 7240:    }
 7241:    return %returnhash;
 7242: }
 7243: 
 7244: sub convert_dump_to_currentdump{
 7245:     my %hash = %{shift()};
 7246:     my %returnhash;
 7247:     # Code ripped from lond, essentially.  The only difference
 7248:     # here is the unescaping done by lonnet::dump().  Conceivably
 7249:     # we might run in to problems with parameter names =~ /^v\./
 7250:     while (my ($key,$value) = each(%hash)) {
 7251:         my ($v,$symb,$param) = split(/:/,$key);
 7252: 	$symb  = &unescape($symb);
 7253: 	$param = &unescape($param);
 7254:         next if ($v eq 'version' || $symb eq 'keys');
 7255:         next if (exists($returnhash{$symb}) &&
 7256:                  exists($returnhash{$symb}->{$param}) &&
 7257:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7258:         $returnhash{$symb}->{$param}=$value;
 7259:         $returnhash{$symb}->{'v.'.$param}=$v;
 7260:     }
 7261:     #
 7262:     # Remove all of the keys in the hashes which keep track of
 7263:     # the version of the parameter.
 7264:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7265:         # use a foreach because we are going to delete from the hash.
 7266:         foreach my $key (keys(%$param_hash)) {
 7267:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7268:         }
 7269:     }
 7270:     return \%returnhash;
 7271: }
 7272: 
 7273: # ------------------------------------------------------ critical inc interface
 7274: 
 7275: sub cinc {
 7276:     return &inc(@_,'critical');
 7277: }
 7278: 
 7279: # --------------------------------------------------------------- inc interface
 7280: 
 7281: sub inc {
 7282:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7283:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7284:     if (!$uname) { $uname=$env{'user.name'}; }
 7285:     my $uhome=&homeserver($uname,$udomain);
 7286:     my $items='';
 7287:     if (! ref($store)) {
 7288:         # got a single value, so use that instead
 7289:         $items = &escape($store).'=&';
 7290:     } elsif (ref($store) eq 'SCALAR') {
 7291:         $items = &escape($$store).'=&';        
 7292:     } elsif (ref($store) eq 'ARRAY') {
 7293:         $items = join('=&',map {&escape($_);} @{$store});
 7294:     } elsif (ref($store) eq 'HASH') {
 7295:         while (my($key,$value) = each(%{$store})) {
 7296:             $items.= &escape($key).'='.&escape($value).'&';
 7297:         }
 7298:     }
 7299:     $items=~s/\&$//;
 7300:     if ($critical) {
 7301: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7302:     } else {
 7303: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7304:     }
 7305: }
 7306: 
 7307: # --------------------------------------------------------------- put interface
 7308: 
 7309: sub put {
 7310:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7312:    if (!$uname) { $uname=$env{'user.name'}; }
 7313:    my $uhome=&homeserver($uname,$udomain);
 7314:    my $items='';
 7315:    foreach my $item (keys(%$storehash)) {
 7316:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7317:    }
 7318:    $items=~s/\&$//;
 7319:    if ($encrypt) {
 7320:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7321:    } else {
 7322:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7323:    }
 7324: }
 7325: 
 7326: # ------------------------------------------------------------ newput interface
 7327: 
 7328: sub newput {
 7329:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7330:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7331:    if (!$uname) { $uname=$env{'user.name'}; }
 7332:    my $uhome=&homeserver($uname,$udomain);
 7333:    my $items='';
 7334:    foreach my $key (keys(%$storehash)) {
 7335:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7336:    }
 7337:    $items=~s/\&$//;
 7338:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7339: }
 7340: 
 7341: # ---------------------------------------------------------  putstore interface
 7342: 
 7343: sub putstore {
 7344:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7345:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7346:    if (!$uname) { $uname=$env{'user.name'}; }
 7347:    my $uhome=&homeserver($uname,$udomain);
 7348:    my $items='';
 7349:    foreach my $key (keys(%$storehash)) {
 7350:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7351:    }
 7352:    $items=~s/\&$//;
 7353:    my $esc_symb=&escape($symb);
 7354:    my $esc_v=&escape($version);
 7355:    my $reply =
 7356:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7357: 	      $uhome);
 7358:    if (($tolog) && ($reply eq 'ok')) {
 7359:        my $namevalue='';
 7360:        foreach my $key (keys(%{$storehash})) {
 7361:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7362:        }
 7363:        my $ip = &get_requestor_ip();
 7364:        $namevalue .= 'ip='.&escape($ip).
 7365:                      '&host='.&escape($perlvar{'lonHostID'}).
 7366:                      '&version='.$esc_v.
 7367:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7368:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7369:    }
 7370:    if ($reply eq 'unknown_cmd') {
 7371:        # gfall back to way things use to be done
 7372:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7373: 			    $uname);
 7374:    }
 7375:    return $reply;
 7376: }
 7377: 
 7378: sub old_putstore {
 7379:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7380:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7381:     if (!$uname) { $uname=$env{'user.name'}; }
 7382:     my $uhome=&homeserver($uname,$udomain);
 7383:     my %newstorehash;
 7384:     foreach my $item (keys(%$storehash)) {
 7385: 	my $key = $version.':'.&escape($symb).':'.$item;
 7386: 	$newstorehash{$key} = $storehash->{$item};
 7387:     }
 7388:     my $items='';
 7389:     my %allitems = ();
 7390:     foreach my $item (keys(%newstorehash)) {
 7391: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7392: 	    my $key = $1.':keys:'.$2;
 7393: 	    $allitems{$key} .= $3.':';
 7394: 	}
 7395: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7396:     }
 7397:     foreach my $item (keys(%allitems)) {
 7398: 	$allitems{$item} =~ s/\:$//;
 7399: 	$items.= $item.'='.$allitems{$item}.'&';
 7400:     }
 7401:     $items=~s/\&$//;
 7402:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7403: }
 7404: 
 7405: # ------------------------------------------------------ critical put interface
 7406: 
 7407: sub cput {
 7408:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7409:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7410:    if (!$uname) { $uname=$env{'user.name'}; }
 7411:    my $uhome=&homeserver($uname,$udomain);
 7412:    my $items='';
 7413:    foreach my $item (keys(%$storehash)) {
 7414:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7415:    }
 7416:    $items=~s/\&$//;
 7417:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7418: }
 7419: 
 7420: # -------------------------------------------------------------- eget interface
 7421: 
 7422: sub eget {
 7423:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7424:    my $items='';
 7425:    foreach my $item (@$storearr) {
 7426:        $items.=&escape($item).'&';
 7427:    }
 7428:    $items=~s/\&$//;
 7429:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7430:    if (!$uname) { $uname=$env{'user.name'}; }
 7431:    my $uhome=&homeserver($uname,$udomain);
 7432:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7433:    my @pairs=split(/\&/,$rep);
 7434:    my %returnhash=();
 7435:    my $i=0;
 7436:    foreach my $item (@$storearr) {
 7437:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7438:       $i++;
 7439:    }
 7440:    return %returnhash;
 7441: }
 7442: 
 7443: # ------------------------------------------------------------ tmpput interface
 7444: sub tmpput {
 7445:     my ($storehash,$server,$context)=@_;
 7446:     my $items='';
 7447:     foreach my $item (keys(%$storehash)) {
 7448: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7449:     }
 7450:     $items=~s/\&$//;
 7451:     if (defined($context)) {
 7452:         $items .= ':'.&escape($context);
 7453:     }
 7454:     return &reply("tmpput:$items",$server);
 7455: }
 7456: 
 7457: # ------------------------------------------------------------ tmpget interface
 7458: sub tmpget {
 7459:     my ($token,$server)=@_;
 7460:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7461:     my $rep=&reply("tmpget:$token",$server);
 7462:     my %returnhash;
 7463:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7464:         return %returnhash;
 7465:     }
 7466:     foreach my $item (split(/\&/,$rep)) {
 7467: 	my ($key,$value)=split(/=/,$item);
 7468: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7469:     }
 7470:     return %returnhash;
 7471: }
 7472: 
 7473: # ------------------------------------------------------------ tmpdel interface
 7474: sub tmpdel {
 7475:     my ($token,$server)=@_;
 7476:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7477:     return &reply("tmpdel:$token",$server);
 7478: }
 7479: 
 7480: # ------------------------------------------------------------ get_timebased_id 
 7481: 
 7482: sub get_timebased_id {
 7483:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7484:         $maxtries) = @_;
 7485:     my ($newid,$error,$dellock);
 7486:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7487:         return ('','ok','invalid call to get suffix');
 7488:     }
 7489: 
 7490: # set defaults for any optional args for which values were not supplied
 7491:     if ($who eq '') {
 7492:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7493:     }
 7494:     if (!$locktries) {
 7495:         $locktries = 3;
 7496:     }
 7497:     if (!$maxtries) {
 7498:         $maxtries = 10;
 7499:     }
 7500:     
 7501:     if (($cdom eq '') || ($cnum eq '')) {
 7502:         if ($env{'request.course.id'}) {
 7503:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7504:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7505:         }
 7506:         if (($cdom eq '') || ($cnum eq '')) {
 7507:             return ('','ok','call to get suffix not in course context');
 7508:         }
 7509:     }
 7510: 
 7511: # construct locking item
 7512:     my $lockhash = {
 7513:                       $prefix."\0".'locked_'.$keyid => $who,
 7514:                    };
 7515:     my $tries = 0;
 7516: 
 7517: # attempt to get lock on nohist_$namespace file
 7518:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7519:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7520:         $tries ++;
 7521:         sleep 1;
 7522:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7523:     }
 7524: 
 7525: # attempt to get unique identifier, based on current timestamp
 7526:     if ($gotlock eq 'ok') {
 7527:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7528:         my $id = time;
 7529:         $newid = $id;
 7530:         if ($idtype eq 'addcode') {
 7531:             $newid .= &sixnum_code();
 7532:         }
 7533:         my $idtries = 0;
 7534:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7535:             if ($idtype eq 'concat') {
 7536:                 $newid = $id.$idtries;
 7537:             } elsif ($idtype eq 'addcode') {
 7538:                 $newid = $newid.&sixnum_code();
 7539:             } else {
 7540:                 $newid ++;
 7541:             }
 7542:             $idtries ++;
 7543:         }
 7544:         if (!exists($inuse{$prefix."\0".$newid})) {
 7545:             my %new_item =  (
 7546:                               $prefix."\0".$newid => $who,
 7547:                             );
 7548:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7549:                                                  $cdom,$cnum);
 7550:             if ($putresult ne 'ok') {
 7551:                 undef($newid);
 7552:                 $error = 'error saving new item: '.$putresult;
 7553:             }
 7554:         } else {
 7555:              undef($newid);
 7556:              $error = ('error: no unique suffix available for the new item ');
 7557:         }
 7558: #  remove lock
 7559:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7560:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7561:     } else {
 7562:         $error = "error: could not obtain lockfile\n";
 7563:         $dellock = 'ok';
 7564:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7565:             $dellock = 'nolock';
 7566:         }
 7567:     }
 7568:     return ($newid,$dellock,$error);
 7569: }
 7570: 
 7571: sub sixnum_code {
 7572:     my $code;
 7573:     for (0..6) {
 7574:         $code .= int( rand(9) );
 7575:     }
 7576:     return $code;
 7577: }
 7578: 
 7579: # -------------------------------------------------- portfolio access checking
 7580: 
 7581: sub portfolio_access {
 7582:     my ($requrl,$clientip) = @_;
 7583:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7584:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7585:     if ($result) {
 7586:         my %setters;
 7587:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7588:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7589:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7590:             if (($startblock && $endblock) || ($by_ip)) {
 7591:                 return 'B';
 7592:             }
 7593:         } else {
 7594:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7595:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7596:             if (($startblock && $endblock) || ($by_ip)) {
 7597:                 return 'B';
 7598:             }
 7599:         }
 7600:     }
 7601:     if ($result eq 'ok') {
 7602:        return 'F';
 7603:     } elsif ($result =~ /^[^:]+:guest_/) {
 7604:        return 'A';
 7605:     }
 7606:     return '';
 7607: }
 7608: 
 7609: sub get_portfolio_access {
 7610:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7611: 
 7612:     if (!ref($access_hash)) {
 7613: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7614: 	my %access_controls = &get_access_controls($current_perms,$group,
 7615: 						   $file_name);
 7616: 	$access_hash = $access_controls{$file_name};
 7617:     }
 7618: 
 7619:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7620:     my $now = time;
 7621:     if (ref($access_hash) eq 'HASH') {
 7622:         foreach my $key (keys(%{$access_hash})) {
 7623:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7624:             if ($start > $now) {
 7625:                 next;
 7626:             }
 7627:             if ($end && $end<$now) {
 7628:                 next;
 7629:             }
 7630:             if ($scope eq 'public') {
 7631:                 $public = $key;
 7632:                 last;
 7633:             } elsif ($scope eq 'guest') {
 7634:                 $guest = $key;
 7635:             } elsif ($scope eq 'domains') {
 7636:                 push(@domains,$key);
 7637:             } elsif ($scope eq 'users') {
 7638:                 push(@users,$key);
 7639:             } elsif ($scope eq 'course') {
 7640:                 push(@courses,$key);
 7641:             } elsif ($scope eq 'group') {
 7642:                 push(@groups,$key);
 7643:             } elsif ($scope eq 'ip') {
 7644:                 push(@ips,$key);
 7645:             }
 7646:         }
 7647:         if ($public) {
 7648:             return 'ok';
 7649:         } elsif (@ips > 0) {
 7650:             my $allowed;
 7651:             foreach my $ipkey (@ips) {
 7652:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7653:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7654:                         $allowed = 1;
 7655:                         last; 
 7656:                     }
 7657:                 }
 7658:             }
 7659:             if ($allowed) {
 7660:                 return 'ok';
 7661:             }
 7662:         }
 7663:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7664:             if ($guest) {
 7665:                 return $guest;
 7666:             }
 7667:         } else {
 7668:             if (@domains > 0) {
 7669:                 foreach my $domkey (@domains) {
 7670:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7671:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7672:                             return 'ok';
 7673:                         }
 7674:                     }
 7675:                 }
 7676:             }
 7677:             if (@users > 0) {
 7678:                 foreach my $userkey (@users) {
 7679:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7680:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7681:                             if (ref($item) eq 'HASH') {
 7682:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7683:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7684:                                     return 'ok';
 7685:                                 }
 7686:                             }
 7687:                         }
 7688:                     } 
 7689:                 }
 7690:             }
 7691:             my %roleshash;
 7692:             my @courses_and_groups = @courses;
 7693:             push(@courses_and_groups,@groups); 
 7694:             if (@courses_and_groups > 0) {
 7695:                 my (%allgroups,%allroles); 
 7696:                 my ($start,$end,$role,$sec,$group);
 7697:                 foreach my $envkey (%env) {
 7698:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7699:                         my $cid = $2.'_'.$3; 
 7700:                         if ($1 eq 'gr') {
 7701:                             $group = $4;
 7702:                             $allgroups{$cid}{$group} = $env{$envkey};
 7703:                         } else {
 7704:                             if ($4 eq '') {
 7705:                                 $sec = 'none';
 7706:                             } else {
 7707:                                 $sec = $4;
 7708:                             }
 7709:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7710:                         }
 7711:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7712:                         my $cid = $2.'_'.$3;
 7713:                         if ($4 eq '') {
 7714:                             $sec = 'none';
 7715:                         } else {
 7716:                             $sec = $4;
 7717:                         }
 7718:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7719:                     }
 7720:                 }
 7721:                 if (keys(%allroles) == 0) {
 7722:                     return;
 7723:                 }
 7724:                 foreach my $key (@courses_and_groups) {
 7725:                     my %content = %{$$access_hash{$key}};
 7726:                     my $cnum = $content{'number'};
 7727:                     my $cdom = $content{'domain'};
 7728:                     my $cid = $cdom.'_'.$cnum;
 7729:                     if (!exists($allroles{$cid})) {
 7730:                         next;
 7731:                     }    
 7732:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7733:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7734:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7735:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7736:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7737:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7738:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7739:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7740:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7741:                                         if (grep/^all$/,@sections) {
 7742:                                             return 'ok';
 7743:                                         } else {
 7744:                                             if (grep/^$sec$/,@sections) {
 7745:                                                 return 'ok';
 7746:                                             }
 7747:                                         }
 7748:                                     }
 7749:                                 }
 7750:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7751:                                     if (grep/^none$/,@groups) {
 7752:                                         return 'ok';
 7753:                                     }
 7754:                                 } else {
 7755:                                     if (grep/^all$/,@groups) {
 7756:                                         return 'ok';
 7757:                                     } 
 7758:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7759:                                         if (grep/^$group$/,@groups) {
 7760:                                             return 'ok';
 7761:                                         }
 7762:                                     }
 7763:                                 } 
 7764:                             }
 7765:                         }
 7766:                     }
 7767:                 }
 7768:             }
 7769:             if ($guest) {
 7770:                 return $guest;
 7771:             }
 7772:         }
 7773:     }
 7774:     return;
 7775: }
 7776: 
 7777: sub course_group_datechecker {
 7778:     my ($dates,$now,$status) = @_;
 7779:     my ($start,$end) = split(/\./,$dates);
 7780:     if (!$start && !$end) {
 7781:         return 'ok';
 7782:     }
 7783:     if (grep/^active$/,@{$status}) {
 7784:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7785:             return 'ok';
 7786:         }
 7787:     }
 7788:     if (grep/^previous$/,@{$status}) {
 7789:         if ($end > $now ) {
 7790:             return 'ok';
 7791:         }
 7792:     }
 7793:     if (grep/^future$/,@{$status}) {
 7794:         if ($start > $now) {
 7795:             return 'ok';
 7796:         }
 7797:     }
 7798:     return; 
 7799: }
 7800: 
 7801: sub parse_portfolio_url {
 7802:     my ($url) = @_;
 7803: 
 7804:     my ($type,$udom,$unum,$group,$file_name);
 7805:     
 7806:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7807: 	$type = 1;
 7808:         $udom = $1;
 7809:         $unum = $2;
 7810:         $file_name = $3;
 7811:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7812: 	$type = 2;
 7813:         $udom = $1;
 7814:         $unum = $2;
 7815:         $group = $3;
 7816:         $file_name = $3.'/'.$4;
 7817:     }
 7818:     if (wantarray) {
 7819: 	return ($type,$udom,$unum,$file_name,$group);
 7820:     }
 7821:     return $type;
 7822: }
 7823: 
 7824: sub is_portfolio_url {
 7825:     my ($url) = @_;
 7826:     return scalar(&parse_portfolio_url($url));
 7827: }
 7828: 
 7829: sub is_portfolio_file {
 7830:     my ($file) = @_;
 7831:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7832:         return 1;
 7833:     }
 7834:     return;
 7835: }
 7836: 
 7837: sub usertools_access {
 7838:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7839:     my ($access,%tools);
 7840:     if ($context eq '') {
 7841:         $context = 'tools';
 7842:     }
 7843:     if ($context eq 'requestcourses') {
 7844:         %tools = (
 7845:                       official   => 1,
 7846:                       unofficial => 1,
 7847:                       community  => 1,
 7848:                       textbook   => 1,
 7849:                       placement  => 1,
 7850:                       lti        => 1,
 7851:                  );
 7852:     } elsif ($context eq 'requestauthor') {
 7853:         %tools = (
 7854:                       requestauthor => 1,
 7855:                  );
 7856:     } else {
 7857:         %tools = (
 7858:                       aboutme   => 1,
 7859:                       blog      => 1,
 7860:                       webdav    => 1,
 7861:                       portfolio => 1,
 7862:                  );
 7863:     }
 7864:     return if (!defined($tools{$tool}));
 7865: 
 7866:     if (($udom eq '') || ($uname eq '')) {
 7867:         $udom = $env{'user.domain'};
 7868:         $uname = $env{'user.name'};
 7869:     }
 7870: 
 7871:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7872:         if ($action ne 'reload') {
 7873:             if ($context eq 'requestcourses') {
 7874:                 return $env{'environment.canrequest.'.$tool};
 7875:             } elsif ($context eq 'requestauthor') {
 7876:                 return $env{'environment.canrequest.author'};
 7877:             } else {
 7878:                 return $env{'environment.availabletools.'.$tool};
 7879:             }
 7880:         }
 7881:     }
 7882: 
 7883:     my ($toolstatus,$inststatus,$envkey);
 7884:     if ($context eq 'requestauthor') {
 7885:         $envkey = $context; 
 7886:     } else {
 7887:         $envkey = $context.'.'.$tool;
 7888:     }
 7889: 
 7890:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7891:          ($action ne 'reload')) {
 7892:         $toolstatus = $env{'environment.'.$envkey};
 7893:         $inststatus = $env{'environment.inststatus'};
 7894:     } else {
 7895:         if (ref($userenvref) eq 'HASH') {
 7896:             $toolstatus = $userenvref->{$envkey};
 7897:             $inststatus = $userenvref->{'inststatus'};
 7898:         } else {
 7899:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7900:             $toolstatus = $userenv{$envkey};
 7901:             $inststatus = $userenv{'inststatus'};
 7902:         }
 7903:     }
 7904: 
 7905:     if ($toolstatus ne '') {
 7906:         if ($toolstatus) {
 7907:             $access = 1;
 7908:         } else {
 7909:             $access = 0;
 7910:         }
 7911:         return $access;
 7912:     }
 7913: 
 7914:     my ($is_adv,%domdef);
 7915:     if (ref($is_advref) eq 'HASH') {
 7916:         $is_adv = $is_advref->{'is_adv'};
 7917:     } else {
 7918:         $is_adv = &is_advanced_user($udom,$uname);
 7919:     }
 7920:     if (ref($domdefref) eq 'HASH') {
 7921:         %domdef = %{$domdefref};
 7922:     } else {
 7923:         %domdef = &get_domain_defaults($udom);
 7924:     }
 7925:     if (ref($domdef{$tool}) eq 'HASH') {
 7926:         if ($is_adv) {
 7927:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7928:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7929:                     $access = 1;
 7930:                 } else {
 7931:                     $access = 0;
 7932:                 }
 7933:                 return $access;
 7934:             }
 7935:         }
 7936:         if ($inststatus ne '') {
 7937:             my ($hasaccess,$hasnoaccess);
 7938:             foreach my $affiliation (split(/:/,$inststatus)) {
 7939:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7940:                     if ($domdef{$tool}{$affiliation}) {
 7941:                         $hasaccess = 1;
 7942:                     } else {
 7943:                         $hasnoaccess = 1;
 7944:                     }
 7945:                 }
 7946:             }
 7947:             if ($hasaccess || $hasnoaccess) {
 7948:                 if ($hasaccess) {
 7949:                     $access = 1;
 7950:                 } elsif ($hasnoaccess) {
 7951:                     $access = 0; 
 7952:                 }
 7953:                 return $access;
 7954:             }
 7955:         } else {
 7956:             if ($domdef{$tool}{'default'} ne '') {
 7957:                 if ($domdef{$tool}{'default'}) {
 7958:                     $access = 1;
 7959:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7960:                     $access = 0;
 7961:                 }
 7962:                 return $access;
 7963:             }
 7964:         }
 7965:     } else {
 7966:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7967:             $access = 1;
 7968:         } else {
 7969:             $access = 0;
 7970:         }
 7971:         return $access;
 7972:     }
 7973: }
 7974: 
 7975: sub is_course_owner {
 7976:     my ($cdom,$cnum,$udom,$uname) = @_;
 7977:     if (($udom eq '') || ($uname eq '')) {
 7978:         $udom = $env{'user.domain'};
 7979:         $uname = $env{'user.name'};
 7980:     }
 7981:     unless (($udom eq '') || ($uname eq '')) {
 7982:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7983:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7984:                 return 1;
 7985:             } else {
 7986:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7987:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7988:                     return 1;
 7989:                 }
 7990:             }
 7991:         }
 7992:     }
 7993:     return;
 7994: }
 7995: 
 7996: sub is_advanced_user {
 7997:     my ($udom,$uname) = @_;
 7998:     if ($udom ne '' && $uname ne '') {
 7999:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8000:             if (wantarray) {
 8001:                 return ($env{'user.adv'},$env{'user.author'});
 8002:             } else {
 8003:                 return $env{'user.adv'};
 8004:             }
 8005:         }
 8006:     }
 8007:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8008:     my %allroles;
 8009:     my ($is_adv,$is_author);
 8010:     foreach my $role (keys(%roleshash)) {
 8011:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8012:         my $area = '/'.$tdomain.'/'.$trest;
 8013:         if ($sec ne '') {
 8014:             $area .= '/'.$sec;
 8015:         }
 8016:         if (($area ne '') && ($trole ne '')) {
 8017:             my $spec=$trole.'.'.$area;
 8018:             if ($trole =~ /^cr\//) {
 8019:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8020:             } elsif ($trole ne 'gr') {
 8021:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8022:             }
 8023:             if ($trole eq 'au') {
 8024:                 $is_author = 1;
 8025:             }
 8026:         }
 8027:     }
 8028:     foreach my $role (keys(%allroles)) {
 8029:         last if ($is_adv);
 8030:         foreach my $item (split(/:/,$allroles{$role})) {
 8031:             if ($item ne '') {
 8032:                 my ($privilege,$restrictions)=split(/&/,$item);
 8033:                 if ($privilege eq 'adv') {
 8034:                     $is_adv = 1;
 8035:                     last;
 8036:                 }
 8037:             }
 8038:         }
 8039:     }
 8040:     if (wantarray) {
 8041:         return ($is_adv,$is_author);
 8042:     }
 8043:     return $is_adv;
 8044: }
 8045: 
 8046: sub check_can_request {
 8047:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8048:     my $canreq = 0;
 8049:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8050:         $uname = $env{'user.name'};
 8051:         $udom = $env{'user.domain'};
 8052:     }
 8053:     my ($types,$typename) = &Apache::loncommon::course_types();
 8054:     my @options = ('approval','validate','autolimit');
 8055:     my $optregex = join('|',@options);
 8056:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8057:         foreach my $type (@{$types}) {
 8058:             if (&usertools_access($uname,$udom,$type,undef,
 8059:                                   'requestcourses')) {
 8060:                 $canreq ++;
 8061:                 if (ref($request_domains) eq 'HASH') {
 8062:                     push(@{$request_domains->{$type}},$udom);
 8063:                 }
 8064:                 if ($dom eq $udom) {
 8065:                     $can_request->{$type} = 1;
 8066:                 }
 8067:             }
 8068:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8069:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8070:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8071:                 if (@curr > 0) {
 8072:                     foreach my $item (@curr) {
 8073:                         if (ref($request_domains) eq 'HASH') {
 8074:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8075:                             if ($otherdom ne '') {
 8076:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8077:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8078:                                         push(@{$request_domains->{$type}},$otherdom);
 8079:                                     }
 8080:                                 } else {
 8081:                                     push(@{$request_domains->{$type}},$otherdom);
 8082:                                 }
 8083:                             }
 8084:                         }
 8085:                     }
 8086:                     unless ($dom eq $env{'user.domain'}) {
 8087:                         $canreq ++;
 8088:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8089:                             $can_request->{$type} = 1;
 8090:                         }
 8091:                     }
 8092:                 }
 8093:             }
 8094:         }
 8095:     }
 8096:     return $canreq;
 8097: }
 8098: 
 8099: # ---------------------------------------------- Custom access rule evaluation
 8100: 
 8101: sub customaccess {
 8102:     my ($priv,$uri)=@_;
 8103:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8104:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8105:     $udom = &LONCAPA::clean_domain($udom);
 8106:     $ucrs = &LONCAPA::clean_username($ucrs);
 8107:     my $access=0;
 8108:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8109: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8110: 	if ($type eq 'user') {
 8111: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8112: 		my ($tdom,$tuname)=split(m{/},$scope);
 8113: 		if ($tdom) {
 8114: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8115: 		}
 8116: 		if ($tuname) {
 8117: 		    if ($tuname ne $env{'user.name'}) { next; }
 8118: 		}
 8119: 		$access=($effect eq 'allow');
 8120: 		last;
 8121: 	    }
 8122: 	} else {
 8123: 	    if ($role) {
 8124: 		if ($role ne $urole) { next; }
 8125: 	    }
 8126: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8127: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8128: 		if ($tdom) {
 8129: 		    if ($tdom ne $udom) { next; }
 8130: 		}
 8131: 		if ($tcrs) {
 8132: 		    if ($tcrs ne $ucrs) { next; }
 8133: 		}
 8134: 		if ($tsec) {
 8135: 		    if ($tsec ne $usec) { next; }
 8136: 		}
 8137: 		$access=($effect eq 'allow');
 8138: 		last;
 8139: 	    }
 8140: 	    if ($realm eq '' && $role eq '') {
 8141: 		$access=($effect eq 'allow');
 8142: 	    }
 8143: 	}
 8144:     }
 8145:     return $access;
 8146: }
 8147: 
 8148: # ------------------------------------------------- Check for a user privilege
 8149: 
 8150: sub allowed {
 8151:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8152:     my $ver_orguri=$uri;
 8153:     $uri=&deversion($uri);
 8154:     my $orguri=$uri;
 8155:     $uri=&declutter($uri);
 8156: 
 8157:     if ($priv eq 'evb') {
 8158: # Evade communication block restrictions for specified role in a course or domain
 8159:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8160:             return $1;
 8161:         } else {
 8162:             return;
 8163:         }
 8164:     }
 8165: 
 8166:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8167: # Free bre access to adm and meta resources
 8168:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8169: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8170: 	&& ($priv eq 'bre')) {
 8171: 	return 'F';
 8172:     }
 8173: 
 8174: # Free bre access to user's own portfolio contents
 8175:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8176:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8177: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8178:         my %setters;
 8179:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8180:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8181:         if (($startblock && $endblock) || ($by_ip)) {
 8182:             return 'B';
 8183:         } else {
 8184:             return 'F';
 8185:         }
 8186:     }
 8187: 
 8188: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8189:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8190:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8191:         if (exists($env{'request.course.id'})) {
 8192:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8193:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8194:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8195:                 my $courseprivid=$env{'request.course.id'};
 8196:                 $courseprivid=~s/\_/\//;
 8197:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8198:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8199:                     return $1; 
 8200:                 } else {
 8201:                     if ($env{'request.course.sec'}) {
 8202:                         $courseprivid.='/'.$env{'request.course.sec'};
 8203:                     }
 8204:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8205:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8206:                         return $2;
 8207:                     }
 8208:                 }
 8209:             }
 8210:         }
 8211:     }
 8212: 
 8213: # Free bre to public access
 8214: 
 8215:     if ($priv eq 'bre') {
 8216:         my $copyright;
 8217:         unless ($uri =~ /ext\.tool/) {
 8218:             $copyright=&metadata($uri,'copyright');
 8219:         }
 8220: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8221:            return 'F'; 
 8222:         }
 8223:         if ($copyright eq 'priv') {
 8224:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8225: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8226: 		return '';
 8227:             }
 8228:         }
 8229:         if ($copyright eq 'domain') {
 8230:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8231: 	    unless (($env{'user.domain'} eq $1) ||
 8232:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8233: 		return '';
 8234:             }
 8235:         }
 8236:         if ($env{'request.role'}=~ /li\.\//) {
 8237:             # Library role, so allow browsing of resources in this domain.
 8238:             return 'F';
 8239:         }
 8240:         if ($copyright eq 'custom') {
 8241: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8242:         }
 8243:     }
 8244:     # Domain coordinator is trying to create a course
 8245:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8246:         # uri is the requested domain in this case.
 8247:         # comparison to 'request.role.domain' shows if the user has selected
 8248:         # a role of dc for the domain in question.
 8249:         return 'F' if ($uri eq $env{'request.role.domain'});
 8250:     }
 8251: 
 8252:     my $thisallowed='';
 8253:     my $statecond=0;
 8254:     my $courseprivid='';
 8255: 
 8256:     my $ownaccess;
 8257:     # Community Coordinator or Assistant Co-author browsing resource space.
 8258:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8259:         if ($uri eq '') {
 8260:             $ownaccess = 1;
 8261:         } else {
 8262:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8263:                 my $udom = $env{'user.domain'};
 8264:                 my $uname = $env{'user.name'};
 8265:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8266:                     $ownaccess = 1;
 8267:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8268:                     unless ($uri =~ m{\.\./}) {
 8269:                         $ownaccess = 1;
 8270:                     }
 8271:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8272:                     my $now = time;
 8273:                     if ($uri =~ m{^([^/]+)/?$}) {
 8274:                         my $adom = $1;
 8275:                         foreach my $key (keys(%env)) {
 8276:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8277:                                 my ($start,$end) = split(/\./,$env{$key});
 8278:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8279:                                     $ownaccess = 1;
 8280:                                     last;
 8281:                                 }
 8282:                             }
 8283:                         }
 8284:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8285:                         my $adom = $1;
 8286:                         my $aname = $2;
 8287:                         foreach my $role ('ca','aa') { 
 8288:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8289:                                 my ($start,$end) =
 8290:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8291:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8292:                                     $ownaccess = 1;
 8293:                                     last;
 8294:                                 }
 8295:                             }
 8296:                         }
 8297:                     }
 8298:                 }
 8299:             }
 8300:         }
 8301:     }
 8302: 
 8303: # Course
 8304: 
 8305:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8306:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8307:             $thisallowed.=$1;
 8308:         }
 8309:     }
 8310: 
 8311: # Domain
 8312: 
 8313:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8314:        =~/\Q$priv\E\&([^\:]*)/) {
 8315:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8316:             $thisallowed.=$1;
 8317:         }
 8318:     }
 8319: 
 8320: # User who is not author or co-author might still be able to edit
 8321: # resource of an author in the domain (e.g., if Domain Coordinator).
 8322:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8323:         (&allowed('mdc',$env{'request.course.id'}))) {
 8324:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8325:             $thisallowed.=$1;
 8326:         }
 8327:     }
 8328: 
 8329: # Course: uri itself is a course
 8330:     my $courseuri=$uri;
 8331:     $courseuri=~s/\_(\d)/\/$1/;
 8332:     $courseuri=~s/^([^\/])/\/$1/;
 8333: 
 8334:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8335:        =~/\Q$priv\E\&([^\:]*)/) {
 8336:         if ($priv eq 'mip') {
 8337:             my $rem = $1;
 8338:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8339:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8340:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8341:                 if ($cdom ne '') {
 8342:                     my %passwdconf = &get_passwdconf($cdom);
 8343:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8344:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8345:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8346:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8347:                                 unless (@inststatuses) {
 8348:                                     @inststatuses = ('default');
 8349:                                 }
 8350:                                 foreach my $status (@inststatuses) {
 8351:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8352:                                         $thisallowed.=$rem;
 8353:                                     }
 8354:                                 }
 8355:                             }
 8356:                         }
 8357:                     }
 8358:                 }
 8359:             }
 8360:         } else {
 8361:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8362:                 $thisallowed.=$1;
 8363:             }
 8364:         }
 8365:     }
 8366: 
 8367: # URI is an uploaded document for this course, default permissions don't matter
 8368: # not allowing 'edit' access (editupload) to uploaded course docs
 8369:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8370: 	$thisallowed='';
 8371:         my ($match)=&is_on_map($uri);
 8372:         if ($match) {
 8373:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8374:                   =~/\Q$priv\E\&([^\:]*)/) {
 8375:                 my $value = $1;
 8376:                 my $deeplinkblock;
 8377:                 unless ($nodeeplinkcheck) {
 8378:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8379:                 }
 8380:                 if ($deeplinkblock) {
 8381:                     $thisallowed='D';
 8382:                 } elsif ($noblockcheck) {
 8383:                     $thisallowed.=$value;
 8384:                 } else {
 8385:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8386:                     if (@blockers > 0) {
 8387:                         $thisallowed = 'B';
 8388:                     } else {
 8389:                         $thisallowed.=$value;
 8390:                     }
 8391:                 }
 8392:             }
 8393:         } else {
 8394:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8395:             if ($refuri) {
 8396:                 if ($refuri =~ m|^/adm/|) {
 8397:                     $thisallowed='F';
 8398:                 } else {
 8399:                     $refuri=&declutter($refuri);
 8400:                     my ($match) = &is_on_map($refuri);
 8401:                     if ($match) {
 8402:                         my $deeplinkblock;
 8403:                         unless ($nodeeplinkcheck) {
 8404:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8405:                         }
 8406:                         if ($deeplinkblock) {
 8407:                             $thisallowed='D';
 8408:                         } elsif ($noblockcheck) {
 8409:                             $thisallowed='F';
 8410:                         } else {
 8411:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8412:                             if (@blockers > 0) {
 8413:                                 $thisallowed = 'B';
 8414:                             } else {
 8415:                                 $thisallowed='F';
 8416:                             }
 8417:                         }
 8418:                     }
 8419:                 }
 8420:             }
 8421:         }
 8422:     }
 8423: 
 8424:     if ($priv eq 'bre'
 8425: 	&& $thisallowed ne 'F' 
 8426: 	&& $thisallowed ne '2'
 8427: 	&& &is_portfolio_url($uri)) {
 8428: 	$thisallowed = &portfolio_access($uri,$clientip);
 8429:     }
 8430: 
 8431: # Full access at system, domain or course-wide level? Exit.
 8432:     if ($thisallowed=~/F/) {
 8433: 	return 'F';
 8434:     }
 8435: 
 8436: # If this is generating or modifying users, exit with special codes
 8437: 
 8438:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8439: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8440: 	    my ($audom,$auname)=split('/',$uri);
 8441: # no author name given, so this just checks on the general right to make a co-author in this domain
 8442: 	    unless ($auname) { return $thisallowed; }
 8443: # an author name is given, so we are about to actually make a co-author for a certain account
 8444: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8445: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8446: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8447: 	}
 8448: 	return $thisallowed;
 8449:     }
 8450: #
 8451: # Gathered so far: system, domain and course wide privileges
 8452: #
 8453: # Course: See if uri or referer is an individual resource that is part of 
 8454: # the course
 8455: 
 8456:     if ($env{'request.course.id'}) {
 8457: 
 8458: # If this is modifying password (internal auth) domains must match for user and user's role.
 8459: 
 8460:         if ($priv eq 'mip') {
 8461:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8462:                 return $thisallowed;
 8463:             } else {
 8464:                 return '';
 8465:             }
 8466:         }
 8467: 
 8468:        $courseprivid=$env{'request.course.id'};
 8469:        if ($env{'request.course.sec'}) {
 8470:           $courseprivid.='/'.$env{'request.course.sec'};
 8471:        }
 8472:        $courseprivid=~s/\_/\//;
 8473:        my $checkreferer=1;
 8474:        my ($match,$cond)=&is_on_map($uri);
 8475:        if ($match) {
 8476:            $statecond=$cond;
 8477:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8478:                =~/\Q$priv\E\&([^\:]*)/) {
 8479:                my $value = $1;
 8480:                if ($priv eq 'bre') {
 8481:                    my $deeplinkblock;
 8482:                    unless ($nodeeplinkcheck) {
 8483:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8484:                    }
 8485:                    if ($deeplinkblock) {
 8486:                        $thisallowed = 'D';
 8487:                    } elsif ($noblockcheck) {
 8488:                        $thisallowed.=$value;
 8489:                    } else {
 8490:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8491:                        if (@blockers > 0) {
 8492:                            $thisallowed = 'B';
 8493:                        } else {
 8494:                            $thisallowed.=$value;
 8495:                        }
 8496:                    }
 8497:                } else {
 8498:                    $thisallowed.=$value;
 8499:                }
 8500:                $checkreferer=0;
 8501:            }
 8502:        }
 8503: 
 8504:        if ($checkreferer) {
 8505: 	  my $refuri=$env{'httpref.'.$orguri};
 8506:             unless ($refuri) {
 8507:                 foreach my $key (keys(%env)) {
 8508: 		    if ($key=~/^httpref\..*\*/) {
 8509: 			my $pattern=$key;
 8510:                         $pattern=~s/^httpref\.\/res\///;
 8511:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8512:                         $pattern=~s/\//\\\//g;
 8513:                         if ($orguri=~/$pattern/) {
 8514: 			    $refuri=$env{$key};
 8515:                         }
 8516:                     }
 8517:                 }
 8518:             }
 8519: 
 8520:          if ($refuri) { 
 8521: 	  $refuri=&declutter($refuri);
 8522:           my ($match,$cond)=&is_on_map($refuri);
 8523:             if ($match) {
 8524:               my $refstatecond=$cond;
 8525:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8526:                   =~/\Q$priv\E\&([^\:]*)/) {
 8527:                   my $value = $1;
 8528:                   if ($priv eq 'bre') {
 8529:                       my $deeplinkblock;
 8530:                       unless ($nodeeplinkcheck) {
 8531:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8532:                       }
 8533:                       if ($deeplinkblock) {
 8534:                           $thisallowed = 'D';
 8535:                       } elsif ($noblockcheck) {
 8536:                           $thisallowed.=$value;
 8537:                       } else {
 8538:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8539:                           if (@blockers > 0) {
 8540:                               $thisallowed = 'B';
 8541:                           } else {
 8542:                               $thisallowed.=$value;
 8543:                           }
 8544:                       }
 8545:                   } else {
 8546:                       $thisallowed.=$value;
 8547:                   }
 8548:                   $uri=$refuri;
 8549:                   $statecond=$refstatecond;
 8550:               }
 8551:           }
 8552:         }
 8553:        }
 8554:    }
 8555: 
 8556: #
 8557: # Gathered now: all privileges that could apply, and condition number
 8558: # 
 8559: #
 8560: # Full or no access?
 8561: #
 8562: 
 8563:     if ($thisallowed=~/F/) {
 8564: 	return 'F';
 8565:     }
 8566: 
 8567:     unless ($thisallowed) {
 8568:         return '';
 8569:     }
 8570: 
 8571: # Restrictions exist, deal with them
 8572: #
 8573: #   C:according to course preferences
 8574: #   R:according to resource settings
 8575: #   L:unless locked
 8576: #   X:according to user session state
 8577: #
 8578: 
 8579: # Possibly locked functionality, check all courses
 8580: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8581: # Locks might take effect only after 10 minutes cache expiration for other
 8582: # courses, and 2 minutes for current course, in which user has st or ta role
 8583: # which is neither expired nor a future role (unless current course).
 8584: 
 8585:     my ($needlockcheck,$now,$crsonly);
 8586:     if ($thisallowed=~/L/) {
 8587:         $now = time;
 8588:         if ($priv eq 'bre') {
 8589:             if ($uri ne '') {
 8590:                 if ($orguri =~ m{^/+res/}) {
 8591:                     if ($uri =~ m{^lib/templates/}) {
 8592:                         if ($env{'request.course.id'}) {
 8593:                             $crsonly = 1;
 8594:                             $needlockcheck = 1;
 8595:                         }
 8596:                     } else {
 8597:                         $needlockcheck = 1;
 8598:                     }
 8599:                 } elsif ($env{'request.course.id'}) {
 8600:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8601:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8602:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8603:                         $crsonly = 1;
 8604:                     }
 8605:                     $needlockcheck = 1;
 8606:                 }
 8607:             }
 8608:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8609:             $needlockcheck = 1;
 8610:         }
 8611:     }
 8612:     if ($needlockcheck) {
 8613:         foreach my $envkey (keys(%env)) {
 8614:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8615:                my $courseid=$2;
 8616:                my $roleid=$1.'.'.$2;
 8617:                $courseid=~s/^\///;
 8618:                unless ($env{'request.role'} eq $roleid) {
 8619:                    my ($start,$end) = split(/\./,$env{$envkey});
 8620:                    next unless (($now >= $start) && (!$end || $end > $now));
 8621:                }
 8622:                my $expiretime=600;
 8623:                if ($env{'request.role'} eq $roleid) {
 8624: 		  $expiretime=120;
 8625:                }
 8626: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8627:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8628:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8629: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8630:                }
 8631:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8632:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8633: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8634:                        &log($env{'user.domain'},$env{'user.name'},
 8635:                             $env{'user.home'},
 8636:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8637:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8638:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8639: 		       return '';
 8640:                    }
 8641:                }
 8642:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8643:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8644: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8645:                        &log($env{'user.domain'},$env{'user.name'},
 8646:                             $env{'user.home'},
 8647:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8648:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8649:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8650: 		       return '';
 8651:                    }
 8652:                }
 8653: 	   }
 8654:        }
 8655:     }
 8656: 
 8657: #
 8658: # Rest of the restrictions depend on selected course
 8659: #
 8660: 
 8661:     unless ($env{'request.course.id'}) {
 8662: 	if ($thisallowed eq 'A') {
 8663: 	    return 'A';
 8664:         } elsif ($thisallowed eq 'B') {
 8665:             return 'B';
 8666: 	} else {
 8667: 	    return '1';
 8668: 	}
 8669:     }
 8670: 
 8671: #
 8672: # Now user is definitely in a course
 8673: #
 8674: 
 8675: 
 8676: # Course preferences
 8677: 
 8678:    if ($thisallowed=~/C/) {
 8679:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8680:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8681:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8682: 	   =~/\Q$rolecode\E/) {
 8683: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8684: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8685: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8686: 			$env{'request.course.id'});
 8687: 	   }
 8688:            return '';
 8689:        }
 8690: 
 8691:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8692: 	   =~/\Q$unamedom\E/) {
 8693: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8694: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8695: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8696: 			$env{'request.course.id'});
 8697: 	   }
 8698:            return '';
 8699:        }
 8700:    }
 8701: 
 8702: # Resource preferences
 8703: 
 8704:    if ($thisallowed=~/R/) {
 8705:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8706:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8707: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8708: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8709: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8710: 	   }
 8711: 	   return '';
 8712:        }
 8713:    }
 8714: 
 8715: # Restricted for deeplinked session?
 8716: 
 8717:     if ($env{'request.deeplink.login'}) {
 8718:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 8719:             if (!$symb) { $symb=&symbread($uri,1); }
 8720:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 8721:                 return '';
 8722:             }
 8723:         }
 8724:     }
 8725: 
 8726: # Restricted by state or randomout?
 8727: 
 8728:    if ($thisallowed=~/X/) {
 8729:       if ($env{'acc.randomout'}) {
 8730: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8731:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8732:             return ''; 
 8733:          }
 8734:       }
 8735:       if (&condval($statecond)) {
 8736: 	 return '2';
 8737:       } else {
 8738:          return '';
 8739:       }
 8740:    }
 8741: 
 8742:     if ($thisallowed eq 'A') {
 8743: 	return 'A';
 8744:     } elsif ($thisallowed eq 'B') {
 8745:         return 'B';
 8746:     } elsif ($thisallowed eq 'D') {
 8747:         return 'D';
 8748:     }
 8749:    return 'F';
 8750: }
 8751: 
 8752: # ------------------------------------------- Check construction space access
 8753: 
 8754: sub constructaccess {
 8755:     my ($url,$setpriv)=@_;
 8756: 
 8757: # We do not allow editing of previous versions of files
 8758:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8759: 
 8760: # Get username and domain from URL
 8761:     my ($ownername,$ownerdomain,$ownerhome);
 8762: 
 8763:     ($ownerdomain,$ownername) =
 8764:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8765: 
 8766: # The URL does not really point to any authorspace, forget it
 8767:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8768: 
 8769: # Now we need to see if the user has access to the authorspace of
 8770: # $ownername at $ownerdomain
 8771: 
 8772:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8773: # Real author for this?
 8774:        $ownerhome = $env{'user.home'};
 8775:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8776:           return ($ownername,$ownerdomain,$ownerhome);
 8777:        }
 8778:     } else {
 8779: # Co-author for this?
 8780:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8781:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8782:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8783:             return ($ownername,$ownerdomain,$ownerhome);
 8784:         }
 8785:         if ($env{'request.course.id'}) {
 8786:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8787:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8788:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8789:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8790:                     return ($ownername,$ownerdomain,$ownerhome);
 8791:                 }
 8792:             }
 8793:         }
 8794:     }
 8795: 
 8796: # We don't have any access right now. If we are not possibly going to do anything about this,
 8797: # we might as well leave
 8798:    unless ($setpriv) { return ''; }
 8799: 
 8800: # Backdoor access?
 8801:     my $allowed=&allowed('eco',$ownerdomain);
 8802: # Nope
 8803:     unless ($allowed) { return ''; }
 8804: # Looks like we may have access, but could be locked by the owner of the construction space
 8805:     if ($allowed eq 'U') {
 8806:         my %blocked=&get('environment',['domcoord.author'],
 8807:                          $ownerdomain,$ownername);
 8808: # Is blocked by owner
 8809:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8810:     }
 8811:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8812: # Grant temporary access
 8813:         my $then=$env{'user.login.time'};
 8814:         my $update=$env{'user.update.time'};
 8815:         if (!$update) { $update = $then; }
 8816:         my $refresh=$env{'user.refresh.time'};
 8817:         if (!$refresh) { $refresh = $update; }
 8818:         my $now = time;
 8819:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8820:                            $now,'ca','constructaccess');
 8821:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8822:         return($ownername,$ownerdomain,$ownerhome);
 8823:     }
 8824: # No business here
 8825:     return '';
 8826: }
 8827: 
 8828: # ----------------------------------------------------------- Content Blocking
 8829: 
 8830: {
 8831: # Caches for faster Course Contents display where content blocking
 8832: # is in operation (i.e., interval param set) for timed quiz.
 8833: #
 8834: # User for whom data are being temporarily cached.
 8835: my $cacheduser='';
 8836: # Course for which data are being temporarily cached.
 8837: my $cachedcid='';
 8838: # Cached blockers for this user (a hash of blocking items). 
 8839: my %cachedblockers=();
 8840: # When the data were last cached.
 8841: my $cachedlast='';
 8842: 
 8843: sub load_all_blockers {
 8844:     my ($uname,$udom)=@_;
 8845:     if (($uname ne '') && ($udom ne '')) { 
 8846:         if (($cacheduser eq $uname.':'.$udom) &&
 8847:             ($cachedcid eq $env{'request.course.id'}) &&
 8848:             (abs($cachedlast-time)<5)) {
 8849:             return;
 8850:         }
 8851:     }
 8852:     $cachedlast=time;
 8853:     $cacheduser=$uname.':'.$udom;
 8854:     $cachedcid=$env{'request.course.id'};
 8855:     %cachedblockers = &get_commblock_resources();
 8856:     return;
 8857: }
 8858: 
 8859: sub get_comm_blocks {
 8860:     my ($cdom,$cnum) = @_;
 8861:     if ($cdom eq '' || $cnum eq '') {
 8862:         return unless ($env{'request.course.id'});
 8863:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8864:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8865:     }
 8866:     my %commblocks;
 8867:     my $hashid=$cdom.'_'.$cnum;
 8868:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8869:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8870:         %commblocks = %{$blocksref};
 8871:     } else {
 8872:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8873:         my $cachetime = 600;
 8874:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8875:     }
 8876:     return %commblocks;
 8877: }
 8878: 
 8879: sub get_commblock_resources {
 8880:     my ($blocks) = @_;
 8881:     my %blockers = ();
 8882:     return %blockers unless ($env{'request.course.id'});
 8883:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8884:     if ($env{'request.course.sec'}) {
 8885:         $courseurl .= '/'.$env{'request.course.sec'};
 8886:     }
 8887:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 8888:     my %commblocks;
 8889:     if (ref($blocks) eq 'HASH') {
 8890:         %commblocks = %{$blocks};
 8891:     } else {
 8892:         %commblocks = &get_comm_blocks();
 8893:     }
 8894:     return %blockers unless (keys(%commblocks) > 0); 
 8895:     my $navmap = Apache::lonnavmaps::navmap->new();
 8896:     return %blockers unless (ref($navmap));
 8897:     my $now = time;
 8898:     foreach my $block (keys(%commblocks)) {
 8899:         if ($block =~ /^(\d+)____(\d+)$/) {
 8900:             my ($start,$end) = ($1,$2);
 8901:             if ($start <= $now && $end >= $now) {
 8902:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8903:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8904:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8905:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8906:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8907:                             }
 8908:                         }
 8909:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8910:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8911:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8912:                             }
 8913:                         }
 8914:                     }
 8915:                 }
 8916:             }
 8917:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8918:             my $item = $1;
 8919:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8920:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8921:                     my (@interval,$mapname);
 8922:                     my $type = 'map';
 8923:                     if ($item eq 'course') {
 8924:                         $type = 'course';
 8925:                         @interval=&EXT("resource.0.interval");
 8926:                     } else {
 8927:                         if ($item =~ /___\d+___/) {
 8928:                             $type = 'resource';
 8929:                             @interval=&EXT("resource.0.interval",$item);
 8930:                         } else {
 8931:                             $mapname = &deversion($item);
 8932:                             if (ref($navmap)) {
 8933:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 8934:                                 @interval = ($timelimit,'map');
 8935:                             }
 8936:                         }
 8937:                     }
 8938:                     if ($interval[0] =~ /^(\d+)/) {
 8939:                         my $timelimit = $1; 
 8940:                         my $first_access;
 8941:                         if ($type eq 'resource') {
 8942:                             $first_access=&get_first_access($interval[1],$item);
 8943:                         } elsif ($type eq 'map') {
 8944:                             $first_access=&get_first_access($interval[1],undef,$item);
 8945:                         } else {
 8946:                             $first_access=&get_first_access($interval[1]);
 8947:                         }
 8948:                         if ($first_access) {
 8949:                             my $timesup = $first_access+$timelimit;
 8950:                             if ($timesup > $now) {
 8951:                                 my $activeblock;
 8952:                                 if ($type eq 'resource') {
 8953:                                     if (ref($navmap)) {
 8954:                                         my $res = $navmap->getBySymb($item);
 8955:                                         if ($res->answerable()) {
 8956:                                             $activeblock = 1;
 8957:                                         }
 8958:                                     }
 8959:                                 } elsif ($type eq 'map') {
 8960:                                     my $mapsymb = &symbread($mapname,1);
 8961:                                     if (($mapsymb) && (ref($navmap))) {
 8962:                                         my $mapres = $navmap->getBySymb($mapsymb);
 8963:                                         if (ref($mapres)) {
 8964:                                             my $first = $mapres->map_start();
 8965:                                             my $finish = $mapres->map_finish();
 8966:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8967:                                             if (ref($it)) {
 8968:                                                 my $res;
 8969:                                                 while ($res = $it->next(undef,1)) {
 8970:                                                     next unless (ref($res));
 8971:                                                     my $symb = $res->symb();
 8972:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 8973:                                                     @interval=&EXT("resource.0.interval",$symb);
 8974:                                                     if ($interval[1] eq 'map') {
 8975:                                                         if ($res->answerable()) {
 8976:                                                             $activeblock = 1;
 8977:                                                             last;
 8978:                                                         }
 8979:                                                     }
 8980:                                                 }
 8981:                                             }
 8982:                                         }
 8983:                                     }
 8984:                                 }
 8985:                                 if ($activeblock) {
 8986:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8987:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8988:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8989:                                          }
 8990:                                     }
 8991:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8992:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8993:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8994:                                         }
 8995:                                     }
 8996:                                 }
 8997:                             }
 8998:                         }
 8999:                     }
 9000:                 }
 9001:             }
 9002:         }
 9003:     }
 9004:     return %blockers;
 9005: }
 9006: 
 9007: sub has_comm_blocking {
 9008:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9009:     my @blockers;
 9010:     return unless ($env{'request.course.id'});
 9011:     return unless ($priv eq 'bre');
 9012:     return if ($env{'request.state'} eq 'construct');
 9013:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9014:     if ($env{'request.course.sec'}) {
 9015:         $courseurl .= '/'.$env{'request.course.sec'};
 9016:     }
 9017:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9018:     my %blockinfo;
 9019:     if (ref($blocks) eq 'HASH') {
 9020:         %blockinfo = &get_commblock_resources($blocks);
 9021:     } else {
 9022:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9023:         %blockinfo = %cachedblockers;
 9024:     }
 9025:     return unless (keys(%blockinfo) > 0);
 9026:     my (%possibles,@symbs);
 9027:     if (!$symb) {
 9028:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9029:     }
 9030:     if ($symb) {
 9031:         @symbs = ($symb);
 9032:     } elsif (keys(%possibles)) { 
 9033:         @symbs = keys(%possibles);
 9034:     }
 9035:     my $noblock;
 9036:     foreach my $symb (@symbs) {
 9037:         last if ($noblock);
 9038:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9039:         foreach my $block (keys(%blockinfo)) {
 9040:             if ($block =~ /^firstaccess____(.+)$/) {
 9041:                 my $item = $1;
 9042:                 unless ($blocked) {
 9043:                     if (($item eq $map) || ($item eq $symb)) {
 9044:                         $noblock = 1;
 9045:                         last;
 9046:                     }
 9047:                 }
 9048:             }
 9049:             if (ref($blockinfo{$block}) eq 'HASH') {
 9050:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9051:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9052:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9053:                             push(@blockers,$block);
 9054:                         }
 9055:                     }
 9056:                 }
 9057:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9058:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9059:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9060:                             push(@blockers,$block);
 9061:                         }
 9062:                     }
 9063:                 }
 9064:             }
 9065:         }
 9066:     }
 9067:     unless ($noblock) { 
 9068:         return @blockers;
 9069:     }
 9070:     return;
 9071: }
 9072: }
 9073: 
 9074: sub deeplink_check {
 9075:     my ($priv,$symb,$uri) = @_;
 9076:     return unless ($env{'request.course.id'});
 9077:     return unless ($priv eq 'bre');
 9078:     return if ($env{'request.state'} eq 'construct');
 9079:     return if ($env{'request.role.adv'});
 9080:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9081:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9082:     my (%possibles,@symbs);
 9083:     if (!$symb) {
 9084:         $symb = &symbread($uri,1,1,1,\%possibles);
 9085:     }
 9086:     if ($symb) {
 9087:         @symbs = ($symb);
 9088:     } elsif (keys(%possibles)) {
 9089:         @symbs = keys(%possibles);
 9090:     }
 9091: 
 9092:     my ($deeplink_symb,$allow);
 9093:     if ($env{'request.deeplink.login'}) {
 9094:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9095:     }
 9096:     foreach my $symb (@symbs) {
 9097:         last if ($allow);
 9098:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9099:         if ($deeplink eq '') {
 9100:             $allow = 1;
 9101:         } else {
 9102:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9103:             if ($state ne 'only') {
 9104:                 $allow = 1;
 9105:             } else {
 9106:                 my $check_deeplink_entry;
 9107:                 if ($protect ne 'none') {
 9108:                     my ($acctype,$item) = split(/:/,$protect);
 9109:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9110:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9111:                             $check_deeplink_entry = 1
 9112:                         }
 9113:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9114:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9115:                             $check_deeplink_entry = 1;
 9116:                         }
 9117:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9118:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9119:                             $check_deeplink_entry = 1;
 9120:                         }
 9121:                     }
 9122:                 }
 9123:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9124:                     if ($scope eq 'res') {
 9125:                         if ($symb eq $deeplink_symb) {
 9126:                             $allow = 1;
 9127:                         }
 9128:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9129:                         my ($map_from_symb,$map_from_login);
 9130:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9131:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9132:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9133:                         } else {
 9134:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9135:                         }
 9136:                         if (($map_from_symb) && ($map_from_login)) {
 9137:                             if ($map_from_symb eq $map_from_login) {
 9138:                                 $allow = 1;
 9139:                             } elsif ($scope eq 'rec') {
 9140:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9141:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9142:                                     $allow = 1;
 9143:                                 }
 9144:                             }
 9145:                         }
 9146:                     }
 9147:                 }
 9148:             }
 9149:         }
 9150:     }
 9151:     return if ($allow);
 9152:     return 1;
 9153: }
 9154: 
 9155: # -------------------------------- Deversion and split uri into path an filename   
 9156: 
 9157: #
 9158: #   Removes the version from a URI and
 9159: #   splits it in to its filename and path to the filename.
 9160: #   Seems like File::Basename could have done this more clearly.
 9161: #   Parameters:
 9162: #      $uri   - input URI
 9163: #   Returns:
 9164: #     Two element list consisting of 
 9165: #     $pathname  - the URI up to and excluding the trailing /
 9166: #     $filename  - The part of the URI following the last /
 9167: #  NOTE:
 9168: #    Another realization of this is simply:
 9169: #    use File::Basename;
 9170: #    ...
 9171: #    $uri = shift;
 9172: #    $filename = basename($uri);
 9173: #    $path     = dirname($uri);
 9174: #    return ($filename, $path);
 9175: #
 9176: #     The implementation below is probably faster however.
 9177: #
 9178: sub split_uri_for_cond {
 9179:     my $uri=&deversion(&declutter(shift));
 9180:     my @uriparts=split(/\//,$uri);
 9181:     my $filename=pop(@uriparts);
 9182:     my $pathname=join('/',@uriparts);
 9183:     return ($pathname,$filename);
 9184: }
 9185: # --------------------------------------------------- Is a resource on the map?
 9186: 
 9187: sub is_on_map {
 9188:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9189:     #Trying to find the conditional for the file
 9190:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9191: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9192:     if ($match) {
 9193: 	return (1,$1);
 9194:     } else {
 9195: 	return (0,0);
 9196:     }
 9197: }
 9198: 
 9199: # --------------------------------------------------------- Get symb from alias
 9200: 
 9201: sub get_symb_from_alias {
 9202:     my $symb=shift;
 9203:     my ($map,$resid,$url)=&decode_symb($symb);
 9204: # Already is a symb
 9205:     if ($url) { return $symb; }
 9206: # Must be an alias
 9207:     my $aliassymb='';
 9208:     my %bighash;
 9209:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9210:                             &GDBM_READER(),0640)) {
 9211:         my $rid=$bighash{'mapalias_'.$symb};
 9212: 	if ($rid) {
 9213: 	    my ($mapid,$resid)=split(/\./,$rid);
 9214: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9215: 				    $resid,$bighash{'src_'.$rid});
 9216: 	}
 9217:         untie %bighash;
 9218:     }
 9219:     return $aliassymb;
 9220: }
 9221: 
 9222: # ----------------------------------------------------------------- Define Role
 9223: 
 9224: sub definerole {
 9225:   if (allowed('mcr','/')) {
 9226:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9227:     foreach my $role (split(':',$sysrole)) {
 9228: 	my ($crole,$cqual)=split(/\&/,$role);
 9229:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9230:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9231: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9232:                return "refused:s:$crole&$cqual"; 
 9233:             }
 9234:         }
 9235:     }
 9236:     foreach my $role (split(':',$domrole)) {
 9237: 	my ($crole,$cqual)=split(/\&/,$role);
 9238:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9239:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9240: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9241:                return "refused:d:$crole&$cqual"; 
 9242:             }
 9243:         }
 9244:     }
 9245:     foreach my $role (split(':',$courole)) {
 9246: 	my ($crole,$cqual)=split(/\&/,$role);
 9247:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9248:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9249: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9250:                return "refused:c:$crole&$cqual"; 
 9251:             }
 9252:         }
 9253:     }
 9254:     my $uhome;
 9255:     if (($uname ne '') && ($udom ne '')) {
 9256:         $uhome = &homeserver($uname,$udom);
 9257:         return $uhome if ($uhome eq 'no_host');
 9258:     } else {
 9259:         $uname = $env{'user.name'};
 9260:         $udom = $env{'user.domain'};
 9261:         $uhome = $env{'user.home'};
 9262:     }
 9263:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9264:                 "$udom:$uname:rolesdef_$rolename=".
 9265:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9266:     return reply($command,$uhome);
 9267:   } else {
 9268:     return 'refused';
 9269:   }
 9270: }
 9271: 
 9272: # ---------------- Make a metadata query against the network of library servers
 9273: 
 9274: sub metadata_query {
 9275:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9276:     my %rhash;
 9277:     my %libserv = &all_library();
 9278:     my @server_list = (defined($server_array) ? @$server_array
 9279:                                               : keys(%libserv) );
 9280:     for my $server (@server_list) {
 9281:         my $domains = ''; 
 9282:         if (ref($domains_hash) eq 'HASH') {
 9283:             $domains = $domains_hash->{$server}; 
 9284:         }
 9285: 	unless ($custom or $customshow) {
 9286: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9287: 	    $rhash{$server}=$reply;
 9288: 	}
 9289: 	else {
 9290: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9291: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9292: 			     $server);
 9293: 	    $rhash{$server}=$reply;
 9294: 	}
 9295:     }
 9296:     return \%rhash;
 9297: }
 9298: 
 9299: # ----------------------------------------- Send log queries and wait for reply
 9300: 
 9301: sub log_query {
 9302:     my ($uname,$udom,$query,%filters)=@_;
 9303:     my $uhome=&homeserver($uname,$udom);
 9304:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9305:     my $uhost=&hostname($uhome);
 9306:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9307:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9308:                        $uhome);
 9309:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9310:     return get_query_reply($queryid);
 9311: }
 9312: 
 9313: # -------------------------- Update MySQL table for portfolio file
 9314: 
 9315: sub update_portfolio_table {
 9316:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9317:     if ($group ne '') {
 9318:         $file_name =~s /^\Q$group\E//;
 9319:     }
 9320:     my $homeserver = &homeserver($uname,$udom);
 9321:     my $queryid=
 9322:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9323:                ':'.&escape($file_name).':'.$action,$homeserver);
 9324:     my $reply = &get_query_reply($queryid);
 9325:     return $reply;
 9326: }
 9327: 
 9328: # -------------------------- Update MySQL allusers table
 9329: 
 9330: sub update_allusers_table {
 9331:     my ($uname,$udom,$names) = @_;
 9332:     my $homeserver = &homeserver($uname,$udom);
 9333:     my $queryid=
 9334:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9335:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9336:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9337:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9338:                'generation='.&escape($names->{'generation'}).'%%'.
 9339:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9340:                'id='.&escape($names->{'id'}),$homeserver);
 9341:     return;
 9342: }
 9343: 
 9344: # ------- Request retrieval of institutional classlists for course(s)
 9345: 
 9346: sub fetch_enrollment_query {
 9347:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9348:     my ($homeserver,$sleep,$loopmax);
 9349:     my $maxtries = 1;
 9350:     if ($context eq 'automated') {
 9351:         $homeserver = $perlvar{'lonHostID'};
 9352:         $sleep = 2;
 9353:         $loopmax = 100;
 9354:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9355:     } else {
 9356:         $homeserver = &homeserver($cnum,$dom);
 9357:     }
 9358:     my $host=&hostname($homeserver);
 9359:     my $cmd = '';
 9360:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9361:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9362:     }
 9363:     $cmd =~ s/%%$//;
 9364:     $cmd = &escape($cmd);
 9365:     my $query = 'fetchenrollment';
 9366:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9367:     unless ($queryid=~/^\Q$host\E\_/) { 
 9368:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9369:         return 'error: '.$queryid;
 9370:     }
 9371:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9372:     my $tries = 1;
 9373:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9374:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9375:         $tries ++;
 9376:     }
 9377:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9378:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9379:     } else {
 9380:         my @responses = split(/:/,$reply);
 9381:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9382:             foreach my $line (@responses) {
 9383:                 my ($key,$value) = split(/=/,$line,2);
 9384:                 $$replyref{$key} = $value;
 9385:             }
 9386:         } else {
 9387:             my $pathname = LONCAPA::tempdir();
 9388:             foreach my $line (@responses) {
 9389:                 my ($key,$value) = split(/=/,$line);
 9390:                 $$replyref{$key} = $value;
 9391:                 if ($value > 0) {
 9392:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9393:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9394:                         my $destname = $pathname.'/'.$filename;
 9395:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9396:                         if ($xml_classlist =~ /^error/) {
 9397:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9398:                         } else {
 9399:                             if ( open(FILE,">",$destname) ) {
 9400:                                 print FILE &unescape($xml_classlist);
 9401:                                 close(FILE);
 9402:                             } else {
 9403:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9404:                             }
 9405:                         }
 9406:                     }
 9407:                 }
 9408:             }
 9409:         }
 9410:         return 'ok';
 9411:     }
 9412:     return 'error';
 9413: }
 9414: 
 9415: sub get_query_reply {
 9416:     my ($queryid,$sleep,$loopmax) = @_;
 9417:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9418:         $sleep = 0.2;
 9419:     }
 9420:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9421:         $loopmax = 100;
 9422:     }
 9423:     my $replyfile=LONCAPA::tempdir().$queryid;
 9424:     my $reply='';
 9425:     for (1..$loopmax) {
 9426: 	sleep($sleep);
 9427:         if (-e $replyfile.'.end') {
 9428: 	    if (open(my $fh,"<",$replyfile)) {
 9429: 		$reply = join('',<$fh>);
 9430: 		close($fh);
 9431: 	   } else { return 'error: reply_file_error'; }
 9432:            return &unescape($reply);
 9433: 	}
 9434:     }
 9435:     return 'timeout:'.$queryid;
 9436: }
 9437: 
 9438: sub courselog_query {
 9439: #
 9440: # possible filters:
 9441: # url: url or symb
 9442: # username
 9443: # domain
 9444: # action: view, submit, grade
 9445: # start: timestamp
 9446: # end: timestamp
 9447: #
 9448:     my (%filters)=@_;
 9449:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9450:     if ($filters{'url'}) {
 9451: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9452:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9453:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9454:     }
 9455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9457:     return &log_query($cname,$cdom,'courselog',%filters);
 9458: }
 9459: 
 9460: sub userlog_query {
 9461: #
 9462: # possible filters:
 9463: # action: log check role
 9464: # start: timestamp
 9465: # end: timestamp
 9466: #
 9467:     my ($uname,$udom,%filters)=@_;
 9468:     return &log_query($uname,$udom,'userlog',%filters);
 9469: }
 9470: 
 9471: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9472: 
 9473: sub auto_run {
 9474:     my ($cnum,$cdom) = @_;
 9475:     my $response = 0;
 9476:     my $settings;
 9477:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9478:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9479:         $settings = $domconfig{'autoenroll'};
 9480:         if ($settings->{'run'} eq '1') {
 9481:             $response = 1;
 9482:         }
 9483:     } else {
 9484:         my $homeserver;
 9485:         if (&is_course($cdom,$cnum)) {
 9486:             $homeserver = &homeserver($cnum,$cdom);
 9487:         } else {
 9488:             $homeserver = &domain($cdom,'primary');
 9489:         }
 9490:         if ($homeserver ne 'no_host') {
 9491:             $response = &reply('autorun:'.$cdom,$homeserver);
 9492:         }
 9493:     }
 9494:     return $response;
 9495: }
 9496: 
 9497: sub auto_get_sections {
 9498:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9499:     my $homeserver;
 9500:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9501:         $homeserver = &homeserver($cnum,$cdom);
 9502:     }
 9503:     if (!defined($homeserver)) { 
 9504:         if ($cdom =~ /^$match_domain$/) {
 9505:             $homeserver = &domain($cdom,'primary');
 9506:         }
 9507:     }
 9508:     my @secs;
 9509:     if (defined($homeserver)) {
 9510:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9511:         unless ($response eq 'refused') {
 9512:             @secs = split(/:/,$response);
 9513:         }
 9514:     }
 9515:     return @secs;
 9516: }
 9517: 
 9518: sub auto_new_course {
 9519:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9520:     my $homeserver = &homeserver($cnum,$cdom);
 9521:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9522:     return $response;
 9523: }
 9524: 
 9525: sub auto_validate_courseID {
 9526:     my ($cnum,$cdom,$inst_course_id) = @_;
 9527:     my $homeserver = &homeserver($cnum,$cdom);
 9528:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9529:     return $response;
 9530: }
 9531: 
 9532: sub auto_validate_instcode {
 9533:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9534:     my ($homeserver,$response);
 9535:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9536:         $homeserver = &homeserver($cnum,$cdom);
 9537:     }
 9538:     if (!defined($homeserver)) {
 9539:         if ($cdom =~ /^$match_domain$/) {
 9540:             $homeserver = &domain($cdom,'primary');
 9541:         }
 9542:     }
 9543:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9544:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9545:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9546:     return ($outcome,$description,$defaultcredits);
 9547: }
 9548: 
 9549: sub auto_validate_inst_crosslist {
 9550:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9551:     my ($homeserver,$response);
 9552:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9553:         $homeserver = &homeserver($cnum,$cdom);
 9554:     }
 9555:     if (!defined($homeserver)) {
 9556:         if ($cdom =~ /^$match_domain$/) {
 9557:             $homeserver = &domain($cdom,'primary');
 9558:         }
 9559:     }
 9560:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9561:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9562:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9563:                          &escape($coowner),$homeserver);
 9564:     }
 9565:     return $response;
 9566: }
 9567: 
 9568: sub auto_create_password {
 9569:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9570:     my ($homeserver,$response);
 9571:     my $create_passwd = 0;
 9572:     my $authchk = '';
 9573:     if ($udom =~ /^$match_domain$/) {
 9574:         $homeserver = &domain($udom,'primary');
 9575:     }
 9576:     if ($homeserver eq '') {
 9577:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9578:             $homeserver = &homeserver($cnum,$cdom);
 9579:         }
 9580:     }
 9581:     if ($homeserver eq '') {
 9582:         $authchk = 'nodomain';
 9583:     } else {
 9584:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9585:         if ($response eq 'refused') {
 9586:             $authchk = 'refused';
 9587:         } else {
 9588:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9589:         }
 9590:     }
 9591:     return ($authparam,$create_passwd,$authchk);
 9592: }
 9593: 
 9594: sub auto_photo_permission {
 9595:     my ($cnum,$cdom,$students) = @_;
 9596:     my $homeserver = &homeserver($cnum,$cdom);
 9597:     my ($outcome,$perm_reqd,$conditions) = 
 9598: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9599:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9600: 	return (undef,undef);
 9601:     }
 9602:     return ($outcome,$perm_reqd,$conditions);
 9603: }
 9604: 
 9605: sub auto_checkphotos {
 9606:     my ($uname,$udom,$pid) = @_;
 9607:     my $homeserver = &homeserver($uname,$udom);
 9608:     my ($result,$resulttype);
 9609:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9610: 				   &escape($uname).':'.&escape($pid),
 9611: 				   $homeserver));
 9612:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9613: 	return (undef,undef);
 9614:     }
 9615:     if ($outcome) {
 9616:         ($result,$resulttype) = split(/:/,$outcome);
 9617:     } 
 9618:     return ($result,$resulttype);
 9619: }
 9620: 
 9621: sub auto_photochoice {
 9622:     my ($cnum,$cdom) = @_;
 9623:     my $homeserver = &homeserver($cnum,$cdom);
 9624:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9625: 						       &escape($cdom),
 9626: 						       $homeserver)));
 9627:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9628: 	return (undef,undef);
 9629:     }
 9630:     return ($update,$comment);
 9631: }
 9632: 
 9633: sub auto_photoupdate {
 9634:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9635:     my $homeserver = &homeserver($cnum,$dom);
 9636:     my $host=&hostname($homeserver);
 9637:     my $cmd = '';
 9638:     my $maxtries = 1;
 9639:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9640:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9641:     }
 9642:     $cmd =~ s/%%$//;
 9643:     $cmd = &escape($cmd);
 9644:     my $query = 'institutionalphotos';
 9645:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9646:     unless ($queryid=~/^\Q$host\E\_/) {
 9647:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9648:         return 'error: '.$queryid;
 9649:     }
 9650:     my $reply = &get_query_reply($queryid);
 9651:     my $tries = 1;
 9652:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9653:         $reply = &get_query_reply($queryid);
 9654:         $tries ++;
 9655:     }
 9656:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9657:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9658:     } else {
 9659:         my @responses = split(/:/,$reply);
 9660:         my $outcome = shift(@responses); 
 9661:         foreach my $item (@responses) {
 9662:             my ($key,$value) = split(/=/,$item);
 9663:             $$photo{$key} = $value;
 9664:         }
 9665:         return $outcome;
 9666:     }
 9667:     return 'error';
 9668: }
 9669: 
 9670: sub auto_instcode_format {
 9671:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9672: 	$cat_order) = @_;
 9673:     my $courses = '';
 9674:     my @homeservers;
 9675:     if ($caller eq 'global') {
 9676: 	my %servers = &get_servers($codedom,'library');
 9677: 	foreach my $tryserver (keys(%servers)) {
 9678: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9679: 		push(@homeservers,$tryserver);
 9680: 	    }
 9681:         }
 9682:     } elsif ($caller eq 'requests') {
 9683:         if ($codedom =~ /^$match_domain$/) {
 9684:             my $chome = &domain($codedom,'primary');
 9685:             unless ($chome eq 'no_host') {
 9686:                 push(@homeservers,$chome);
 9687:             }
 9688:         }
 9689:     } else {
 9690:         push(@homeservers,&homeserver($caller,$codedom));
 9691:     }
 9692:     foreach my $code (keys(%{$instcodes})) {
 9693:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9694:     }
 9695:     chop($courses);
 9696:     my $ok_response = 0;
 9697:     my $response;
 9698:     while (@homeservers > 0 && $ok_response == 0) {
 9699:         my $server = shift(@homeservers); 
 9700:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9701:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9702:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9703: 		split(/:/,$response);
 9704:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9705:             push(@{$codetitles},&str2array($codetitles_str));
 9706:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9707:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9708:             $ok_response = 1;
 9709:         }
 9710:     }
 9711:     if ($ok_response) {
 9712:         return 'ok';
 9713:     } else {
 9714:         return $response;
 9715:     }
 9716: }
 9717: 
 9718: sub auto_instcode_defaults {
 9719:     my ($domain,$returnhash,$code_order) = @_;
 9720:     my @homeservers;
 9721: 
 9722:     my %servers = &get_servers($domain,'library');
 9723:     foreach my $tryserver (keys(%servers)) {
 9724: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9725: 	    push(@homeservers,$tryserver);
 9726: 	}
 9727:     }
 9728: 
 9729:     my $response;
 9730:     foreach my $server (@homeservers) {
 9731:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9732:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9733: 	
 9734: 	foreach my $pair (split(/\&/,$response)) {
 9735: 	    my ($name,$value)=split(/\=/,$pair);
 9736: 	    if ($name eq 'code_order') {
 9737: 		@{$code_order} = split(/\&/,&unescape($value));
 9738: 	    } else {
 9739: 		$returnhash->{&unescape($name)}=&unescape($value);
 9740: 	    }
 9741: 	}
 9742: 	return 'ok';
 9743:     }
 9744: 
 9745:     return $response;
 9746: }
 9747: 
 9748: sub auto_possible_instcodes {
 9749:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9750:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9751:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9752:         return;
 9753:     }
 9754:     my (@homeservers,$uhome);
 9755:     if (defined(&domain($domain,'primary'))) {
 9756:         $uhome=&domain($domain,'primary');
 9757:         push(@homeservers,&domain($domain,'primary'));
 9758:     } else {
 9759:         my %servers = &get_servers($domain,'library');
 9760:         foreach my $tryserver (keys(%servers)) {
 9761:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9762:                 push(@homeservers,$tryserver);
 9763:             }
 9764:         }
 9765:     }
 9766:     my $response;
 9767:     foreach my $server (@homeservers) {
 9768:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9769:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9770:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9771:             split(':',$response);
 9772:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9773:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9774:         foreach my $item (split('&',$cat_title)) {   
 9775:             my ($name,$value)=split('=',$item);
 9776:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9777:         }
 9778:         foreach my $item (split('&',$cat_order)) {
 9779:             my ($name,$value)=split('=',$item);
 9780:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9781:         }
 9782:         return 'ok';
 9783:     }
 9784:     return $response;
 9785: }
 9786: 
 9787: sub auto_courserequest_checks {
 9788:     my ($dom) = @_;
 9789:     my ($homeserver,%validations);
 9790:     if ($dom =~ /^$match_domain$/) {
 9791:         $homeserver = &domain($dom,'primary');
 9792:     }
 9793:     unless ($homeserver eq 'no_host') {
 9794:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9795:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9796:             my @items = split(/&/,$response);
 9797:             foreach my $item (@items) {
 9798:                 my ($key,$value) = split('=',$item);
 9799:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9800:             }
 9801:         }
 9802:     }
 9803:     return %validations; 
 9804: }
 9805: 
 9806: sub auto_courserequest_validation {
 9807:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9808:     my ($homeserver,$response);
 9809:     if ($dom =~ /^$match_domain$/) {
 9810:         $homeserver = &domain($dom,'primary');
 9811:     }
 9812:     unless ($homeserver eq 'no_host') {
 9813:         my $customdata;
 9814:         if (ref($custominfo) eq 'HASH') {
 9815:             $customdata = &freeze_escape($custominfo);
 9816:         }
 9817:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9818:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9819:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9820:                                     $customdata,$homeserver));
 9821:     }
 9822:     return $response;
 9823: }
 9824: 
 9825: sub auto_validate_class_sec {
 9826:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9827:     my $homeserver = &homeserver($cnum,$cdom);
 9828:     my $ownerlist;
 9829:     if (ref($owners) eq 'ARRAY') {
 9830:         $ownerlist = join(',',@{$owners});
 9831:     } else {
 9832:         $ownerlist = $owners;
 9833:     }
 9834:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9835:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9836:     return $response;
 9837: }
 9838: 
 9839: sub auto_instsec_reformat {
 9840:     my ($cdom,$action,$instsecref) = @_;
 9841:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
 9842:     my @homeservers;
 9843:     if (defined(&domain($cdom,'primary'))) {
 9844:         push(@homeservers,&domain($cdom,'primary'));
 9845:     } else {
 9846:         my %servers = &get_servers($cdom,'library');
 9847:         foreach my $tryserver (keys(%servers)) {
 9848:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9849:                 push(@homeservers,$tryserver);
 9850:             }
 9851:         }
 9852:     }
 9853:     my $response;
 9854:     my %reformatted = %{$instsecref};
 9855:     foreach my $server (@homeservers) {
 9856:         if (ref($instsecref) eq 'HASH') {
 9857:             my $info = &freeze_escape($instsecref);
 9858:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
 9859:                                 $action.':'.$info,$server);
 9860:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
 9861:             my @items = split(/&/,$response);
 9862:             foreach my $item (@items) {
 9863:                 my ($key,$value) = split(/=/,$item);
 9864:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
 9865:             }
 9866:         }
 9867:     }
 9868:     return %reformatted;
 9869: }
 9870: 
 9871: sub auto_validate_instclasses {
 9872:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9873:     my ($homeserver,%validations);
 9874:     $homeserver = &homeserver($cnum,$cdom);
 9875:     unless ($homeserver eq 'no_host') {
 9876:         my $ownerlist;
 9877:         if (ref($owners) eq 'ARRAY') {
 9878:             $ownerlist = join(',',@{$owners});
 9879:         } else {
 9880:             $ownerlist = $owners;
 9881:         }
 9882:         if (ref($classesref) eq 'HASH') {
 9883:             my $classes = &freeze_escape($classesref);
 9884:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9885:                                 ':'.$cdom.':'.$classes,$homeserver);
 9886:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9887:                 my @items = split(/&/,$response);
 9888:                 foreach my $item (@items) {
 9889:                     my ($key,$value) = split('=',$item);
 9890:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9891:                 }
 9892:             }
 9893:         }
 9894:     }
 9895:     return %validations;
 9896: }
 9897: 
 9898: sub auto_crsreq_update {
 9899:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9900:         $code,$accessstart,$accessend,$inbound) = @_;
 9901:     my ($homeserver,%crsreqresponse);
 9902:     if ($cdom =~ /^$match_domain$/) {
 9903:         $homeserver = &domain($cdom,'primary');
 9904:     }
 9905:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9906:         my $info;
 9907:         if (ref($inbound) eq 'HASH') {
 9908:             $info = &freeze_escape($inbound);
 9909:         }
 9910:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9911:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9912:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9913:                             &escape($title).':'.&escape($code).':'.
 9914:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9915:                             $homeserver);
 9916:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9917:             my @items = split(/&/,$response);
 9918:             foreach my $item (@items) {
 9919:                 my ($key,$value) = split('=',$item);
 9920:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9921:             }
 9922:         }
 9923:     }
 9924:     return \%crsreqresponse;
 9925: }
 9926: 
 9927: sub auto_export_grades {
 9928:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9929:     my ($homeserver,%exportresponse);
 9930:     if ($cdom =~ /^$match_domain$/) {
 9931:         $homeserver = &domain($cdom,'primary');
 9932:     }
 9933:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9934:         my $info;
 9935:         if (ref($inforef) eq 'HASH') {
 9936:             $info = &freeze_escape($inforef);
 9937:         }
 9938:         if (ref($gradesref) eq 'HASH') {
 9939:             my $grades = &freeze_escape($gradesref);
 9940:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9941:                                 $info.':'.$grades,$homeserver);
 9942:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9943:                 my @items = split(/&/,$response);
 9944:                 foreach my $item (@items) {
 9945:                     my ($key,$value) = split('=',$item);
 9946:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9947:                 }
 9948:             }
 9949:         }
 9950:     }
 9951:     return \%exportresponse;
 9952: }
 9953: 
 9954: sub check_instcode_cloning {
 9955:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9956:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9957:         return;
 9958:     }
 9959:     my $canclone;
 9960:     if (@{$code_order} > 0) {
 9961:         my $instcoderegexp ='^';
 9962:         my @clonecodes = split(/\&/,$cloner);
 9963:         foreach my $item (@{$code_order}) {
 9964:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9965:                 foreach my $pair (@clonecodes) {
 9966:                     my ($key,$val) = split(/\=/,$pair,2);
 9967:                     $val = &unescape($val);
 9968:                     if ($key eq $item) {
 9969:                         $instcoderegexp .= '('.$val.')';
 9970:                         last;
 9971:                     }
 9972:                 }
 9973:             } else {
 9974:                 $instcoderegexp .= $codedefaults->{$item};
 9975:             }
 9976:         }
 9977:         $instcoderegexp .= '$';
 9978:         my (@from,@to);
 9979:         eval {
 9980:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9981:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9982:         };
 9983:         if ((@from > 0) && (@to > 0)) {
 9984:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9985:             if (!@diffs) {
 9986:                 $canclone = 1;
 9987:             }
 9988:         }
 9989:     }
 9990:     return $canclone;
 9991: }
 9992: 
 9993: sub default_instcode_cloning {
 9994:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9995:     my (%codedefaults,@code_order,$canclone);
 9996:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9997:         %codedefaults = %{$codedefaultsref};
 9998:         @code_order = @{$codeorderref};
 9999:     } elsif ($clonedom) {
10000:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10001:     }
10002:     if (($domdefclone) && (@code_order)) {
10003:         my @clonecodes = split(/\+/,$domdefclone);
10004:         my $instcoderegexp ='^';
10005:         foreach my $item (@code_order) {
10006:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10007:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10008:             } else {
10009:                 $instcoderegexp .= $codedefaults{$item};
10010:             }
10011:         }
10012:         $instcoderegexp .= '$';
10013:         my (@from,@to);
10014:         eval {
10015:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10016:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10017:         };
10018:         if ((@from > 0) && (@to > 0)) {
10019:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10020:             if (!@diffs) {
10021:                 $canclone = 1;
10022:             }
10023:         }
10024:     }
10025:     return $canclone;
10026: }
10027: 
10028: # ------------------------------------------------------- Course Group routines
10029: 
10030: sub get_coursegroups {
10031:     my ($cdom,$cnum,$group,$namespace) = @_;
10032:     return(&dump($namespace,$cdom,$cnum,$group));
10033: }
10034: 
10035: sub modify_coursegroup {
10036:     my ($cdom,$cnum,$groupsettings) = @_;
10037:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10038: }
10039: 
10040: sub toggle_coursegroup_status {
10041:     my ($cdom,$cnum,$group,$action) = @_;
10042:     my ($from_namespace,$to_namespace);
10043:     if ($action eq 'delete') {
10044:         $from_namespace = 'coursegroups';
10045:         $to_namespace = 'deleted_groups';
10046:     } else {
10047:         $from_namespace = 'deleted_groups';
10048:         $to_namespace = 'coursegroups';
10049:     }
10050:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10051:     if (my $tmp = &error(%curr_group)) {
10052:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10053:         return ('read error',$tmp);
10054:     } else {
10055:         my %savedsettings = %curr_group; 
10056:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10057:         my $deloutcome;
10058:         if ($result eq 'ok') {
10059:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10060:         } else {
10061:             return ('write error',$result);
10062:         }
10063:         if ($deloutcome eq 'ok') {
10064:             return 'ok';
10065:         } else {
10066:             return ('delete error',$deloutcome);
10067:         }
10068:     }
10069: }
10070: 
10071: sub modify_group_roles {
10072:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
10073:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10074:     my $role = 'gr/'.&escape($userprivs);
10075:     my ($uname,$udom) = split(/:/,$user);
10076:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
10077:     if ($result eq 'ok') {
10078:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10079:     }
10080:     return $result;
10081: }
10082: 
10083: sub modify_coursegroup_membership {
10084:     my ($cdom,$cnum,$membership) = @_;
10085:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10086:     return $result;
10087: }
10088: 
10089: sub get_active_groups {
10090:     my ($udom,$uname,$cdom,$cnum) = @_;
10091:     my $now = time;
10092:     my %groups = ();
10093:     foreach my $key (keys(%env)) {
10094:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10095:             my ($start,$end) = split(/\./,$env{$key});
10096:             if (($end!=0) && ($end<$now)) { next; }
10097:             if (($start!=0) && ($start>$now)) { next; }
10098:             if ($1 eq $cdom && $2 eq $cnum) {
10099:                 $groups{$3} = $env{$key} ;
10100:             }
10101:         }
10102:     }
10103:     return %groups;
10104: }
10105: 
10106: sub get_group_membership {
10107:     my ($cdom,$cnum,$group) = @_;
10108:     return(&dump('groupmembership',$cdom,$cnum,$group));
10109: }
10110: 
10111: sub get_users_groups {
10112:     my ($udom,$uname,$courseid) = @_;
10113:     my @usersgroups;
10114:     my $cachetime=1800;
10115: 
10116:     my $hashid="$udom:$uname:$courseid";
10117:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10118:     if (defined($cached)) {
10119:         @usersgroups = split(/:/,$grouplist);
10120:     } else {  
10121:         $grouplist = '';
10122:         my $courseurl = &courseid_to_courseurl($courseid);
10123:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10124:         my $access_end = $env{'course.'.$courseid.
10125:                               '.default_enrollment_end_date'};
10126:         my $now = time;
10127:         foreach my $key (keys(%roleshash)) {
10128:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10129:                 my $group = $1;
10130:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10131:                     my $start = $2;
10132:                     my $end = $1;
10133:                     if ($start == -1) { next; } # deleted from group
10134:                     if (($start!=0) && ($start>$now)) { next; }
10135:                     if (($end!=0) && ($end<$now)) {
10136:                         if ($access_end && $access_end < $now) {
10137:                             if ($access_end - $end < 86400) {
10138:                                 push(@usersgroups,$group);
10139:                             }
10140:                         }
10141:                         next;
10142:                     }
10143:                     push(@usersgroups,$group);
10144:                 }
10145:             }
10146:         }
10147:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10148:         $grouplist = join(':',@usersgroups);
10149:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10150:     }
10151:     return @usersgroups;
10152: }
10153: 
10154: sub devalidate_getgroups_cache {
10155:     my ($udom,$uname,$cdom,$cnum)=@_;
10156:     my $courseid = $cdom.'_'.$cnum;
10157: 
10158:     my $hashid="$udom:$uname:$courseid";
10159:     &devalidate_cache_new('getgroups',$hashid);
10160: }
10161: 
10162: # ------------------------------------------------------------------ Plain Text
10163: 
10164: sub plaintext {
10165:     my ($short,$type,$cid,$forcedefault) = @_;
10166:     if ($short =~ m{^cr/}) {
10167: 	return (split('/',$short))[-1];
10168:     }
10169:     if (!defined($cid)) {
10170:         $cid = $env{'request.course.id'};
10171:     }
10172:     my %rolenames = (
10173:                       Course    => 'std',
10174:                       Community => 'alt1',
10175:                       Placement => 'std',
10176:                     );
10177:     if ($cid ne '') {
10178:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10179:             unless ($forcedefault) {
10180:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10181:                 &Apache::lonlocal::mt_escape(\$roletext);
10182:                 return &Apache::lonlocal::mt($roletext);
10183:             }
10184:         }
10185:     }
10186:     if ((defined($type)) && (defined($rolenames{$type})) &&
10187:         (defined($rolenames{$type})) && 
10188:         (defined($prp{$short}{$rolenames{$type}}))) {
10189:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10190:     } elsif ($cid ne '') {
10191:         my $crstype = $env{'course.'.$cid.'.type'};
10192:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10193:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10194:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10195:         }
10196:     }
10197:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10198: }
10199: 
10200: # ----------------------------------------------------------------- Assign Role
10201: 
10202: sub assignrole {
10203:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10204:         $context)=@_;
10205:     my $mrole;
10206:     if ($role =~ /^cr\//) {
10207:         my $cwosec=$url;
10208:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10209: 	unless (&allowed('ccr',$cwosec)) {
10210:            my $refused = 1;
10211:            if ($context eq 'requestcourses') {
10212:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10213:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10214:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10215:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10216:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10217:                            if ($crsenv{'internal.courseowner'} eq
10218:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10219:                                $refused = '';
10220:                            }
10221:                        }
10222:                    }
10223:                }
10224:            }
10225:            if ($refused) {
10226:                &logthis('Refused custom assignrole: '.
10227:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10228:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10229:                return 'refused';
10230:            }
10231:         }
10232:         $mrole='cr';
10233:     } elsif ($role =~ /^gr\//) {
10234:         my $cwogrp=$url;
10235:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10236:         unless (&allowed('mdg',$cwogrp)) {
10237:             &logthis('Refused group assignrole: '.
10238:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10239:                     $env{'user.name'}.' at '.$env{'user.domain'});
10240:             return 'refused';
10241:         }
10242:         $mrole='gr';
10243:     } else {
10244:         my $cwosec=$url;
10245:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10246:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10247:             my $refused;
10248:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10249:                 if (!(&allowed('c'.$role,$url))) {
10250:                     $refused = 1;
10251:                 }
10252:             } else {
10253:                 $refused = 1;
10254:             }
10255:             if ($refused) {
10256:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10257:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10258:                     my %crsenv;
10259:                     if ($role eq 'cc' || $role eq 'co') {
10260:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10261:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10262:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10263:                                 if ($crsenv{'internal.courseowner'} eq 
10264:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10265:                                     $refused = '';
10266:                                 }
10267:                             }
10268:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10269:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10270:                                 if ($crsenv{'internal.courseowner'} eq 
10271:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10272:                                     $refused = '';
10273:                                 }
10274:                             }
10275:                         }
10276:                     }
10277:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10278:                     if ($role eq 'st') {
10279:                         $refused = '';
10280:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10281:                         $refused = '';
10282:                     }
10283:                 } elsif ($context eq 'requestcourses') {
10284:                     my @possroles = ('st','ta','ep','in','cc','co');
10285:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10286:                         my $wrongcc;
10287:                         if ($cnum =~ /^$match_community$/) {
10288:                             $wrongcc = 1 if ($role eq 'cc');
10289:                         } else {
10290:                             $wrongcc = 1 if ($role eq 'co');
10291:                         }
10292:                         unless ($wrongcc) {
10293:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10294:                             if ($crsenv{'internal.courseowner'} eq 
10295:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10296:                                 $refused = '';
10297:                             }
10298:                         }
10299:                     }
10300:                 } elsif ($context eq 'requestauthor') {
10301:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10302:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10303:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10304:                             $refused = '';
10305:                         } else {
10306:                             my %domdefaults = &get_domain_defaults($udom);
10307:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10308:                                 my $checkbystatus;
10309:                                 if ($env{'user.adv'}) { 
10310:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10311:                                     if ($disposition eq 'automatic') {
10312:                                         $refused = '';
10313:                                     } elsif ($disposition eq '') {
10314:                                         $checkbystatus = 1;
10315:                                     } 
10316:                                 } else {
10317:                                     $checkbystatus = 1;
10318:                                 }
10319:                                 if ($checkbystatus) {
10320:                                     if ($env{'environment.inststatus'}) {
10321:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10322:                                         foreach my $type (@inststatuses) {
10323:                                             if (($type ne '') &&
10324:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10325:                                                 $refused = '';
10326:                                             }
10327:                                         }
10328:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10329:                                         $refused = '';
10330:                                     }
10331:                                 }
10332:                             }
10333:                         }
10334:                     }
10335:                 }
10336:                 if ($refused) {
10337:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10338:                              ' '.$role.' '.$end.' '.$start.' by '.
10339: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10340:                     return 'refused';
10341:                 }
10342:             }
10343:         } elsif ($role eq 'au') {
10344:             if ($url ne '/'.$udom.'/') {
10345:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10346:                          ' to assign author role for '.$uname.':'.$udom.
10347:                          ' in domain: '.$url.' refused (wrong domain).');
10348:                 return 'refused';
10349:             }
10350:         }
10351:         $mrole=$role;
10352:     }
10353:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10354:                 "$udom:$uname:$url".'_'."$mrole=$role";
10355:     if ($end) { $command.='_'.$end; }
10356:     if ($start) {
10357: 	if ($end) { 
10358:            $command.='_'.$start; 
10359:         } else {
10360:            $command.='_0_'.$start;
10361:         }
10362:     }
10363:     my $origstart = $start;
10364:     my $origend = $end;
10365:     my $delflag;
10366: # actually delete
10367:     if ($deleteflag) {
10368: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10369: # modify command to delete the role
10370:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10371:                 "$udom:$uname:$url".'_'."$mrole";
10372: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10373: # set start and finish to negative values for userrolelog
10374:            $start=-1;
10375:            $end=-1;
10376:            $delflag = 1;
10377:         }
10378:     }
10379: # send command
10380:     my $answer=&reply($command,&homeserver($uname,$udom));
10381: # log new user role if status is ok
10382:     if ($answer eq 'ok') {
10383: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10384:         if (($role eq 'cc') || ($role eq 'in') ||
10385:             ($role eq 'ep') || ($role eq 'ad') ||
10386:             ($role eq 'ta') || ($role eq 'st') ||
10387:             ($role=~/^cr/) || ($role eq 'gr') ||
10388:             ($role eq 'co')) {
10389: # for course roles, perform group memberships changes triggered by role change.
10390:             unless ($role =~ /^gr/) {
10391:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10392:                                                  $origstart,$selfenroll,$context);
10393:             }
10394:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10395:                            $selfenroll,$context);
10396:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10397:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10398:                  ($role eq 'da')) {
10399:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10400:                            $context);
10401:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10402:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10403:                              $context); 
10404:         }
10405:         if ($role eq 'cc') {
10406:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10407:         }
10408:     }
10409:     return $answer;
10410: }
10411: 
10412: sub autoupdate_coowners {
10413:     my ($url,$end,$start,$uname,$udom) = @_;
10414:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10415:     if (($cdom ne '') && ($cnum ne '')) {
10416:         my $now = time;
10417:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10418:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10419:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10420:             my $instcode = $coursehash{'internal.coursecode'};
10421:             my $xlists = $coursehash{'internal.crosslistings'};
10422:             if ($instcode ne '') {
10423:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10424:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10425:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10426:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10427:                         unless ($result eq 'valid') {
10428:                             if ($xlists ne '') {
10429:                                 foreach my $xlist (split(',',$xlists)) {
10430:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10431:                                     $result =
10432:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10433:                                                                       $inst_crosslist,$uname.':'.$udom);
10434:                                     last if ($result eq 'valid');
10435:                                 }
10436:                             }
10437:                         }
10438:                         if ($result eq 'valid') {
10439:                             if ($coursehash{'internal.co-owners'}) {
10440:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10441:                                     push(@newcoowners,$coowner);
10442:                                 }
10443:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10444:                                     push(@newcoowners,$uname.':'.$udom);
10445:                                 }
10446:                                 @newcoowners = sort(@newcoowners);
10447:                             } else {
10448:                                 push(@newcoowners,$uname.':'.$udom);
10449:                             }
10450:                         } elsif ($coursehash{'internal.co-owners'}) {
10451:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10452:                                 unless ($coowner eq $uname.':'.$udom) {
10453:                                     push(@newcoowners,$coowner);
10454:                                 }
10455:                             }
10456:                             unless (@newcoowners > 0) {
10457:                                 $delcoowners = 1;
10458:                                 $coowners = '';
10459:                             }
10460:                         }
10461:                         if (@newcoowners || $delcoowners) {
10462:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10463:                                             $delcoowners,@newcoowners);
10464:                         }
10465:                     }
10466:                 }
10467:             }
10468:         }
10469:     }
10470: }
10471: 
10472: sub store_coowners {
10473:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10474:     my $cid = $cdom.'_'.$cnum;
10475:     my ($coowners,$delresult,$putresult);
10476:     if (@newcoowners) {
10477:         $coowners = join(',',@newcoowners);
10478:         my %coownershash = (
10479:                             'internal.co-owners' => $coowners,
10480:                            );
10481:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10482:         if ($putresult eq 'ok') {
10483:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10484:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10485:             }
10486:         }
10487:     }
10488:     if ($delcoowners) {
10489:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10490:         if ($delresult eq 'ok') {
10491:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10492:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10493:             }
10494:         }
10495:     }
10496:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10497:         my %crsinfo =
10498:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10499:         if (ref($crsinfo{$cid}) eq 'HASH') {
10500:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10501:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10502:         }
10503:     }
10504: }
10505: 
10506: # -------------------------------------------------- Modify user authentication
10507: # Overrides without validation
10508: 
10509: sub modifyuserauth {
10510:     my ($udom,$uname,$umode,$upass)=@_;
10511:     my $uhome=&homeserver($uname,$udom);
10512:     my $allowed;
10513:     if (&allowed('mau',$udom)) {
10514:         $allowed = 1;
10515:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10516:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10517:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10518:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10519:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10520:         if (($cdom ne '') && ($cnum ne '')) {
10521:             my $is_owner = &is_course_owner($cdom,$cnum);
10522:             if ($is_owner) {
10523:                 $allowed = 1;
10524:             }
10525:         }
10526:     }
10527:     unless ($allowed) { return 'refused'; }
10528:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10529:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10530:              ' in domain '.$env{'request.role.domain'});  
10531:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10532: 		     &escape($upass),$uhome);
10533:     my $ip = &get_requestor_ip();
10534:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10535:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10536:          '(Remote '.$ip.'): '.$reply);
10537:     &log($udom,,$uname,$uhome,
10538:         'Authentication changed by '.$env{'user.domain'}.', '.
10539:                                      $env{'user.name'}.', '.$umode.
10540:          '(Remote '.$ip.'): '.$reply);
10541:     unless ($reply eq 'ok') {
10542:         &logthis('Authentication mode error: '.$reply);
10543: 	return 'error: '.$reply;
10544:     }   
10545:     return 'ok';
10546: }
10547: 
10548: # --------------------------------------------------------------- Modify a user
10549: 
10550: sub modifyuser {
10551:     my ($udom,    $uname, $uid,
10552:         $umode,   $upass, $first,
10553:         $middle,  $last,  $gene,
10554:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10555:     $udom= &LONCAPA::clean_domain($udom);
10556:     $uname=&LONCAPA::clean_username($uname);
10557:     my $showcandelete = 'none';
10558:     if (ref($candelete) eq 'ARRAY') {
10559:         if (@{$candelete} > 0) {
10560:             $showcandelete = join(', ',@{$candelete});
10561:         }
10562:     }
10563:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10564:              $umode.', '.$first.', '.$middle.', '.
10565: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10566:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10567:                                      ' desiredhome not specified'). 
10568:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10569:              ' in domain '.$env{'request.role.domain'});
10570:     my $uhome=&homeserver($uname,$udom,'true');
10571:     my $newuser;
10572:     if ($uhome eq 'no_host') {
10573:         $newuser = 1;
10574:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10575:                 ($umode eq 'lti')) {
10576:             return 'error: more information needed to create new user';
10577:         }
10578:     }
10579: # ----------------------------------------------------------------- Create User
10580:     if (($uhome eq 'no_host') && 
10581: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10582:         my $unhome='';
10583:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10584:             $unhome = $desiredhome;
10585: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10586: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10587:         } else { # load balancing routine for determining $unhome
10588:             my $loadm=10000000;
10589: 	    my %servers = &get_servers($udom,'library');
10590: 	    foreach my $tryserver (keys(%servers)) {
10591: 		my $answer=reply('load',$tryserver);
10592: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10593: 		    $loadm=$answer;
10594: 		    $unhome=$tryserver;
10595: 		}
10596: 	    }
10597:         }
10598:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10599: 	    return 'error: unable to find a home server for '.$uname.
10600:                    ' in domain '.$udom;
10601:         }
10602:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10603:                          &escape($upass),$unhome);
10604: 	unless ($reply eq 'ok') {
10605:             return 'error: '.$reply;
10606:         }   
10607:         $uhome=&homeserver($uname,$udom,'true');
10608:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10609: 	    return 'error: unable verify users home machine.';
10610:         }
10611:     }   # End of creation of new user
10612: # ---------------------------------------------------------------------- Add ID
10613:     if ($uid) {
10614:        $uid=~tr/A-Z/a-z/;
10615:        my %uidhash=&idrget($udom,$uname);
10616:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10617:          && (!$forceid)) {
10618: 	  unless ($uid eq $uidhash{$uname}) {
10619: 	      return 'error: user id "'.$uid.'" does not match '.
10620:                   'current user id "'.$uidhash{$uname}.'".';
10621:           }
10622:        } else {
10623: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10624:        }
10625:     }
10626: # -------------------------------------------------------------- Add names, etc
10627:     my @tmp=&get('environment',
10628: 		   ['firstname','middlename','lastname','generation','id',
10629:                     'permanentemail','inststatus'],
10630: 		   $udom,$uname);
10631:     my (%names,%oldnames);
10632:     if ($tmp[0] =~ m/^error:.*/) { 
10633:         %names=(); 
10634:     } else {
10635:         %names = @tmp;
10636:         %oldnames = %names;
10637:     }
10638: #
10639: # If name, email and/or uid are blank (e.g., because an uploaded file
10640: # of users did not contain them), do not overwrite existing values
10641: # unless field is in $candelete array ref.  
10642: #
10643: 
10644:     my @fields = ('firstname','middlename','lastname','generation',
10645:                   'permanentemail','id');
10646:     my %newvalues;
10647:     if (ref($candelete) eq 'ARRAY') {
10648:         foreach my $field (@fields) {
10649:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10650:                 if ($field eq 'firstname') {
10651:                     $names{$field} = $first;
10652:                 } elsif ($field eq 'middlename') {
10653:                     $names{$field} = $middle;
10654:                 } elsif ($field eq 'lastname') {
10655:                     $names{$field} = $last;
10656:                 } elsif ($field eq 'generation') { 
10657:                     $names{$field} = $gene;
10658:                 } elsif ($field eq 'permanentemail') {
10659:                     $names{$field} = $email;
10660:                 } elsif ($field eq 'id') {
10661:                     $names{$field}  = $uid;
10662:                 }
10663:             }
10664:         }
10665:     }
10666:     if ($first)  { $names{'firstname'}  = $first; }
10667:     if (defined($middle)) { $names{'middlename'} = $middle; }
10668:     if ($last)   { $names{'lastname'}   = $last; }
10669:     if (defined($gene))   { $names{'generation'} = $gene; }
10670:     if ($email) {
10671:        $email=~s/[^\w\@\.\-\,]//gs;
10672:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10673:     }
10674:     if ($uid) { $names{'id'}  = $uid; }
10675:     if (defined($inststatus)) {
10676:         $names{'inststatus'} = '';
10677:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10678:         if (ref($usertypes) eq 'HASH') {
10679:             my @okstatuses; 
10680:             foreach my $item (split(/:/,$inststatus)) {
10681:                 if (defined($usertypes->{$item})) {
10682:                     push(@okstatuses,$item);  
10683:                 }
10684:             }
10685:             if (@okstatuses) {
10686:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10687:             }
10688:         }
10689:     }
10690:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10691:                  $umode.', '.$first.', '.$middle.', '.
10692:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10693:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10694:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10695:     } else {
10696:         $logmsg .= ' during self creation';
10697:     }
10698:     my $changed;
10699:     if ($newuser) {
10700:         $changed = 1;
10701:     } else {
10702:         foreach my $field (@fields) {
10703:             if ($names{$field} ne $oldnames{$field}) {
10704:                 $changed = 1;
10705:                 last;
10706:             }
10707:         }
10708:     }
10709:     unless ($changed) {
10710:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10711:         &logthis($logmsg);
10712:         return 'ok';
10713:     }
10714:     my $reply = &put('environment', \%names, $udom,$uname);
10715:     if ($reply ne 'ok') { 
10716:         return 'error: '.$reply;
10717:     }
10718:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10719:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10720:     }
10721:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10722:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10723:     $logmsg = 'Success modifying user '.$logmsg;
10724:     &logthis($logmsg);
10725:     return 'ok';
10726: }
10727: 
10728: # -------------------------------------------------------------- Modify student
10729: 
10730: sub modifystudent {
10731:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10732:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10733:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10734:     if (!$cid) {
10735: 	unless ($cid=$env{'request.course.id'}) {
10736: 	    return 'not_in_class';
10737: 	}
10738:     }
10739: # --------------------------------------------------------------- Make the user
10740:     my $reply=&modifyuser
10741: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10742:          $desiredhome,$email,$inststatus);
10743:     unless ($reply eq 'ok') { return $reply; }
10744:     # This will cause &modify_student_enrollment to get the uid from the
10745:     # student's environment
10746:     $uid = undef if (!$forceid);
10747:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10748:                                         $gene,$usec,$end,$start,$type,$locktype,
10749:                                         $cid,$selfenroll,$context,$credits,$instsec);
10750:     return $reply;
10751: }
10752: 
10753: sub modify_student_enrollment {
10754:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10755:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10756:     my ($cdom,$cnum,$chome);
10757:     if (!$cid) {
10758: 	unless ($cid=$env{'request.course.id'}) {
10759: 	    return 'not_in_class';
10760: 	}
10761: 	$cdom=$env{'course.'.$cid.'.domain'};
10762: 	$cnum=$env{'course.'.$cid.'.num'};
10763:     } else {
10764: 	($cdom,$cnum)=split(/_/,$cid);
10765:     }
10766:     $chome=$env{'course.'.$cid.'.home'};
10767:     if (!$chome) {
10768: 	$chome=&homeserver($cnum,$cdom);
10769:     }
10770:     if (!$chome) { return 'unknown_course'; }
10771:     # Make sure the user exists
10772:     my $uhome=&homeserver($uname,$udom);
10773:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10774: 	return 'error: no such user';
10775:     }
10776:     # Get student data if we were not given enough information
10777:     if (!defined($first)  || $first  eq '' || 
10778:         !defined($last)   || $last   eq '' || 
10779:         !defined($uid)    || $uid    eq '' || 
10780:         !defined($middle) || $middle eq '' || 
10781:         !defined($gene)   || $gene   eq '') {
10782:         # They did not supply us with enough data to enroll the student, so
10783:         # we need to pick up more information.
10784:         my %tmp = &get('environment',
10785:                        ['firstname','middlename','lastname', 'generation','id']
10786:                        ,$udom,$uname);
10787: 
10788:         #foreach my $key (keys(%tmp)) {
10789:         #    &logthis("key $key = ".$tmp{$key});
10790:         #}
10791:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10792:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10793:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10794:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10795:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10796:     }
10797:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10798:     my $user = "$uname:$udom";
10799:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10800:     my $reply=cput('classlist',
10801: 		   {$user => 
10802: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10803: 		   $cdom,$cnum);
10804:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10805:         &devalidate_getsection_cache($udom,$uname,$cid);
10806:     } else { 
10807: 	return 'error: '.$reply;
10808:     }
10809:     # Add student role to user
10810:     my $uurl='/'.$cid;
10811:     $uurl=~s/\_/\//g;
10812:     if ($usec) {
10813: 	$uurl.='/'.$usec;
10814:     }
10815:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10816:                              $selfenroll,$context);
10817:     if ($result ne 'ok') {
10818:         if ($old_entry{$user} ne '') {
10819:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10820:         } else {
10821:             $reply = &del('classlist',[$user],$cdom,$cnum);
10822:         }
10823:     }
10824:     return $result; 
10825: }
10826: 
10827: sub format_name {
10828:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10829:     my $name;
10830:     if ($first ne 'lastname') {
10831: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10832:     } else {
10833: 	if ($lastname=~/\S/) {
10834: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10835: 	    $name=~s/\s+,/,/;
10836: 	} else {
10837: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10838: 	}
10839:     }
10840:     $name=~s/^\s+//;
10841:     $name=~s/\s+$//;
10842:     $name=~s/\s+/ /g;
10843:     return $name;
10844: }
10845: 
10846: # ------------------------------------------------- Write to course preferences
10847: 
10848: sub writecoursepref {
10849:     my ($courseid,%prefs)=@_;
10850:     $courseid=~s/^\///;
10851:     $courseid=~s/\_/\//g;
10852:     my ($cdomain,$cnum)=split(/\//,$courseid);
10853:     my $chome=homeserver($cnum,$cdomain);
10854:     if (($chome eq '') || ($chome eq 'no_host')) { 
10855: 	return 'error: no such course';
10856:     }
10857:     my $cstring='';
10858:     foreach my $pref (keys(%prefs)) {
10859: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10860:     }
10861:     $cstring=~s/\&$//;
10862:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10863: }
10864: 
10865: # ---------------------------------------------------------- Make/modify course
10866: 
10867: sub createcourse {
10868:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10869:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10870:     $url=&declutter($url);
10871:     my $cid='';
10872:     if ($context eq 'requestcourses') {
10873:         my $can_create = 0;
10874:         my ($ownername,$ownerdom) = split(':',$course_owner);
10875:         if ($udom eq $ownerdom) {
10876:             my $reload;
10877:             if (($callercontext eq 'auto') &&
10878:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10879:                 $reload = 'reload';
10880:             }
10881:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10882:                                   $context)) {
10883:                 $can_create = 1;
10884:             }
10885:         } else {
10886:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10887:                                            $category);
10888:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10889:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10890:                 if (@curr > 0) {
10891:                     my @options = qw(approval validate autolimit);
10892:                     my $optregex = join('|',@options);
10893:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10894:                         $can_create = 1;
10895:                     }
10896:                 }
10897:             }
10898:         }
10899:         if ($can_create) {
10900:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10901:                 unless (&allowed('ccc',$udom)) {
10902:                     return 'refused'; 
10903:                 }
10904:             }
10905:         } else {
10906:             return 'refused';
10907:         }
10908:     } elsif (!&allowed('ccc',$udom)) {
10909:         return 'refused';
10910:     }
10911: # --------------------------------------------------------------- Get Unique ID
10912:     my $uname;
10913:     if ($cnum =~ /^$match_courseid$/) {
10914:         my $chome=&homeserver($cnum,$udom,'true');
10915:         if (($chome eq '') || ($chome eq 'no_host')) {
10916:             $uname = $cnum;
10917:         } else {
10918:             $uname = &generate_coursenum($udom,$crstype);
10919:         }
10920:     } else {
10921:         $uname = &generate_coursenum($udom,$crstype);
10922:     }
10923:     return $uname if ($uname =~ /^error/);
10924: # -------------------------------------------------- Check supplied server name
10925:     if (!defined($course_server)) {
10926:         if (defined(&domain($udom,'primary'))) {
10927:             $course_server = &domain($udom,'primary');
10928:         } else {
10929:             $course_server = $env{'user.home'}; 
10930:         }
10931:     }
10932:     my %host_servers =
10933:         &Apache::lonnet::get_servers($udom,'library');
10934:     unless ($host_servers{$course_server}) {
10935:         return 'error: invalid home server for course: '.$course_server;
10936:     }
10937: # ------------------------------------------------------------- Make the course
10938:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10939:                       $course_server);
10940:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10941:     my $uhome=&homeserver($uname,$udom,'true');
10942:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10943: 	return 'error: no such course';
10944:     }
10945: # ----------------------------------------------------------------- Course made
10946: # log existence
10947:     my $now = time;
10948:     my $newcourse = {
10949:                     $udom.'_'.$uname => {
10950:                                      description => $description,
10951:                                      inst_code   => $inst_code,
10952:                                      owner       => $course_owner,
10953:                                      type        => $crstype,
10954:                                      creator     => $env{'user.name'}.':'.
10955:                                                     $env{'user.domain'},
10956:                                      created     => $now,
10957:                                      context     => $context,
10958:                                                 },
10959:                     };
10960:     &courseidput($udom,$newcourse,$uhome,'notime');
10961: # set toplevel url
10962:     my $topurl=$url;
10963:     unless ($nonstandard) {
10964: # ------------------------------------------ For standard courses, make top url
10965:         my $mapurl=&clutter($url);
10966:         if ($mapurl eq '/res/') { $mapurl=''; }
10967:         $env{'form.initmap'}=(<<ENDINITMAP);
10968: <map>
10969: <resource id="1" type="start"></resource>
10970: <resource id="2" src="$mapurl"></resource>
10971: <resource id="3" type="finish"></resource>
10972: <link index="1" from="1" to="2"></link>
10973: <link index="2" from="2" to="3"></link>
10974: </map>
10975: ENDINITMAP
10976:         $topurl=&declutter(
10977:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10978:                           );
10979:     }
10980: # ----------------------------------------------------------- Write preferences
10981:     &writecoursepref($udom.'_'.$uname,
10982:                      ('description'              => $description,
10983:                       'url'                      => $topurl,
10984:                       'internal.creator'         => $env{'user.name'}.':'.
10985:                                                     $env{'user.domain'},
10986:                       'internal.created'         => $now,
10987:                       'internal.creationcontext' => $context)
10988:                     );
10989:     return '/'.$udom.'/'.$uname;
10990: }
10991: 
10992: # ------------------------------------------------------------------- Create ID
10993: sub generate_coursenum {
10994:     my ($udom,$crstype) = @_;
10995:     my $domdesc = &domain($udom);
10996:     return 'error: invalid domain' if ($domdesc eq '');
10997:     my $first;
10998:     if ($crstype eq 'Community') {
10999:         $first = '0';
11000:     } else {
11001:         $first = int(1+rand(9)); 
11002:     } 
11003:     my $uname=$first.
11004:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11005:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11006:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11007: # ----------------------------------------------- Make sure that does not exist
11008:     my $uhome=&homeserver($uname,$udom,'true');
11009:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11010:         if ($crstype eq 'Community') {
11011:             $first = '0';
11012:         } else {
11013:             $first = int(1+rand(9));
11014:         }
11015:         $uname=$first.
11016:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11017:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11018:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11019:         $uhome=&homeserver($uname,$udom,'true');
11020:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11021:             return 'error: unable to generate unique course-ID';
11022:         }
11023:     }
11024:     return $uname;
11025: }
11026: 
11027: sub is_course {
11028:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11029:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11030: 
11031:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11032:     my $uhome=&homeserver($cnum,$cdom);
11033:     my $iscourse;
11034:     if (grep { $_ eq $uhome } current_machine_ids()) {
11035:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11036:     } else {
11037:         my $hashid = $cdom.':'.$cnum;
11038:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11039:         unless (defined($cached)) {
11040:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11041:                                         $cnum,undef,undef,'.');
11042:             $iscourse = 0;
11043:             if (exists($courses{$cdom.'_'.$cnum})) {
11044:                 $iscourse = 1;
11045:             }
11046:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11047:         }
11048:     }
11049:     return unless ($iscourse);
11050:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11051: }
11052: 
11053: sub store_userdata {
11054:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11055:     my $result;
11056:     if ($datakey ne '') {
11057:         if (ref($storehash) eq 'HASH') {
11058:             if ($udom eq '' || $uname eq '') {
11059:                 $udom = $env{'user.domain'};
11060:                 $uname = $env{'user.name'};
11061:             }
11062:             my $uhome=&homeserver($uname,$udom);
11063:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11064:                 $result = 'error: no_host';
11065:             } else {
11066:                 $storehash->{'ip'} = &get_requestor_ip();
11067:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11068: 
11069:                 my $namevalue='';
11070:                 foreach my $key (keys(%{$storehash})) {
11071:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11072:                 }
11073:                 $namevalue=~s/\&$//;
11074:                 unless ($namespace eq 'courserequests') {
11075:                     $datakey = &escape($datakey);
11076:                 }
11077:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11078:                                   $namevalue,$uhome);
11079:             }
11080:         } else {
11081:             $result = 'error: data to store was not a hash reference'; 
11082:         }
11083:     } else {
11084:         $result= 'error: invalid requestkey'; 
11085:     }
11086:     return $result;
11087: }
11088: 
11089: # ---------------------------------------------------------- Assign Custom Role
11090: 
11091: sub assigncustomrole {
11092:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
11093:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11094:                        $end,$start,$deleteflag,$selfenroll,$context);
11095: }
11096: 
11097: # ----------------------------------------------------------------- Revoke Role
11098: 
11099: sub revokerole {
11100:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11101:     my $now=time;
11102:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11103: }
11104: 
11105: # ---------------------------------------------------------- Revoke Custom Role
11106: 
11107: sub revokecustomrole {
11108:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11109:     my $now=time;
11110:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11111:            $deleteflag,$selfenroll,$context);
11112: }
11113: 
11114: # ------------------------------------------------------------ Disk usage
11115: sub diskusage {
11116:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11117:     $directorypath =~ s/\/$//;
11118:     my $listing=&reply('du2:'.&escape($directorypath).':'
11119:                        .&escape($getpropath).':'.&escape($uname).':'
11120:                        .&escape($udom),homeserver($uname,$udom));
11121:     if ($listing eq 'unknown_cmd') {
11122:         if ($getpropath) {
11123:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11124:         }
11125:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11126:     }
11127:     return $listing;
11128: }
11129: 
11130: sub is_locked {
11131:     my ($file_name, $domain, $user, $which) = @_;
11132:     my @check;
11133:     my $is_locked;
11134:     push (@check,$file_name);
11135:     my %locked = &get('file_permissions',\@check,
11136: 		      $env{'user.domain'},$env{'user.name'});
11137:     my ($tmp)=keys(%locked);
11138:     if ($tmp=~/^error:/) { undef(%locked); }
11139:     
11140:     if (ref($locked{$file_name}) eq 'ARRAY') {
11141:         $is_locked = 'false';
11142:         foreach my $entry (@{$locked{$file_name}}) {
11143:            if (ref($entry) eq 'ARRAY') {
11144:                $is_locked = 'true';
11145:                if (ref($which) eq 'ARRAY') {
11146:                    push(@{$which},$entry);
11147:                } else {
11148:                    last;
11149:                }
11150:            }
11151:        }
11152:     } else {
11153:         $is_locked = 'false';
11154:     }
11155:     return $is_locked;
11156: }
11157: 
11158: sub declutter_portfile {
11159:     my ($file) = @_;
11160:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11161:     return $file;
11162: }
11163: 
11164: # ------------------------------------------------------------- Mark as Read Only
11165: 
11166: sub mark_as_readonly {
11167:     my ($domain,$user,$files,$what) = @_;
11168:     my %current_permissions = &dump('file_permissions',$domain,$user);
11169:     my ($tmp)=keys(%current_permissions);
11170:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11171:     foreach my $file (@{$files}) {
11172: 	$file = &declutter_portfile($file);
11173:         push(@{$current_permissions{$file}},$what);
11174:     }
11175:     &put('file_permissions',\%current_permissions,$domain,$user);
11176:     return;
11177: }
11178: 
11179: # ------------------------------------------------------------Save Selected Files
11180: 
11181: sub save_selected_files {
11182:     my ($user, $path, @files) = @_;
11183:     my $filename = $user."savedfiles";
11184:     my @other_files = &files_not_in_path($user, $path);
11185:     open (OUT,'>',LONCAPA::tempdir().$filename);
11186:     foreach my $file (@files) {
11187:         print (OUT $env{'form.currentpath'}.$file."\n");
11188:     }
11189:     foreach my $file (@other_files) {
11190:         print (OUT $file."\n");
11191:     }
11192:     close (OUT);
11193:     return 'ok';
11194: }
11195: 
11196: sub clear_selected_files {
11197:     my ($user) = @_;
11198:     my $filename = $user."savedfiles";
11199:     open (OUT,'>',LONCAPA::tempdir().$filename);
11200:     print (OUT undef);
11201:     close (OUT);
11202:     return ("ok");    
11203: }
11204: 
11205: sub files_in_path {
11206:     my ($user, $path) = @_;
11207:     my $filename = $user."savedfiles";
11208:     my %return_files;
11209:     open (IN,'<',LONCAPA::tempdir().$filename);
11210:     while (my $line_in = <IN>) {
11211:         chomp ($line_in);
11212:         my @paths_and_file = split (m!/!, $line_in);
11213:         my $file_part = pop (@paths_and_file);
11214:         my $path_part = join ('/', @paths_and_file);
11215:         $path_part.='/';
11216:         my $path_and_file = $path_part.$file_part;
11217:         if ($path_part eq $path) {
11218:             $return_files{$file_part}= 'selected';
11219:         }
11220:     }
11221:     close (IN);
11222:     return (\%return_files);
11223: }
11224: 
11225: # called in portfolio select mode, to show files selected NOT in current directory
11226: sub files_not_in_path {
11227:     my ($user, $path) = @_;
11228:     my $filename = $user."savedfiles";
11229:     my @return_files;
11230:     my $path_part;
11231:     open(IN, '<',LONCAPA::tempdir().$filename);
11232:     while (my $line = <IN>) {
11233:         #ok, I know it's clunky, but I want it to work
11234:         my @paths_and_file = split(m|/|, $line);
11235:         my $file_part = pop(@paths_and_file);
11236:         chomp($file_part);
11237:         my $path_part = join('/', @paths_and_file);
11238:         $path_part .= '/';
11239:         my $path_and_file = $path_part.$file_part;
11240:         if ($path_part ne $path) {
11241:             push(@return_files, ($path_and_file));
11242:         }
11243:     }
11244:     close(OUT);
11245:     return (@return_files);
11246: }
11247: 
11248: #------------------------------Submitted/Handedback Portfolio Files Versioning
11249:  
11250: sub portfiles_versioning {
11251:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11252:     my $portfolio_root = '/userfiles/portfolio';
11253:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11254:     foreach my $file (@{$portfiles}) {
11255:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11256:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11257:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11258:         my $getpropath = 1;
11259:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11260:                                              $stu_name,$getpropath);
11261:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11262:         my $new_answer = 
11263:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11264:         if ($new_answer ne 'problem getting file') {
11265:             push(@{$versioned_portfiles}, $directory.$new_answer);
11266:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11267:                               [$symb,$env{'request.course.id'},'graded']);
11268:         }
11269:     }
11270: }
11271: 
11272: sub get_next_version {
11273:     my ($answer_name, $answer_ext, $dir_list) = @_;
11274:     my $version;
11275:     if (ref($dir_list) eq 'ARRAY') {
11276:         foreach my $row (@{$dir_list}) {
11277:             my ($file) = split(/\&/,$row,2);
11278:             my ($file_name,$file_version,$file_ext) =
11279:                 &file_name_version_ext($file);
11280:             if (($file_name eq $answer_name) &&
11281:                 ($file_ext eq $answer_ext)) {
11282:                      # gets here if filename and extension match,
11283:                      # regardless of version
11284:                 if ($file_version ne '') {
11285:                     # a versioned file is found  so save it for later
11286:                     if ($file_version > $version) {
11287:                         $version = $file_version;
11288:                     }
11289:                 }
11290:             }
11291:         }
11292:     }
11293:     $version ++;
11294:     return($version);
11295: }
11296: 
11297: sub version_selected_portfile {
11298:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11299:     my ($answer_name,$answer_ver,$answer_ext) =
11300:         &file_name_version_ext($file_name);
11301:     my $new_answer;
11302:     $env{'form.copy'} =
11303:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11304:     if($env{'form.copy'} eq '-1') {
11305:         $new_answer = 'problem getting file';
11306:     } else {
11307:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11308:         my $copy_result = 
11309:             &finishuserfileupload($stu_name,$domain,'copy',
11310:                                   '/portfolio'.$directory.$new_answer);
11311:     }
11312:     undef($env{'form.copy'});
11313:     return ($new_answer);
11314: }
11315: 
11316: sub file_name_version_ext {
11317:     my ($file)=@_;
11318:     my @file_parts = split(/\./, $file);
11319:     my ($name,$version,$ext);
11320:     if (@file_parts > 1) {
11321:         $ext=pop(@file_parts);
11322:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11323:             $version=pop(@file_parts);
11324:         }
11325:         $name=join('.',@file_parts);
11326:     } else {
11327:         $name=join('.',@file_parts);
11328:     }
11329:     return($name,$version,$ext);
11330: }
11331: 
11332: #----------------------------------------------Get portfolio file permissions
11333: 
11334: sub get_portfile_permissions {
11335:     my ($domain,$user) = @_;
11336:     my %current_permissions = &dump('file_permissions',$domain,$user);
11337:     my ($tmp)=keys(%current_permissions);
11338:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11339:     return \%current_permissions;
11340: }
11341: 
11342: #---------------------------------------------Get portfolio file access controls
11343: 
11344: sub get_access_controls {
11345:     my ($current_permissions,$group,$file) = @_;
11346:     my %access;
11347:     my $real_file = $file;
11348:     $file =~ s/\.meta$//;
11349:     if (defined($file)) {
11350:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11351:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11352:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11353:             }
11354:         }
11355:     } else {
11356:         foreach my $key (keys(%{$current_permissions})) {
11357:             if ($key =~ /\0accesscontrol$/) {
11358:                 if (defined($group)) {
11359:                     if ($key !~ m-^\Q$group\E/-) {
11360:                         next;
11361:                     }
11362:                 }
11363:                 my ($fullpath) = split(/\0/,$key);
11364:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11365:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11366:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11367:                     }
11368:                 }
11369:             }
11370:         }
11371:     }
11372:     return %access;
11373: }
11374: 
11375: sub modify_access_controls {
11376:     my ($file_name,$changes,$domain,$user)=@_;
11377:     my ($outcome,$deloutcome);
11378:     my %store_permissions;
11379:     my %new_values;
11380:     my %new_control;
11381:     my %translation;
11382:     my @deletions = ();
11383:     my $now = time;
11384:     if (exists($$changes{'activate'})) {
11385:         if (ref($$changes{'activate'}) eq 'HASH') {
11386:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11387:             my $numnew = scalar(@newitems);
11388:             for (my $i=0; $i<$numnew; $i++) {
11389:                 my $newkey = $newitems[$i];
11390:                 my $newid = &Apache::loncommon::get_cgi_id();
11391:                 if ($newkey =~ /^\d+:/) { 
11392:                     $newkey =~ s/^(\d+)/$newid/;
11393:                     $translation{$1} = $newid;
11394:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11395:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11396:                     $translation{$1} = $newid;
11397:                 }
11398:                 $new_values{$file_name."\0".$newkey} = 
11399:                                           $$changes{'activate'}{$newitems[$i]};
11400:                 $new_control{$newkey} = $now;
11401:             }
11402:         }
11403:     }
11404:     my %todelete;
11405:     my %changed_items;
11406:     foreach my $action ('delete','update') {
11407:         if (exists($$changes{$action})) {
11408:             if (ref($$changes{$action}) eq 'HASH') {
11409:                 foreach my $key (keys(%{$$changes{$action}})) {
11410:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11411:                     if ($action eq 'delete') { 
11412:                         $todelete{$itemnum} = 1;
11413:                     } else {
11414:                         $changed_items{$itemnum} = $key;
11415:                     }
11416:                 }
11417:             }
11418:         }
11419:     }
11420:     # get lock on access controls for file.
11421:     my $lockhash = {
11422:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11423:                                                        ':'.$env{'user.domain'},
11424:                    }; 
11425:     my $tries = 0;
11426:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11427:    
11428:     while (($gotlock ne 'ok') && $tries < 10) {
11429:         $tries ++;
11430:         sleep(0.1);
11431:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11432:     }
11433:     if ($gotlock eq 'ok') {
11434:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11435:         my ($tmp)=keys(%curr_permissions);
11436:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11437:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11438:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11439:             if (ref($curr_controls) eq 'HASH') {
11440:                 foreach my $control_item (keys(%{$curr_controls})) {
11441:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11442:                     if (defined($todelete{$itemnum})) {
11443:                         push(@deletions,$file_name."\0".$control_item);
11444:                     } else {
11445:                         if (defined($changed_items{$itemnum})) {
11446:                             $new_control{$changed_items{$itemnum}} = $now;
11447:                             push(@deletions,$file_name."\0".$control_item);
11448:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11449:                         } else {
11450:                             $new_control{$control_item} = $$curr_controls{$control_item};
11451:                         }
11452:                     }
11453:                 }
11454:             }
11455:         }
11456:         my ($group);
11457:         if (&is_course($domain,$user)) {
11458:             ($group,my $file) = split(/\//,$file_name,2);
11459:         }
11460:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11461:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11462:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11463:         #  remove lock
11464:         my @del_lock = ($file_name."\0".'locked_access_records');
11465:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11466:         my $sqlresult =
11467:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11468:                                     $group);
11469:     } else {
11470:         $outcome = "error: could not obtain lockfile\n";  
11471:     }
11472:     return ($outcome,$deloutcome,\%new_values,\%translation);
11473: }
11474: 
11475: sub make_public_indefinitely {
11476:     my (@requrl) = @_;
11477:     return &automated_portfile_access('public',\@requrl);
11478: }
11479: 
11480: sub automated_portfile_access {
11481:     my ($accesstype,$addsref,$delsref,$info) = @_;
11482:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11483:         return 'invalid';
11484:     }
11485:     my %urls;
11486:     if (ref($addsref) eq 'ARRAY') {
11487:         foreach my $requrl (@{$addsref}) {
11488:             if (&is_portfolio_url($requrl)) {
11489:                 unless (exists($urls{$requrl})) {
11490:                     $urls{$requrl} = 'add';
11491:                 }
11492:             }
11493:         }
11494:     }
11495:     if (ref($delsref) eq 'ARRAY') {
11496:         foreach my $requrl (@{$delsref}) { 
11497:             if (&is_portfolio_url($requrl)) {
11498:                 unless (exists($urls{$requrl})) {
11499:                     $urls{$requrl} = 'delete'; 
11500:                 }
11501:             }
11502:         }
11503:     }
11504:     unless (keys(%urls)) {
11505:         return 'invalid';
11506:     }
11507:     my $ip;
11508:     if ($accesstype eq 'ip') {
11509:         if (ref($info) eq 'HASH') {
11510:             if ($info->{'ip'} ne '') {
11511:                 $ip = $info->{'ip'};
11512:             }
11513:         }
11514:         if ($ip eq '') {
11515:             return 'invalid';
11516:         }
11517:     }
11518:     my $errors;
11519:     my $now = time;
11520:     my %current_perms;
11521:     foreach my $requrl (sort(keys(%urls))) {
11522:         my $action;
11523:         if ($urls{$requrl} eq 'add') {
11524:             $action = 'activate';
11525:         } else {
11526:             $action = 'none';
11527:         }
11528:         my $aclnum = 0;
11529:         my (undef,$udom,$unum,$file_name,$group) =
11530:             &parse_portfolio_url($requrl);
11531:         unless (exists($current_perms{$unum.':'.$udom})) {
11532:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11533:         }
11534:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11535:                                                    $group,$file_name);
11536:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11537:             my ($num,$scope,$end,$start) = 
11538:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11539:             if ($scope eq $accesstype) {
11540:                 if (($start <= $now) && ($end == 0)) {
11541:                     if ($accesstype eq 'ip') {
11542:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11543:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11544:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11545:                                     if ($urls{$requrl} eq 'add') {
11546:                                         $action = 'none';
11547:                                         last;
11548:                                     } else {
11549:                                         $action = 'delete';
11550:                                         $aclnum = $num;
11551:                                         last;
11552:                                     }
11553:                                 }
11554:                             }
11555:                         }
11556:                     } elsif ($accesstype eq 'public') {
11557:                         if ($urls{$requrl} eq 'add') {
11558:                             $action = 'none';
11559:                             last;
11560:                         } else {
11561:                             $action = 'delete';
11562:                             $aclnum = $num;
11563:                             last;
11564:                         }
11565:                     }
11566:                 } elsif ($accesstype eq 'public') {
11567:                     $action = 'update';
11568:                     $aclnum = $num;
11569:                     last;
11570:                 }
11571:             }
11572:         }
11573:         if ($action eq 'none') {
11574:             next;
11575:         } else {
11576:             my %changes;
11577:             my $newend = 0;
11578:             my $newstart = $now;
11579:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11580:             $changes{$action}{$newkey} = {
11581:                 type => $accesstype,
11582:                 time => {
11583:                     start => $newstart,
11584:                     end   => $newend,
11585:                 },
11586:             };
11587:             if ($accesstype eq 'ip') {
11588:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11589:             }
11590:             my ($outcome,$deloutcome,$new_values,$translation) =
11591:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11592:             unless ($outcome eq 'ok') {
11593:                 $errors .= $outcome.' ';
11594:             }
11595:         }
11596:     }
11597:     if ($errors) {
11598:         $errors =~ s/\s$//;
11599:         return $errors;
11600:     } else {
11601:         return 'ok';
11602:     }
11603: }
11604: 
11605: #------------------------------------------------------Get Marked as Read Only
11606: 
11607: sub get_marked_as_readonly {
11608:     my ($domain,$user,$what,$group) = @_;
11609:     my $current_permissions = &get_portfile_permissions($domain,$user);
11610:     my @readonly_files;
11611:     my $cmp1=$what;
11612:     if (ref($what)) { $cmp1=join('',@{$what}) };
11613:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11614:         if (defined($group)) {
11615:             if ($file_name !~ m-^\Q$group\E/-) {
11616:                 next;
11617:             }
11618:         }
11619:         if (ref($value) eq "ARRAY"){
11620:             foreach my $stored_what (@{$value}) {
11621:                 my $cmp2=$stored_what;
11622:                 if (ref($stored_what) eq 'ARRAY') {
11623:                     $cmp2=join('',@{$stored_what});
11624:                 }
11625:                 if ($cmp1 eq $cmp2) {
11626:                     push(@readonly_files, $file_name);
11627:                     last;
11628:                 } elsif (!defined($what)) {
11629:                     push(@readonly_files, $file_name);
11630:                     last;
11631:                 }
11632:             }
11633:         }
11634:     }
11635:     return @readonly_files;
11636: }
11637: #-----------------------------------------------------------Get Marked as Read Only Hash
11638: 
11639: sub get_marked_as_readonly_hash {
11640:     my ($current_permissions,$group,$what) = @_;
11641:     my %readonly_files;
11642:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11643:         if (defined($group)) {
11644:             if ($file_name !~ m-^\Q$group\E/-) {
11645:                 next;
11646:             }
11647:         }
11648:         if (ref($value) eq "ARRAY"){
11649:             foreach my $stored_what (@{$value}) {
11650:                 if (ref($stored_what) eq 'ARRAY') {
11651:                     foreach my $lock_descriptor(@{$stored_what}) {
11652:                         if ($lock_descriptor eq 'graded') {
11653:                             $readonly_files{$file_name} = 'graded';
11654:                         } elsif ($lock_descriptor eq 'handback') {
11655:                             $readonly_files{$file_name} = 'handback';
11656:                         } else {
11657:                             if (!exists($readonly_files{$file_name})) {
11658:                                 $readonly_files{$file_name} = 'locked';
11659:                             }
11660:                         }
11661:                     }
11662:                 } 
11663:             }
11664:         } 
11665:     }
11666:     return %readonly_files;
11667: }
11668: # ------------------------------------------------------------ Unmark as Read Only
11669: 
11670: sub unmark_as_readonly {
11671:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11672:     # for portfolio submissions, $what contains [$symb,$crsid] 
11673:     my ($domain,$user,$what,$file_name,$group) = @_;
11674:     $file_name = &declutter_portfile($file_name);
11675:     my $symb_crs = $what;
11676:     if (ref($what)) { $symb_crs=join('',@$what); }
11677:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11678:     my ($tmp)=keys(%current_permissions);
11679:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11680:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11681:     foreach my $file (@readonly_files) {
11682: 	my $clean_file = &declutter_portfile($file);
11683: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11684: 	my $current_locks = $current_permissions{$file};
11685:         my @new_locks;
11686:         my @del_keys;
11687:         if (ref($current_locks) eq "ARRAY"){
11688:             foreach my $locker (@{$current_locks}) {
11689:                 my $compare=$locker;
11690:                 if (ref($locker) eq 'ARRAY') {
11691:                     $compare=join('',@{$locker});
11692:                     if ($compare ne $symb_crs) {
11693:                         push(@new_locks, $locker);
11694:                     }
11695:                 }
11696:             }
11697:             if (scalar(@new_locks) > 0) {
11698:                 $current_permissions{$file} = \@new_locks;
11699:             } else {
11700:                 push(@del_keys, $file);
11701:                 &del('file_permissions',\@del_keys, $domain, $user);
11702:                 delete($current_permissions{$file});
11703:             }
11704:         }
11705:     }
11706:     &put('file_permissions',\%current_permissions,$domain,$user);
11707:     return;
11708: }
11709: 
11710: # ------------------------------------------------------------ Directory lister
11711: 
11712: sub dirlist {
11713:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11714:     $uri=~s/^\///;
11715:     $uri=~s/\/$//;
11716:     my ($udom, $uname);
11717:     if ($getuserdir) {
11718:         $udom = $userdomain;
11719:         $uname = $username;
11720:     } else {
11721:         (undef,$udom,$uname)=split(/\//,$uri);
11722:         if(defined($userdomain)) {
11723:             $udom = $userdomain;
11724:         }
11725:         if(defined($username)) {
11726:             $uname = $username;
11727:         }
11728:     }
11729:     my ($dirRoot,$listing,@listing_results);
11730: 
11731:     $dirRoot = $perlvar{'lonDocRoot'};
11732:     if (defined($getpropath)) {
11733:         $dirRoot = &propath($udom,$uname);
11734:         $dirRoot =~ s/\/$//;
11735:     } elsif (defined($getuserdir)) {
11736:         my $subdir=$uname.'__';
11737:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11738:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11739:                    ."/$udom/$subdir/$uname";
11740:     } elsif (defined($alternateRoot)) {
11741:         $dirRoot = $alternateRoot;
11742:     }
11743: 
11744:     if($udom) {
11745:         if($uname) {
11746:             my $uhome = &homeserver($uname,$udom);
11747:             if ($uhome eq 'no_host') {
11748:                 return ([],'no_host');
11749:             }
11750:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11751:                               .$getuserdir.':'.&escape($dirRoot)
11752:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11753:             if ($listing eq 'unknown_cmd') {
11754:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11755:             } else {
11756:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11757:             }
11758:             if ($listing eq 'unknown_cmd') {
11759:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11760:                 @listing_results = split(/:/,$listing);
11761:             } else {
11762:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11763:             }
11764:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11765:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11766:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11767:                 return ([],$listing);
11768:             } else {
11769:                 return (\@listing_results);
11770:             }
11771:         } elsif(!$alternateRoot) {
11772:             my (%allusers,%listerror);
11773: 	    my %servers = &get_servers($udom,'library');
11774:  	    foreach my $tryserver (keys(%servers)) {
11775:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11776:                                   &escape($udom),$tryserver);
11777:                 if ($listing eq 'unknown_cmd') {
11778: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11779: 				      $udom, $tryserver);
11780:                 } else {
11781:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11782:                 }
11783: 		if ($listing eq 'unknown_cmd') {
11784: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11785: 				      $udom, $tryserver);
11786: 		    @listing_results = split(/:/,$listing);
11787: 		} else {
11788: 		    @listing_results =
11789: 			map { &unescape($_); } split(/:/,$listing);
11790: 		}
11791:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11792:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11793:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11794:                     $listerror{$tryserver} = $listing;
11795:                 } else {
11796: 		    foreach my $line (@listing_results) {
11797: 			my ($entry) = split(/&/,$line,2);
11798: 			$allusers{$entry} = 1;
11799: 		    }
11800: 		}
11801:             }
11802:             my @alluserslist=();
11803:             foreach my $user (sort(keys(%allusers))) {
11804:                 push(@alluserslist,$user.'&user');
11805:             }
11806: 
11807:             if (!%listerror) {
11808:                 # no errors
11809:                 return (\@alluserslist);
11810:             } elsif (scalar(keys(%servers)) == 1) {
11811:                 # one library server, one error 
11812:                 my ($key) = keys(%listerror);
11813:                 return (\@alluserslist, $listerror{$key});
11814:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11815:                 # con_lost indicates that we might miss data from at least one
11816:                 # library server
11817:                 return (\@alluserslist, 'con_lost');
11818:             } else {
11819:                 # multiple library servers and no con_lost -> data should be
11820:                 # complete. 
11821:                 return (\@alluserslist);
11822:             }
11823: 
11824:         } else {
11825:             return ([],'missing username');
11826:         }
11827:     } elsif(!defined($getpropath)) {
11828:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11829:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11830:         return (\@all_domains);
11831:     } else {
11832:         return ([],'missing domain');
11833:     }
11834: }
11835: 
11836: # --------------------------------------------- GetFileTimestamp
11837: # This function utilizes dirlist and returns the date stamp for
11838: # when it was last modified.  It will also return an error of -1
11839: # if an error occurs
11840: 
11841: sub GetFileTimestamp {
11842:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11843:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11844:     $studentName   = &LONCAPA::clean_username($studentName);
11845:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11846:                                     undef,$getuserdir);
11847:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11848:         return -1;
11849:     }
11850:     if (ref($fileref) eq 'ARRAY') {
11851:         my @stats = split('&',$fileref->[0]);
11852:         # @stats contains first the filename, then the stat output
11853:         return $stats[10]; # so this is 10 instead of 9.
11854:     } else {
11855:         return -1;
11856:     }
11857: }
11858: 
11859: sub stat_file {
11860:     my ($uri) = @_;
11861:     $uri = &clutter_with_no_wrapper($uri);
11862: 
11863:     my ($udom,$uname,$file);
11864:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11865: 	($udom,$uname,$file) =
11866: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11867: 	$file = 'userfiles/'.$file;
11868:     }
11869:     if ($uri =~ m-^/res/-) {
11870: 	($udom,$uname) = 
11871: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11872: 	$file = $uri;
11873:     }
11874: 
11875:     if (!$udom || !$uname || !$file) {
11876: 	# unable to handle the uri
11877: 	return ();
11878:     }
11879:     my $getpropath;
11880:     if ($file =~ /^userfiles\//) {
11881:         $getpropath = 1;
11882:     }
11883:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11884:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11885:         return ();
11886:     } else {
11887:         if (ref($listref) eq 'ARRAY') {
11888:             my @stats = split('&',$listref->[0]);
11889: 	    shift(@stats); #filename is first
11890: 	    return @stats;
11891:         }
11892:     }
11893:     return ();
11894: }
11895: 
11896: # --------------------------------------------------------- recursedirs
11897: # Recursive function to traverse either a specific user's Authoring Space
11898: # or corresponding Published Resource Space, and populate the hash ref:
11899: # $dirhashref with URLs of all directories, and if $filehashref hash
11900: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11901: # or .rights files in resource space, and .meta, .save, .log, and .bak
11902: # files in Authoring Space.
11903: #
11904: # Inputs:
11905: #
11906: # $is_home - true if current server is home server for user's space
11907: # $context - either: priv, or res respectively for Authoring or Resource Space.
11908: # $docroot - Document root (i.e., /home/httpd/html
11909: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11910: # $relpath - Current path (relative to top level).
11911: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11912: # $filehashref - reference to hash to populate with URLs of files (Optional)
11913: #
11914: # Returns: nothing
11915: #
11916: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11917: #
11918: # Currently used by interface/londocs.pm to create linked select boxes for
11919: # directory and filename to import a Course "Author" resource into a course, and
11920: # also to create linked select boxes for Authoring Space and Directory to choose
11921: # save location for creation of a new "standard" problem from the Course Editor.
11922: #
11923: 
11924: sub recursedirs {
11925:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11926:     return unless (ref($dirhashref) eq 'HASH');
11927:     my $currpath = $docroot.$toppath;
11928:     if ($relpath) {
11929:         $currpath .= "/$relpath";
11930:     }
11931:     my $savefile;
11932:     if (ref($filehashref)) {
11933:         $savefile = 1;
11934:     }
11935:     if ($is_home) {
11936:         if (opendir(my $dirh,$currpath)) {
11937:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11938:                 next if ($item eq '');
11939:                 if (-d "$currpath/$item") {
11940:                     my $newpath;
11941:                     if ($relpath) {
11942:                         $newpath = "$relpath/$item";
11943:                     } else {
11944:                         $newpath = $item;
11945:                     }
11946:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11947:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11948:                 } elsif ($savefile) {
11949:                     if ($context eq 'priv') {
11950:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11951:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11952:                         }
11953:                     } else {
11954:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11955:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11956:                         }
11957:                     }
11958:                 }
11959:             }
11960:             closedir($dirh);
11961:         }
11962:     } else {
11963:         my ($dirlistref,$listerror) =
11964:             &dirlist($toppath.$relpath);
11965:         my @dir_lines;
11966:         my $dirptr=16384;
11967:         if (ref($dirlistref) eq 'ARRAY') {
11968:             foreach my $dir_line (sort
11969:                               {
11970:                                   my ($afile)=split('&',$a,2);
11971:                                   my ($bfile)=split('&',$b,2);
11972:                                   return (lc($afile) cmp lc($bfile));
11973:                               } (@{$dirlistref})) {
11974:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11975:                     split(/\&/,$dir_line,16);
11976:                 $item =~ s/\s+$//;
11977:                 next if (($item =~ /^\.\.?$/) || ($obs));
11978:                 if ($dirptr&$testdir) {
11979:                     my $newpath;
11980:                     if ($relpath) {
11981:                         $newpath = "$relpath/$item";
11982:                     } else {
11983:                         $relpath = '/';
11984:                         $newpath = $item;
11985:                     }
11986:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11987:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11988:                 } elsif ($savefile) {
11989:                     if ($context eq 'priv') {
11990:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11991:                             $filehashref->{$relpath}{$item} = 1;
11992:                         }
11993:                     } else {
11994:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11995:                             $filehashref->{$relpath}{$item} = 1;
11996:                         }
11997:                     }
11998:                 }
11999:             }
12000:         }
12001:     }
12002:     return;
12003: }
12004: 
12005: # -------------------------------------------------------- Value of a Condition
12006: 
12007: # gets the value of a specific preevaluated condition
12008: #    stored in the string  $env{user.state.<cid>}
12009: # or looks up a condition reference in the bighash and if if hasn't
12010: # already been evaluated recurses into docondval to get the value of
12011: # the condition, then memoizing it to 
12012: #   $env{user.state.<cid>.<condition>}
12013: sub directcondval {
12014:     my $number=shift;
12015:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12016: 	&Apache::lonuserstate::evalstate();
12017:     }
12018:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12019: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12020:     } elsif ($number =~ /^_/) {
12021: 	my $sub_condition;
12022: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12023: 		&GDBM_READER(),0640)) {
12024: 	    $sub_condition=$bighash{'conditions'.$number};
12025: 	    untie(%bighash);
12026: 	}
12027: 	my $value = &docondval($sub_condition);
12028: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12029: 	return $value;
12030:     }
12031:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12032:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12033:     } else {
12034:        return 2;
12035:     }
12036: }
12037: 
12038: # get the collection of conditions for this resource
12039: sub condval {
12040:     my $condidx=shift;
12041:     my $allpathcond='';
12042:     foreach my $cond (split(/\|/,$condidx)) {
12043: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12044: 	    $allpathcond.=
12045: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12046: 	}
12047:     }
12048:     $allpathcond=~s/\|$//;
12049:     return &docondval($allpathcond);
12050: }
12051: 
12052: #evaluates an expression of conditions
12053: sub docondval {
12054:     my ($allpathcond) = @_;
12055:     my $result=0;
12056:     if ($env{'request.course.id'}
12057: 	&& defined($allpathcond)) {
12058: 	my $operand='|';
12059: 	my @stack;
12060: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12061: 	    if ($chunk eq '(') {
12062: 		push @stack,($operand,$result);
12063: 	    } elsif ($chunk eq ')') {
12064: 		my $before=pop @stack;
12065: 		if (pop @stack eq '&') {
12066: 		    $result=$result>$before?$before:$result;
12067: 		} else {
12068: 		    $result=$result>$before?$result:$before;
12069: 		}
12070: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12071: 		$operand=$chunk;
12072: 	    } else {
12073: 		my $new=directcondval($chunk);
12074: 		if ($operand eq '&') {
12075: 		    $result=$result>$new?$new:$result;
12076: 		} else {
12077: 		    $result=$result>$new?$result:$new;
12078: 		}
12079: 	    }
12080: 	}
12081:     }
12082:     return $result;
12083: }
12084: 
12085: # ---------------------------------------------------- Devalidate courseresdata
12086: 
12087: sub devalidatecourseresdata {
12088:     my ($coursenum,$coursedomain)=@_;
12089:     my $hashid=$coursenum.':'.$coursedomain;
12090:     &devalidate_cache_new('courseres',$hashid);
12091: }
12092: 
12093: 
12094: # --------------------------------------------------- Course Resourcedata Query
12095: #
12096: #  Parameters:
12097: #      $coursenum    - Number of the course.
12098: #      $coursedomain - Domain at which the course was created.
12099: #  Returns:
12100: #     A hash of the course parameters along (I think) with timestamps
12101: #     and version info.
12102: 
12103: sub get_courseresdata {
12104:     my ($coursenum,$coursedomain)=@_;
12105:     my $coursehom=&homeserver($coursenum,$coursedomain);
12106:     my $hashid=$coursenum.':'.$coursedomain;
12107:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12108:     my %dumpreply;
12109:     unless (defined($cached)) {
12110: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12111: 	$result=\%dumpreply;
12112: 	my ($tmp) = keys(%dumpreply);
12113: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12114: 	    &do_cache_new('courseres',$hashid,$result,600);
12115: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12116: 	    return $tmp;
12117: 	} elsif ($tmp =~ /^(error)/) {
12118: 	    $result=undef;
12119: 	    &do_cache_new('courseres',$hashid,$result,600);
12120: 	}
12121:     }
12122:     return $result;
12123: }
12124: 
12125: sub devalidateuserresdata {
12126:     my ($uname,$udom)=@_;
12127:     my $hashid="$udom:$uname";
12128:     &devalidate_cache_new('userres',$hashid);
12129: }
12130: 
12131: sub get_userresdata {
12132:     my ($uname,$udom)=@_;
12133:     #most student don\'t have any data set, check if there is some data
12134:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12135: 
12136:     my $hashid="$udom:$uname";
12137:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12138:     if (!defined($cached)) {
12139: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12140: 	$result=\%resourcedata;
12141: 	&do_cache_new('userres',$hashid,$result,600);
12142:     }
12143:     my ($tmp)=keys(%$result);
12144:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12145: 	return $result;
12146:     }
12147:     #error 2 occurs when the .db doesn't exist
12148:     if ($tmp!~/error: 2 /) {
12149:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12150: 	    &logthis("<font color=\"blue\">WARNING:".
12151: 		     " Trying to get resource data for ".
12152: 		     $uname." at ".$udom.": ".
12153: 		     $tmp."</font>");
12154:         }
12155:     } elsif ($tmp=~/error: 2 /) {
12156: 	#&EXT_cache_set($udom,$uname);
12157: 	&do_cache_new('userres',$hashid,undef,600);
12158: 	undef($tmp); # not really an error so don't send it back
12159:     }
12160:     return $tmp;
12161: }
12162: #----------------------------------------------- resdata - return resource data
12163: #  Purpose:
12164: #    Return resource data for either users or for a course.
12165: #  Parameters:
12166: #     $name      - Course/user name.
12167: #     $domain    - Name of the domain the user/course is registered on.
12168: #     $type      - Type of thing $name is (must be 'course' or 'user')
12169: #     $mapp      - decluttered URL of enclosing map  
12170: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12171: #     $recurseup - Ref to array of map URLs, starting with map containing
12172: #                  $mapp up through hierarchy of nested maps to top level map.  
12173: #     $courseid  - CourseID (first part of param identifier).
12174: #     $modifier  - Middle part of param identifier.
12175: #     $what      - Last part of param identifier.
12176: #     @which     - Array of names of resources desired.
12177: #  Returns:
12178: #     The value of the first reasource in @which that is found in the
12179: #     resource hash.
12180: #  Exceptional Conditions:
12181: #     If the $type passed in is not valid (not the string 'course' or 
12182: #     'user', an undefined  reference is returned.
12183: #     If none of the resources are found, an undef is returned
12184: sub resdata {
12185:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12186:         $modifier,$what,@which)=@_;
12187:     my $result;
12188:     if ($type eq 'course') {
12189: 	$result=&get_courseresdata($name,$domain);
12190:     } elsif ($type eq 'user') {
12191: 	$result=&get_userresdata($name,$domain);
12192:     }
12193:     if (!ref($result)) { return $result; }    
12194:     foreach my $item (@which) {
12195:         if ($item->[1] eq 'course') {
12196:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12197:                 unless ($$recursed) {
12198:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12199:                     $$recursed = 1;
12200:                 }
12201:                 foreach my $item (@${recurseup}) {
12202:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12203:                     last if (defined($result->{$norecursechk}));
12204:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12205:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12206:                 }
12207:             }
12208:         }
12209:         if (defined($result->{$item->[0]})) {
12210: 	    return [$result->{$item->[0]},$item->[1]];
12211: 	}
12212:     }
12213:     return undef;
12214: }
12215: 
12216: sub get_domain_lti {
12217:     my ($cdom,$context) = @_;
12218:     my ($name,%lti);
12219:     if ($context eq 'consumer') {
12220:         $name = 'ltitools';
12221:     } elsif ($context eq 'provider') {
12222:         $name = 'lti';
12223:     } else {
12224:         return %lti;
12225:     }
12226:     my ($result,$cached)=&is_cached_new($name,$cdom);
12227:     if (defined($cached)) {
12228:         if (ref($result) eq 'HASH') {
12229:             %lti = %{$result};
12230:         }
12231:     } else {
12232:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12233:         if (ref($domconfig{$name}) eq 'HASH') {
12234:             %lti = %{$domconfig{$name}};
12235:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12236:             if (ref($encdomconfig{$name}) eq 'HASH') {
12237:                 foreach my $id (keys(%lti)) {
12238:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12239:                         foreach my $item ('key','secret') {
12240:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12241:                         }
12242:                     }
12243:                 }
12244:             }
12245:         }
12246:         my $cachetime = 24*60*60;
12247:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12248:     }
12249:     return %lti;
12250: }
12251: 
12252: sub get_course_lti {
12253:     my ($cnum,$cdom) = @_;
12254:     my $hashid=$cdom.'_'.$cnum;
12255:     my %courselti;
12256:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
12257:     if (defined($cached)) {
12258:         if (ref($result) eq 'HASH') {
12259:             %courselti = %{$result};
12260:         }
12261:     } else {
12262:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12263:         my $cachetime = 24*60*60;
12264:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12265:     }
12266:     return %courselti;
12267: }
12268: 
12269: sub get_numsuppfiles {
12270:     my ($cnum,$cdom,$ignorecache)=@_;
12271:     my $hashid=$cnum.':'.$cdom;
12272:     my ($suppcount,$cached);
12273:     unless ($ignorecache) {
12274:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12275:     }
12276:     unless (defined($cached)) {
12277:         my $chome=&homeserver($cnum,$cdom);
12278:         unless ($chome eq 'no_host') {
12279:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12280:             my $suppmap = 'supplemental.sequence';
12281:             ($suppcount,$supptools,$errors) =
12282:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12283:                                                          $supptools,$errors);
12284:         }
12285:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12286:     }
12287:     return $suppcount;
12288: }
12289: 
12290: #
12291: # EXT resource caching routines
12292: #
12293: 
12294: {
12295: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12296: #
12297: # The course for which we cache
12298: my $cachedmapkey='';
12299: # The cached recursive maps for this course
12300: my %cachedmaps=();
12301: # When this was last done
12302: my $cachedmaptime='';
12303: 
12304: sub clear_EXT_cache_status {
12305:     &delenv('cache.EXT.');
12306: }
12307: 
12308: sub EXT_cache_status {
12309:     my ($target_domain,$target_user) = @_;
12310:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12311:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12312:         # We know already the user has no data
12313:         return 1;
12314:     } else {
12315:         return 0;
12316:     }
12317: }
12318: 
12319: sub EXT_cache_set {
12320:     my ($target_domain,$target_user) = @_;
12321:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12322:     #&appenv({$cachename => time});
12323: }
12324: 
12325: # --------------------------------------------------------- Value of a Variable
12326: sub EXT {
12327: 
12328:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12329:     unless ($varname) { return ''; }
12330:     #get real user name/domain, courseid and symb
12331:     my $courseid;
12332:     my $publicuser;
12333:     if ($symbparm) {
12334: 	$symbparm=&get_symb_from_alias($symbparm);
12335:     }
12336:     if (!($uname && $udom)) {
12337:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12338:       if (!$symbparm) {	$symbparm=$cursymb; }
12339:     } else {
12340: 	$courseid=$env{'request.course.id'};
12341:     }
12342:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12343:     my $rest;
12344:     if (defined($therest[0])) {
12345:        $rest=join('.',@therest);
12346:     } else {
12347:        $rest='';
12348:     }
12349: 
12350:     my $qualifierrest=$qualifier;
12351:     if ($rest) { $qualifierrest.='.'.$rest; }
12352:     my $spacequalifierrest=$space;
12353:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12354:     if ($realm eq 'user') {
12355: # --------------------------------------------------------------- user.resource
12356: 	if ($space eq 'resource') {
12357: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12358: 		  || defined($Apache::lonhomework::parsing_a_task))
12359: 		 &&
12360: 		 ($symbparm eq &symbread()) ) {
12361: 		# if we are in the middle of processing the resource the
12362: 		# get the value we are planning on committing
12363:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12364:                     return $Apache::lonhomework::results{$qualifierrest};
12365:                 } else {
12366:                     return $Apache::lonhomework::history{$qualifierrest};
12367:                 }
12368: 	    } else {
12369: 		my %restored;
12370: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12371: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12372: 		} else {
12373: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12374: 		}
12375: 		return $restored{$qualifierrest};
12376: 	    }
12377: # ----------------------------------------------------------------- user.access
12378:         } elsif ($space eq 'access') {
12379: 	    # FIXME - not supporting calls for a specific user
12380:             return &allowed($qualifier,$rest);
12381: # ------------------------------------------ user.preferences, user.environment
12382:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12383: 	    if (($uname eq $env{'user.name'}) &&
12384: 		($udom eq $env{'user.domain'})) {
12385: 		return $env{join('.',('environment',$qualifierrest))};
12386: 	    } else {
12387: 		my %returnhash;
12388: 		if (!$publicuser) {
12389: 		    %returnhash=&userenvironment($udom,$uname,
12390: 						 $qualifierrest);
12391: 		}
12392: 		return $returnhash{$qualifierrest};
12393: 	    }
12394: # ----------------------------------------------------------------- user.course
12395:         } elsif ($space eq 'course') {
12396: 	    # FIXME - not supporting calls for a specific user
12397:             return $env{join('.',('request.course',$qualifier))};
12398: # ------------------------------------------------------------------- user.role
12399:         } elsif ($space eq 'role') {
12400: 	    # FIXME - not supporting calls for a specific user
12401:             my ($role,$where)=split(/\./,$env{'request.role'});
12402:             if ($qualifier eq 'value') {
12403: 		return $role;
12404:             } elsif ($qualifier eq 'extent') {
12405:                 return $where;
12406:             }
12407: # ----------------------------------------------------------------- user.domain
12408:         } elsif ($space eq 'domain') {
12409:             return $udom;
12410: # ------------------------------------------------------------------- user.name
12411:         } elsif ($space eq 'name') {
12412:             return $uname;
12413: # ---------------------------------------------------- Any other user namespace
12414:         } else {
12415: 	    my %reply;
12416: 	    if (!$publicuser) {
12417: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12418: 	    }
12419: 	    return $reply{$qualifierrest};
12420:         }
12421:     } elsif ($realm eq 'query') {
12422: # ---------------------------------------------- pull stuff out of query string
12423:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12424: 						[$spacequalifierrest]);
12425: 	return $env{'form.'.$spacequalifierrest}; 
12426:    } elsif ($realm eq 'request') {
12427: # ------------------------------------------------------------- request.browser
12428:         if ($space eq 'browser') {
12429:             return $env{'browser.'.$qualifier};
12430: # ------------------------------------------------------------ request.filename
12431:         } else {
12432:             return $env{'request.'.$spacequalifierrest};
12433:         }
12434:     } elsif ($realm eq 'course') {
12435: # ---------------------------------------------------------- course.description
12436:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12437:     } elsif ($realm eq 'resource') {
12438: 
12439: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12440: 	    if (!$symbparm) { $symbparm=&symbread(); }
12441: 	}
12442: 
12443:         if ($qualifier eq '') {
12444: 	    if ($space eq 'title') {
12445: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12446: 	        return &gettitle($symbparm);
12447: 	    }
12448: 	
12449: 	    if ($space eq 'map') {
12450: 	        my ($map) = &decode_symb($symbparm);
12451: 	        return &symbread($map);
12452: 	    }
12453:             if ($space eq 'maptitle') {
12454:                 my ($map) = &decode_symb($symbparm);
12455:                 return &gettitle($map);
12456:             }
12457: 	    if ($space eq 'filename') {
12458: 	        if ($symbparm) {
12459: 		    return &clutter((&decode_symb($symbparm))[2]);
12460: 	        }
12461: 	        return &hreflocation('',$env{'request.filename'});
12462: 	    }
12463: 
12464:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12465:                 if ($space eq 'visibleparts') {
12466:                     my $navmap = Apache::lonnavmaps::navmap->new();
12467:                     my $item;
12468:                     if (ref($navmap)) {
12469:                         my $res = $navmap->getBySymb($symbparm);
12470:                         my $parts = $res->parts();
12471:                         if (ref($parts) eq 'ARRAY') {
12472:                             $item = join(',',@{$parts});
12473:                         }
12474:                         undef($navmap);
12475:                     }
12476:                     return $item;
12477:                 }
12478:             }
12479:         }
12480: 
12481: 	my ($section, $group, @groups, @recurseup, $recursed);
12482:         if (ref($recurseupref) eq 'ARRAY') {
12483:             @recurseup = @{$recurseupref};
12484:             $recursed = 1;
12485:         }
12486: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12487:         if (($courseid eq '') && ($cid)) {
12488:             $courseid = $cid;
12489:         }
12490: 	if (($symbparm && $courseid) && 
12491: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12492: 
12493: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12494: 
12495: # ----------------------------------------------------- Cascading lookup scheme
12496: 	    my $symbp=$symbparm;
12497: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12498: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12499:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12500: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12501: 	    if (($env{'user.name'} eq $uname) &&
12502: 		($env{'user.domain'} eq $udom)) {
12503: 		$section=$env{'request.course.sec'};
12504:                 @groups = split(/:/,$env{'request.course.groups'});  
12505:                 @groups=&sort_course_groups($courseid,@groups); 
12506: 	    } else {
12507: 		if (! defined($usection)) {
12508: 		    $section=&getsection($udom,$uname,$courseid);
12509: 		} else {
12510: 		    $section = $usection;
12511: 		}
12512:                 @groups = &get_users_groups($udom,$uname,$courseid);
12513: 	    }
12514: 
12515: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12516: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12517:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12518: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12519: 
12520: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12521: 	    my $courselevelr=$courseid.'.'.$symbparm;
12522:             $courseleveli=$courseid.'.'.$recurseparm;
12523: 	    $courselevelm=$courseid.'.'.$mapparm;
12524: 
12525: # ----------------------------------------------------------- first, check user
12526: 
12527: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12528:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12529: 				       ([$courselevelr,'resource'],
12530: 					[$courselevelm,'map'     ],
12531:                                         [$courseleveli,'map'     ],
12532: 					[$courselevel, 'course'  ]));
12533: 	    if (defined($userreply)) { return &get_reply($userreply); }
12534: 
12535: # ------------------------------------------------ second, check some of course
12536:             my $coursereply;
12537:             if (@groups > 0) {
12538:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12539:                                        $recurseparm,$mapparm,$spacequalifierrest,
12540:                                        $mapp,\$recursed,\@recurseup);
12541:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12542:             }
12543: 
12544: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12545: 				  $env{'course.'.$courseid.'.domain'},
12546: 				  'course',$mapp,\$recursed,\@recurseup,
12547:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12548: 				  ([$seclevelr,   'resource'],
12549: 				   [$seclevelm,   'map'     ],
12550:                                    [$secleveli,   'map'     ],
12551: 				   [$seclevel,    'course'  ],
12552: 				   [$courselevelr,'resource']));
12553: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12554: 
12555: # ------------------------------------------------------ third, check map parms
12556: 	    my %parmhash=();
12557: 	    my $thisparm='';
12558: 	    if (tie(%parmhash,'GDBM_File',
12559: 		    $env{'request.course.fn'}.'_parms.db',
12560: 		    &GDBM_READER(),0640)) {
12561: 		$thisparm=$parmhash{$symbparm};
12562: 		untie(%parmhash);
12563: 	    }
12564: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12565: 	}
12566: # ------------------------------------------ fourth, look in resource metadata
12567:  
12568:         my $what = $spacequalifierrest;
12569: 	$what=~s/\./\_/;
12570: 	my $filename;
12571: 	if (!$symbparm) { $symbparm=&symbread(); }
12572: 	if ($symbparm) {
12573: 	    $filename=(&decode_symb($symbparm))[2];
12574: 	} else {
12575: 	    $filename=$env{'request.filename'};
12576: 	}
12577:         my $toolsymb;
12578:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12579:             $toolsymb = $symbparm;
12580:         }
12581: 	my $metadata=&metadata($filename,$what,$toolsymb);
12582: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12583: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12584: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12585: 
12586: # ----------------------------------------------- fifth, look in rest of course
12587: 	if ($symbparm && defined($courseid) && 
12588: 	    $courseid eq $env{'request.course.id'}) {
12589: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12590: 				     $env{'course.'.$courseid.'.domain'},
12591: 				     'course',$mapp,\$recursed,\@recurseup,
12592:                                      $courseid,'.',$spacequalifierrest,
12593: 				     ([$courselevelm,'map'   ],
12594:                                       [$courseleveli,'map'   ],
12595: 				      [$courselevel, 'course']));
12596: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12597: 	}
12598: # ------------------------------------------------------------------ Cascade up
12599: 	unless ($space eq '0') {
12600: 	    my @parts=split(/_/,$space);
12601: 	    my $id=pop(@parts);
12602: 	    my $part=join('_',@parts);
12603: 	    if ($part eq '') { $part='0'; }
12604: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12605: 				 $symbparm,$udom,$uname,$section,1);
12606: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12607: 	}
12608: 	if ($recurse) { return undef; }
12609: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12610: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12611: # ---------------------------------------------------- Any other user namespace
12612:     } elsif ($realm eq 'environment') {
12613: # ----------------------------------------------------------------- environment
12614: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12615: 	    return $env{'environment.'.$spacequalifierrest};
12616: 	} else {
12617: 	    if ($uname eq 'anonymous' && $udom eq '') {
12618: 		return '';
12619: 	    }
12620: 	    my %returnhash=&userenvironment($udom,$uname,
12621: 					    $spacequalifierrest);
12622: 	    return $returnhash{$spacequalifierrest};
12623: 	}
12624:     } elsif ($realm eq 'system') {
12625: # ----------------------------------------------------------------- system.time
12626: 	if ($space eq 'time') {
12627: 	    return time;
12628:         }
12629:     } elsif ($realm eq 'server') {
12630: # ----------------------------------------------------------------- system.time
12631: 	if ($space eq 'name') {
12632: 	    return $ENV{'SERVER_NAME'};
12633:         }
12634:     } elsif ($realm eq 'client') {
12635:         if ($space eq 'remote_addr') {
12636:             return &get_requestor_ip();
12637:         }
12638:     }
12639:     return '';
12640: }
12641: 
12642: sub get_reply {
12643:     my ($reply_value) = @_;
12644:     if (ref($reply_value) eq 'ARRAY') {
12645:         if (wantarray) {
12646: 	    return @$reply_value;
12647:         }
12648:         return $reply_value->[0];
12649:     } else {
12650:         return $reply_value;
12651:     }
12652: }
12653: 
12654: sub check_group_parms {
12655:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12656:         $recursed,$recurseupref) = @_;
12657:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12658:                   [$what,'course']);
12659:     my $coursereply;
12660:     foreach my $group (@{$groups}) {
12661:         my @groupitems = ();
12662:         foreach my $level (@levels) {
12663:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12664:              push(@groupitems,[$item,$level->[1]]);
12665:         }
12666:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12667:                                    $env{'course.'.$courseid.'.domain'},
12668:                                    'course',$mapp,$recursed,$recurseupref,
12669:                                    $courseid,'.['.$group.'].',$what,
12670:                                    @groupitems);
12671:         last if (defined($coursereply));
12672:     }
12673:     return $coursereply;
12674: }
12675: 
12676: sub get_map_hierarchy {
12677:     my ($mapname,$courseid) = @_;
12678:     my @recurseup = ();
12679:     if ($mapname) {
12680:         if (($cachedmapkey eq $courseid) &&
12681:             (abs($cachedmaptime-time)<5)) {
12682:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12683:                 return @{$cachedmaps{$mapname}};
12684:             }
12685:         }
12686:         my $navmap = Apache::lonnavmaps::navmap->new();
12687:         if (ref($navmap)) {
12688:             @recurseup = $navmap->recurseup_maps($mapname);
12689:             undef($navmap);
12690:             $cachedmaps{$mapname} = \@recurseup;
12691:             $cachedmaptime=time;
12692:             $cachedmapkey=$courseid;
12693:         }
12694:     }
12695:     return @recurseup;
12696: }
12697: 
12698: }
12699: 
12700: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12701:     my ($courseid,@groups) = @_;
12702:     @groups = sort(@groups);
12703:     return @groups;
12704: }
12705: 
12706: sub packages_tab_default {
12707:     my ($uri,$varname,$toolsymb)=@_;
12708:     my (undef,$part,$name)=split(/\./,$varname);
12709: 
12710:     my (@extension,@specifics,$do_default);
12711:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12712: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12713: 	if ($pack_type eq 'default') {
12714: 	    $do_default=1;
12715: 	} elsif ($pack_type eq 'extension') {
12716: 	    push(@extension,[$package,$pack_type,$pack_part]);
12717: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12718: 	    # only look at packages defaults for packages that this id is
12719: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12720: 	}
12721:     }
12722:     # first look for a package that matches the requested part id
12723:     foreach my $package (@specifics) {
12724: 	my (undef,$pack_type,$pack_part)=@{$package};
12725: 	next if ($pack_part ne $part);
12726: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12727: 	    return $packagetab{"$pack_type&$name&default"};
12728: 	}
12729:     }
12730:     # look for any possible matching non extension_ package
12731:     foreach my $package (@specifics) {
12732: 	my (undef,$pack_type,$pack_part)=@{$package};
12733: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12734: 	    return $packagetab{"$pack_type&$name&default"};
12735: 	}
12736: 	if ($pack_type eq 'part') { $pack_part='0'; }
12737: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12738: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12739: 	}
12740:     }
12741:     # look for any posible extension_ match
12742:     foreach my $package (@extension) {
12743: 	my ($package,$pack_type)=@{$package};
12744: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12745: 	    return $packagetab{"$pack_type&$name&default"};
12746: 	}
12747: 	if (defined($packagetab{$package."&$name&default"})) {
12748: 	    return $packagetab{$package."&$name&default"};
12749: 	}
12750:     }
12751:     # look for a global default setting
12752:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12753: 	return $packagetab{"default&$name&default"};
12754:     }
12755:     return undef;
12756: }
12757: 
12758: sub add_prefix_and_part {
12759:     my ($prefix,$part)=@_;
12760:     my $keyroot;
12761:     if (defined($prefix) && $prefix !~ /^__/) {
12762: 	# prefix that has a part already
12763: 	$keyroot=$prefix;
12764:     } elsif (defined($prefix)) {
12765: 	# prefix that is missing a part
12766: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12767:     } else {
12768: 	# no prefix at all
12769: 	if (defined($part)) { $keyroot='_'.$part; }
12770:     }
12771:     return $keyroot;
12772: }
12773: 
12774: # ---------------------------------------------------------------- Get metadata
12775: 
12776: my %metaentry;
12777: my %importedpartids;
12778: my %importedrespids;
12779: sub metadata {
12780:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12781:     $uri=&declutter($uri);
12782:     # if it is a non metadata possible uri return quickly
12783:     if (($uri eq '') || 
12784: 	(($uri =~ m|^/*adm/|) && 
12785: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12786:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12787: 	return undef;
12788:     }
12789:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12790: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12791: 	return undef;
12792:     }
12793:     my $filename=$uri;
12794:     $uri=~s/\.meta$//;
12795: #
12796: # Is the metadata already cached?
12797: # Look at timestamp of caching
12798: # Everything is cached by the main uri, libraries are never directly cached
12799: #
12800:     if (!defined($liburi)) {
12801: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12802: 	if (defined($cached)) { return $result->{':'.$what}; }
12803:     }
12804: 
12805: #
12806: # If the uri is for an external tool the file from
12807: # which metadata should be retrieved depends on whether
12808: # the tool had been configured to be gradable (set in the Course
12809: # Editor or Resource Editor).
12810: #
12811: # If a valid symb has been included as the third arg in the call
12812: # to &metadata() that can be used to retrieve the value of
12813: # parameter_0_gradable set for the resource, and included in the
12814: # uploaded map containing the tool. The value is retrieved via
12815: # &EXT(), if a valid symb is available.  Otherwise the value of
12816: # gradable in the exttool_$marker.db file for the tool instance
12817: # is retrieved via &get().
12818: #
12819: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12820: # hiddenresource and encrypturl (during course initialization)
12821: # the map-level parameter for resource.0.gradable included in the 
12822: # uploaded map containing the tool will not yet have been stored
12823: # in the user_course_parms.db file for the user's session, so in 
12824: # this case fall back to retrieving gradable status from the
12825: # exttool_$marker.db file.
12826: #
12827: # In order to avoid an infinite loop, &metadata() will return
12828: # before a call to &EXT(), if the uri is for an external tool
12829: # and the $what for which metadata is being requested is
12830: # parameter_0_gradable or 0_gradable.
12831: #
12832: 
12833:     if ($uri =~ /ext\.tool$/) {
12834:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12835:             return;
12836:         } else {
12837:             my ($checked,$use_passback);
12838:             if ($toolsymb ne '') {
12839:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12840:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12841:                     $checked = 1;
12842:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12843:                         $use_passback = 1;
12844:                     }
12845:                 }
12846:             }
12847:             unless ($checked) {
12848:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12849:                 $marker=~s/\D//g;
12850:                 if ($marker) {
12851:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12852:                     $use_passback = $toolsettings{'gradable'};
12853:                 }
12854:             }
12855:             if ($use_passback) {
12856:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12857:             } else {
12858:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12859:             }
12860:         }
12861:     }
12862: 
12863:     {
12864: # Imported parts would go here
12865:         my @origfiletagids=();
12866:         my $importedparts=0;
12867: 
12868: # Imported responseids would go here
12869:         my $importedresponses=0;
12870: #
12871: # Is this a recursive call for a library?
12872: #
12873: #	if (! exists($metacache{$uri})) {
12874: #	    $metacache{$uri}={};
12875: #	}
12876: 	my $cachetime = 60*60;
12877:         if ($liburi) {
12878: 	    $liburi=&declutter($liburi);
12879:             $filename=$liburi;
12880:         } else {
12881: 	    &devalidate_cache_new('meta',$uri);
12882: 	    undef(%metaentry);
12883: 	}
12884:         my %metathesekeys=();
12885:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12886: 	my $metastring;
12887: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12888: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12889: 	    $metastring = 
12890: 		&Apache::lonnet::ssi_body($which,
12891: 					  ('grade_target' => 'meta'));
12892: 	    $cachetime = 1; # only want this cached in the child not long term
12893: 	} elsif (($uri !~ m -^(editupload)/-) && 
12894:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12895: 	    my $file=&filelocation('',&clutter($filename));
12896: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12897: 	    $metastring=&getfile($file);
12898: 	}
12899:         my $parser=HTML::LCParser->new(\$metastring);
12900:         my $token;
12901:         undef %metathesekeys;
12902:         while ($token=$parser->get_token) {
12903: 	    if ($token->[0] eq 'S') {
12904: 		if (defined($token->[2]->{'package'})) {
12905: #
12906: # This is a package - get package info
12907: #
12908: 		    my $package=$token->[2]->{'package'};
12909: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12910: 		    if (defined($token->[2]->{'id'})) { 
12911: 			$keyroot.='_'.$token->[2]->{'id'}; 
12912: 		    }
12913: 		    if ($metaentry{':packages'}) {
12914: 			$metaentry{':packages'}.=','.$package.$keyroot;
12915: 		    } else {
12916: 			$metaentry{':packages'}=$package.$keyroot;
12917: 		    }
12918: 		    foreach my $pack_entry (keys(%packagetab)) {
12919: 			my $part=$keyroot;
12920: 			$part=~s/^\_//;
12921: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12922: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12923: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12924: 			    # ignore package.tab specified default values
12925:                             # here &package_tab_default() will fetch those
12926: 			    if ($subp eq 'default') { next; }
12927: 			    my $value=$packagetab{$pack_entry};
12928: 			    my $unikey;
12929: 			    if ($pack =~ /_0$/) {
12930: 				$unikey='parameter_0_'.$name;
12931: 				$part=0;
12932: 			    } else {
12933: 				$unikey='parameter'.$keyroot.'_'.$name;
12934: 			    }
12935: 			    if ($subp eq 'display') {
12936: 				$value.=' [Part: '.$part.']';
12937: 			    }
12938: 			    $metaentry{':'.$unikey.'.part'}=$part;
12939: 			    $metathesekeys{$unikey}=1;
12940: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12941: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12942: 			    }
12943: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12944: 				$metaentry{':'.$unikey}=
12945: 				    $metaentry{':'.$unikey.'.default'};
12946: 			    }
12947: 			}
12948: 		    }
12949: 		} else {
12950: #
12951: # This is not a package - some other kind of start tag
12952: #
12953: 		    my $entry=$token->[1];
12954: 		    my $unikey='';
12955: 
12956: 		    if ($entry eq 'import') {
12957: #
12958: # Importing a library here
12959: #
12960:                         my $location=$parser->get_text('/import');
12961:                         my $dir=$filename;
12962:                         $dir=~s|[^/]*$||;
12963:                         $location=&filelocation($dir,$location);
12964: 
12965:                         my $importid=$token->[2]->{'id'};
12966:                         my $importmode=$token->[2]->{'importmode'};
12967: #
12968: # Check metadata for imported file to
12969: # see if it contained response items
12970: #
12971:                         my ($origfile,@libfilekeys);
12972:                         my %currmetaentry = %metaentry;
12973:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12974:                                                            $depthcount+1));
12975:                         if (grep(/^responseorder$/,@libfilekeys)) {
12976:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12977:                                                              undef,$depthcount+1);
12978:                             if ($libresponseorder ne '') {
12979:                                 if ($#origfiletagids<0) {
12980:                                     undef(%importedrespids);
12981:                                     undef(%importedpartids);
12982:                                 }
12983:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12984:                                 if (@respids) {
12985:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12986:                                 }
12987:                                 if ($importedrespids{$importid} ne '') {
12988:                                     $importedresponses = 1;
12989: # We need to get the original file and the imported file to get the response order correct
12990: # Load and inspect original file
12991:                                     if ($#origfiletagids<0) {
12992:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12993:                                         $origfile=&getfile($origfilelocation);
12994:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12995:                                     }
12996:                                 }
12997:                             }
12998:                         }
12999: # Do not overwrite contents of %metaentry hash for resource itself with 
13000: # hash populated for imported library file
13001:                         %metaentry = %currmetaentry;
13002:                         undef(%currmetaentry);
13003:                         if ($importmode eq 'part') {
13004: # Import as part(s)
13005:                            $importedparts=1;
13006: # We need to get the original file and the imported file to get the part order correct
13007: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13008: # Load and inspect original file if we didn't do that already
13009:                            if ($#origfiletagids<0) {
13010:                                undef(%importedrespids);
13011:                                undef(%importedpartids);
13012:                                if ($origfile eq '') {
13013:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13014:                                    $origfile=&getfile($origfilelocation);
13015:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13016:                                }
13017:                            }
13018:                            my @impfilepartids;
13019: # If <partorder> tag is included in metadata for the imported file
13020: # get the parts in the imported file from that.
13021:                            if (grep(/^partorder$/,@libfilekeys)) {
13022:                                %currmetaentry = %metaentry;
13023:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13024:                                                             $depthcount+1);
13025:                                %metaentry = %currmetaentry;
13026:                                undef(%currmetaentry);
13027:                                if ($libpartorder ne '') {
13028:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13029:                                }
13030:                            } else {
13031: # If no <partorder> tag available, load and inspect imported file
13032:                                my $impfile=&getfile($location);
13033:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13034:                            }
13035:                            if ($#impfilepartids>=0) {
13036: # This problem had parts
13037:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13038:                            } else {
13039: # Importing by turning a single problem into a problem part
13040: # It gets the import-tags ID as part-ID
13041:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13042:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13043:                            }
13044:                         } else {
13045: # Import as problem or as normal import
13046:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13047:                             unless ($importmode eq 'problem') {
13048: # Normal import
13049:                                 if (defined($token->[2]->{'id'})) {
13050:                                     $unikey.='_'.$token->[2]->{'id'};
13051:                                 }
13052:                             }
13053: # Check metadata for imported file to
13054: # see if it contained parts
13055:                             if (grep(/^partorder$/,@libfilekeys)) {
13056:                                 %currmetaentry = %metaentry;
13057:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13058:                                                              $depthcount+1);
13059:                                 %metaentry = %currmetaentry;
13060:                                 undef(%currmetaentry);
13061:                                 if ($libpartorder ne '') {
13062:                                     $importedparts = 1;
13063:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13064:                                 }
13065:                             }
13066:                         }
13067: 			if ($depthcount<20) {
13068: 			    my $metadata = 
13069: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13070: 					  $depthcount+1);
13071: 			    foreach my $meta (split(',',$metadata)) {
13072: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13073: 				$metathesekeys{$meta}=1;
13074: 			    }
13075:                         }
13076: 		    } else {
13077: #
13078: # Not importing, some other kind of non-package, non-library start tag
13079: # 
13080:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13081:                         if (defined($token->[2]->{'id'})) {
13082:                             $unikey.='_'.$token->[2]->{'id'};
13083:                         }
13084: 			if (defined($token->[2]->{'name'})) { 
13085: 			    $unikey.='_'.$token->[2]->{'name'}; 
13086: 			}
13087: 			$metathesekeys{$unikey}=1;
13088: 			foreach my $param (@{$token->[3]}) {
13089: 			    $metaentry{':'.$unikey.'.'.$param} =
13090: 				$token->[2]->{$param};
13091: 			}
13092: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13093: 			my $default=$metaentry{':'.$unikey.'.default'};
13094: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13095: 		 # only ws inside the tag, and not in default, so use default
13096: 		 # as value
13097: 			    $metaentry{':'.$unikey}=$default;
13098: 			} elsif ( $internaltext =~ /\S/ ) {
13099: 		  # something interesting inside the tag
13100: 			    $metaentry{':'.$unikey}=$internaltext;
13101: 			} else {
13102: 		  # no interesting values, don't set a default
13103: 			}
13104: # end of not-a-package not-a-library import
13105: 		    }
13106: # end of not-a-package start tag
13107: 		}
13108: # the next is the end of "start tag"
13109: 	    }
13110: 	}
13111: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13112: 	$extension = lc($extension);
13113: 	if ($extension eq 'htm') { $extension='html'; }
13114: 
13115: 	foreach my $key (keys(%packagetab)) {
13116: 	    #no specific packages #how's our extension
13117: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13118: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13119: 					 \%metathesekeys);
13120: 	}
13121: 
13122: 	if (!exists($metaentry{':packages'})
13123: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13124: 	    foreach my $key (keys(%packagetab)) {
13125: 		#no specific packages well let's get default then
13126: 		if ($key!~/^default&/) { next; }
13127: 		&metadata_create_package_def($uri,$key,'default',
13128: 					     \%metathesekeys);
13129: 	    }
13130: 	}
13131: # are there custom rights to evaluate
13132: 	if ($metaentry{':copyright'} eq 'custom') {
13133: 
13134:     #
13135:     # Importing a rights file here
13136:     #
13137: 	    unless ($depthcount) {
13138: 		my $location=$metaentry{':customdistributionfile'};
13139: 		my $dir=$filename;
13140: 		$dir=~s|[^/]*$||;
13141: 		$location=&filelocation($dir,$location);
13142: 		my $rights_metadata =
13143: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13144: 			      $depthcount+1);
13145: 		foreach my $rights (split(',',$rights_metadata)) {
13146: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13147: 		    $metathesekeys{$rights}=1;
13148: 		}
13149: 	    }
13150: 	}
13151: 	# uniqifiy package listing
13152: 	my %seen;
13153: 	my @uniq_packages =
13154: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13155: 	$metaentry{':packages'} = join(',',@uniq_packages);
13156: 
13157:         if (($importedresponses) || ($importedparts)) {
13158:             if ($importedparts) {
13159: # We had imported parts and need to rebuild partorder
13160:                 $metaentry{':partorder'}='';
13161:                 $metathesekeys{'partorder'}=1;
13162:             }
13163:             if ($importedresponses) {
13164: # We had imported responses and need to rebuil responseorder
13165:                 $metaentry{':responseorder'}='';
13166:                 $metathesekeys{'responseorder'}=1;
13167:             }
13168:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13169:                 my $origid = $origfiletagids[$index+1];
13170:                 if ($origfiletagids[$index] eq 'part') {
13171: # Original part, part of the problem
13172:                     if ($importedparts) {
13173:                         $metaentry{':partorder'}.=','.$origid;
13174:                     }
13175:                 } elsif ($origfiletagids[$index] eq 'import') {
13176:                     if ($importedparts) {
13177: # We have imported parts at this position
13178:                         if ($importedpartids{$origid} ne '') {
13179:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13180:                         }
13181:                     }
13182:                     if ($importedresponses) {
13183: # We have imported responses at this position
13184:                         if ($importedrespids{$origid} ne '') {
13185:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13186:                         }
13187:                     }
13188:                 } else {
13189: # Original response item, part of the problem
13190:                     if ($importedresponses) {
13191:                         $metaentry{':responseorder'}.=','.$origid;
13192:                     }
13193:                 }
13194:             }
13195:             if ($importedparts) {
13196:                 $metaentry{':partorder'}=~s/^\,//;
13197:             }
13198:             if ($importedresponses) {
13199:                 $metaentry{':responseorder'}=~s/^\,//;
13200:             }
13201:         }
13202: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13203: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13204: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13205:         unless ($liburi) {
13206: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13207:         }
13208: # this is the end of "was not already recently cached
13209:     }
13210:     return $metaentry{':'.$what};
13211: }
13212: 
13213: sub metadata_create_package_def {
13214:     my ($uri,$key,$package,$metathesekeys)=@_;
13215:     my ($pack,$name,$subp)=split(/\&/,$key);
13216:     if ($subp eq 'default') { next; }
13217:     
13218:     if (defined($metaentry{':packages'})) {
13219: 	$metaentry{':packages'}.=','.$package;
13220:     } else {
13221: 	$metaentry{':packages'}=$package;
13222:     }
13223:     my $value=$packagetab{$key};
13224:     my $unikey;
13225:     $unikey='parameter_0_'.$name;
13226:     $metaentry{':'.$unikey.'.part'}=0;
13227:     $$metathesekeys{$unikey}=1;
13228:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13229: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13230:     }
13231:     if (defined($metaentry{':'.$unikey.'.default'})) {
13232: 	$metaentry{':'.$unikey}=
13233: 	    $metaentry{':'.$unikey.'.default'};
13234:     }
13235: }
13236: 
13237: sub metadata_generate_part0 {
13238:     my ($metadata,$metacache,$uri) = @_;
13239:     my %allnames;
13240:     foreach my $metakey (keys(%$metadata)) {
13241: 	if ($metakey=~/^parameter\_(.*)/) {
13242: 	  my $part=$$metacache{':'.$metakey.'.part'};
13243: 	  my $name=$$metacache{':'.$metakey.'.name'};
13244: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13245: 	    $allnames{$name}=$part;
13246: 	  }
13247: 	}
13248:     }
13249:     foreach my $name (keys(%allnames)) {
13250:       $$metadata{"parameter_0_$name"}=1;
13251:       my $key=":parameter_0_$name";
13252:       $$metacache{"$key.part"}='0';
13253:       $$metacache{"$key.name"}=$name;
13254:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13255: 					   $allnames{$name}.'_'.$name.
13256: 					   '.type'};
13257:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13258: 			     '.display'};
13259:       my $expr='[Part: '.$allnames{$name}.']';
13260:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13261:       $$metacache{"$key.display"}=$olddis;
13262:     }
13263: }
13264: 
13265: # ------------------------------------------------------ Devalidate title cache
13266: 
13267: sub devalidate_title_cache {
13268:     my ($url)=@_;
13269:     if (!$env{'request.course.id'}) { return; }
13270:     my $symb=&symbread($url);
13271:     if (!$symb) { return; }
13272:     my $key=$env{'request.course.id'}."\0".$symb;
13273:     &devalidate_cache_new('title',$key);
13274: }
13275: 
13276: # ------------------------------------------------- Get the title of a course
13277: 
13278: sub current_course_title {
13279:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13280: }
13281: # ------------------------------------------------- Get the title of a resource
13282: 
13283: sub gettitle {
13284:     my $urlsymb=shift;
13285:     my $symb=&symbread($urlsymb);
13286:     if ($symb) {
13287: 	my $key=$env{'request.course.id'}."\0".$symb;
13288: 	my ($result,$cached)=&is_cached_new('title',$key);
13289: 	if (defined($cached)) { 
13290: 	    return $result;
13291: 	}
13292: 	my ($map,$resid,$url)=&decode_symb($symb);
13293: 	my $title='';
13294: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13295: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13296: 	} else {
13297: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13298: 		    &GDBM_READER(),0640)) {
13299: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13300: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13301: 		untie(%bighash);
13302: 	    }
13303: 	}
13304: 	$title=~s/\&colon\;/\:/gs;
13305: 	if ($title) {
13306: # Remember both $symb and $title for dynamic metadata
13307:             $accesshash{$symb.'___crstitle'}=$title;
13308:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13309: # Cache this title and then return it
13310: 	    return &do_cache_new('title',$key,$title,600);
13311: 	}
13312: 	$urlsymb=$url;
13313:     }
13314:     my $title=&metadata($urlsymb,'title');
13315:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13316:     return $title;
13317: }
13318: 
13319: sub get_slot {
13320:     my ($which,$cnum,$cdom)=@_;
13321:     if (!$cnum || !$cdom) {
13322: 	(undef,my $courseid)=&whichuser();
13323: 	$cdom=$env{'course.'.$courseid.'.domain'};
13324: 	$cnum=$env{'course.'.$courseid.'.num'};
13325:     }
13326:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13327:     my %slotinfo;
13328:     if (exists($remembered{$key})) {
13329: 	$slotinfo{$which} = $remembered{$key};
13330:     } else {
13331: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13332: 	&Apache::lonhomework::showhash(%slotinfo);
13333: 	my ($tmp)=keys(%slotinfo);
13334: 	if ($tmp=~/^error:/) { return (); }
13335: 	$remembered{$key} = $slotinfo{$which};
13336:     }
13337:     if (ref($slotinfo{$which}) eq 'HASH') {
13338: 	return %{$slotinfo{$which}};
13339:     }
13340:     return $slotinfo{$which};
13341: }
13342: 
13343: sub get_reservable_slots {
13344:     my ($cnum,$cdom,$uname,$udom) = @_;
13345:     my $now = time;
13346:     my $reservable_info;
13347:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13348:     if (exists($remembered{$key})) {
13349:         $reservable_info = $remembered{$key};
13350:     } else {
13351:         my %resv;
13352:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13353:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13354:         $reservable_info = \%resv;
13355:         $remembered{$key} = $reservable_info;
13356:     }
13357:     return $reservable_info;
13358: }
13359: 
13360: sub get_course_slots {
13361:     my ($cnum,$cdom) = @_;
13362:     my $hashid=$cnum.':'.$cdom;
13363:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13364:     if (defined($cached)) {
13365:         if (ref($result) eq 'HASH') {
13366:             return %{$result};
13367:         }
13368:     } else {
13369:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13370:         my ($tmp) = keys(%slots);
13371:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13372:             &do_cache_new('allslots',$hashid,\%slots,600);
13373:             return %slots;
13374:         }
13375:     }
13376:     return;
13377: }
13378: 
13379: sub devalidate_slots_cache {
13380:     my ($cnum,$cdom)=@_;
13381:     my $hashid=$cnum.':'.$cdom;
13382:     &devalidate_cache_new('allslots',$hashid);
13383: }
13384: 
13385: sub get_coursechange {
13386:     my ($cdom,$cnum) = @_;
13387:     if ($cdom eq '' || $cnum eq '') {
13388:         return unless ($env{'request.course.id'});
13389:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13390:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13391:     }
13392:     my $hashid=$cdom.'_'.$cnum;
13393:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13394:     if ((defined($cached)) && ($change ne '')) {
13395:         return $change;
13396:     } else {
13397:         my %crshash;
13398:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13399:         if ($crshash{'internal.contentchange'} eq '') {
13400:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13401:             if ($change eq '') {
13402:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13403:                 $change = $crshash{'internal.created'};
13404:             }
13405:         } else {
13406:             $change = $crshash{'internal.contentchange'};
13407:         }
13408:         my $cachetime = 600;
13409:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13410:     }
13411:     return $change;
13412: }
13413: 
13414: sub devalidate_coursechange_cache {
13415:     my ($cnum,$cdom)=@_;
13416:     my $hashid=$cnum.':'.$cdom;
13417:     &devalidate_cache_new('crschange',$hashid);
13418: }
13419: 
13420: # ------------------------------------------------- Update symbolic store links
13421: 
13422: sub symblist {
13423:     my ($mapname,%newhash)=@_;
13424:     $mapname=&deversion(&declutter($mapname));
13425:     my %hash;
13426:     if (($env{'request.course.fn'}) && (%newhash)) {
13427:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13428:                       &GDBM_WRCREAT(),0640)) {
13429: 	    foreach my $url (keys(%newhash)) {
13430: 		next if ($url eq 'last_known'
13431: 			 && $env{'form.no_update_last_known'});
13432: 		$hash{declutter($url)}=&encode_symb($mapname,
13433: 						    $newhash{$url}->[1],
13434: 						    $newhash{$url}->[0]);
13435:             }
13436:             if (untie(%hash)) {
13437: 		return 'ok';
13438:             }
13439:         }
13440:     }
13441:     return 'error';
13442: }
13443: 
13444: # --------------------------------------------------------------- Verify a symb
13445: 
13446: sub symbverify {
13447:     my ($symb,$thisurl,$encstate)=@_;
13448:     my $thisfn=$thisurl;
13449:     $thisfn=&declutter($thisfn);
13450: # direct jump to resource in page or to a sequence - will construct own symbs
13451:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13452: # check URL part
13453:     my ($map,$resid,$url)=&decode_symb($symb);
13454: 
13455:     unless ($url eq $thisfn) { return 0; }
13456: 
13457:     $symb=&symbclean($symb);
13458:     $thisurl=&deversion($thisurl);
13459:     $thisfn=&deversion($thisfn);
13460: 
13461:     my %bighash;
13462:     my $okay=0;
13463: 
13464:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13465:                             &GDBM_READER(),0640)) {
13466:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13467:             $thisurl =~ s/\?.+$//;
13468:             if ($map =~ m{^uploaded/.+\.page$}) {
13469:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13470:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13471:             }
13472:         }
13473:         my $ids;
13474:         if ($map =~ m{^uploaded/.+\.page$}) {
13475:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13476:         } else {
13477:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13478:         }
13479:         unless ($ids) {
13480:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13481:             $ids=$bighash{$idkey};
13482:         }
13483:         if ($ids) {
13484: # ------------------------------------------------------------------- Has ID(s)
13485:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13486:                 $symb =~ s/\?.+$//;
13487:             }
13488: 	    foreach my $id (split(/\,/,$ids)) {
13489: 	       my ($mapid,$resid)=split(/\./,$id);
13490:                if (
13491:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13492:    eq $symb) {
13493:                    if (ref($encstate)) {
13494:                        $$encstate = $bighash{'encrypted_'.$id};
13495:                    }
13496: 		   if (($env{'request.role.adv'}) ||
13497: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13498:                        ($thisurl eq '/adm/navmaps')) {
13499: 		       $okay=1;
13500:                        last;
13501: 		   }
13502: 	       }
13503: 	   }
13504:         }
13505: 	untie(%bighash);
13506:     }
13507:     return $okay;
13508: }
13509: 
13510: # --------------------------------------------------------------- Clean-up symb
13511: 
13512: sub symbclean {
13513:     my $symb=shift;
13514:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13515: # remove version from map
13516:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13517: 
13518: # remove version from URL
13519:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13520: 
13521: # remove wrapper
13522: 
13523:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13524:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13525:     return $symb;
13526: }
13527: 
13528: # ---------------------------------------------- Split symb to find map and url
13529: 
13530: sub encode_symb {
13531:     my ($map,$resid,$url)=@_;
13532:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13533: }
13534: 
13535: sub decode_symb {
13536:     my $symb=shift;
13537:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13538:     my ($map,$resid,$url)=split(/___/,$symb);
13539:     return (&fixversion($map),$resid,&fixversion($url));
13540: }
13541: 
13542: sub fixversion {
13543:     my $fn=shift;
13544:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13545:     my %bighash;
13546:     my $uri=&clutter($fn);
13547:     my $key=$env{'request.course.id'}.'_'.$uri;
13548: # is this cached?
13549:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13550:     if (defined($cached)) { return $result; }
13551: # unfortunately not cached, or expired
13552:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13553: 	    &GDBM_READER(),0640)) {
13554:  	if ($bighash{'version_'.$uri}) {
13555:  	    my $version=$bighash{'version_'.$uri};
13556:  	    unless (($version eq 'mostrecent') || 
13557: 		    ($version==&getversion($uri))) {
13558:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13559:  	    }
13560:  	}
13561:  	untie %bighash;
13562:     }
13563:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13564: }
13565: 
13566: sub deversion {
13567:     my $url=shift;
13568:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13569:     return $url;
13570: }
13571: 
13572: # ------------------------------------------------------ Return symb list entry
13573: 
13574: sub symbread {
13575:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13576:         $ignoresymbdb,$noenccheck)=@_;
13577:     my $cache_str='request.symbread.cached.'.$thisfn;
13578:     if (defined($env{$cache_str})) {
13579:         unless (ref($possibles) eq 'HASH') {
13580:             if ($ignorecachednull) {
13581:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13582:             } else {
13583:                 return $env{$cache_str};
13584:             }
13585:         }
13586:     }
13587: # no filename provided? try from environment
13588:     unless ($thisfn) {
13589:         if ($env{'request.symb'}) {
13590:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13591: 	}
13592: 	$thisfn=$env{'request.filename'};
13593:     }
13594:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13595: # is that filename actually a symb? Verify, clean, and return
13596:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13597: 	if (&symbverify($thisfn,$1)) {
13598: 	    return $env{$cache_str}=&symbclean($thisfn);
13599: 	}
13600:     }
13601:     $thisfn=declutter($thisfn);
13602:     my %hash;
13603:     my %bighash;
13604:     my $syval='';
13605:     if (($env{'request.course.fn'}) && ($thisfn)) {
13606:         my $targetfn = $thisfn;
13607:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13608:             $targetfn = 'adm/wrapper/'.$thisfn;
13609:         }
13610: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13611: 	    $targetfn=$1;
13612: 	}
13613:         unless ($ignoresymbdb) {
13614:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13615:                           &GDBM_READER(),0640)) {
13616: 	        $syval=$hash{$targetfn};
13617:                 untie(%hash);
13618:             }
13619:             if ($syval && $checkforblock) {
13620:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13621:                 if (@blockers) {
13622:                     $syval='';
13623:                 }
13624:             }
13625:         }
13626: # ---------------------------------------------------------- There was an entry
13627:         if ($syval) {
13628: 	    #unless ($syval=~/\_\d+$/) {
13629: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13630: 		    #&appenv({'request.ambiguous' => $thisfn});
13631: 		    #return $env{$cache_str}='';
13632: 		#}    
13633: 		#$syval.=$1;
13634: 	    #}
13635:         } else {
13636: # ------------------------------------------------------- Was not in symb table
13637:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13638:                             &GDBM_READER(),0640)) {
13639: # ---------------------------------------------- Get ID(s) for current resource
13640:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13641:               unless ($ids) { 
13642:                  $ids=$bighash{'ids_/'.$thisfn};
13643:               }
13644:               unless ($ids) {
13645: # alias?
13646: 		  $ids=$bighash{'mapalias_'.$thisfn};
13647:               }
13648:               if ($ids) {
13649: # ------------------------------------------------------------------- Has ID(s)
13650:                  my @possibilities=split(/\,/,$ids);
13651:                  if ($#possibilities==0) {
13652: # ----------------------------------------------- There is only one possibility
13653: 		     my ($mapid,$resid)=split(/\./,$ids);
13654: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13655: 						    $resid,$thisfn);
13656:                      if (ref($possibles) eq 'HASH') {
13657:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13658:                              $possibles->{$syval} = 1;
13659:                          }
13660:                      }
13661:                      if ($checkforblock) {
13662:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13663:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13664:                              if (@blockers) {
13665:                                  $syval = '';
13666:                                  untie(%bighash);
13667:                                  return $env{$cache_str}='';
13668:                              }
13669:                          }
13670:                      }
13671:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13672: # ------------------------------------------ There is more than one possibility
13673:                      my $realpossible=0;
13674:                      foreach my $id (@possibilities) {
13675: 			 my $file=$bighash{'src_'.$id};
13676:                          my $canaccess;
13677:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13678:                              $canaccess = 1;
13679:                          } else { 
13680:                              $canaccess = &allowed('bre',$file);
13681:                          }
13682:                          if ($canaccess) {
13683:          		     my ($mapid,$resid)=split(/\./,$id);
13684:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13685:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13686: 						             $resid,$thisfn);
13687:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13688:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13689:                                  if ($checkforblock) {
13690:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13691:                                      if (@blockers > 0) {
13692:                                          $syval = '';
13693:                                      } else {
13694:                                          $syval = $poss_syval;
13695:                                          $realpossible++;
13696:                                      }
13697:                                  } else {
13698:                                      $syval = $poss_syval;
13699:                                      $realpossible++;
13700:                                  }
13701:                                  if ($syval) {
13702:                                      if (ref($possibles) eq 'HASH') {
13703:                                          $possibles->{$syval} = 1;
13704:                                      }
13705:                                  }
13706:                              }
13707: 			 }
13708:                      }
13709: 		     if ($realpossible!=1) { $syval=''; }
13710:                  } else {
13711:                      $syval='';
13712:                  }
13713: 	      }
13714:               untie(%bighash);
13715:            }
13716:         }
13717:         if ($syval) {
13718: 	    return $env{$cache_str}=$syval;
13719:         }
13720:     }
13721:     &appenv({'request.ambiguous' => $thisfn});
13722:     return $env{$cache_str}='';
13723: }
13724: 
13725: # ---------------------------------------------------------- Return random seed
13726: 
13727: sub numval {
13728:     my $txt=shift;
13729:     $txt=~tr/A-J/0-9/;
13730:     $txt=~tr/a-j/0-9/;
13731:     $txt=~tr/K-T/0-9/;
13732:     $txt=~tr/k-t/0-9/;
13733:     $txt=~tr/U-Z/0-5/;
13734:     $txt=~tr/u-z/0-5/;
13735:     $txt=~s/\D//g;
13736:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13737:     return int($txt);
13738: }
13739: 
13740: sub numval2 {
13741:     my $txt=shift;
13742:     $txt=~tr/A-J/0-9/;
13743:     $txt=~tr/a-j/0-9/;
13744:     $txt=~tr/K-T/0-9/;
13745:     $txt=~tr/k-t/0-9/;
13746:     $txt=~tr/U-Z/0-5/;
13747:     $txt=~tr/u-z/0-5/;
13748:     $txt=~s/\D//g;
13749:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13750:     my $total;
13751:     foreach my $val (@txts) { $total+=$val; }
13752:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13753:     return int($total);
13754: }
13755: 
13756: sub numval3 {
13757:     use integer;
13758:     my $txt=shift;
13759:     $txt=~tr/A-J/0-9/;
13760:     $txt=~tr/a-j/0-9/;
13761:     $txt=~tr/K-T/0-9/;
13762:     $txt=~tr/k-t/0-9/;
13763:     $txt=~tr/U-Z/0-5/;
13764:     $txt=~tr/u-z/0-5/;
13765:     $txt=~s/\D//g;
13766:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13767:     my $total;
13768:     foreach my $val (@txts) { $total+=$val; }
13769:     if ($_64bit) { $total=(($total<<32)>>32); }
13770:     return $total;
13771: }
13772: 
13773: sub digest {
13774:     my ($data)=@_;
13775:     my $digest=&Digest::MD5::md5($data);
13776:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13777:     my ($e,$f);
13778:     {
13779:         use integer;
13780:         $e=($a+$b);
13781:         $f=($c+$d);
13782:         if ($_64bit) {
13783:             $e=(($e<<32)>>32);
13784:             $f=(($f<<32)>>32);
13785:         }
13786:     }
13787:     if (wantarray) {
13788: 	return ($e,$f);
13789:     } else {
13790: 	my $g;
13791: 	{
13792: 	    use integer;
13793: 	    $g=($e+$f);
13794: 	    if ($_64bit) {
13795: 		$g=(($g<<32)>>32);
13796: 	    }
13797: 	}
13798: 	return $g;
13799:     }
13800: }
13801: 
13802: sub latest_rnd_algorithm_id {
13803:     return '64bit5';
13804: }
13805: 
13806: sub get_rand_alg {
13807:     my ($courseid)=@_;
13808:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13809:     if ($courseid) {
13810: 	return $env{"course.$courseid.rndseed"};
13811:     }
13812:     return &latest_rnd_algorithm_id();
13813: }
13814: 
13815: sub validCODE {
13816:     my ($CODE)=@_;
13817:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13818:     return 0;
13819: }
13820: 
13821: sub getCODE {
13822:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13823:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13824: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13825: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13826: 	return $Apache::lonhomework::history{'resource.CODE'};
13827:     }
13828:     return undef;
13829: }
13830: #
13831: #  Determines the random seed for a specific context:
13832: #
13833: # parameters:
13834: #   symb      - in course context the symb for the seed.
13835: #   course_id - The course id of the form domain_coursenum.
13836: #   domain    - Domain for the user.
13837: #   course    - Course for the user.
13838: #   cenv      - environment of the course.
13839: #
13840: # NOTE:
13841: #   All parameters are picked out of the environment if missing
13842: #   or not defined.
13843: #   If a symb cannot be determined the current time is used instead.
13844: #
13845: #  For a given well defined symb, courside, domain, username,
13846: #  and course environment, the seed is reproducible.
13847: #
13848: sub rndseed {
13849:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13850:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13851:     if (!defined($symb)) {
13852: 	unless ($symb=$wsymb) { return time; }
13853:     }
13854:     if (!defined $courseid) { 
13855: 	$courseid=$wcourseid; 
13856:     }
13857:     if (!defined $domain) { $domain=$wdomain; }
13858:     if (!defined $username) { $username=$wusername }
13859: 
13860:     my $which;
13861:     if (defined($cenv->{'rndseed'})) {
13862: 	$which = $cenv->{'rndseed'};
13863:     } else {
13864: 	$which =&get_rand_alg($courseid);
13865:     }
13866:     if (defined(&getCODE())) {
13867: 
13868: 	if ($which eq '64bit5') {
13869: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13870: 	} elsif ($which eq '64bit4') {
13871: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13872: 	} else {
13873: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13874: 	}
13875:     } elsif ($which eq '64bit5') {
13876: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13877:     } elsif ($which eq '64bit4') {
13878: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13879:     } elsif ($which eq '64bit3') {
13880: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13881:     } elsif ($which eq '64bit2') {
13882: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13883:     } elsif ($which eq '64bit') {
13884: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13885:     }
13886:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13887: }
13888: 
13889: sub rndseed_32bit {
13890:     my ($symb,$courseid,$domain,$username)=@_;
13891:     {
13892: 	use integer;
13893: 	my $symbchck=unpack("%32C*",$symb) << 27;
13894: 	my $symbseed=numval($symb) << 22;
13895: 	my $namechck=unpack("%32C*",$username) << 17;
13896: 	my $nameseed=numval($username) << 12;
13897: 	my $domainseed=unpack("%32C*",$domain) << 7;
13898: 	my $courseseed=unpack("%32C*",$courseid);
13899: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13900: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13901: 	#&logthis("rndseed :$num:$symb");
13902: 	if ($_64bit) { $num=(($num<<32)>>32); }
13903: 	return $num;
13904:     }
13905: }
13906: 
13907: sub rndseed_64bit {
13908:     my ($symb,$courseid,$domain,$username)=@_;
13909:     {
13910: 	use integer;
13911: 	my $symbchck=unpack("%32S*",$symb) << 21;
13912: 	my $symbseed=numval($symb) << 10;
13913: 	my $namechck=unpack("%32S*",$username);
13914: 	
13915: 	my $nameseed=numval($username) << 21;
13916: 	my $domainseed=unpack("%32S*",$domain) << 10;
13917: 	my $courseseed=unpack("%32S*",$courseid);
13918: 	
13919: 	my $num1=$symbchck+$symbseed+$namechck;
13920: 	my $num2=$nameseed+$domainseed+$courseseed;
13921: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13922: 	#&logthis("rndseed :$num:$symb");
13923: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13924: 	return "$num1,$num2";
13925:     }
13926: }
13927: 
13928: sub rndseed_64bit2 {
13929:     my ($symb,$courseid,$domain,$username)=@_;
13930:     {
13931: 	use integer;
13932: 	# strings need to be an even # of cahracters long, it it is odd the
13933:         # last characters gets thrown away
13934: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13935: 	my $symbseed=numval($symb) << 10;
13936: 	my $namechck=unpack("%32S*",$username.' ');
13937: 	
13938: 	my $nameseed=numval($username) << 21;
13939: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13940: 	my $courseseed=unpack("%32S*",$courseid.' ');
13941: 	
13942: 	my $num1=$symbchck+$symbseed+$namechck;
13943: 	my $num2=$nameseed+$domainseed+$courseseed;
13944: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13945: 	#&logthis("rndseed :$num:$symb");
13946: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13947: 	return "$num1,$num2";
13948:     }
13949: }
13950: 
13951: sub rndseed_64bit3 {
13952:     my ($symb,$courseid,$domain,$username)=@_;
13953:     {
13954: 	use integer;
13955: 	# strings need to be an even # of cahracters long, it it is odd the
13956:         # last characters gets thrown away
13957: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13958: 	my $symbseed=numval2($symb) << 10;
13959: 	my $namechck=unpack("%32S*",$username.' ');
13960: 	
13961: 	my $nameseed=numval2($username) << 21;
13962: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13963: 	my $courseseed=unpack("%32S*",$courseid.' ');
13964: 	
13965: 	my $num1=$symbchck+$symbseed+$namechck;
13966: 	my $num2=$nameseed+$domainseed+$courseseed;
13967: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13968: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13969: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13970: 	
13971: 	return "$num1:$num2";
13972:     }
13973: }
13974: 
13975: sub rndseed_64bit4 {
13976:     my ($symb,$courseid,$domain,$username)=@_;
13977:     {
13978: 	use integer;
13979: 	# strings need to be an even # of cahracters long, it it is odd the
13980:         # last characters gets thrown away
13981: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13982: 	my $symbseed=numval3($symb) << 10;
13983: 	my $namechck=unpack("%32S*",$username.' ');
13984: 	
13985: 	my $nameseed=numval3($username) << 21;
13986: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13987: 	my $courseseed=unpack("%32S*",$courseid.' ');
13988: 	
13989: 	my $num1=$symbchck+$symbseed+$namechck;
13990: 	my $num2=$nameseed+$domainseed+$courseseed;
13991: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13992: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13993: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13994: 	
13995: 	return "$num1:$num2";
13996:     }
13997: }
13998: 
13999: sub rndseed_64bit5 {
14000:     my ($symb,$courseid,$domain,$username)=@_;
14001:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14002:     return "$num1:$num2";
14003: }
14004: 
14005: sub rndseed_CODE_64bit {
14006:     my ($symb,$courseid,$domain,$username)=@_;
14007:     {
14008: 	use integer;
14009: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14010: 	my $symbseed=numval2($symb);
14011: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14012: 	my $CODEseed=numval(&getCODE());
14013: 	my $courseseed=unpack("%32S*",$courseid.' ');
14014: 	my $num1=$symbseed+$CODEchck;
14015: 	my $num2=$CODEseed+$courseseed+$symbchck;
14016: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14017: 	#&logthis("rndseed :$num1:$num2:$symb");
14018: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14019: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14020: 	return "$num1:$num2";
14021:     }
14022: }
14023: 
14024: sub rndseed_CODE_64bit4 {
14025:     my ($symb,$courseid,$domain,$username)=@_;
14026:     {
14027: 	use integer;
14028: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14029: 	my $symbseed=numval3($symb);
14030: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14031: 	my $CODEseed=numval3(&getCODE());
14032: 	my $courseseed=unpack("%32S*",$courseid.' ');
14033: 	my $num1=$symbseed+$CODEchck;
14034: 	my $num2=$CODEseed+$courseseed+$symbchck;
14035: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14036: 	#&logthis("rndseed :$num1:$num2:$symb");
14037: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14038: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14039: 	return "$num1:$num2";
14040:     }
14041: }
14042: 
14043: sub rndseed_CODE_64bit5 {
14044:     my ($symb,$courseid,$domain,$username)=@_;
14045:     my $code = &getCODE();
14046:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14047:     return "$num1:$num2";
14048: }
14049: 
14050: sub setup_random_from_rndseed {
14051:     my ($rndseed)=@_;
14052:     if ($rndseed =~/([,:])/) {
14053:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14054:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14055:             &Math::Random::random_set_seed_from_phrase($rndseed);
14056:         } else {
14057:             &Math::Random::random_set_seed($num1,$num2);
14058:         }
14059:     } else {
14060: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14061:     }
14062: }
14063: 
14064: sub latest_receipt_algorithm_id {
14065:     return 'receipt3';
14066: }
14067: 
14068: sub recunique {
14069:     my $fucourseid=shift;
14070:     my $unique;
14071:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14072: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14073: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14074:     } else {
14075: 	$unique=$perlvar{'lonReceipt'};
14076:     }
14077:     return unpack("%32C*",$unique);
14078: }
14079: 
14080: sub recprefix {
14081:     my $fucourseid=shift;
14082:     my $prefix;
14083:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14084: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14085: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14086:     } else {
14087: 	$prefix=$perlvar{'lonHostID'};
14088:     }
14089:     return unpack("%32C*",$prefix);
14090: }
14091: 
14092: sub ireceipt {
14093:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14094: 
14095:     my $return =&recprefix($fucourseid).'-';
14096: 
14097:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14098: 	$env{'request.state'} eq 'construct') {
14099: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14100: 	return $return;
14101:     }
14102: 
14103:     my $cuname=unpack("%32C*",$funame);
14104:     my $cudom=unpack("%32C*",$fudom);
14105:     my $cucourseid=unpack("%32C*",$fucourseid);
14106:     my $cusymb=unpack("%32C*",$fusymb);
14107:     my $cunique=&recunique($fucourseid);
14108:     my $cpart=unpack("%32S*",$part);
14109:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14110: 
14111: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14112: 			       
14113: 	$return.= ($cunique%$cuname+
14114: 		   $cunique%$cudom+
14115: 		   $cusymb%$cuname+
14116: 		   $cusymb%$cudom+
14117: 		   $cucourseid%$cuname+
14118: 		   $cucourseid%$cudom+
14119: 		   $cpart%$cuname+
14120: 		   $cpart%$cudom);
14121:     } else {
14122: 	$return.= ($cunique%$cuname+
14123: 		   $cunique%$cudom+
14124: 		   $cusymb%$cuname+
14125: 		   $cusymb%$cudom+
14126: 		   $cucourseid%$cuname+
14127: 		   $cucourseid%$cudom);
14128:     }
14129:     return $return;
14130: }
14131: 
14132: sub receipt {
14133:     my ($part)=@_;
14134:     my ($symb,$courseid,$domain,$name) = &whichuser();
14135:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14136: }
14137: 
14138: sub whichuser {
14139:     my ($passedsymb)=@_;
14140:     my ($symb,$courseid,$domain,$name,$publicuser);
14141:     if (defined($env{'form.grade_symb'})) {
14142: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14143: 	my $allowed=&allowed('vgr',$tmp_courseid);
14144: 	if (!$allowed &&
14145: 	    exists($env{'request.course.sec'}) &&
14146: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14147: 	    $allowed=&allowed('vgr',$tmp_courseid.
14148: 			      '/'.$env{'request.course.sec'});
14149: 	}
14150: 	if ($allowed) {
14151: 	    ($symb)=&get_env_multiple('form.grade_symb');
14152: 	    $courseid=$tmp_courseid;
14153: 	    ($domain)=&get_env_multiple('form.grade_domain');
14154: 	    ($name)=&get_env_multiple('form.grade_username');
14155: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14156: 	}
14157:     }
14158:     if (!$passedsymb) {
14159: 	$symb=&symbread();
14160:     } else {
14161: 	$symb=$passedsymb;
14162:     }
14163:     $courseid=$env{'request.course.id'};
14164:     $domain=$env{'user.domain'};
14165:     $name=$env{'user.name'};
14166:     if ($name eq 'public' && $domain eq 'public') {
14167: 	if (!defined($env{'form.username'})) {
14168: 	    $env{'form.username'}.=time.rand(10000000);
14169: 	}
14170: 	$name.=$env{'form.username'};
14171:     }
14172:     return ($symb,$courseid,$domain,$name,$publicuser);
14173: 
14174: }
14175: 
14176: # ------------------------------------------------------------ Serves up a file
14177: # returns either the contents of the file or 
14178: # -1 if the file doesn't exist
14179: #
14180: # if the target is a file that was uploaded via DOCS, 
14181: # a check will be made to see if a current copy exists on the local server,
14182: # if it does this will be served, otherwise a copy will be retrieved from
14183: # the home server for the course and stored in /home/httpd/html/userfiles on
14184: # the local server.   
14185: 
14186: sub getfile {
14187:     my ($file) = @_;
14188:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14189:     &repcopy($file);
14190:     return &readfile($file);
14191: }
14192: 
14193: sub repcopy_userfile {
14194:     my ($file)=@_;
14195:     my $londocroot = $perlvar{'lonDocRoot'};
14196:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14197:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14198:     my ($cdom,$cnum,$filename) = 
14199: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14200:     my $uri="/uploaded/$cdom/$cnum/$filename";
14201:     if (-e "$file") {
14202: # we already have a local copy, check it out
14203: 	my @fileinfo = stat($file);
14204: 	my $rtncode;
14205: 	my $info;
14206: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14207: 	if ($lwpresp ne 'ok') {
14208: # there is no such file anymore, even though we had a local copy
14209: 	    if ($rtncode eq '404') {
14210: 		unlink($file);
14211: 	    }
14212: 	    return -1;
14213: 	}
14214: 	if ($info < $fileinfo[9]) {
14215: # nice, the file we have is up-to-date, just say okay
14216: 	    return 'ok';
14217: 	} else {
14218: # the file is outdated, get rid of it
14219: 	    unlink($file);
14220: 	}
14221:     }
14222: # one way or the other, at this point, we don't have the file
14223: # construct the correct path for the file
14224:     my @parts = ($cdom,$cnum); 
14225:     if ($filename =~ m|^(.+)/[^/]+$|) {
14226: 	push @parts, split(/\//,$1);
14227:     }
14228:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14229:     foreach my $part (@parts) {
14230: 	$path .= '/'.$part;
14231: 	if (!-e $path) {
14232: 	    mkdir($path,0770);
14233: 	}
14234:     }
14235: # now the path exists for sure
14236: # get a user agent
14237:     my $transferfile=$file.'.in.transfer';
14238: # FIXME: this should flock
14239:     if (-e $transferfile) { return 'ok'; }
14240:     my $request;
14241:     $uri=~s/^\///;
14242:     my $homeserver = &homeserver($cnum,$cdom);
14243:     my $hostname = &hostname($homeserver);
14244:     my $protocol = $protocol{$homeserver};
14245:     $protocol = 'http' if ($protocol ne 'https');
14246:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14247:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14248: # did it work?
14249:     if ($response->is_error()) {
14250: 	unlink($transferfile);
14251: 	&logthis("Userfile repcopy failed for $uri");
14252: 	return -1;
14253:     }
14254: # worked, rename the transfer file
14255:     rename($transferfile,$file);
14256:     return 'ok';
14257: }
14258: 
14259: sub tokenwrapper {
14260:     my $uri=shift;
14261:     $uri=~s|^https?\://([^/]+)||;
14262:     $uri=~s|^/||;
14263:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14264:     my $token=$1;
14265:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14266:     if ($udom && $uname && $file) {
14267: 	$file=~s|(\?\.*)*$||;
14268:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14269:         my $homeserver = &homeserver($uname,$udom);
14270:         my $hostname = &hostname($homeserver);
14271:         my $protocol = $protocol{$homeserver};
14272:         $protocol = 'http' if ($protocol ne 'https');
14273:         return $protocol.'://'.$hostname.'/'.$uri.
14274:                (($uri=~/\?/)?'&':'?').'token='.$token.
14275:                                '&tokenissued='.$perlvar{'lonHostID'};
14276:     } else {
14277:         return '/adm/notfound.html';
14278:     }
14279: }
14280: 
14281: # call with reqtype HEAD: get last modification time
14282: # call with reqtype GET: get the file contents
14283: # Do not call this with reqtype GET for large files! It loads everything into memory
14284: #
14285: sub getuploaded {
14286:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14287:     $uri=~s/^\///;
14288:     my $homeserver = &homeserver($cnum,$cdom);
14289:     my $hostname = &hostname($homeserver);
14290:     my $protocol = $protocol{$homeserver};
14291:     $protocol = 'http' if ($protocol ne 'https');
14292:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14293:     my $request=new HTTP::Request($reqtype,$uri);
14294:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14295:     $$rtncode = $response->code;
14296:     if (! $response->is_success()) {
14297: 	return 'failed';
14298:     }      
14299:     if ($reqtype eq 'HEAD') {
14300: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14301:     } elsif ($reqtype eq 'GET') {
14302: 	$$info = $response->content;
14303:     }
14304:     return 'ok';
14305: }
14306: 
14307: sub readfile {
14308:     my $file = shift;
14309:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14310:     my $fh;
14311:     open($fh,"<",$file);
14312:     my $a='';
14313:     while (my $line = <$fh>) { $a .= $line; }
14314:     return $a;
14315: }
14316: 
14317: sub filelocation {
14318:     my ($dir,$file) = @_;
14319:     my $location;
14320:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14321: 
14322:     if ($file =~ m-^/adm/-) {
14323: 	$file=~s-^/adm/wrapper/-/-;
14324: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14325:     }
14326: 
14327:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14328:         $location = $file;
14329:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14330:         my ($udom,$uname,$filename)=
14331:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14332:         my $home=&homeserver($uname,$udom);
14333:         my $is_me=0;
14334:         my @ids=&current_machine_ids();
14335:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14336:         if ($is_me) {
14337:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14338:         } else {
14339:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14340:   	      $udom.'/'.$uname.'/'.$filename;
14341:         }
14342:     } elsif ($file =~ m-^/adm/-) {
14343: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14344:     } else {
14345:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14346:         $file=~s:^/(res|priv)/:/:;
14347:         my $space=$1;
14348:         if ( !( $file =~ m:^/:) ) {
14349:             $location = $dir. '/'.$file;
14350:         } else {
14351:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14352:         }
14353:     }
14354:     $location=~s://+:/:g; # remove duplicate /
14355:     while ($location=~m{/\.\./}) {
14356: 	if ($location =~ m{/[^/]+/\.\./}) {
14357: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14358: 	} else {
14359: 	    $location=~ s{/\.\./}{/}g;
14360: 	}
14361:     } #remove dir/..
14362:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14363:     return $location;
14364: }
14365: 
14366: sub hreflocation {
14367:     my ($dir,$file)=@_;
14368:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14369: 	$file=filelocation($dir,$file);
14370:     } elsif ($file=~m-^/adm/-) {
14371: 	$file=~s-^/adm/wrapper/-/-;
14372: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14373:     }
14374:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14375: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14376:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14377: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14378: 	        {/uploaded/$1/$2/}x;
14379:     }
14380:     if ($file=~ m{^/userfiles/}) {
14381: 	$file =~ s{^/userfiles/}{/uploaded/};
14382:     }
14383:     return $file;
14384: }
14385: 
14386: 
14387: 
14388: 
14389: 
14390: sub current_machine_domains {
14391:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14392: }
14393: 
14394: sub machine_domains {
14395:     my ($hostname) = @_;
14396:     my @domains;
14397:     my %hostname = &all_hostnames();
14398:     while( my($id, $name) = each(%hostname)) {
14399: #	&logthis("-$id-$name-$hostname-");
14400: 	if ($hostname eq $name) {
14401: 	    push(@domains,&host_domain($id));
14402: 	}
14403:     }
14404:     return @domains;
14405: }
14406: 
14407: sub current_machine_ids {
14408:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14409: }
14410: 
14411: sub machine_ids {
14412:     my ($hostname) = @_;
14413:     $hostname ||= &hostname($perlvar{'lonHostID'});
14414:     my @ids;
14415:     my %name_to_host = &all_names();
14416:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14417: 	return @{ $name_to_host{$hostname} };
14418:     }
14419:     return;
14420: }
14421: 
14422: sub additional_machine_domains {
14423:     my @domains;
14424:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14425:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14426:             while (my $line = <$fh>) {
14427:                 chomp($line);           
14428:                 $line =~ s/\s//g;
14429:                 push(@domains,$line);
14430:             }
14431:             close($fh);
14432:         }
14433:     }
14434:     return @domains;
14435: }
14436: 
14437: sub default_login_domain {
14438:     my $domain = $perlvar{'lonDefDomain'};
14439:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14440:     foreach my $posdom (&current_machine_domains(),
14441:                         &additional_machine_domains()) {
14442:         if (lc($posdom) eq lc($testdomain)) {
14443:             $domain=$posdom;
14444:             last;
14445:         }
14446:     }
14447:     return $domain;
14448: }
14449: 
14450: sub shared_institution {
14451:     my ($dom,$lonhost) = @_;
14452:     if ($lonhost eq '') {
14453:         $lonhost = $perlvar{'lonHostID'};
14454:     }
14455:     my $same_intdom;
14456:     my $hostintdom = &internet_dom($lonhost);
14457:     if ($hostintdom ne '') {
14458:         my %iphost = &get_iphost();
14459:         my $primary_id = &domain($dom,'primary');
14460:         my $primary_ip = &get_host_ip($primary_id);
14461:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14462:             foreach my $id (@{$iphost{$primary_ip}}) {
14463:                 my $intdom = &internet_dom($id);
14464:                 if ($intdom eq $hostintdom) {
14465:                     $same_intdom = 1;
14466:                     last;
14467:                 }
14468:             }
14469:         }
14470:     }
14471:     return $same_intdom;
14472: }
14473: 
14474: sub uses_sts {
14475:     my ($ignore_cache) = @_;
14476:     my $lonhost = $perlvar{'lonHostID'};
14477:     my $hostname = &hostname($lonhost);
14478:     my $sts_on;
14479:     if ($protocol{$lonhost} eq 'https') {
14480:         my $cachetime = 12*3600;
14481:         if (!$ignore_cache) {
14482:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14483:             if (defined($cached)) {
14484:                 return $sts_on;
14485:             }
14486:         }
14487:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14488:         my $request=new HTTP::Request('HEAD',$url);
14489:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14490:         if ($response->is_success) {
14491:             my $has_sts = $response->header('Strict-Transport-Security');
14492:             if ($has_sts eq '') {
14493:                 $sts_on = 0;
14494:             } else {
14495:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14496:                     my $maxage = $1;
14497:                     if ($maxage) {
14498:                         $sts_on = 1;
14499:                     } else {
14500:                         $sts_on = 0;
14501:                     }
14502:                 } else {
14503:                     $sts_on = 0;
14504:                 }
14505:             }
14506:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14507:         }
14508:     }
14509:     return;
14510: }
14511: 
14512: sub waf_allssl {
14513:     my ($host_name) = @_;
14514:     my $alias = &get_proxy_alias();
14515:     if ($host_name eq '') {
14516:         $host_name = $ENV{'SERVER_NAME'};
14517:     }
14518:     if (($host_name ne '') && ($alias eq $host_name)) {
14519:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14520:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14521:         if ($defdomdefaults{'waf_sslopt'}) {
14522:             return $defdomdefaults{'waf_sslopt'};
14523:         }
14524:     }
14525:     return;
14526: }
14527: 
14528: sub get_requestor_ip {
14529:     my ($r,$nolookup,$noproxy) = @_;
14530:     my $from_ip;
14531:     if (ref($r)) {
14532:         if ($r->can('useragent_ip')) {
14533:             if ($noproxy && $r->can('client_ip')) {
14534:                 $from_ip = $r->client_ip();
14535:             } else {
14536:                 $from_ip = $r->useragent_ip();
14537:             }
14538:         } elsif ($r->connection->can('remote_ip')) {
14539:             $from_ip = $r->connection->remote_ip();
14540:         } else {
14541:             $from_ip = $r->get_remote_host($nolookup);
14542:         }
14543:     } else {
14544:         $from_ip = $ENV{'REMOTE_ADDR'};
14545:     }
14546:     return $from_ip if ($noproxy); 
14547:     # Who controls proxy settings for server
14548:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14549:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14550:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14551:         if ($proxyinfo->{'vpnint'}) {
14552:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14553:                 return $from_ip;
14554:             }
14555:         }
14556:         if ($proxyinfo->{'trusted'}) {
14557:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14558:                 my $ipheader = $proxyinfo->{'ipheader'};
14559:                 my ($ip,$xfor);
14560:                 if (ref($r)) {
14561:                     if ($ipheader) {
14562:                         $ip = $r->headers_in->{$ipheader};
14563:                     }
14564:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14565:                 } else {
14566:                     if ($ipheader) {
14567:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14568:                     }
14569:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14570:                 }
14571:                 if (($ip eq '') && ($xfor ne '')) {
14572:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14573:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14574:                             $ip = $poss_ip;
14575:                             last;
14576:                         }
14577:                     }
14578:                 }
14579:                 if ($ip ne '') {
14580:                     return $ip;
14581:                 }
14582:             }
14583:         }
14584:     }
14585:     return $from_ip;
14586: }
14587: 
14588: sub get_proxy_settings {
14589:     my ($dom_in_use) = @_;
14590:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14591:     my $proxyinfo = {
14592:                        ipheader => $domdefaults{'waf_ipheader'},
14593:                        trusted  => $domdefaults{'waf_trusted'},
14594:                        vpnint   => $domdefaults{'waf_vpnint'},
14595:                        vpnext   => $domdefaults{'waf_vpnext'},
14596:                        sslopt   => $domdefaults{'waf_sslopt'},
14597:                     };
14598:     return $proxyinfo;
14599: }
14600: 
14601: sub ip_match {
14602:     my ($ip,$pattern_str) = @_;
14603:     $ip=Net::CIDR::cidrvalidate($ip);
14604:     if ($ip) {
14605:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14606:     }
14607:     return;
14608: }
14609: 
14610: sub get_proxy_alias {
14611:     my ($lonid) = @_;
14612:     if ($lonid eq '') {
14613:         $lonid = $perlvar{'lonHostID'};
14614:     }
14615:     if (!defined(&hostname($lonid))) {
14616:         return;
14617:     }
14618:     if ($lonid ne '') {
14619:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14620:         if ($cached) {
14621:             return $alias;
14622:         }
14623:         my $dom = &Apache::lonnet::host_domain($lonid);
14624:         if ($dom ne '') {
14625:             my $cachetime = 60*60*24;
14626:             my %domconfig =
14627:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14628:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14629:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14630:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14631:                 }
14632:             }
14633:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14634:         }
14635:     }
14636:     return;
14637: }
14638: 
14639: sub use_proxy_alias {
14640:     my ($r,$lonid) = @_;
14641:     my $alias = &get_proxy_alias($lonid);
14642:     if ($alias) {
14643:         my $dom = &host_domain($lonid);
14644:         if ($dom ne '') {
14645:             my $proxyinfo = &get_proxy_settings($dom);
14646:             my ($vpnint,$remote_ip);
14647:             if (ref($proxyinfo) eq 'HASH') {
14648:                 $vpnint = $proxyinfo->{'vpnint'};
14649:                 if ($vpnint) {
14650:                     $remote_ip = &get_requestor_ip($r,1,1);
14651:                 }
14652:             }
14653:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14654:                 return $alias;
14655:             }
14656:         }
14657:     }
14658:     return;
14659: }
14660: 
14661: sub alias_sso {
14662:     my ($lonid) = @_;
14663:     if ($lonid eq '') {
14664:         $lonid = $perlvar{'lonHostID'};
14665:     }
14666:     if (!defined(&hostname($lonid))) {
14667:         return;
14668:     }
14669:     if ($lonid ne '') {
14670:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14671:         if ($cached) {
14672:             return $use_alias;
14673:         }
14674:         my $dom = &Apache::lonnet::host_domain($lonid);
14675:         if ($dom ne '') {
14676:             my $cachetime = 60*60*24;
14677:             my %domconfig =
14678:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14679:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14680:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14681:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14682:                 }
14683:             }
14684:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14685:         }
14686:     }
14687:     return;
14688: }
14689: 
14690: sub get_saml_landing {
14691:     my ($lonid) = @_;
14692:     if ($lonid eq '') {
14693:         my $defdom = &default_login_domain();
14694:         my @hosts = &current_machine_ids();
14695:         if (@hosts > 1) {
14696:             foreach my $hostid (@hosts) {
14697:                 if (&host_domain($hostid) eq $defdom) {
14698:                     $lonid = $hostid;
14699:                     last;
14700:                 }
14701:             }
14702:         } else {
14703:             $lonid = $perlvar{'lonHostID'};
14704:         }
14705:         if ($lonid) {
14706:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14707:                 return;
14708:             }
14709:         } else {
14710:             return;
14711:         }
14712:     } elsif (!defined(&hostname($lonid))) {
14713:         return;
14714:     }
14715:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14716:     if ($cached) {
14717:         return $landing;
14718:     }
14719:     my $dom = &Apache::lonnet::host_domain($lonid);
14720:     if ($dom ne '') {
14721:         my $cachetime = 60*60*24;
14722:         my %domconfig =
14723:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
14724:         if (ref($domconfig{'login'}) eq 'HASH') {
14725:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14726:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14727:                     $landing = 1;
14728:                 }
14729:             }
14730:         }
14731:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14732:     }
14733:     return;
14734: }
14735: 
14736: # ------------------------------------------------------------- Declutters URLs
14737: 
14738: sub declutter {
14739:     my $thisfn=shift;
14740:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14741:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14742:         $thisfn=~s{^/home/httpd/html}{};
14743:     }
14744:     $thisfn=~s/^\///;
14745:     $thisfn=~s|^adm/wrapper/||;
14746:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14747:     $thisfn=~s/^res\///;
14748:     $thisfn=~s/^priv\///;
14749:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14750:         $thisfn=~s/\?.+$//;
14751:     }
14752:     return $thisfn;
14753: }
14754: 
14755: # ------------------------------------------------------------- Clutter up URLs
14756: 
14757: sub clutter {
14758:     my $thisfn='/'.&declutter(shift);
14759:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14760: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14761:        $thisfn='/res'.$thisfn; 
14762:     }
14763:     if ($thisfn !~m|^/adm|) {
14764: 	if ($thisfn =~ m|^/ext/|) {
14765: 	    $thisfn='/adm/wrapper'.$thisfn;
14766: 	} else {
14767: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14768: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14769: 	    if ($embstyle eq 'ssi'
14770: 		|| ($embstyle eq 'hdn')
14771: 		|| ($embstyle eq 'rat')
14772: 		|| ($embstyle eq 'prv')
14773: 		|| ($embstyle eq 'ign')) {
14774: 		#do nothing with these
14775: 	    } elsif (($embstyle eq 'img') 
14776: 		|| ($embstyle eq 'emb')
14777: 		|| ($embstyle eq 'wrp')) {
14778: 		$thisfn='/adm/wrapper'.$thisfn;
14779: 	    } elsif ($embstyle eq 'unk'
14780: 		     && $thisfn!~/\.(sequence|page)$/) {
14781: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14782: 	    } else {
14783: #		&logthis("Got a blank emb style");
14784: 	    }
14785: 	}
14786:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14787:         $thisfn='/adm/wrapper'.$thisfn;
14788:     }
14789:     return $thisfn;
14790: }
14791: 
14792: sub clutter_with_no_wrapper {
14793:     my $uri = &clutter(shift);
14794:     if ($uri =~ m-^/adm/-) {
14795: 	$uri =~ s-^/adm/wrapper/-/-;
14796: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14797:     }
14798:     return $uri;
14799: }
14800: 
14801: sub freeze_escape {
14802:     my ($value)=@_;
14803:     if (ref($value)) {
14804: 	$value=&nfreeze($value);
14805: 	return '__FROZEN__'.&escape($value);
14806:     }
14807:     return &escape($value);
14808: }
14809: 
14810: 
14811: sub thaw_unescape {
14812:     my ($value)=@_;
14813:     if ($value =~ /^__FROZEN__/) {
14814: 	substr($value,0,10,undef);
14815: 	$value=&unescape($value);
14816: 	return &thaw($value);
14817:     }
14818:     return &unescape($value);
14819: }
14820: 
14821: sub correct_line_ends {
14822:     my ($result)=@_;
14823:     $$result =~s/\r\n/\n/mg;
14824:     $$result =~s/\r/\n/mg;
14825: }
14826: # ================================================================ Main Program
14827: 
14828: sub goodbye {
14829:    &logthis("Starting Shut down");
14830: #not converted to using infrastruture and probably shouldn't be
14831:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14832: #converted
14833: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14834:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14835: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14836: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14837: #1.1 only
14838: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14839: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14840: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14841: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14842:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14843:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14844:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14845:    &flushcourselogs();
14846:    &logthis("Shutting down");
14847: }
14848: 
14849: sub get_dns {
14850:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14851:     if (!$ignore_cache) {
14852: 	my ($content,$cached)=
14853: 	    &Apache::lonnet::is_cached_new('dns',$url);
14854: 	if ($cached) {
14855: 	    &$func($content,$hashref);
14856: 	    return;
14857: 	}
14858:     }
14859: 
14860:     my %alldns;
14861:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14862:         foreach my $dns (<$config>) {
14863: 	    next if ($dns !~ /^\^(\S*)/x);
14864:             my $line = $1;
14865:             my ($host,$protocol) = split(/:/,$line);
14866:             if ($protocol ne 'https') {
14867:                 $protocol = 'http';
14868:             }
14869: 	    $alldns{$host} = $protocol;
14870:         }
14871:         close($config);
14872:     }
14873:     while (%alldns) {
14874: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14875:         my ($contents,@content);
14876:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14877:             my $command = (split('/',$url))[3];
14878:             my ($dir,$file) = &parse_getdns_url($command,$url);
14879:             delete($alldns{$dns});
14880:             next if (($dir eq '') || ($file eq ''));
14881:             if (open(my $config,'<',"$dir/$file")) {
14882:                 @content = <$config>;
14883:                 close($config);
14884:             }
14885:             if ($url eq '/adm/dns/loncapaCRL') {
14886:                 $contents = join('',@content);
14887:             }
14888:         } else {
14889: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14890:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14891:             delete($alldns{$dns});
14892: 	    next if ($response->is_error());
14893:             if ($url eq '/adm/dns/loncapaCRL') {
14894:                 $contents = $response->content;
14895:             } else {
14896:                 @content = split("\n",$response->content);
14897:             }
14898:         }
14899:         if ($url eq '/adm/dns/loncapaCRL') {
14900:             return &$func($contents);
14901:         } else {
14902: 	    unless ($nocache) {
14903: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14904: 	    }
14905: 	    &$func(\@content,$hashref);
14906:             return;
14907:         }
14908:     }
14909:     my $which = (split('/',$url,4))[3];
14910:     if ($which eq 'loncapaCRL') {
14911:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14912:         if (-e $diskfile) {
14913:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14914:         } else {
14915:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14916:         }
14917:     } else {
14918:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14919:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14920:             my @content = <$config>;
14921:             close($config);
14922:             &$func(\@content,$hashref);
14923:         }
14924:     }
14925:     return;
14926: }
14927: 
14928: # ------------------------------------------------------Get DNS checksums file
14929: sub parse_dns_checksums_tab {
14930:     my ($lines,$hashref) = @_;
14931:     my $lonhost = $perlvar{'lonHostID'};
14932:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14933:     my $loncaparev = &get_server_loncaparev($machine_dom);
14934:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14935:     my $webconfdir = '/etc/httpd/conf';
14936:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14937:         $webconfdir = '/etc/apache2';
14938:     } elsif ($distro =~ /^sles(\d+)$/) {
14939:         if ($1 >= 10) {
14940:             $webconfdir = '/etc/apache2';
14941:         }
14942:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14943:         if ($1 >= 10.0) {
14944:             $webconfdir = '/etc/apache2';
14945:         }
14946:     }
14947:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14948:     my (%chksum,%revnum);
14949:     if (ref($lines) eq 'ARRAY') {
14950:         chomp(@{$lines});
14951:         my $version = shift(@{$lines});
14952:         if ($version eq $release) {  
14953:             foreach my $line (@{$lines}) {
14954:                 my ($file,$version,$shasum) = split(/,/,$line);
14955:                 if ($file =~ m{^/etc/httpd/conf}) {
14956:                     if ($webconfdir eq '/etc/apache2') {
14957:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14958:                     }
14959:                 }
14960:                 $chksum{$file} = $shasum;
14961:                 $revnum{$file} = $version;
14962:             }
14963:             if (ref($hashref) eq 'HASH') {
14964:                 %{$hashref} = (
14965:                                 sums     => \%chksum,
14966:                                 versions => \%revnum,
14967:                               );
14968:             }
14969:         }
14970:     }
14971:     return;
14972: }
14973: 
14974: sub fetch_dns_checksums {
14975:     my %checksums;
14976:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14977:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14978:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14979:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14980:              \%checksums);
14981:     return \%checksums;
14982: }
14983: 
14984: sub fetch_crl_pemfile {
14985:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14986: }
14987: 
14988: sub save_crl_pem {
14989:     my ($content) = @_;
14990:     my ($msg,$hadchanges);
14991:     if ($content ne '') {
14992:         my $now = time;
14993:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14994:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14995:         if (open(my $fh,'>',"$tmpcrl")) {
14996:             print $fh $content;
14997:             close($fh);
14998:             if (-e $lonca) {
14999:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15000:                     my $check = <PIPE>;
15001:                     close(PIPE);
15002:                     chomp($check);
15003:                     if ($check eq 'verify OK') {
15004:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15005:                         my $backup;
15006:                         if (-e $dest) {
15007:                             if (&File::Copy::move($dest,"$dest.bak")) {
15008:                                 $backup = 'ok';
15009:                             }
15010:                         }
15011:                         if (&File::Copy::move($tmpcrl,$dest)) {
15012:                             $msg = 'ok';
15013:                             if ($backup) {
15014:                                 my (%oldnums,%newnums);
15015:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15016:                                     while (<PIPE>) {
15017:                                         $oldnums{(split(/:/))[1]} = 1;
15018:                                     }
15019:                                     close(PIPE);
15020:                                 }
15021:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15022:                                     while(<PIPE>) {
15023:                                         $newnums{(split(/:/))[1]} = 1;
15024:                                     }
15025:                                     close(PIPE);
15026:                                 }
15027:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15028:                                     unless (exists($oldnums{$key})) {
15029:                                         $hadchanges = 1;
15030:                                         last;
15031:                                     }
15032:                                 }
15033:                                 unless ($hadchanges) {
15034:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15035:                                         unless (exists($newnums{$key})) {
15036:                                             $hadchanges = 1;
15037:                                             last;
15038:                                         }
15039:                                     }
15040:                                 }
15041:                             }
15042:                         }
15043:                     } else {
15044:                         unlink($tmpcrl);
15045:                     }
15046:                 } else {
15047:                     unlink($tmpcrl);
15048:                 }
15049:             } else {
15050:                 unlink($tmpcrl);
15051:             }
15052:         }
15053:     }
15054:     return ($msg,$hadchanges);
15055: }
15056: 
15057: sub parse_getdns_url {
15058:     my ($command,$url) = @_;
15059:     my $dir = $perlvar{'lonTabDir'};
15060:     my $file;
15061:     if ($command eq 'hosts') {
15062:         $file = 'dns_hosts.tab';
15063:     } elsif ($command eq 'domain') {
15064:         $file = 'dns_domain.tab';
15065:     } elsif ($command eq 'checksums') {
15066:         my $version = (split('/',$url))[4];
15067:         $file = "dns_checksums/$version.tab",
15068:     } elsif ($command eq 'loncapaCRL') {
15069:         $dir = $perlvar{'lonCertificateDirectory'};
15070:         $file = $perlvar{'lonnetCertRevocationList'};
15071:     }
15072:     return ($dir,$file);
15073: }
15074: 
15075: # ------------------------------------------------------------ Read domain file
15076: {
15077:     my $loaded;
15078:     my %domain;
15079: 
15080:     sub parse_domain_tab {
15081: 	my ($lines) = @_;
15082: 	foreach my $line (@$lines) {
15083: 	    next if ($line =~ /^(\#|\s*$ )/x);
15084: 
15085: 	    chomp($line);
15086: 	    my ($name,@elements) = split(/:/,$line,9);
15087: 	    my %this_domain;
15088: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15089: 			       'lang_def', 'city', 'longi', 'lati',
15090: 			       'primary') {
15091: 		$this_domain{$field} = shift(@elements);
15092: 	    }
15093: 	    $domain{$name} = \%this_domain;
15094: 	}
15095:     }
15096: 
15097:     sub reset_domain_info {
15098: 	undef($loaded);
15099: 	undef(%domain);
15100:     }
15101: 
15102:     sub load_domain_tab {
15103: 	my ($ignore_cache,$nocache) = @_;
15104: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15105: 	my $fh;
15106: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15107: 	    my @lines = <$fh>;
15108: 	    &parse_domain_tab(\@lines);
15109: 	}
15110: 	close($fh);
15111: 	$loaded = 1;
15112:     }
15113: 
15114:     sub domain {
15115: 	&load_domain_tab() if (!$loaded);
15116: 
15117: 	my ($name,$what) = @_;
15118: 	return if ( !exists($domain{$name}) );
15119: 
15120: 	if (!$what) {
15121: 	    return $domain{$name}{'description'};
15122: 	}
15123: 	return $domain{$name}{$what};
15124:     }
15125: 
15126:     sub domain_info {
15127:         &load_domain_tab() if (!$loaded);
15128:         return %domain;
15129:     }
15130: 
15131: }
15132: 
15133: 
15134: # ------------------------------------------------------------- Read hosts file
15135: {
15136:     my %hostname;
15137:     my %hostdom;
15138:     my %libserv;
15139:     my $loaded;
15140:     my %name_to_host;
15141:     my %internetdom;
15142:     my %LC_dns_serv;
15143: 
15144:     sub parse_hosts_tab {
15145: 	my ($file) = @_;
15146: 	foreach my $configline (@$file) {
15147: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15148:             chomp($configline);
15149: 	    if ($configline =~ /^\^/) {
15150:                 if ($configline =~ /^\^([\w.\-]+)/) {
15151:                     $LC_dns_serv{$1} = 1;
15152:                 }
15153:                 next;
15154:             }
15155: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15156: 	    $name=~s/\s//g;
15157: 	    if ($id && $domain && $role && $name) {
15158:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15159:                     my $curr = $hostname{$id};
15160:                     my $skip;
15161:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15162:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15163:                             $skip = 1;
15164:                         } else {
15165:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15166:                         }
15167:                     }
15168:                     unless ($skip) {
15169:                         push(@{$name_to_host{$name}},$id);
15170:                     }
15171:                 } else {
15172:                     push(@{$name_to_host{$name}},$id);
15173:                 }
15174: 		$hostname{$id}=$name;
15175: 		$hostdom{$id}=$domain;
15176: 		if ($role eq 'library') { $libserv{$id}=$name; }
15177:                 if (defined($protocol)) {
15178:                     if ($protocol eq 'https') {
15179:                         $protocol{$id} = $protocol;
15180:                     } else {
15181:                         $protocol{$id} = 'http'; 
15182:                     }
15183:                 } else {
15184:                     $protocol{$id} = 'http';
15185:                 }
15186:                 if (defined($intdom)) {
15187:                     $internetdom{$id} = $intdom;
15188:                 }
15189: 	    }
15190: 	}
15191:     }
15192:     
15193:     sub reset_hosts_info {
15194: 	&purge_remembered();
15195: 	&reset_domain_info();
15196: 	&reset_hosts_ip_info();
15197:         undef(%internetdom);
15198: 	undef(%name_to_host);
15199: 	undef(%hostname);
15200: 	undef(%hostdom);
15201: 	undef(%libserv);
15202: 	undef($loaded);
15203:     }
15204: 
15205:     sub load_hosts_tab {
15206: 	my ($ignore_cache,$nocache) = @_;
15207: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15208: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15209: 	my @config = <$config>;
15210: 	&parse_hosts_tab(\@config);
15211: 	close($config);
15212: 	$loaded=1;
15213:     }
15214: 
15215:     sub hostname {
15216: 	&load_hosts_tab() if (!$loaded);
15217: 
15218: 	my ($lonid) = @_;
15219: 	return $hostname{$lonid};
15220:     }
15221: 
15222:     sub all_hostnames {
15223: 	&load_hosts_tab() if (!$loaded);
15224: 
15225: 	return %hostname;
15226:     }
15227: 
15228:     sub all_names {
15229:         my ($ignore_cache,$nocache) = @_;
15230: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15231: 
15232: 	return %name_to_host;
15233:     }
15234: 
15235:     sub all_host_domain {
15236:         &load_hosts_tab() if (!$loaded);
15237:         return %hostdom;
15238:     }
15239: 
15240:     sub all_host_intdom {
15241:         &load_hosts_tab() if (!$loaded);
15242:         return %internetdom;
15243:     }
15244: 
15245:     sub is_library {
15246: 	&load_hosts_tab() if (!$loaded);
15247: 
15248: 	return exists($libserv{$_[0]});
15249:     }
15250: 
15251:     sub all_library {
15252: 	&load_hosts_tab() if (!$loaded);
15253: 
15254: 	return %libserv;
15255:     }
15256: 
15257:     sub unique_library {
15258: 	#2x reverse removes all hostnames that appear more than once
15259:         my %unique = reverse &all_library();
15260:         return reverse %unique;
15261:     }
15262: 
15263:     sub get_servers {
15264: 	&load_hosts_tab() if (!$loaded);
15265: 
15266: 	my ($domain,$type) = @_;
15267: 	my %possible_hosts = ($type eq 'library') ? %libserv
15268: 	                                          : %hostname;
15269: 	my %result;
15270: 	if (ref($domain) eq 'ARRAY') {
15271: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15272: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15273: 		    $result{$host} = $hostname;
15274: 		}
15275: 	    }
15276: 	} else {
15277: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15278: 		if ($hostdom{$host} eq $domain) {
15279: 		    $result{$host} = $hostname;
15280: 		}
15281: 	    }
15282: 	}
15283: 	return %result;
15284:     }
15285: 
15286:     sub get_unique_servers {
15287:         my %unique = reverse &get_servers(@_);
15288: 	return reverse %unique;
15289:     }
15290: 
15291:     sub host_domain {
15292: 	&load_hosts_tab() if (!$loaded);
15293: 
15294: 	my ($lonid) = @_;
15295: 	return $hostdom{$lonid};
15296:     }
15297: 
15298:     sub all_domains {
15299: 	&load_hosts_tab() if (!$loaded);
15300: 
15301: 	my %seen;
15302: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15303: 	return @uniq;
15304:     }
15305: 
15306:     sub internet_dom {
15307:         &load_hosts_tab() if (!$loaded);
15308: 
15309:         my ($lonid) = @_;
15310:         return $internetdom{$lonid};
15311:     }
15312: 
15313:     sub is_LC_dns {
15314:         &load_hosts_tab() if (!$loaded);
15315: 
15316:         my ($hostname) = @_;
15317:         return exists($LC_dns_serv{$hostname});
15318:     }
15319: 
15320: }
15321: 
15322: { 
15323:     my %iphost;
15324:     my %name_to_ip;
15325:     my %lonid_to_ip;
15326: 
15327:     sub get_hosts_from_ip {
15328: 	my ($ip) = @_;
15329: 	my %iphosts = &get_iphost();
15330: 	if (ref($iphosts{$ip})) {
15331: 	    return @{$iphosts{$ip}};
15332: 	}
15333: 	return;
15334:     }
15335:     
15336:     sub reset_hosts_ip_info {
15337: 	undef(%iphost);
15338: 	undef(%name_to_ip);
15339: 	undef(%lonid_to_ip);
15340:     }
15341: 
15342:     sub get_host_ip {
15343: 	my ($lonid) = @_;
15344: 	if (exists($lonid_to_ip{$lonid})) {
15345: 	    return $lonid_to_ip{$lonid};
15346: 	}
15347: 	my $name=&hostname($lonid);
15348:    	my $ip = gethostbyname($name);
15349: 	return if (!$ip || length($ip) ne 4);
15350: 	$ip=inet_ntoa($ip);
15351: 	$name_to_ip{$name}   = $ip;
15352: 	$lonid_to_ip{$lonid} = $ip;
15353: 	return $ip;
15354:     }
15355:     
15356:     sub get_iphost {
15357: 	my ($ignore_cache,$nocache) = @_;
15358: 
15359: 	if (!$ignore_cache) {
15360: 	    if (%iphost) {
15361: 		return %iphost;
15362: 	    }
15363: 	    my ($ip_info,$cached)=
15364: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15365: 	    if ($cached) {
15366: 		%iphost      = %{$ip_info->[0]};
15367: 		%name_to_ip  = %{$ip_info->[1]};
15368: 		%lonid_to_ip = %{$ip_info->[2]};
15369: 		return %iphost;
15370: 	    }
15371: 	}
15372: 
15373: 	# get yesterday's info for fallback
15374: 	my %old_name_to_ip;
15375: 	my ($ip_info,$cached)=
15376: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15377: 	if ($cached) {
15378: 	    %old_name_to_ip = %{$ip_info->[1]};
15379: 	}
15380: 
15381: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15382: 	foreach my $name (keys(%name_to_host)) {
15383: 	    my $ip;
15384: 	    if (!exists($name_to_ip{$name})) {
15385: 		$ip = gethostbyname($name);
15386: 		if (!$ip || length($ip) ne 4) {
15387: 		    if (defined($old_name_to_ip{$name})) {
15388: 			$ip = $old_name_to_ip{$name};
15389: 			&logthis("Can't find $name defaulting to old $ip");
15390: 		    } else {
15391: 			&logthis("Name $name no IP found");
15392: 			next;
15393: 		    }
15394: 		} else {
15395: 		    $ip=inet_ntoa($ip);
15396: 		}
15397: 		$name_to_ip{$name} = $ip;
15398: 	    } else {
15399: 		$ip = $name_to_ip{$name};
15400: 	    }
15401: 	    foreach my $id (@{ $name_to_host{$name} }) {
15402: 		$lonid_to_ip{$id} = $ip;
15403: 	    }
15404: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15405: 	}
15406:         unless ($nocache) {
15407: 	    &do_cache_new('iphost','iphost',
15408: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15409: 		          48*60*60);
15410:         }
15411: 
15412: 	return %iphost;
15413:     }
15414: 
15415:     #
15416:     #  Given a DNS returns the loncapa host name for that DNS 
15417:     # 
15418:     sub host_from_dns {
15419:         my ($dns) = @_;
15420:         my @hosts;
15421:         my $ip;
15422: 
15423:         if (exists($name_to_ip{$dns})) {
15424:             $ip = $name_to_ip{$dns};
15425:         }
15426:         if (!$ip) {
15427:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15428:             if (length($ip) == 4) { 
15429: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15430:             }
15431:         }
15432:         if ($ip) {
15433: 	    @hosts = get_hosts_from_ip($ip);
15434: 	    return $hosts[0];
15435:         }
15436:         return undef;
15437:     }
15438: 
15439:     sub get_internet_names {
15440:         my ($lonid) = @_;
15441:         return if ($lonid eq '');
15442:         my ($idnref,$cached)=
15443:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15444:         if ($cached) {
15445:             return $idnref;
15446:         }
15447:         my $ip = &get_host_ip($lonid);
15448:         my @hosts = &get_hosts_from_ip($ip);
15449:         my %iphost = &get_iphost();
15450:         my (@idns,%seen);
15451:         foreach my $id (@hosts) {
15452:             my $dom = &host_domain($id);
15453:             my $prim_id = &domain($dom,'primary');
15454:             my $prim_ip = &get_host_ip($prim_id);
15455:             next if ($seen{$prim_ip});
15456:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15457:                 foreach my $id (@{$iphost{$prim_ip}}) {
15458:                     my $intdom = &internet_dom($id);
15459:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15460:                         push(@idns,$intdom);
15461:                     }
15462:                 }
15463:             }
15464:             $seen{$prim_ip} = 1;
15465:         }
15466:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15467:     }
15468: 
15469: }
15470: 
15471: sub all_loncaparevs {
15472:     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);
15473: }
15474: 
15475: # ---------------------------------------------------------- Read loncaparev table
15476: {
15477:     sub load_loncaparevs { 
15478:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15479:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15480:                 while (my $configline=<$config>) {
15481:                     chomp($configline);
15482:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15483:                     $loncaparevs{$hostid}=$loncaparev;
15484:                 }
15485:                 close($config);
15486:             }
15487:         }
15488:     }
15489: }
15490: 
15491: # ---------------------------------------------------------- Read serverhostID table
15492: {
15493:     sub load_serverhomeIDs {
15494:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15495:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15496:                 while (my $configline=<$config>) {
15497:                     chomp($configline);
15498:                     my ($name,$id)=split(/:/,$configline);
15499:                     $serverhomeIDs{$name}=$id;
15500:                 }
15501:                 close($config);
15502:             }
15503:         }
15504:     }
15505: }
15506: 
15507: 
15508: BEGIN {
15509: 
15510: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15511:     unless ($readit) {
15512: {
15513:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15514:     %perlvar = (%perlvar,%{$configvars});
15515: }
15516: 
15517: 
15518: # ------------------------------------------------------ Read spare server file
15519: {
15520:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15521: 
15522:     while (my $configline=<$config>) {
15523:        chomp($configline);
15524:        if ($configline) {
15525: 	   my ($host,$type) = split(':',$configline,2);
15526: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15527: 	   push(@{ $spareid{$type} }, $host);
15528:        }
15529:     }
15530:     close($config);
15531: }
15532: # ------------------------------------------------------------ Read permissions
15533: {
15534:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15535: 
15536:     while (my $configline=<$config>) {
15537: 	chomp($configline);
15538: 	if ($configline) {
15539: 	    my ($role,$perm)=split(/ /,$configline);
15540: 	    if ($perm ne '') { $pr{$role}=$perm; }
15541: 	}
15542:     }
15543:     close($config);
15544: }
15545: 
15546: # -------------------------------------------- Read plain texts for permissions
15547: {
15548:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15549: 
15550:     while (my $configline=<$config>) {
15551: 	chomp($configline);
15552: 	if ($configline) {
15553: 	    my ($short,@plain)=split(/:/,$configline);
15554:             %{$prp{$short}} = ();
15555: 	    if (@plain > 0) {
15556:                 $prp{$short}{'std'} = $plain[0];
15557:                 for (my $i=1; $i<@plain; $i++) {
15558:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15559:                 }
15560:             }
15561: 	}
15562:     }
15563:     close($config);
15564: }
15565: 
15566: # ---------------------------------------------------------- Read package table
15567: {
15568:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15569: 
15570:     while (my $configline=<$config>) {
15571: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15572: 	chomp($configline);
15573: 	my ($short,$plain)=split(/:/,$configline);
15574: 	my ($pack,$name)=split(/\&/,$short);
15575: 	if ($plain ne '') {
15576: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15577: 	    $packagetab{$short}=$plain; 
15578: 	}
15579:     }
15580:     close($config);
15581: }
15582: 
15583: # ---------------------------------------------------------- Read loncaparev table
15584: 
15585: &load_loncaparevs();
15586: 
15587: # ---------------------------------------------------------- Read serverhostID table
15588: 
15589: &load_serverhomeIDs();
15590: 
15591: # ---------------------------------------------------------- Read releaseslist XML
15592: {
15593:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15594:     if (-e $file) {
15595:         my $parser = HTML::LCParser->new($file);
15596:         while (my $token = $parser->get_token()) {
15597:             if ($token->[0] eq 'S') {
15598:                 my $item = $token->[1];
15599:                 my $name = $token->[2]{'name'};
15600:                 my $value = $token->[2]{'value'};
15601:                 my $valuematch = $token->[2]{'valuematch'};
15602:                 my $namematch = $token->[2]{'namematch'};
15603:                 if ($item eq 'parameter') {
15604:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15605:                         my $release = $parser->get_text();
15606:                         $release =~ s/(^\s*|\s*$ )//gx;
15607:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15608:                     }
15609:                 } elsif ($item ne '' && $name ne '') {
15610:                     my $release = $parser->get_text();
15611:                     $release =~ s/(^\s*|\s*$ )//gx;
15612:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15613:                 }
15614:             }
15615:         }
15616:     }
15617: }
15618: 
15619: # ---------------------------------------------------------- Read managers table
15620: {
15621:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15622:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15623:             while (my $configline=<$config>) {
15624:                 chomp($configline);
15625:                 next if ($configline =~ /^\#/);
15626:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15627:                     $managerstab{$configline} = 1;
15628:                 }
15629:             }
15630:             close($config);
15631:         }
15632:     }
15633: }
15634: 
15635: # ------------- set up temporary directory
15636: {
15637:     $tmpdir = LONCAPA::tempdir();
15638: 
15639: }
15640: 
15641: # ------------- set default texengine (domain default overrides this)
15642: {
15643:     $deftex = LONCAPA::texengine();
15644: }
15645: 
15646: # ------------- set default minimum length for passwords for internal auth users
15647: {
15648:     $passwdmin = LONCAPA::passwd_min();
15649: }
15650: 
15651: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15652: 				'compress_threshold'=> 20_000,
15653:  			        });
15654: 
15655: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15656: $dumpcount=0;
15657: $locknum=0;
15658: 
15659: &logtouch();
15660: &logthis('<font color="yellow">INFO: Read configuration</font>');
15661: $readit=1;
15662:     {
15663: 	use integer;
15664: 	my $test=(2**32)+1;
15665: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15666: 	&logthis(" Detected 64bit platform ($_64bit)");
15667:     }
15668: }
15669: }
15670: 
15671: 1;
15672: __END__
15673: 
15674: =pod
15675: 
15676: =head1 NAME
15677: 
15678: Apache::lonnet - Subroutines to ask questions about things in the network.
15679: 
15680: =head1 SYNOPSIS
15681: 
15682: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15683: 
15684:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15685: 
15686: Common parameters:
15687: 
15688: =over 4
15689: 
15690: =item *
15691: 
15692: $uname : an internal username (if $cname expecting a course Id specifically)
15693: 
15694: =item *
15695: 
15696: $udom : a domain (if $cdom expecting a course's domain specifically)
15697: 
15698: =item *
15699: 
15700: $symb : a resource instance identifier
15701: 
15702: =item *
15703: 
15704: $namespace : the name of a .db file that contains the data needed or
15705: being set.
15706: 
15707: =back
15708: 
15709: =head1 OVERVIEW
15710: 
15711: lonnet provides subroutines which interact with the
15712: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15713: about classes, users, and resources.
15714: 
15715: For many of these objects you can also use this to store data about
15716: them or modify them in various ways.
15717: 
15718: =head2 Symbs
15719: 
15720: To identify a specific instance of a resource, LON-CAPA uses symbols
15721: or "symbs"X<symb>. These identifiers are built from the URL of the
15722: map, the resource number of the resource in the map, and the URL of
15723: the resource itself. The latter is somewhat redundant, but might help
15724: if maps change.
15725: 
15726: An example is
15727: 
15728:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15729: 
15730: The respective map entry is
15731: 
15732:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15733:   title="Problem 2">
15734:  </resource>
15735: 
15736: Symbs are used by the random number generator, as well as to store and
15737: restore data specific to a certain instance of for example a problem.
15738: 
15739: =head2 Storing And Retrieving Data
15740: 
15741: X<store()>X<cstore()>X<restore()>Three of the most important functions
15742: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15743: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15744: is is the non-critical message twin of cstore. These functions are for
15745: handlers to store a perl hash to a user's permanent data space in an
15746: easy manner, and to retrieve it again on another call. It is expected
15747: that a handler would use this once at the beginning to retrieve data,
15748: and then again once at the end to send only the new data back.
15749: 
15750: The data is stored in the user's data directory on the user's
15751: homeserver under the ID of the course.
15752: 
15753: The hash that is returned by restore will have all of the previous
15754: value for all of the elements of the hash.
15755: 
15756: Example:
15757: 
15758:  #creating a hash
15759:  my %hash;
15760:  $hash{'foo'}='bar';
15761: 
15762:  #storing it
15763:  &Apache::lonnet::cstore(\%hash);
15764: 
15765:  #changing a value
15766:  $hash{'foo'}='notbar';
15767: 
15768:  #adding a new value
15769:  $hash{'bar'}='foo';
15770:  &Apache::lonnet::cstore(\%hash);
15771: 
15772:  #retrieving the hash
15773:  my %history=&Apache::lonnet::restore();
15774: 
15775:  #print the hash
15776:  foreach my $key (sort(keys(%history))) {
15777:    print("\%history{$key} = $history{$key}");
15778:  }
15779: 
15780: Will print out:
15781: 
15782:  %history{1:foo} = bar
15783:  %history{1:keys} = foo:timestamp
15784:  %history{1:timestamp} = 990455579
15785:  %history{2:bar} = foo
15786:  %history{2:foo} = notbar
15787:  %history{2:keys} = foo:bar:timestamp
15788:  %history{2:timestamp} = 990455580
15789:  %history{bar} = foo
15790:  %history{foo} = notbar
15791:  %history{timestamp} = 990455580
15792:  %history{version} = 2
15793: 
15794: Note that the special hash entries C<keys>, C<version> and
15795: C<timestamp> were added to the hash. C<version> will be equal to the
15796: total number of versions of the data that have been stored. The
15797: C<timestamp> attribute will be the UNIX time the hash was
15798: stored. C<keys> is available in every historical section to list which
15799: keys were added or changed at a specific historical revision of a
15800: hash.
15801: 
15802: B<Warning>: do not store the hash that restore returns directly. This
15803: will cause a mess since it will restore the historical keys as if the
15804: were new keys. I.E. 1:foo will become 1:1:foo etc.
15805: 
15806: Calling convention:
15807: 
15808:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15809:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15810: 
15811: For more detailed information, see lonnet specific documentation.
15812: 
15813: =head1 RETURN MESSAGES
15814: 
15815: =over 4
15816: 
15817: =item * B<con_lost>: unable to contact remote host
15818: 
15819: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15820: when the connection is brought back up
15821: 
15822: =item * B<con_failed>: unable to contact remote host and unable to save message
15823: for later delivery
15824: 
15825: =item * B<error:>: an error a occurred, a description of the error follows the :
15826: 
15827: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15828: that was requested
15829: 
15830: =back
15831: 
15832: =head1 PUBLIC SUBROUTINES
15833: 
15834: =head2 Session Environment Functions
15835: 
15836: =over 4
15837: 
15838: =item * 
15839: X<appenv()>
15840: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15841: the user envirnoment file, and will be restored for each access this
15842: user makes during this session, also modifies the %env for the current
15843: process. Optional rolesarrayref - if defined contains a reference to an array
15844: of roles which are exempt from the restriction on modifying user.role entries 
15845: in the user's environment.db and in %env.    
15846: 
15847: =item *
15848: X<delenv()>
15849: B<delenv($delthis,$regexp)>: removes all items from the session
15850: environment file that begin with $delthis. If the 
15851: optional second arg - $regexp - is true, $delthis is treated as a 
15852: regular expression, otherwise \Q$delthis\E is used. 
15853: The values are also deleted from the current processes %env.
15854: 
15855: =item * get_env_multiple($name) 
15856: 
15857: gets $name from the %env hash, it seemlessly handles the cases where multiple
15858: values may be defined and end up as an array ref.
15859: 
15860: returns an array of values
15861: 
15862: =back
15863: 
15864: =head2 User Information
15865: 
15866: =over 4
15867: 
15868: =item *
15869: X<queryauthenticate()>
15870: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15871: authentication scheme
15872: 
15873: =item *
15874: X<authenticate()>
15875: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15876: authenticate user from domain's lib servers (first use the current
15877: one). C<$upass> should be the users password.
15878: $checkdefauth is optional (value is 1 if a check should be made to
15879:    authenticate user using default authentication method, and allow
15880:    account creation if username does not have account in the domain).
15881: $clientcancheckhost is optional (value is 1 if checking whether the
15882:    server can host will occur on the client side in lonauth.pm).   
15883: 
15884: =item *
15885: X<homeserver()>
15886: B<homeserver($uname,$udom)>: find the server which has
15887: the user's directory and files (there must be only one), this caches
15888: the answer, and also caches if there is a borken connection.
15889: 
15890: =item *
15891: X<idget()>
15892: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15893: a list of student/employee IDs or clicker IDs
15894: (student/employee IDs are a unique resource in a domain, there must be 
15895: only 1 ID per username, and only 1 username per ID in a specific domain).
15896: clickerIDs are not necessarily unique, as students might share clickers.
15897: (returns hash: id=>name,id=>name)
15898: 
15899: =item *
15900: X<idrget()>
15901: B<idrget($udom,@unames)>: find the IDs behind a list of
15902: usernames (returns hash: name=>id,name=>id)
15903: 
15904: =item *
15905: X<idput()>
15906: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15907: names and associated student/employee IDs or clicker IDs.
15908: 
15909: =item *
15910: X<iddel()>
15911: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15912: student/employee ID or clicker ID username look-ups from domain.
15913: The homeserver ($uhome) and namespace ($namespace) are optional.
15914: If no $uhome is provided, it will be determined usig &homeserver()
15915: for each user.  If no $namespace is provided, the default is ids.
15916: 
15917: =item *
15918: X<updateclickers()>
15919: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15920: clicker ID-to-username look-ups in clickers.db on library server.
15921: Permitted actions are add or del (i.e., add or delete). The 
15922: clickers.db contains clickerID as keys (escaped), and each corresponding
15923: value is an escaped comma-separated list of usernames (for whom the
15924: library server is the homeserver), who registered that particular ID.
15925: If $critical is true, the update will be sent via &critical, otherwise
15926: &reply() will be used.
15927: 
15928: =item *
15929: X<rolesinit()>
15930: B<rolesinit($udom,$username)>: get user privileges.
15931: returns user role, first access and timer interval hashes
15932: 
15933: =item *
15934: X<privileged()>
15935: B<privileged($username,$domain)>: returns a true if user has a
15936: privileged and active role (i.e. su or dc), false otherwise.
15937: 
15938: =item *
15939: X<getsection()>
15940: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15941: course $cname, return section name/number or '' for "not in course"
15942: and '-1' for "no section"
15943: 
15944: =item *
15945: X<userenvironment()>
15946: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15947: passed in @what from the requested user's environment, returns a hash
15948: 
15949: =item * 
15950: X<userlog_query()>
15951: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15952: activity.log file. %filters defines filters applied when parsing the
15953: log file. These can be start or end timestamps, or the type of action
15954: - log to look for Login or Logout events, check for Checkin or
15955: Checkout, role for role selection. The response is in the form
15956: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15957: escaped strings of the action recorded in the activity.log file.
15958: 
15959: =back
15960: 
15961: =head2 User Roles
15962: 
15963: =over 4
15964: 
15965: =item *
15966: 
15967: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15968: returns codes for allowed actions.
15969: 
15970: The first argument is required, all others are optional.
15971: 
15972: $priv is the privilege being checked.
15973: $uri contains additional information about what is being checked for access (e.g.,
15974: URL, course ID etc.). 
15975: $symb is the unique resource instance identifier in a course; if needed,
15976: but not provided, it will be retrieved via a call to &symbread(). 
15977: $role is the role for which a priv is being checked (only used if priv is evb). 
15978: $clientip is the user's IP address (only used when checking for access to portfolio 
15979: files).
15980: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15981: prevents recursive calls to &allowed.
15982: 
15983:  F: full access
15984:  U,I,K: authentication modes (cxx only)
15985:  '': forbidden
15986:  1: user needs to choose course
15987:  2: browse allowed
15988:  A: passphrase authentication needed
15989:  B: access temporarily blocked because of a blocking event in a course.
15990:  D: access blocked because access is required via session initiated via deep-link 
15991: 
15992: =item *
15993: 
15994: constructaccess($url,$setpriv) : check for access to construction space URL
15995: 
15996: See if the owner domain and name in the URL match those in the
15997: expected environment.  If so, return three element list
15998: ($ownername,$ownerdomain,$ownerhome).
15999: 
16000: Otherwise return the null string.
16001: 
16002: If second argument 'setpriv' is true, it assigns the privileges,
16003: and returns the same three element list, unless the owner has
16004: blocked "ad hoc" Domain Coordinator access to the Author Space,
16005: in which case the null string is returned.
16006: 
16007: =item *
16008: 
16009: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16010: define a custom role rolename set privileges in format of lonTabs/roles.tab
16011: for system, domain, and course level. $uname and $udom are optional (current
16012: user's username and domain will be used when either of $uname or $udom are absent.
16013: 
16014: =item *
16015: 
16016: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16017: (rolesplain.tab); plain text explanation of a user role term.
16018: $type is Course (default) or Community.
16019: If $forcedefault evaluates to true, text returned will be default 
16020: text for $type. Otherwise, if this is a course, the text returned 
16021: will be a custom name for the role (if defined in the course's 
16022: environment).  If no custom name is defined the default is returned.
16023:    
16024: =item *
16025: 
16026: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16027: All arguments are optional. Returns a hash of a roles, either for
16028: co-author/assistant author roles for a user's Construction Space
16029: (default), or if $context is 'userroles', roles for the user himself,
16030: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16031: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16032: For each key, value is set to colon-separated start and end times for
16033: the role.  If no username and domain are specified, will default to
16034: current user/domain. Types, roles, and roledoms are references to arrays
16035: of role statuses (active, future or previous), roles 
16036: (e.g., cc,in, st etc.) and domains of the roles which can be used
16037: to restrict the list of roles reported. If no array ref is 
16038: provided for types, will default to return only active roles.
16039: 
16040: =item *
16041: 
16042: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16043: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16044: 
16045: Additional optional arguments are: $type (if role checking is to be restricted 
16046: to certain user status types -- previous (expired roles), active (currently
16047: available roles) or future (roles available in the future), and
16048: $hideprivileged -- if true will not report course roles for users who
16049: have active Domain Coordinator role in course's domain or in additional
16050: domains (specified in 'Domains to check for privileged users' in course
16051: environment -- set via:  Course Settings -> Classlists and staff listing).
16052: 
16053: =item *
16054: 
16055: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16056: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16057: $possdomains and $possroles are optional array refs -- to domains to check and
16058: roles to check.  If $possdomains is not specified, a dump will be done of the
16059: users' roles.db to check for a dc or su role in any domain. This can be
16060: time consuming if &privileged is called repeatedly (e.g., when displaying a
16061: classlist), so in such cases, supplying a $possdomains array is preferred, as
16062: this then allows &privileged_by_domain() to be used, which caches the identity
16063: of privileged users, eliminating the need for repeated calls to &dump().
16064: 
16065: =item *
16066: 
16067: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16068: where the outer hash keys are domains specified in the $possdomains array ref,
16069: next inner hash keys are privileged roles specified in the $roles array ref,
16070: and the innermost hash contains key = value pairs for username:domain = end:start
16071: for active or future "privileged" users with that role in that domain. To avoid
16072: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16073: innerhash are cached using priv_$role and $dom as the identifiers.
16074: 
16075: =back
16076: 
16077: =head2 User Modification
16078: 
16079: =over 4
16080: 
16081: =item *
16082: 
16083: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16084: user for the level given by URL.  Optional start and end dates (leave empty
16085: string or zero for "no date")
16086: 
16087: =item *
16088: 
16089: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16090: change a users, password, possible return values are: ok,
16091: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16092: refused
16093: 
16094: =item *
16095: 
16096: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16097: 
16098: =item *
16099: 
16100: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16101:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16102: 
16103: will update user information (firstname,middlename,lastname,generation,
16104: permanentemail), and if forceid is true, student/employee ID also.
16105: A user's institutional affiliation(s) can also be updated.
16106: User information fields will not be overwritten with empty entries 
16107: unless the field is included in the $candelete array reference.
16108: This array is included when a single user is modified via "Manage Users",
16109: or when Autoupdate.pl is run by cron in a domain.
16110: 
16111: =item *
16112: 
16113: modifystudent
16114: 
16115: modify a student's enrollment and identification information.
16116: The course id is resolved based on the current user's environment.  
16117: This means the invoking user must be a course coordinator or otherwise
16118: associated with a course.
16119: 
16120: This call is essentially a wrapper for lonnet::modifyuser and
16121: lonnet::modify_student_enrollment
16122: 
16123: Inputs: 
16124: 
16125: =over 4
16126: 
16127: =item B<$udom> Student's loncapa domain
16128: 
16129: =item B<$uname> Student's loncapa login name
16130: 
16131: =item B<$uid> Student/Employee ID
16132: 
16133: =item B<$umode> Student's authentication mode
16134: 
16135: =item B<$upass> Student's password
16136: 
16137: =item B<$first> Student's first name
16138: 
16139: =item B<$middle> Student's middle name
16140: 
16141: =item B<$last> Student's last name
16142: 
16143: =item B<$gene> Student's generation
16144: 
16145: =item B<$usec> Student's section in course
16146: 
16147: =item B<$end> Unix time of the roles expiration
16148: 
16149: =item B<$start> Unix time of the roles start date
16150: 
16151: =item B<$forceid> If defined, allow $uid to be changed
16152: 
16153: =item B<$desiredhome> server to use as home server for student
16154: 
16155: =item B<$email> Student's permanent e-mail address
16156: 
16157: =item B<$type> Type of enrollment (auto or manual)
16158: 
16159: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16160: 
16161: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16162: 
16163: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16164: 
16165: =item B<$context> role change context (shown in User Management Logs display in a course)
16166: 
16167: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16168: 
16169: =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.
16170: 
16171: =back
16172: 
16173: =item *
16174: 
16175: modify_student_enrollment
16176: 
16177: Change a student's enrollment status in a class.  The environment variable
16178: 'role.request.course' must be defined for this function to proceed.
16179: 
16180: Inputs:
16181: 
16182: =over 4
16183: 
16184: =item $udom, student's domain
16185: 
16186: =item $uname, student's name
16187: 
16188: =item $uid, student's user id
16189: 
16190: =item $first, student's first name
16191: 
16192: =item $middle
16193: 
16194: =item $last
16195: 
16196: =item $gene
16197: 
16198: =item $usec
16199: 
16200: =item $end
16201: 
16202: =item $start
16203: 
16204: =item $type
16205: 
16206: =item $locktype
16207: 
16208: =item $cid
16209: 
16210: =item $selfenroll
16211: 
16212: =item $context
16213: 
16214: =item $credits, number of credits student will earn from this class
16215: 
16216: =item $instsec, institutional course section code for student
16217: 
16218: =back
16219: 
16220: 
16221: =item *
16222: 
16223: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16224: custom role; give a custom role to a user for the level given by URL.  Specify
16225: name and domain of role author, and role name
16226: 
16227: =item *
16228: 
16229: revokerole($udom,$uname,$url,$role) : revoke a role for url
16230: 
16231: =item *
16232: 
16233: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16234: 
16235: =back
16236: 
16237: =head2 Course Infomation
16238: 
16239: =over 4
16240: 
16241: =item *
16242: 
16243: coursedescription($courseid,$options) : returns a hash of information about the
16244: specified course id, including all environment settings for the
16245: course, the description of the course will be in the hash under the
16246: key 'description'
16247: 
16248: $options is an optional parameter that if supplied is a hash reference that controls
16249: what how this function works.  It has the following key/values:
16250: 
16251: =over 4
16252: 
16253: =item freshen_cache
16254: 
16255: If defined, and the environment cache for the course is valid, it is 
16256: returned in the returned hash.
16257: 
16258: =item one_time
16259: 
16260: If defined, the last cache time is set to _now_
16261: 
16262: =item user
16263: 
16264: If defined, the supplied username is used instead of the current user.
16265: 
16266: 
16267: =back
16268: 
16269: =item *
16270: 
16271: resdata($name,$domain,$type,@which) : request for current parameter
16272: setting for a specific $type, where $type is either 'course' or 'user',
16273: @what should be a list of parameters to ask about. This routine caches
16274: answers for 10 minutes.
16275: 
16276: =item *
16277: 
16278: get_courseresdata($courseid, $domain) : dump the entire course resource
16279: data base, returning a hash that is keyed by the resource name and has
16280: values that are the resource value.  I believe that the timestamps and
16281: versions are also returned.
16282: 
16283: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16284: supplemental content area. This routine caches the number of files for 
16285: 10 minutes.
16286: 
16287: =back
16288: 
16289: =head2 Course Modification
16290: 
16291: =over 4
16292: 
16293: =item *
16294: 
16295: writecoursepref($courseid,%prefs) : write preferences (environment
16296: database) for a course
16297: 
16298: =item *
16299: 
16300: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16301: 
16302: =item *
16303: 
16304: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16305: 
16306: =item *
16307: 
16308: is_course($courseid), is_course($cdom, $cnum)
16309: 
16310: Accepts either a combined $courseid (in the form of domain_courseid) or the
16311: two component version $cdom, $cnum. It checks if the specified course exists.
16312: 
16313: Returns:
16314:     undef if the course doesn't exist, otherwise
16315:     in scalar context the combined courseid.
16316:     in list context the two components of the course identifier, domain and 
16317:     courseid.    
16318: 
16319: =back
16320: 
16321: =head2 Bubblesheet Configuration
16322: 
16323: =over 4
16324: 
16325: =item *
16326: 
16327: get_scantron_config($which)
16328: 
16329: $which - the name of the configuration to parse from the file.
16330: 
16331: Parses and returns the bubblesheet configuration line selected as a
16332: hash of configuration file fields.
16333: 
16334: 
16335: Returns:
16336:     If the named configuration is not in the file, an empty
16337:     hash is returned.
16338: 
16339:     a hash with the fields
16340:       name         - internal name for the this configuration setup
16341:       description  - text to display to operator that describes this config
16342:       CODElocation - if 0 or the string 'none'
16343:                           - no CODE exists for this config
16344:                      if -1 || the string 'letter'
16345:                           - a CODE exists for this config and is
16346:                             a string of letters
16347:                      Unsupported value (but planned for future support)
16348:                           if a positive integer
16349:                                - The CODE exists as the first n items from
16350:                                  the question section of the form
16351:                           if the string 'number'
16352:                                - The CODE exists for this config and is
16353:                                  a string of numbers
16354:       CODEstart   - (only matter if a CODE exists) column in the line where
16355:                      the CODE starts
16356:       CODElength  - length of the CODE
16357:       IDstart     - column where the student/employee ID starts
16358:       IDlength    - length of the student/employee ID info
16359:       Qstart      - column where the information from the bubbled
16360:                     'questions' start
16361:       Qlength     - number of columns comprising a single bubble line from
16362:                     the sheet. (usually either 1 or 10)
16363:       Qon         - either a single character representing the character used
16364:                     to signal a bubble was chosen in the positional setup, or
16365:                     the string 'letter' if the letter of the chosen bubble is
16366:                     in the final, or 'number' if a number representing the
16367:                     chosen bubble is in the file (1->A 0->J)
16368:       Qoff        - the character used to represent that a bubble was
16369:                     left blank
16370:       PaperID     - if the scanning process generates a unique number for each
16371:                     sheet scanned the column that this ID number starts in
16372:       PaperIDlength - number of columns that comprise the unique ID number
16373:                       for the sheet of paper
16374:       FirstName   - column that the first name starts in
16375:       FirstNameLength - number of columns that the first name spans
16376:       LastName    - column that the last name starts in
16377:       LastNameLength - number of columns that the last name spans
16378:       BubblesPerRow - number of bubbles available in each row used to
16379:                       bubble an answer. (If not specified, 10 assumed).
16380: 
16381: 
16382: =item *
16383: 
16384: get_scantronformat_file($cdom)
16385: 
16386: $cdom - the course's domain (optional); if not supplied, uses
16387: domain for current $env{'request.course.id'}.
16388: 
16389: Returns an array containing lines from the scantron format file for
16390: the domain of the course.
16391: 
16392: If a url for a custom.tab file is listed in domain's configuration.db,
16393: lines are from this file.
16394: 
16395: Otherwise, if a default.tab has been published in RES space by the
16396: domainconfig user, lines are from this file.
16397: 
16398: Otherwise, fall back to getting lines from the legacy file on the
16399: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16400: 
16401: =back
16402: 
16403: =head2 Resource Subroutines
16404: 
16405: =over 4
16406: 
16407: =item *
16408: 
16409: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16410: 
16411: =item *
16412: 
16413: repcopy($filename) : subscribes to the requested file, and attempts to
16414: replicate from the owning library server, Might return
16415: 'unavailable', 'not_found', 'forbidden', 'ok', or
16416: 'bad_request', also attempts to grab the metadata for the
16417: resource. Expects the local filesystem pathname
16418: (/home/httpd/html/res/....)
16419: 
16420: =back
16421: 
16422: =head2 Resource Information
16423: 
16424: =over 4
16425: 
16426: =item *
16427: 
16428: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16429: and returns the value of a variety of different possible values,
16430: $varname should be a request string, and the other parameters can be
16431: used to specify who and what one is asking about. Ordinarily, $cid 
16432: does not need to be specified, as it is retrived from 
16433: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16434: within lonuserstate::loadmap() when initializing a course, before
16435: $env{'request.course.id'} has been set, so it needs to be provided
16436: in that one case.
16437: 
16438: Possible values for $varname are environment.lastname (or other item
16439: from the envirnment hash), user.name (or someother aspect about the
16440: user), resource.0.maxtries (or some other part and parameter of a
16441: resource)
16442: 
16443: =item *
16444: 
16445: directcondval($number) : get current value of a condition; reads from a state
16446: string
16447: 
16448: =item *
16449: 
16450: condval($condidx) : value of condition index based on state
16451: 
16452: =item *
16453: 
16454: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16455: resource's metadata, $what should be either a specific key, or either
16456: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16457: packages that this resource currently uses, the last 3 arguments are 
16458: only used internally for recursive metadata.
16459: 
16460: the toolsymb is only used where the uri is for an external tool (for which
16461: the uri as well as the symb are guaranteed to be unique).
16462: 
16463: this function automatically caches all requests except any made recursively
16464: to retrieve a list of metadata keys for an imported library file ($liburi is 
16465: defined).
16466: 
16467: =item *
16468: 
16469: metadata_query($query,$custom,$customshow) : make a metadata query against the
16470: network of library servers; returns file handle of where SQL and regex results
16471: will be stored for query
16472: 
16473: =item *
16474: 
16475: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16476: return symbolic list entry (all arguments optional). 
16477: 
16478: Args: filename is the filename (including path) for the file for which a symb 
16479: is required; donotrecurse, if true will prevent calls to allowed() being made 
16480: to check access status if more than one resource was found in the bighash 
16481: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16482: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16483: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16484: cause possible symbs to be checked to determine if they are subject to content
16485: blocking, if so they will not be included as possible symbs; possibles is a
16486: ref to a hash, which, as a side effect, will be populated with all possible 
16487: symbs (content blocking not tested).
16488:  
16489: returns the data handle
16490: 
16491: =item *
16492: 
16493: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16494: and is a possible symb for the URL in $thisfn, and if is an encrypted
16495: resource that the user accessed using /enc/ returns a 1 on success, 0
16496: on failure, user must be in a course, as it assumes the existence of
16497: the course initial hash, and uses $env('request.course.id'}.  The third
16498: arg is an optional reference to a scalar.  If this arg is passed in the 
16499: call to symbverify, it will be set to 1 if the symb has been set to be 
16500: encrypted; otherwise it will be null.  
16501: 
16502: =item *
16503: 
16504: symbclean($symb) : removes versions numbers from a symb, returns the
16505: cleaned symb
16506: 
16507: =item *
16508: 
16509: is_on_map($uri) : checks if the $uri is somewhere on the current
16510: course map, user must be in a course for it to work.
16511: 
16512: =item *
16513: 
16514: numval($salt) : return random seed value (addend for rndseed)
16515: 
16516: =item *
16517: 
16518: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16519: a random seed, all arguments are optional, if they aren't sent it uses the
16520: environment to derive them. Note: if symb isn't sent and it can't get one
16521: from &symbread it will use the current time as its return value
16522: 
16523: =item *
16524: 
16525: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16526: unfakeable, receipt
16527: 
16528: =item *
16529: 
16530: receipt() : API to ireceipt working off of env values; given out to users
16531: 
16532: =item *
16533: 
16534: countacc($url) : count the number of accesses to a given URL
16535: 
16536: =item *
16537: 
16538: 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
16539: 
16540: =item *
16541: 
16542: 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)
16543: 
16544: =item *
16545: 
16546: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16547: 
16548: =item *
16549: 
16550: devalidate($symb) : devalidate temporary spreadsheet calculations,
16551: forcing spreadsheet to reevaluate the resource scores next time.
16552: 
16553: =item * 
16554: 
16555: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16556: when viewing in course context.
16557: 
16558:  input: six args -- filename (decluttered), course number, course domain,
16559:                     url, symb (if registered) and group (if this is a 
16560:                     group item -- e.g., bulletin board, group page etc.).
16561: 
16562:  output: array of five scalars --
16563:          $cfile -- url for file editing if editable on current server
16564:          $home -- homeserver of resource (i.e., for author if published,
16565:                                           or course if uploaded.).
16566:          $switchserver --  1 if server switch will be needed.
16567:          $forceedit -- 1 if icon/link should be to go to edit mode 
16568:          $forceview -- 1 if icon/link should be to go to view mode
16569: 
16570: =item *
16571: 
16572: is_course_upload($file,$cnum,$cdom)
16573: 
16574: Used in course context to determine if current file was uploaded to 
16575: the course (i.e., would be found in /userfiles/docs on the course's 
16576: homeserver.
16577: 
16578:   input: 3 args -- filename (decluttered), course number and course domain.
16579:   output: boolean -- 1 if file was uploaded.
16580: 
16581: =back
16582: 
16583: =head2 Storing/Retreiving Data
16584: 
16585: =over 4
16586: 
16587: =item *
16588: 
16589: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16590: permanently for this url; hashref needs to be given and should be a \%hashname;
16591: the remaining args aren't required and if they aren't passed or are '' they will
16592: be derived from the env (with the exception of $laststore, which is an 
16593: optional arg used when a user's submission is stored in grading).
16594: $laststore is $version=$timestamp, where $version is the most recent version
16595: number retrieved for the corresponding $symb in the $namespace db file, and
16596: $timestamp is the timestamp for that transaction (UNIX time).
16597: $laststore is currently only passed when cstore() is called by 
16598: structuretags::finalize_storage().
16599: 
16600: =item *
16601: 
16602: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16603: but uses critical subroutine
16604: 
16605: =item *
16606: 
16607: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16608: all args are optional
16609: 
16610: =item *
16611: 
16612: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16613: dumps the complete (or key matching regexp) namespace into a hash
16614: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16615: normally &store()ed into
16616: 
16617: $range should be either an integer '100' (give me the first 100
16618:                                            matching records)
16619:               or be  two integers sperated by a - with no spaces
16620:                  '30-50' (give me the 30th through the 50th matching
16621:                           records)
16622: 
16623: 
16624: =item *
16625: 
16626: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16627: replaces a &store() version of data with a replacement set of data
16628: for a particular resource in a namespace passed in the $storehash hash 
16629: reference. If $tolog is true, the transaction is logged in the courselog
16630: with an action=PUTSTORE.
16631: 
16632: =item *
16633: 
16634: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16635: works very similar to store/cstore, but all data is stored in a
16636: temporary location and can be reset using tmpreset, $storehash should
16637: be a hash reference, returns nothing on success
16638: 
16639: =item *
16640: 
16641: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16642: similar to restore, but all data is stored in a temporary location and
16643: can be reset using tmpreset. Returns a hash of values on success,
16644: error string otherwise.
16645: 
16646: =item *
16647: 
16648: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16649: deltes all keys for $symb form the temporary storage hash.
16650: 
16651: =item *
16652: 
16653: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16654: reference filled in from namesp ($udom and $uname are optional)
16655: 
16656: =item *
16657: 
16658: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16659: namesp ($udom and $uname are optional)
16660: 
16661: =item *
16662: 
16663: dump($namespace,$udom,$uname,$regexp,$range) : 
16664: dumps the complete (or key matching regexp) namespace into a hash
16665: ($udom, $uname, $regexp, $range are optional)
16666: 
16667: $range should be either an integer '100' (give me the first 100
16668:                                            matching records)
16669:               or be  two integers sperated by a - with no spaces
16670:                  '30-50' (give me the 30th through the 50th matching
16671:                           records)
16672: =item *
16673: 
16674: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16675: $store can be a scalar, an array reference, or if the amount to be 
16676: incremented is > 1, a hash reference.
16677: 
16678: ($udom and $uname are optional)
16679: 
16680: =item *
16681: 
16682: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16683: ($udom and $uname are optional)
16684: 
16685: =item *
16686: 
16687: cput($namespace,$storehash,$udom,$uname) : critical put
16688: ($udom and $uname are optional)
16689: 
16690: =item *
16691: 
16692: newput($namespace,$storehash,$udom,$uname) :
16693: 
16694: Attempts to store the items in the $storehash, but only if they don't
16695: currently exist, if this succeeds you can be certain that you have 
16696: successfully created a new key value pair in the $namespace db.
16697: 
16698: 
16699: Args:
16700:  $namespace: name of database to store values to
16701:  $storehash: hashref to store to the db
16702:  $udom: (optional) domain of user containing the db
16703:  $uname: (optional) name of user caontaining the db
16704: 
16705: Returns:
16706:  'ok' -> succeeded in storing all keys of $storehash
16707:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16708:                         least <key> already existed in the db (other
16709:                         requested keys may also already exist)
16710:  'error: <msg>' -> unable to tie the DB or other error occurred
16711:  'con_lost' -> unable to contact request server
16712:  'refused' -> action was not allowed by remote machine
16713: 
16714: 
16715: =item *
16716: 
16717: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16718: reference filled in from namesp (encrypts the return communication)
16719: ($udom and $uname are optional)
16720: 
16721: =item *
16722: 
16723: log($udom,$name,$home,$message) : write to permanent log for user; use
16724: critical subroutine
16725: 
16726: =item *
16727: 
16728: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16729: array reference filled in from namespace found in domain level on either
16730: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16731: 
16732: =item *
16733: 
16734: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16735: domain level either on specified domain server ($uhome) or primary domain 
16736: server ($udom and $uhome are optional)
16737: 
16738: =item * 
16739: 
16740: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16741: for: authentication, language, quotas, timezone, date locale, and portal URL in
16742: the target domain.
16743: 
16744: May also include additional key => value pairs for the following groups:
16745: 
16746: =over
16747: 
16748: =item
16749: disk quotas (MB allocated by default to portfolios and authoring spaces).
16750: 
16751: =over
16752: 
16753: =item defaultquota, authorquota
16754: 
16755: =back
16756: 
16757: =item
16758: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16759: portfolio for users).
16760: 
16761: =over
16762: 
16763: =item
16764: aboutme, blog, webdav, portfolio
16765: 
16766: =back
16767: 
16768: =item
16769: requestcourses: ability to request courses, and how requests are processed.
16770: 
16771: =over
16772: 
16773: =item
16774: official, unofficial, community, textbook, placement
16775: 
16776: =back
16777: 
16778: =item
16779: inststatus: types of institutional affiliation, and order in which they are displayed.
16780: 
16781: =over
16782: 
16783: =item
16784: inststatustypes, inststatusorder, inststatusguest
16785: 
16786: =back
16787: 
16788: =item
16789: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16790: for course's uploaded content.
16791: 
16792: =over
16793: 
16794: =item
16795: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16796: communityquota, textbookquota, placementquota
16797: 
16798: =back
16799: 
16800: =item
16801: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16802: on your servers.
16803: 
16804: =over
16805: 
16806: =item 
16807: remotesessions, hostedsessions
16808: 
16809: =back
16810: 
16811: =back
16812: 
16813: In cases where a domain coordinator has never used the "Set Domain Configuration"
16814: utility to create a configuration.db file on a domain's primary library server 
16815: only the following domain defaults: auth_def, auth_arg_def, lang_def
16816: -- corresponding values are authentication type (internal, krb4, krb5,
16817: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16818: will be available. Values are retrieved from cache (if current), unless the
16819: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16820: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16821: 
16822: Typical usage:
16823: 
16824: %domdefaults = &get_domain_defaults($target_domain);
16825: 
16826: =back
16827: 
16828: =head2 Network Status Functions
16829: 
16830: =over 4
16831: 
16832: =item *
16833: 
16834: dirlist() : return directory list based on URI (first arg).
16835: 
16836: Inputs: 1 required, 5 optional.
16837: 
16838: =over
16839: 
16840: =item 
16841: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16842: 
16843: =item
16844: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16845: 
16846: =item
16847: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16848: 
16849: =item
16850: $getpropath - boolean: 1 if prepend path using &propath(). 
16851: 
16852: =item
16853: $getuserdir - boolean: 1 if prepend path for "userfiles".
16854: 
16855: =item 
16856: $alternateRoot - path to prepend in place of path from $uri.
16857: 
16858: =back
16859: 
16860: Returns: Array of up to two items.
16861: 
16862: =over
16863: 
16864: a reference to an array of files/subdirectories
16865: 
16866: =over
16867: 
16868: Each element in the array of files/subdirectories is a & separated list of
16869: item name and the result of running stat on the item.  If dirlist was requested
16870: for a file instead of a directory, the item name will be ''. For a directory 
16871: listing, if the item is a metadata file, the element will end &N&M 
16872: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16873: default copyright set (1).  
16874: 
16875: =back
16876: 
16877: a scalar containing error condition (if encountered).
16878: 
16879: =over
16880: 
16881: =item 
16882: no_host (no homeserver identified for $username:$domain).
16883: 
16884: =item 
16885: no_such_host (server contacted for listing not identified as valid host).
16886: 
16887: =item 
16888: con_lost (connection to remote server failed).
16889: 
16890: =item 
16891: refused (invalid $username:$domain received on lond side).
16892: 
16893: =item 
16894: no_such_dir (directory at specified path on lond side does not exist). 
16895: 
16896: =item 
16897: empty (directory at specified path on lond side is empty).
16898: 
16899: =over
16900: 
16901: This is currently not encountered because the &ls3, &ls2, 
16902: &ls (_handler) routines on the lond side do not filter out
16903: . and .. from a directory listing. 
16904: 
16905: =back
16906: 
16907: =back
16908: 
16909: =back
16910: 
16911: =item *
16912: 
16913: spareserver() : find server with least workload from spare.tab
16914: 
16915: 
16916: =item *
16917: 
16918: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16919: if there is no corresponding loncapa host.
16920: 
16921: =back
16922: 
16923: 
16924: =head2 Apache Request
16925: 
16926: =over 4
16927: 
16928: =item *
16929: 
16930: ssi($url,%hash) : server side include, does a complete request cycle on url to
16931: localhost, posts hash
16932: 
16933: =back
16934: 
16935: =head2 Data to String to Data
16936: 
16937: =over 4
16938: 
16939: =item *
16940: 
16941: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16942: and '&' separators, supports elements that are arrayrefs and hashrefs
16943: 
16944: =item *
16945: 
16946: hashref2str($hashref) : convert a hashref into a string complete with
16947: escaping and '=' and '&' separators, supports elements that are
16948: arrayrefs and hashrefs
16949: 
16950: =item *
16951: 
16952: arrayref2str($arrayref) : convert an arrayref into a string complete
16953: with escaping and '&' separators, supports elements that are arrayrefs
16954: and hashrefs
16955: 
16956: =item *
16957: 
16958: str2hash($string) : convert string to hash using unescaping and
16959: splitting on '=' and '&', supports elements that are arrayrefs and
16960: hashrefs
16961: 
16962: =item *
16963: 
16964: str2array($string) : convert string to hash using unescaping and
16965: splitting on '&', supports elements that are arrayrefs and hashrefs
16966: 
16967: =back
16968: 
16969: =head2 Logging Routines
16970: 
16971: 
16972: These routines allow one to make log messages in the lonnet.log and
16973: lonnet.perm logfiles.
16974: 
16975: =over 4
16976: 
16977: =item *
16978: 
16979: logtouch() : make sure the logfile, lonnet.log, exists
16980: 
16981: =item *
16982: 
16983: logthis() : append message to the normal lonnet.log file, it gets
16984: preiodically rolled over and deleted.
16985: 
16986: =item *
16987: 
16988: logperm() : append a permanent message to lonnet.perm.log, this log
16989: file never gets deleted by any automated portion of the system, only
16990: messages of critical importance should go in here.
16991: 
16992: 
16993: =back
16994: 
16995: =head2 General File Helper Routines
16996: 
16997: =over 4
16998: 
16999: =item *
17000: 
17001: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17002: (a) files in /uploaded
17003:   (i) If a local copy of the file exists - 
17004:       compares modification date of local copy with last-modified date for 
17005:       definitive version stored on home server for course. If local copy is 
17006:       stale, requests a new version from the home server and stores it. 
17007:       If the original has been removed from the home server, then local copy 
17008:       is unlinked.
17009:   (ii) If local copy does not exist -
17010:       requests the file from the home server and stores it. 
17011:   
17012:   If $caller is 'uploadrep':  
17013:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17014:     for request for files originally uploaded via DOCS. 
17015:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17016:   
17017:   Otherwise:
17018:      This indicates a call from the content generation phase of the request.
17019:      -  returns the entire contents of the file or -1.
17020:      
17021: (b) files in /res
17022:    - returns the entire contents of a file or -1; 
17023:    it properly subscribes to and replicates the file if neccessary.
17024: 
17025: 
17026: =item *
17027: 
17028: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17029:                   reference
17030: 
17031: returns either a stat() list of data about the file or an empty list
17032: if the file doesn't exist or couldn't find out about it (connection
17033: problems or user unknown)
17034: 
17035: =item *
17036: 
17037: filelocation($dir,$file) : returns file system location of a file
17038: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17039: directory that relative $file lookups are to looked in ($dir of /a/dir
17040: and a file of ../bob will become /a/bob)
17041: 
17042: =item *
17043: 
17044: hreflocation($dir,$file) : returns file system location or a URL; same as
17045: filelocation except for hrefs
17046: 
17047: =item *
17048: 
17049: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17050: also removes beginning /home/httpd/html unless /priv/ follows it.
17051: 
17052: =back
17053: 
17054: =head2 Usererfile file routines (/uploaded*)
17055: 
17056: =over 4
17057: 
17058: =item *
17059: 
17060: userfileupload(): main rotine for putting a file in a user or course's
17061:                   filespace, arguments are,
17062: 
17063:  formname - required - this is the name of the element in $env where the
17064:            filename, and the contents of the file to create/modifed exist
17065:            the filename is in $env{'form.'.$formname.'.filename'} and the
17066:            contents of the file is located in $env{'form.'.$formname}
17067:  context - if coursedoc, store the file in the course of the active role
17068:              of the current user; 
17069:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17070:            if 'canceloverwrite': delete file in tmp/overwrites directory
17071:  subdir - required - subdirectory to put the file in under ../userfiles/
17072:          if undefined, it will be placed in "unknown"
17073: 
17074:  (This routine calls clean_filename() to remove any dangerous
17075:  characters from the filename, and then calls finuserfileupload() to
17076:  complete the transaction)
17077: 
17078:  returns either the url of the uploaded file (/uploaded/....) if successful
17079:  and /adm/notfound.html if unsuccessful
17080: 
17081: =item *
17082: 
17083: clean_filename(): routine for cleaing a filename up for storage in
17084:                  userfile space, argument is:
17085: 
17086:  filename - proposed filename
17087: 
17088: returns: the new clean filename
17089: 
17090: =item *
17091: 
17092: finishuserfileupload(): routine that creates and sends the file to
17093: userspace, probably shouldn't be called directly
17094: 
17095:   docuname: username or courseid of destination for the file
17096:   docudom: domain of user/course of destination for the file
17097:   formname: same as for userfileupload()
17098:   fname: filename (including subdirectories) for the file
17099:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17100:           if hashref, and context is scantron, will convert csv format to standard format
17101:   allfiles: reference to hash used to store objects found by parser
17102:   codebase: reference to hash used for codebases of java objects found by parser
17103:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17104:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17105:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17106:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17107:   context: if 'overwrite', will move the uploaded file from its temporary location to
17108:             userfiles to facilitate overwriting a previously uploaded file with same name.
17109:   mimetype: reference to scalar to accommodate mime type determined
17110:             from File::MMagic if $parser = parse.
17111: 
17112:  returns either the url of the uploaded file (/uploaded/....) if successful
17113:  and /adm/notfound.html if unsuccessful (or an error message if context 
17114:  was 'overwrite').
17115:  
17116: 
17117: =item *
17118: 
17119: renameuserfile(): renames an existing userfile to a new name
17120: 
17121:   Args:
17122:    docuname: username or courseid of destination for the file
17123:    docudom: domain of user/course of destination for the file
17124:    old: current file name (including any subdirs under userfiles)
17125:    new: desired file name (including any subdirs under userfiles)
17126: 
17127: =item *
17128: 
17129: mkdiruserfile(): creates a directory is a userfiles dir
17130: 
17131:   Args:
17132:    docuname: username or courseid of destination for the file
17133:    docudom: domain of user/course of destination for the file
17134:    dir: dir to create (including any subdirs under userfiles)
17135: 
17136: =item *
17137: 
17138: removeuserfile(): removes a file that exists in userfiles
17139: 
17140:   Args:
17141:    docuname: username or courseid of destination for the file
17142:    docudom: domain of user/course of destination for the file
17143:    fname: filname to delete (including any subdirs under userfiles)
17144: 
17145: =item *
17146: 
17147: removeuploadedurl(): convience function for removeuserfile()
17148: 
17149:   Args:
17150:    url:  a full /uploaded/... url to delete
17151: 
17152: =item * 
17153: 
17154: get_portfile_permissions():
17155:   Args:
17156:     domain: domain of user or course contain the portfolio files
17157:     user: name of user or num of course contain the portfolio files
17158:   Returns:
17159:     hashref of a dump of the proper file_permissions.db
17160:    
17161: 
17162: =item * 
17163: 
17164: get_access_controls():
17165: 
17166: Args:
17167:   current_permissions: the hash ref returned from get_portfile_permissions()
17168:   group: (optional) the group you want the files associated with
17169:   file: (optional) the file you want access info on
17170: 
17171: Returns:
17172:     a hash (keys are file names) of hashes containing
17173:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17174:         values are XML containing access control settings (see below) 
17175: 
17176: Internal notes:
17177: 
17178:  access controls are stored in file_permissions.db as key=value pairs.
17179:     key -> path to file/file_name\0uniqueID:scope_end_start
17180:         where scope -> public,guest,course,group,domains or users.
17181:               end -> UNIX time for end of access (0 -> no end date)
17182:               start -> UNIX time for start of access
17183: 
17184:     value -> XML description of access control
17185:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17186:             <start></start>
17187:             <end></end>
17188: 
17189:             <password></password>  for scope type = guest
17190: 
17191:             <domain></domain>     for scope type = course or group
17192:             <number></number>
17193:             <roles id="">
17194:              <role></role>
17195:              <access></access>
17196:              <section></section>
17197:              <group></group>
17198:             </roles>
17199: 
17200:             <dom></dom>         for scope type = domains
17201: 
17202:             <users>             for scope type = users
17203:              <user>
17204:               <uname></uname>
17205:               <udom></udom>
17206:              </user>
17207:             </users>
17208:            </scope> 
17209:               
17210:  Access data is also aggregated for each file in an additional key=value pair:
17211:  key -> path to file/file_name\0accesscontrol 
17212:  value -> reference to hash
17213:           hash contains key = value pairs
17214:           where key = uniqueID:scope_end_start
17215:                 value = UNIX time record was last updated
17216: 
17217:           Used to improve speed of look-ups of access controls for each file.  
17218:  
17219:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17220: 
17221: =item *
17222: 
17223: modify_access_controls():
17224: 
17225: Modifies access controls for a portfolio file
17226: Args
17227: 1. file name
17228: 2. reference to hash of required changes,
17229: 3. domain
17230: 4. username
17231:   where domain,username are the domain of the portfolio owner 
17232:   (either a user or a course) 
17233: 
17234: Returns:
17235: 1. result of additions or updates ('ok' or 'error', with error message). 
17236: 2. result of deletions ('ok' or 'error', with error message).
17237: 3. reference to hash of any new or updated access controls.
17238: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17239:    key = integer (inbound ID)
17240:    value = uniqueID
17241: 
17242: =item *
17243: 
17244: get_timebased_id():
17245: 
17246: Attempts to get a unique timestamp-based suffix for use with items added to a 
17247: course via the Course Editor (e.g., folders, composite pages, 
17248: group bulletin boards).
17249: 
17250: Args: (first three required; six others optional)
17251: 
17252: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17253:    docssequence, or name of group
17254: 
17255: 2. keyid (alphanumeric): name of temporary locking key in hash,
17256:    e.g., num, boardids
17257: 
17258: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17259:    file will be named nohist_namespace.db
17260: 
17261: 4. cdom: domain of course; default is current course domain from %env
17262: 
17263: 5. cnum: course number; default is current course number from %env
17264: 
17265: 6. idtype: set to concat if an additional digit is to be appended to the 
17266:    unix timestamp to form the suffix, if the plain timestamp is already
17267:    in use.  Default is to not do this, but simply increment the unix 
17268:    timestamp by 1 until a unique key is obtained.
17269: 
17270: 7. who: holder of locking key; defaults to user:domain for user.
17271: 
17272: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17273:    retrying); default is 3.
17274: 
17275: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17276: 
17277: Returns:
17278: 
17279: 1. suffix obtained (numeric)
17280: 
17281: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17282: 
17283: 3. error: contains (localized) error message if an error occurred.
17284: 
17285: 
17286: =back
17287: 
17288: =head2 HTTP Helper Routines
17289: 
17290: =over 4
17291: 
17292: =item *
17293: 
17294: escape() : unpack non-word characters into CGI-compatible hex codes
17295: 
17296: =item *
17297: 
17298: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17299: 
17300: =back
17301: 
17302: =head1 PRIVATE SUBROUTINES
17303: 
17304: =head2 Underlying communication routines (Shouldn't call)
17305: 
17306: =over 4
17307: 
17308: =item *
17309: 
17310: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17311: 
17312: =item *
17313: 
17314: reply() : uses subreply to send a message to remote machine, logs all failures
17315: 
17316: =item *
17317: 
17318: critical() : passes a critical message to another server; if cannot
17319: get through then place message in connection buffer directory and
17320: returns con_delayed, if incapable of saving message, returns
17321: con_failed
17322: 
17323: =item *
17324: 
17325: reconlonc() : tries to reconnect lonc client processes.
17326: 
17327: =back
17328: 
17329: =head2 Resource Access Logging
17330: 
17331: =over 4
17332: 
17333: =item *
17334: 
17335: flushcourselogs() : flush (save) buffer logs and access logs
17336: 
17337: =item *
17338: 
17339: courselog($what) : save message for course in hash
17340: 
17341: =item *
17342: 
17343: courseacclog($what) : save message for course using &courselog().  Perform
17344: special processing for specific resource types (problems, exams, quizzes, etc).
17345: 
17346: =item *
17347: 
17348: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17349: as a PerlChildExitHandler
17350: 
17351: =back
17352: 
17353: =head2 Other
17354: 
17355: =over 4
17356: 
17357: =item *
17358: 
17359: symblist($mapname,%newhash) : update symbolic storage links
17360: 
17361: =back
17362: 
17363: =cut
17364: 

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