File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1401: download - view: text, annotated - select for diffs
Sun Jan 27 14:40:02 2019 UTC (5 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Uploaded bubblesheet data can consist of comma separated values.
  - Data will be converted to one of formats specified in bubblesheet
    format file, prior to saving in scantron_orig_* file.
  - Domain configuration for bubblesheet data format allows order of
     columns in csv data to be specified.
  - &get_scantronformat_file and &get_scantron_config moved from grades.pm
    to lonnet.pm to facilitate re-use.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1401 2019/01/27 14:40:02 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
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $hostname = &hostname($lonhost);
  315:                     my $protocol = $protocol{$lonhost};
  316:                     $protocol = 'http' if ($protocol ne 'https');
  317:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  318:                     my $request=new HTTP::Request('GET',$url);
  319:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  320:                     unless ($response->is_error()) {
  321:                         my $content = $response->content;
  322:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  323:                             $loncaparev = $1;
  324:                         }
  325:                     }
  326:                 } else {
  327:                     $loncaparev = $loncaparevs{$lonhost};
  328:                 }
  329:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  330:                 $loncaparev = $1;
  331:             }
  332:         }
  333:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  334:     }
  335: }
  336: 
  337: sub get_server_homeID {
  338:     my ($hostname,$ignore_cache,$caller) = @_;
  339:     unless ($ignore_cache) {
  340:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  341:         if (defined($cached)) {
  342:             return $serverhomeID;
  343:         }
  344:     }
  345:     my $cachetime = 12*3600;
  346:     my $serverhomeID;
  347:     if ($caller eq 'loncron') { 
  348:         my @machine_ids = &machine_ids($hostname);
  349:         foreach my $id (@machine_ids) {
  350:             my $response = &reply('serverhomeID',$id);
  351:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  352:                 $serverhomeID = $response;
  353:                 last;
  354:             }
  355:         }
  356:         if ($serverhomeID eq '') {
  357:             $serverhomeID = $machine_ids[-1];
  358:         }
  359:     } else {
  360:         $serverhomeID = $serverhomeIDs{$hostname};
  361:     }
  362:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  363: }
  364: 
  365: sub get_remote_globals {
  366:     my ($lonhost,$whathash,$ignore_cache) = @_;
  367:     my ($result,%returnhash,%whatneeded);
  368:     if (ref($whathash) eq 'HASH') {
  369:         foreach my $what (sort(keys(%{$whathash}))) {
  370:             my $hashid = $lonhost.'-'.$what;
  371:             my ($response,$cached);
  372:             unless ($ignore_cache) {
  373:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  374:             }
  375:             if (defined($cached)) {
  376:                 $returnhash{$what} = $response;
  377:             } else {
  378:                 $whatneeded{$what} = 1;
  379:             }
  380:         }
  381:         if (keys(%whatneeded) == 0) {
  382:             $result = 'ok';
  383:         } else {
  384:             my $requested = &freeze_escape(\%whatneeded);
  385:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  386:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  387:                 ($rep eq 'unknown_cmd')) {
  388:                 $result = $rep;
  389:             } else {
  390:                 $result = 'ok';
  391:                 my @pairs=split(/\&/,$rep);
  392:                 foreach my $item (@pairs) {
  393:                     my ($key,$value)=split(/=/,$item,2);
  394:                     my $what = &unescape($key);
  395:                     my $hashid = $lonhost.'-'.$what;
  396:                     $returnhash{$what}=&thaw_unescape($value);
  397:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  398:                 }
  399:             }
  400:         }
  401:     }
  402:     return ($result,\%returnhash);
  403: }
  404: 
  405: sub remote_devalidate_cache {
  406:     my ($lonhost,$cachekeys) = @_;
  407:     my $items;
  408:     return unless (ref($cachekeys) eq 'ARRAY');
  409:     my $cachestr = join('&',@{$cachekeys});
  410:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  411:     return $response;
  412: }
  413: 
  414: # -------------------------------------------------- Non-critical communication
  415: sub subreply {
  416:     my ($cmd,$server)=@_;
  417:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  418:     #
  419:     #  With loncnew process trimming, there's a timing hole between lonc server
  420:     #  process exit and the master server picking up the listen on the AF_UNIX
  421:     #  socket.  In that time interval, a lock file will exist:
  422: 
  423:     my $lockfile=$peerfile.".lock";
  424:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  425: 	sleep(0.1);
  426:     }
  427:     # At this point, either a loncnew parent is listening or an old lonc
  428:     # or loncnew child is listening so we can connect or everything's dead.
  429:     #
  430:     #   We'll give the connection a few tries before abandoning it.  If
  431:     #   connection is not possible, we'll con_lost back to the client.
  432:     #   
  433:     my $client;
  434:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  435: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  436: 				      Type    => SOCK_STREAM,
  437: 				      Timeout => 10);
  438: 	if ($client) {
  439: 	    last;		# Connected!
  440: 	} else {
  441: 	    &create_connection(&hostname($server),$server);
  442: 	}
  443:         sleep(0.1);	# Try again later if failed connection.
  444:     }
  445:     my $answer;
  446:     if ($client) {
  447: 	print $client "sethost:$server:$cmd\n";
  448: 	$answer=<$client>;
  449: 	if (!$answer) { $answer="con_lost"; }
  450: 	chomp($answer);
  451:     } else {
  452: 	$answer = 'con_lost';	# Failed connection.
  453:     }
  454:     return $answer;
  455: }
  456: 
  457: sub reply {
  458:     my ($cmd,$server)=@_;
  459:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  460:     my $answer=subreply($cmd,$server);
  461:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  462:         my $logged = $cmd;
  463:         if ($cmd =~ /^encrypt:([^:]+):/) {
  464:             my $subcmd = $1;
  465:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  466:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  467:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  468:                 (undef,undef,my @rest) = split(/:/,$cmd);
  469:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  470:                     splice(@rest,2,1,'Hidden');
  471:                 } elsif ($subcmd eq 'passwd') {
  472:                     splice(@rest,2,2,('Hidden','Hidden'));
  473:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  474:                          ($subcmd eq 'autoexportgrades')) {
  475:                     splice(@rest,3,1,'Hidden');
  476:                 }
  477:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  478:             }
  479:         }
  480:         &logthis("<font color=\"blue\">WARNING:".
  481:                  " $logged to $server returned $answer</font>");
  482:     }
  483:     return $answer;
  484: }
  485: 
  486: # ----------------------------------------------------------- Send USR1 to lonc
  487: 
  488: sub reconlonc {
  489:     my ($lonid) = @_;
  490:     if ($lonid) {
  491:         my $hostname = &hostname($lonid);
  492: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  493: 	if ($hostname && -e $peerfile) {
  494: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  495: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  496: 					     Type    => SOCK_STREAM,
  497: 					     Timeout => 10);
  498: 	    if ($client) {
  499: 		print $client ("reset_retries\n");
  500: 		my $answer=<$client>;
  501: 		#reset just this one.
  502: 	    }
  503: 	}
  504: 	return;
  505:     }
  506: 
  507:     &logthis("Trying to reconnect lonc");
  508:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  509:     if (open(my $fh,"<",$loncfile)) {
  510: 	my $loncpid=<$fh>;
  511:         chomp($loncpid);
  512:         if (kill 0 => $loncpid) {
  513: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  514:             kill USR1 => $loncpid;
  515:             sleep 1;
  516:         } else {
  517: 	    &logthis(
  518:                "<font color=\"blue\">WARNING:".
  519:                " lonc at pid $loncpid not responding, giving up</font>");
  520:         }
  521:     } else {
  522: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  523:     }
  524: }
  525: 
  526: # ------------------------------------------------------ Critical communication
  527: 
  528: sub critical {
  529:     my ($cmd,$server)=@_;
  530:     unless (&hostname($server)) {
  531:         &logthis("<font color=\"blue\">WARNING:".
  532:                " Critical message to unknown server ($server)</font>");
  533:         return 'no_such_host';
  534:     }
  535:     my $answer=reply($cmd,$server);
  536:     if ($answer eq 'con_lost') {
  537: 	&reconlonc($server);
  538: 	my $answer=reply($cmd,$server);
  539:         if ($answer eq 'con_lost') {
  540:             my $now=time;
  541:             my $middlename=$cmd;
  542:             $middlename=substr($middlename,0,16);
  543:             $middlename=~s/\W//g;
  544:             my $dfilename=
  545:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  546:             $dumpcount++;
  547:             {
  548: 		my $dfh;
  549: 		if (open($dfh,">",$dfilename)) {
  550: 		    print $dfh "$cmd\n"; 
  551: 		    close($dfh);
  552: 		}
  553:             }
  554:             sleep 1;
  555:             my $wcmd='';
  556:             {
  557: 		my $dfh;
  558: 		if (open($dfh,"<",$dfilename)) {
  559: 		    $wcmd=<$dfh>; 
  560: 		    close($dfh);
  561: 		}
  562:             }
  563:             chomp($wcmd);
  564:             if ($wcmd eq $cmd) {
  565: 		&logthis("<font color=\"blue\">WARNING: ".
  566:                          "Connection buffer $dfilename: $cmd</font>");
  567:                 &logperm("D:$server:$cmd");
  568: 	        return 'con_delayed';
  569:             } else {
  570:                 &logthis("<font color=\"red\">CRITICAL:"
  571:                         ." Critical connection failed: $server $cmd</font>");
  572:                 &logperm("F:$server:$cmd");
  573:                 return 'con_failed';
  574:             }
  575:         }
  576:     }
  577:     return $answer;
  578: }
  579: 
  580: # ------------------------------------------- check if return value is an error
  581: 
  582: sub error {
  583:     my ($result) = @_;
  584:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  585: 	if ($2 == 2) { return undef; }
  586: 	return $1;
  587:     }
  588:     return undef;
  589: }
  590: 
  591: sub convert_and_load_session_env {
  592:     my ($lonidsdir,$handle)=@_;
  593:     my @profile;
  594:     {
  595: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  596: 	if (!$opened) {
  597: 	    return 0;
  598: 	}
  599: 	flock($idf,LOCK_SH);
  600: 	@profile=<$idf>;
  601: 	close($idf);
  602:     }
  603:     my %temp_env;
  604:     foreach my $line (@profile) {
  605: 	if ($line !~ m/=/) {
  606: 	    return 0;
  607: 	}
  608: 	chomp($line);
  609: 	my ($envname,$envvalue)=split(/=/,$line,2);
  610: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  611:     }
  612:     unlink("$lonidsdir/$handle.id");
  613:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  614: 	    0640)) {
  615: 	%disk_env = %temp_env;
  616: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  617: 	untie(%disk_env);
  618:     }
  619:     return 1;
  620: }
  621: 
  622: # ------------------------------------------- Transfer profile into environment
  623: my $env_loaded;
  624: sub transfer_profile_to_env {
  625:     my ($lonidsdir,$handle,$force_transfer) = @_;
  626:     if (!$force_transfer && $env_loaded) { return; } 
  627: 
  628:     if (!defined($lonidsdir)) {
  629: 	$lonidsdir = $perlvar{'lonIDsDir'};
  630:     }
  631:     if (!defined($handle)) {
  632:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  633:     }
  634: 
  635:     my $convert;
  636:     {
  637:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  638: 	if (!$opened) {
  639: 	    return;
  640: 	}
  641: 	flock($idf,LOCK_SH);
  642: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  643: 		&GDBM_READER(),0640)) {
  644: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  645: 	    untie(%disk_env);
  646: 	} else {
  647: 	    $convert = 1;
  648: 	}
  649:     }
  650:     if ($convert) {
  651: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  652: 	    &logthis("Failed to load session, or convert session.");
  653: 	}
  654:     }
  655: 
  656:     my %remove;
  657:     while ( my $envname = each(%env) ) {
  658:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  659:             if ($time < time-300) {
  660:                 $remove{$key}++;
  661:             }
  662:         }
  663:     }
  664: 
  665:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  666:     $env_loaded=1;
  667:     foreach my $expired_key (keys(%remove)) {
  668:         &delenv($expired_key);
  669:     }
  670: }
  671: 
  672: # ---------------------------------------------------- Check for valid session 
  673: sub check_for_valid_session {
  674:     my ($r,$name,$userhashref,$domref) = @_;
  675:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  676:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  677:     if ($name eq 'lonDAV') {
  678:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  679:     } else {
  680:         $lonidsdir=$r->dir_config('lonIDsDir');
  681:         if ($name eq '') {
  682:             $name = 'lonID';
  683:         }
  684:     }
  685:     if ($name eq 'lonID') {
  686:         $secure = 'lonSID';
  687:         $linkname = 'lonLinkID';
  688:         $pubname = 'lonPubID';
  689:         if (exists($cookies{$secure})) {
  690:             $lonid=$cookies{$secure};
  691:         } elsif (exists($cookies{$name})) {
  692:             $lonid=$cookies{$name};
  693:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  694:             $lonid=$cookies{$linkname};
  695:         } elsif (exists($cookies{$pubname})) {
  696:             $lonid=$cookies{$pubname};
  697:         }
  698:     } else {
  699:         $lonid=$cookies{$name};
  700:     }
  701:     return undef if (!$lonid);
  702: 
  703:     my $handle=&LONCAPA::clean_handle($lonid->value);
  704:     if (-l "$lonidsdir/$handle.id") {
  705:         my $link = readlink("$lonidsdir/$handle.id");
  706:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  707:             $handle = $1;
  708:         }
  709:     }
  710:     if (!-e "$lonidsdir/$handle.id") {
  711:         if ((ref($domref)) && ($name eq 'lonID') && 
  712:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  713:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  714:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  715:                 $$domref = $possudom;
  716:             }
  717:         }
  718:         return undef;
  719:     }
  720: 
  721:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  722:     return undef if (!$opened);
  723: 
  724:     flock($idf,LOCK_SH);
  725:     my %disk_env;
  726:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  727: 	    &GDBM_READER(),0640)) {
  728: 	return undef;	
  729:     }
  730: 
  731:     if (!defined($disk_env{'user.name'})
  732: 	|| !defined($disk_env{'user.domain'})) {
  733:         untie(%disk_env);
  734: 	return undef;
  735:     }
  736: 
  737:     if (ref($userhashref) eq 'HASH') {
  738:         $userhashref->{'name'} = $disk_env{'user.name'};
  739:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  740:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  741:         if ($userhashref->{'lti'}) {
  742:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  743:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  744:         }
  745:     }
  746:     untie(%disk_env);
  747: 
  748:     return $handle;
  749: }
  750: 
  751: sub timed_flock {
  752:     my ($file,$lock_type) = @_;
  753:     my $failed=0;
  754:     eval {
  755: 	local $SIG{__DIE__}='DEFAULT';
  756: 	local $SIG{ALRM}=sub {
  757: 	    $failed=1;
  758: 	    die("failed lock");
  759: 	};
  760: 	alarm(13);
  761: 	flock($file,$lock_type);
  762: 	alarm(0);
  763:     };
  764:     if ($failed) {
  765: 	return undef;
  766:     } else {
  767: 	return 1;
  768:     }
  769: }
  770: 
  771: sub get_sessionfile_vars {
  772:     my ($handle,$lonidsdir,$storearr) = @_;
  773:     my %returnhash;
  774:     unless (ref($storearr) eq 'ARRAY') {
  775:         return %returnhash;
  776:     }
  777:     if (-l "$lonidsdir/$handle.id") {
  778:         my $link = readlink("$lonidsdir/$handle.id");
  779:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  780:             $handle = $1;
  781:         }
  782:     }
  783:     if ((-e "$lonidsdir/$handle.id") &&
  784:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  785:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  786:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  787:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  788:                 flock($idf,LOCK_SH);
  789:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  790:                         &GDBM_READER(),0640)) {
  791:                     foreach my $item (@{$storearr}) {
  792:                         $returnhash{$item} = $disk_env{$item};
  793:                     }
  794:                     untie(%disk_env);
  795:                 }
  796:             }
  797:         }
  798:     }
  799:     return %returnhash;
  800: }
  801: 
  802: # ---------------------------------------------------------- Append Environment
  803: 
  804: sub appenv {
  805:     my ($newenv,$roles) = @_;
  806:     if (ref($newenv) eq 'HASH') {
  807:         foreach my $key (keys(%{$newenv})) {
  808:             my $refused = 0;
  809: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  810:                 $refused = 1;
  811:                 if (ref($roles) eq 'ARRAY') {
  812:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  813:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  814:                         $refused = 0;
  815:                     }
  816:                 }
  817:             }
  818:             if ($refused) {
  819:                 &logthis("<font color=\"blue\">WARNING: ".
  820:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  821:                          .'</font>');
  822: 	        delete($newenv->{$key});
  823:             } else {
  824:                 $env{$key}=$newenv->{$key};
  825:             }
  826:         }
  827:         my $lonids = $perlvar{'lonIDsDir'};
  828:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  829:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  830:             if ($opened
  831: 	        && &timed_flock($env_file,LOCK_EX)
  832: 	        &&
  833: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  834: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  835: 	        while (my ($key,$value) = each(%{$newenv})) {
  836: 	            $disk_env{$key} = $value;
  837: 	        }
  838: 	        untie(%disk_env);
  839:             }
  840:         }
  841:     }
  842:     return 'ok';
  843: }
  844: # ----------------------------------------------------- Delete from Environment
  845: 
  846: sub delenv {
  847:     my ($delthis,$regexp,$roles) = @_;
  848:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  849:         my $refused = 1;
  850:         if (ref($roles) eq 'ARRAY') {
  851:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  852:             if (grep(/^\Q$role\E$/,@{$roles})) {
  853:                 $refused = 0;
  854:             }
  855:         }
  856:         if ($refused) {
  857:             &logthis("<font color=\"blue\">WARNING: ".
  858:                      "Attempt to delete from environment ".$delthis);
  859:             return 'error';
  860:         }
  861:     }
  862:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  863:     if ($opened
  864: 	&& &timed_flock($env_file,LOCK_EX)
  865: 	&&
  866: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  867: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  868: 	foreach my $key (keys(%disk_env)) {
  869: 	    if ($regexp) {
  870:                 if ($key=~/^$delthis/) {
  871:                     delete($env{$key});
  872:                     delete($disk_env{$key});
  873:                 } 
  874:             } else {
  875:                 if ($key=~/^\Q$delthis\E/) {
  876: 		    delete($env{$key});
  877: 		    delete($disk_env{$key});
  878: 	        }
  879:             }
  880: 	}
  881: 	untie(%disk_env);
  882:     }
  883:     return 'ok';
  884: }
  885: 
  886: sub get_env_multiple {
  887:     my ($name) = @_;
  888:     my @values;
  889:     if (defined($env{$name})) {
  890:         # exists is it an array
  891:         if (ref($env{$name})) {
  892:             @values=@{ $env{$name} };
  893:         } else {
  894:             $values[0]=$env{$name};
  895:         }
  896:     }
  897:     return(@values);
  898: }
  899: 
  900: # ------------------------------------------------------------------- Locking
  901: 
  902: sub set_lock {
  903:     my ($text)=@_;
  904:     $locknum++;
  905:     my $id=$$.'-'.$locknum;
  906:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  907:              'session.lock.'.$id => $text});
  908:     return $id;
  909: }
  910: 
  911: sub get_locks {
  912:     my $num=0;
  913:     my %texts=();
  914:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  915:        if ($lock=~/\w/) {
  916:           $num++;
  917:           $texts{$lock}=$env{'session.lock.'.$lock};
  918:        }
  919:    }
  920:    return ($num,%texts);
  921: }
  922: 
  923: sub remove_lock {
  924:     my ($id)=@_;
  925:     my $newlocks='';
  926:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  927:        if (($lock=~/\w/) && ($lock ne $id)) {
  928:           $newlocks.=','.$lock;
  929:        }
  930:     }
  931:     &appenv({'session.locks' => $newlocks});
  932:     &delenv('session.lock.'.$id);
  933: }
  934: 
  935: sub remove_all_locks {
  936:     my $activelocks=$env{'session.locks'};
  937:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  938:        if ($lock=~/\w/) {
  939:           &remove_lock($lock);
  940:        }
  941:     }
  942: }
  943: 
  944: 
  945: # ------------------------------------------ Find out current server userload
  946: sub userload {
  947:     my $numusers=0;
  948:     {
  949: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  950: 	my $filename;
  951: 	my $curtime=time;
  952: 	while ($filename=readdir(LONIDS)) {
  953: 	    next if ($filename eq '.' || $filename eq '..');
  954: 	    next if ($filename =~ /publicuser_\d+\.id/);
  955:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  956: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  957: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  958: 	}
  959: 	closedir(LONIDS);
  960:     }
  961:     my $userloadpercent=0;
  962:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  963:     if ($maxuserload) {
  964: 	$userloadpercent=100*$numusers/$maxuserload;
  965:     }
  966:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  967:     return $userloadpercent;
  968: }
  969: 
  970: # ------------------------------ Find server with least workload from spare.tab
  971: 
  972: sub spareserver {
  973:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  974:     my $spare_server;
  975:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  976:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  977:                                                      :  $userloadpercent;
  978:     my ($uint_dom,$remotesessions);
  979:     if (($udom ne '') && (&domain($udom) ne '')) {
  980:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  981:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  982:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  983:         $remotesessions = $udomdefaults{'remotesessions'};
  984:     }
  985:     my $spareshash = &this_host_spares($udom);
  986:     if (ref($spareshash) eq 'HASH') {
  987:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  988:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  989:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  990:                                              $try_server));
  991: 	        ($spare_server, $lowest_load) =
  992: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  993:             }
  994:         }
  995: 
  996:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  997: 
  998:         if (!$found_server) {
  999:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1000: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1001:                     next unless (&spare_can_host($udom,$uint_dom,
 1002:                                                  $remotesessions,$try_server));
 1003: 	            ($spare_server, $lowest_load) =
 1004: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1005:                 }
 1006: 	    }
 1007:         }
 1008:     }
 1009: 
 1010:     if (!$want_server_name) {
 1011:         if (defined($spare_server)) {
 1012:             my $hostname = &hostname($spare_server);
 1013:             if (defined($hostname)) {
 1014:                 my $protocol = 'http';
 1015:                 if ($protocol{$spare_server} eq 'https') {
 1016:                     $protocol = $protocol{$spare_server};
 1017:                 }
 1018: 	        $spare_server = $protocol.'://'.$hostname;
 1019:             }
 1020:         }
 1021:     }
 1022:     return $spare_server;
 1023: }
 1024: 
 1025: sub compare_server_load {
 1026:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1027: 
 1028:     if ($required) {
 1029:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1030:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1031:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1032:         if (($major eq '' && $minor eq '') ||
 1033:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1034:             return ($spare_server,$lowest_load);
 1035:         }
 1036:     }
 1037: 
 1038:     my $loadans     = &reply('load',    $try_server);
 1039:     my $userloadans = &reply('userload',$try_server);
 1040: 
 1041:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1042: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1043:     }
 1044: 
 1045:     my $load;
 1046:     if ($loadans =~ /\d/) {
 1047: 	if ($userloadans =~ /\d/) {
 1048: 	    #both are numbers, pick the bigger one
 1049: 	    $load = ($loadans > $userloadans) ? $loadans 
 1050: 		                              : $userloadans;
 1051: 	} else {
 1052: 	    $load = $loadans;
 1053: 	}
 1054:     } else {
 1055: 	$load = $userloadans;
 1056:     }
 1057: 
 1058:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1059: 	$spare_server = $try_server;
 1060: 	$lowest_load  = $load;
 1061:     }
 1062:     return ($spare_server,$lowest_load);
 1063: }
 1064: 
 1065: # --------------------------- ask offload servers if user already has a session
 1066: sub find_existing_session {
 1067:     my ($udom,$uname) = @_;
 1068:     my $spareshash = &this_host_spares($udom);
 1069:     if (ref($spareshash) eq 'HASH') {
 1070:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1071:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1072:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1073:             }
 1074:         }
 1075:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1076:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1077:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1078:             }
 1079:         }
 1080:     }
 1081:     return;
 1082: }
 1083: 
 1084: # check if user's browser sent load balancer cookie and server still has session
 1085: # and is not overloaded.
 1086: sub check_for_balancer_cookie {
 1087:     my ($r,$update_mtime) = @_;
 1088:     my ($otherserver,$cookie);
 1089:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1090:     if (exists($cookies{'balanceID'})) {
 1091:         my $balid = $cookies{'balanceID'};
 1092:         $cookie=&LONCAPA::clean_handle($balid->value);
 1093:         my $balancedir=$r->dir_config('lonBalanceDir');
 1094:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1095:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1096:                 my ($possudom,$possuname) = ($1,$2);
 1097:                 my $has_session = 0;
 1098:                 if ((&domain($possudom) ne '') &&
 1099:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1100:                     my $try_server;
 1101:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1102:                     if ($opened) {
 1103:                         flock($idf,LOCK_SH);
 1104:                         while (my $line = <$idf>) {
 1105:                             chomp($line);
 1106:                             if (&hostname($line) ne '') {
 1107:                                 $try_server = $line;
 1108:                                 last;
 1109:                             }
 1110:                         }
 1111:                         close($idf);
 1112:                         if (($try_server) &&
 1113:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1114:                             my $lowest_load = 30000;
 1115:                             ($otherserver,$lowest_load) =
 1116:                                 &compare_server_load($try_server,undef,$lowest_load);
 1117:                             if ($otherserver ne '' && $lowest_load < 100) {
 1118:                                 $has_session = 1;
 1119:                             } else {
 1120:                                 undef($otherserver);
 1121:                             }
 1122:                         }
 1123:                     }
 1124:                 }
 1125:                 if ($has_session) {
 1126:                     if ($update_mtime) {
 1127:                         my $atime = my $mtime = time;
 1128:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1129:                     }
 1130:                 } else {
 1131:                     unlink("$balancedir/$cookie.id");
 1132:                 }
 1133:             }
 1134:         }
 1135:     }
 1136:     return ($otherserver,$cookie);
 1137: }
 1138: 
 1139: sub delbalcookie {
 1140:     my ($cookie,$balancer) =@_;
 1141:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1142:         my ($udom,$uname) = ($1,$2);
 1143:         my $uprimary_id = &domain($udom,'primary');
 1144:         my $uintdom = &internet_dom($uprimary_id);
 1145:         my $intdom = &internet_dom($balancer);
 1146:         my $serverhomedom = &host_domain($balancer);
 1147:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1148:             return &reply("delbalcookie:$cookie",$balancer);
 1149:         }
 1150:     }
 1151: }
 1152: 
 1153: # -------------------------------- ask if server already has a session for user
 1154: sub has_user_session {
 1155:     my ($lonid,$udom,$uname) = @_;
 1156:     my $result = &reply(join(':','userhassession',
 1157: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1158:     return 1 if ($result eq 'ok');
 1159: 
 1160:     return 0;
 1161: }
 1162: 
 1163: # --------- determine least loaded server in a user's domain which allows login
 1164: 
 1165: sub choose_server {
 1166:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1167:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1168:     my %servers = &get_servers($udom);
 1169:     my $lowest_load = 30000;
 1170:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1171:     if ($skiploadbal) {
 1172:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1173:         unless (defined($cached)) {
 1174:             my $cachetime = 60*60*24;
 1175:             my %domconfig =
 1176:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1177:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1178:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1179:                                            $cachetime);
 1180:             }
 1181:         }
 1182:     }
 1183:     foreach my $lonhost (keys(%servers)) {
 1184:         if ($skiploadbal) {
 1185:             if (ref($balancers) eq 'HASH') {
 1186:                 next if (exists($balancers->{$lonhost}));
 1187:             }
 1188:         }
 1189:         my $loginvia;
 1190:         if ($checkloginvia) {
 1191:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1192:             if ($loginvia) {
 1193:                 my ($server,$path) = split(/:/,$loginvia);
 1194:                 ($login_host, $lowest_load) =
 1195:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1196:                 if ($login_host eq $server) {
 1197:                     $portal_path = $path;
 1198:                     $isredirect = 1;
 1199:                 }
 1200:             } else {
 1201:                 ($login_host, $lowest_load) =
 1202:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1203:                 if ($login_host eq $lonhost) {
 1204:                     $portal_path = '';
 1205:                     $isredirect = ''; 
 1206:                 }
 1207:             }
 1208:         } else {
 1209:             ($login_host, $lowest_load) =
 1210:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1211:         }
 1212:     }
 1213:     if ($login_host ne '') {
 1214:         $hostname = &hostname($login_host);
 1215:     }
 1216:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1217: }
 1218: 
 1219: # --------------------------------------------- Try to change a user's password
 1220: 
 1221: sub changepass {
 1222:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1223:     $currentpass = &escape($currentpass);
 1224:     $newpass     = &escape($newpass);
 1225:     my $lonhost = $perlvar{'lonHostID'};
 1226:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1227: 		       $server);
 1228:     if (! $answer) {
 1229: 	&logthis("No reply on password change request to $server ".
 1230: 		 "by $uname in domain $udom.");
 1231:     } elsif ($answer =~ "^ok") {
 1232:         &logthis("$uname in $udom successfully changed their password ".
 1233: 		 "on $server.");
 1234:     } elsif ($answer =~ "^pwchange_failure") {
 1235: 	&logthis("$uname in $udom was unable to change their password ".
 1236: 		 "on $server.  The action was blocked by either lcpasswd ".
 1237: 		 "or pwchange");
 1238:     } elsif ($answer =~ "^non_authorized") {
 1239:         &logthis("$uname in $udom did not get their password correct when ".
 1240: 		 "attempting to change it on $server.");
 1241:     } elsif ($answer =~ "^auth_mode_error") {
 1242:         &logthis("$uname in $udom attempted to change their password despite ".
 1243: 		 "not being locally or internally authenticated on $server.");
 1244:     } elsif ($answer =~ "^unknown_user") {
 1245:         &logthis("$uname in $udom attempted to change their password ".
 1246: 		 "on $server but were unable to because $server is not ".
 1247: 		 "their home server.");
 1248:     } elsif ($answer =~ "^refused") {
 1249: 	&logthis("$server refused to change $uname in $udom password because ".
 1250: 		 "it was sent an unencrypted request to change the password.");
 1251:     } elsif ($answer =~ "invalid_client") {
 1252:         &logthis("$server refused to change $uname in $udom password because ".
 1253:                  "it was a reset by e-mail originating from an invalid server.");
 1254:     }
 1255:     return $answer;
 1256: }
 1257: 
 1258: # ----------------------- Try to determine user's current authentication scheme
 1259: 
 1260: sub queryauthenticate {
 1261:     my ($uname,$udom)=@_;
 1262:     my $uhome=&homeserver($uname,$udom);
 1263:     if (!$uhome) {
 1264: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1265: 	return 'no_host';
 1266:     }
 1267:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1268:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1269: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1270:     }
 1271:     return $answer;
 1272: }
 1273: 
 1274: # --------- Try to authenticate user from domain's lib servers (first this one)
 1275: 
 1276: sub authenticate {
 1277:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1278:     $upass=&escape($upass);
 1279:     $uname= &LONCAPA::clean_username($uname);
 1280:     my $uhome=&homeserver($uname,$udom,1);
 1281:     my $newhome;
 1282:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1283: # Maybe the machine was offline and only re-appeared again recently?
 1284:         &reconlonc();
 1285: # One more
 1286: 	$uhome=&homeserver($uname,$udom,1);
 1287:         if (($uhome eq 'no_host') && $checkdefauth) {
 1288:             if (defined(&domain($udom,'primary'))) {
 1289:                 $newhome=&domain($udom,'primary');
 1290:             }
 1291:             if ($newhome ne '') {
 1292:                 $uhome = $newhome;
 1293:             }
 1294:         }
 1295: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1296: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1297: 	    return 'no_host';
 1298:         }
 1299:     }
 1300:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1301:     if ($answer eq 'authorized') {
 1302:         if ($newhome) {
 1303:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1304:             return 'no_account_on_host'; 
 1305:         } else {
 1306:             &logthis("User $uname at $udom authorized by $uhome");
 1307:             return $uhome;
 1308:         }
 1309:     }
 1310:     if ($answer eq 'non_authorized') {
 1311: 	&logthis("User $uname at $udom rejected by $uhome");
 1312: 	return 'no_host'; 
 1313:     }
 1314:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1315:     return 'no_host';
 1316: }
 1317: 
 1318: sub can_host_session {
 1319:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1320:     my $canhost = 1;
 1321:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1322:     if (ref($remotesessions) eq 'HASH') {
 1323:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1324:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1325:                 $canhost = 0;
 1326:             } else {
 1327:                 $canhost = 1;
 1328:             }
 1329:         }
 1330:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1331:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1332:                 $canhost = 1;
 1333:             } else {
 1334:                 $canhost = 0;
 1335:             }
 1336:         }
 1337:         if ($canhost) {
 1338:             if ($remotesessions->{'version'} ne '') {
 1339:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1340:                 if ($reqmajor ne '' && $reqminor ne '') {
 1341:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1342:                         my $major = $1;
 1343:                         my $minor = $2;
 1344:                         if (($major < $reqmajor ) ||
 1345:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1346:                             $canhost = 0;
 1347:                         }
 1348:                     } else {
 1349:                         $canhost = 0;
 1350:                     }
 1351:                 }
 1352:             }
 1353:         }
 1354:     }
 1355:     if ($canhost) {
 1356:         if (ref($hostedsessions) eq 'HASH') {
 1357:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1358:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1359:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1360:                 if (($uint_dom ne '') && 
 1361:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1362:                     $canhost = 0;
 1363:                 } else {
 1364:                     $canhost = 1;
 1365:                 }
 1366:             }
 1367:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1368:                 if (($uint_dom ne '') && 
 1369:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1370:                     $canhost = 1;
 1371:                 } else {
 1372:                     $canhost = 0;
 1373:                 }
 1374:             }
 1375:         }
 1376:     }
 1377:     return $canhost;
 1378: }
 1379: 
 1380: sub spare_can_host {
 1381:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1382:     my $canhost=1;
 1383:     my $try_server_hostname = &hostname($try_server);
 1384:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1385:     my $serverhomedom = &host_domain($serverhomeID);
 1386:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1387:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1388:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1389:             $canhost = 0;
 1390:         }
 1391:     }
 1392:     if (($canhost) && ($uint_dom)) {
 1393:         my @intdoms;
 1394:         my $internet_names = &get_internet_names($try_server);
 1395:         if (ref($internet_names) eq 'ARRAY') {
 1396:             @intdoms = @{$internet_names};
 1397:         }
 1398:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1399:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1400:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1401:                                          $remotesessions,
 1402:                                          $defdomdefaults{'hostedsessions'});
 1403:         }
 1404:     }
 1405:     return $canhost;
 1406: }
 1407: 
 1408: sub this_host_spares {
 1409:     my ($dom) = @_;
 1410:     my ($dom_in_use,$lonhost_in_use,$result);
 1411:     my @hosts = &current_machine_ids();
 1412:     foreach my $lonhost (@hosts) {
 1413:         if (&host_domain($lonhost) eq $dom) {
 1414:             $dom_in_use = $dom;
 1415:             $lonhost_in_use = $lonhost;
 1416:             last;
 1417:         }
 1418:     }
 1419:     if ($dom_in_use ne '') {
 1420:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1421:     }
 1422:     if (ref($result) ne 'HASH') {
 1423:         $lonhost_in_use = $perlvar{'lonHostID'};
 1424:         $dom_in_use = &host_domain($lonhost_in_use);
 1425:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1426:         if (ref($result) ne 'HASH') {
 1427:             $result = \%spareid;
 1428:         }
 1429:     }
 1430:     return $result;
 1431: }
 1432: 
 1433: sub spares_for_offload  {
 1434:     my ($dom_in_use,$lonhost_in_use) = @_;
 1435:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1436:     if (defined($cached)) {
 1437:         return $result;
 1438:     } else {
 1439:         my $cachetime = 60*60*24;
 1440:         my %domconfig =
 1441:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1442:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1443:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1444:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1445:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1446:                 }
 1447:             }
 1448:         }
 1449:     }
 1450:     return;
 1451: }
 1452: 
 1453: sub get_lonbalancer_config {
 1454:     my ($servers) = @_;
 1455:     my ($currbalancer,$currtargets);
 1456:     if (ref($servers) eq 'HASH') {
 1457:         foreach my $server (keys(%{$servers})) {
 1458:             my %what = (
 1459:                          spareid => 1,
 1460:                          perlvar => 1,
 1461:                        );
 1462:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1463:             if ($result eq 'ok') {
 1464:                 if (ref($returnhash) eq 'HASH') {
 1465:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1466:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1467:                             $currbalancer = $server;
 1468:                             $currtargets = {};
 1469:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1470:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1471:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1472:                                 }
 1473:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1474:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1475:                                 }
 1476:                             }
 1477:                             last;
 1478:                         }
 1479:                     }
 1480:                 }
 1481:             }
 1482:         }
 1483:     }
 1484:     return ($currbalancer,$currtargets);
 1485: }
 1486: 
 1487: sub check_loadbalancing {
 1488:     my ($uname,$udom,$caller) = @_;
 1489:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1490:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1491:     my $lonhost = $perlvar{'lonHostID'};
 1492:     my @hosts = &current_machine_ids();
 1493:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1494:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1495:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1496:     my $serverhomedom = &host_domain($lonhost);
 1497:     my $domneedscache;
 1498:     my $cachetime = 60*60*24;
 1499: 
 1500:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1501:         $dom_in_use = $udom;
 1502:         $homeintdom = 1;
 1503:     } else {
 1504:         $dom_in_use = $serverhomedom;
 1505:     }
 1506:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1507:     unless (defined($cached)) {
 1508:         my %domconfig =
 1509:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1510:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1511:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1512:         } else {
 1513:             $domneedscache = $dom_in_use;
 1514:         }
 1515:     }
 1516:     if (ref($result) eq 'HASH') {
 1517:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1518:             &check_balancer_result($result,@hosts);
 1519:         if ($is_balancer) {
 1520:             if (ref($currrules) eq 'HASH') {
 1521:                 if ($homeintdom) {
 1522:                     if ($uname ne '') {
 1523:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1524:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1525:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1526:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1527:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1528:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1529:                             }
 1530:                         }
 1531:                         if ($rule_in_effect eq '') {
 1532:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1533:                             if ($userenv{'inststatus'} ne '') {
 1534:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1535:                                 my ($othertitle,$usertypes,$types) =
 1536:                                     &Apache::loncommon::sorted_inst_types($udom);
 1537:                                 if (ref($types) eq 'ARRAY') {
 1538:                                     foreach my $type (@{$types}) {
 1539:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1540:                                             if (exists($currrules->{$type})) {
 1541:                                                 $rule_in_effect = $currrules->{$type};
 1542:                                             }
 1543:                                         }
 1544:                                     }
 1545:                                 }
 1546:                             } else {
 1547:                                 if (exists($currrules->{'default'})) {
 1548:                                     $rule_in_effect = $currrules->{'default'};
 1549:                                 }
 1550:                             }
 1551:                         }
 1552:                     } else {
 1553:                         if (exists($currrules->{'default'})) {
 1554:                             $rule_in_effect = $currrules->{'default'};
 1555:                         }
 1556:                     }
 1557:                 } else {
 1558:                     if ($currrules->{'_LC_external'} ne '') {
 1559:                         $rule_in_effect = $currrules->{'_LC_external'};
 1560:                     }
 1561:                 }
 1562:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1563:                                                        $uname,$udom);
 1564:             }
 1565:         }
 1566:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1567:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1568:         unless (defined($cached)) {
 1569:             my %domconfig =
 1570:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1571:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1572:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1573:             } else {
 1574:                 $domneedscache = $serverhomedom;
 1575:             }
 1576:         }
 1577:         if (ref($result) eq 'HASH') {
 1578:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1579:                 &check_balancer_result($result,@hosts);
 1580:             if ($is_balancer) {
 1581:                 if (ref($currrules) eq 'HASH') {
 1582:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1583:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1584:                     }
 1585:                 }
 1586:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1587:                                                        $uname,$udom);
 1588:             }
 1589:         } else {
 1590:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1591:                 $is_balancer = 1;
 1592:                 $offloadto = &this_host_spares($dom_in_use);
 1593:             }
 1594:             unless (defined($cached)) {
 1595:                 $domneedscache = $serverhomedom;
 1596:             }
 1597:         }
 1598:     } else {
 1599:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1600:             $is_balancer = 1;
 1601:             $offloadto = &this_host_spares($dom_in_use);
 1602:         }
 1603:         unless (defined($cached)) {
 1604:             $domneedscache = $serverhomedom;
 1605:         }
 1606:     }
 1607:     if ($domneedscache) {
 1608:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1609:     }
 1610:     if ($is_balancer) {
 1611:         my $lowest_load = 30000;
 1612:         if (ref($offloadto) eq 'HASH') {
 1613:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1614:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1615:                     ($otherserver,$lowest_load) =
 1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1617:                 }
 1618:             }
 1619:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1620: 
 1621:             if (!$found_server) {
 1622:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1623:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1624:                         ($otherserver,$lowest_load) =
 1625:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1626:                     }
 1627:                 }
 1628:             }
 1629:         } elsif (ref($offloadto) eq 'ARRAY') {
 1630:             if (@{$offloadto} == 1) {
 1631:                 $otherserver = $offloadto->[0];
 1632:             } elsif (@{$offloadto} > 1) {
 1633:                 foreach my $try_server (@{$offloadto}) {
 1634:                     ($otherserver,$lowest_load) =
 1635:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1636:                 }
 1637:             }
 1638:         }
 1639:         unless ($caller eq 'login') {
 1640:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1641:                 $is_balancer = 0;
 1642:                 if ($uname ne '' && $udom ne '') {
 1643:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1644:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1645:                                  'user.loadbalcheck.time' => time});
 1646:                     }
 1647:                 }
 1648:             }
 1649:         }
 1650:         unless ($homeintdom) {
 1651:             undef($setcookie);
 1652:         }
 1653:     }
 1654:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1655: }
 1656: 
 1657: sub check_balancer_result {
 1658:     my ($result,@hosts) = @_;
 1659:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1660:     if (ref($result) eq 'HASH') {
 1661:         if ($result->{'lonhost'} ne '') {
 1662:             my $currbalancer = $result->{'lonhost'};
 1663:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1664:                 $is_balancer = 1;
 1665:                 $currtargets = $result->{'targets'};
 1666:                 $currrules = $result->{'rules'};
 1667:             }
 1668:             $dom_balancers = $currbalancer;
 1669:         } else {
 1670:             if (keys(%{$result})) {
 1671:                 foreach my $key (keys(%{$result})) {
 1672:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1673:                         (ref($result->{$key}) eq 'HASH')) {
 1674:                         $is_balancer = 1;
 1675:                         $currrules = $result->{$key}{'rules'};
 1676:                         $currtargets = $result->{$key}{'targets'};
 1677:                         $setcookie = $result->{$key}{'cookie'};
 1678:                         last;
 1679:                     }
 1680:                 }
 1681:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1682:             }
 1683:         }
 1684:     }
 1685:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1686: }
 1687: 
 1688: sub get_loadbalancer_targets {
 1689:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1690:     my $offloadto;
 1691:     if ($rule_in_effect eq 'none') {
 1692:         return [$perlvar{'lonHostID'}];
 1693:     } elsif ($rule_in_effect eq '') {
 1694:         $offloadto = $currtargets;
 1695:     } else {
 1696:         if ($rule_in_effect eq 'homeserver') {
 1697:             my $homeserver = &homeserver($uname,$udom);
 1698:             if ($homeserver ne 'no_host') {
 1699:                 $offloadto = [$homeserver];
 1700:             }
 1701:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1702:             my %domconfig =
 1703:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1704:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1705:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1706:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1707:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1708:                     }
 1709:                 }
 1710:             } else {
 1711:                 my %servers = &internet_dom_servers($udom);
 1712:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1713:                 if (&hostname($remotebalancer) ne '') {
 1714:                     $offloadto = [$remotebalancer];
 1715:                 }
 1716:             }
 1717:         } elsif (&hostname($rule_in_effect) ne '') {
 1718:             $offloadto = [$rule_in_effect];
 1719:         }
 1720:     }
 1721:     return $offloadto;
 1722: }
 1723: 
 1724: sub internet_dom_servers {
 1725:     my ($dom) = @_;
 1726:     my (%uniqservers,%servers);
 1727:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1728:     my @machinedoms = &machine_domains($primaryserver);
 1729:     foreach my $mdom (@machinedoms) {
 1730:         my %currservers = %servers;
 1731:         my %server = &get_servers($mdom);
 1732:         %servers = (%currservers,%server);
 1733:     }
 1734:     my %by_hostname;
 1735:     foreach my $id (keys(%servers)) {
 1736:         push(@{$by_hostname{$servers{$id}}},$id);
 1737:     }
 1738:     foreach my $hostname (sort(keys(%by_hostname))) {
 1739:         if (@{$by_hostname{$hostname}} > 1) {
 1740:             my $match = 0;
 1741:             foreach my $id (@{$by_hostname{$hostname}}) {
 1742:                 if (&host_domain($id) eq $dom) {
 1743:                     $uniqservers{$id} = $hostname;
 1744:                     $match = 1;
 1745:                 }
 1746:             }
 1747:             unless ($match) {
 1748:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1749:             }
 1750:         } else {
 1751:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1752:         }
 1753:     }
 1754:     return %uniqservers;
 1755: }
 1756: 
 1757: sub trusted_domains {
 1758:     my ($cmdtype,$calldom) = @_;
 1759:     my ($trusted,$untrusted);
 1760:     if (&domain($calldom) eq '') {
 1761:         return ($trusted,$untrusted);
 1762:     }
 1763:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1764:         return ($trusted,$untrusted);
 1765:     }
 1766:     my $callprimary = &domain($calldom,'primary');
 1767:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1768:     if ($intcalldom eq '') {
 1769:         return ($trusted,$untrusted);
 1770:     }
 1771: 
 1772:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1773:     unless (defined($cached)) {
 1774:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1775:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1776:         $trustconfig = $domconfig{'trust'};
 1777:     }
 1778:     if (ref($trustconfig)) {
 1779:         my (%possexc,%possinc,@allexc,@allinc); 
 1780:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1781:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1782:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1783:             }
 1784:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1785:                 $possinc{$intcalldom} = 1;
 1786:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1787:             }
 1788:         }
 1789:         if (keys(%possexc)) {
 1790:             if (keys(%possinc)) {
 1791:                 foreach my $key (sort(keys(%possexc))) {
 1792:                     next if ($key eq $intcalldom);
 1793:                     unless ($possinc{$key}) {
 1794:                         push(@allexc,$key);
 1795:                     }
 1796:                 }
 1797:             } else {
 1798:                 @allexc = sort(keys(%possexc));
 1799:             }
 1800:         }
 1801:         if (keys(%possinc)) {
 1802:             $possinc{$intcalldom} = 1;
 1803:             @allinc = sort(keys(%possinc));
 1804:         }
 1805:         if ((@allexc > 0) || (@allinc > 0)) {
 1806:             my %doms_by_intdom;
 1807:             my %allintdoms = &all_host_intdom();
 1808:             my %alldoms = &all_host_domain();
 1809:             foreach my $key (%allintdoms) {
 1810:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1811:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1812:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1813:                     }
 1814:                 } else {
 1815:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1816:                 }
 1817:             }
 1818:             foreach my $exc (@allexc) {
 1819:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1820:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1821:                 }
 1822:             }
 1823:             foreach my $inc (@allinc) {
 1824:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1825:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1826:                 }
 1827:             }
 1828:         }
 1829:     }
 1830:     return ($trusted,$untrusted);
 1831: }
 1832: 
 1833: sub will_trust {
 1834:     my ($cmdtype,$domain,$possdom) = @_;
 1835:     return 1 if ($domain eq $possdom);
 1836:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1837:     my $willtrust; 
 1838:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1839:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1840:             $willtrust = 1;
 1841:         }
 1842:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1843:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1844:             $willtrust = 1;
 1845:         }
 1846:     } else {
 1847:         $willtrust = 1;
 1848:     }
 1849:     return $willtrust;
 1850: }
 1851: 
 1852: # ---------------------- Find the homebase for a user from domain's lib servers
 1853: 
 1854: my %homecache;
 1855: sub homeserver {
 1856:     my ($uname,$udom,$ignoreBadCache)=@_;
 1857:     my $index="$uname:$udom";
 1858: 
 1859:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1860: 
 1861:     my %servers = &get_servers($udom,'library');
 1862:     foreach my $tryserver (keys(%servers)) {
 1863:         next if ($ignoreBadCache ne 'true' && 
 1864: 		 exists($badServerCache{$tryserver}));
 1865: 
 1866: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1867: 	if ($answer eq 'found') {
 1868: 	    delete($badServerCache{$tryserver}); 
 1869: 	    return $homecache{$index}=$tryserver;
 1870: 	} elsif ($answer eq 'no_host') {
 1871: 	    $badServerCache{$tryserver}=1;
 1872: 	}
 1873:     }    
 1874:     return 'no_host';
 1875: }
 1876: 
 1877: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1878: 
 1879: sub idget {
 1880:     my ($udom,$idsref,$namespace)=@_;
 1881:     my %returnhash=();
 1882:     my @ids=(); 
 1883:     if (ref($idsref) eq 'ARRAY') {
 1884:         @ids = @{$idsref};
 1885:     } else {
 1886:         return %returnhash; 
 1887:     }
 1888:     if ($namespace eq '') {
 1889:         $namespace = 'ids';
 1890:     }
 1891:     
 1892:     my %servers = &get_servers($udom,'library');
 1893:     foreach my $tryserver (keys(%servers)) {
 1894: 	my $idlist=join('&', map { &escape($_); } @ids);
 1895: 	if ($namespace eq 'ids') {
 1896: 	    $idlist=~tr/A-Z/a-z/;
 1897: 	}
 1898: 	my $reply;
 1899: 	if ($namespace eq 'ids') {
 1900: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1901: 	} else {
 1902: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1903: 	}
 1904: 	my @answer=();
 1905: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1906: 	    @answer=split(/\&/,$reply);
 1907: 	}                    ;
 1908: 	my $i;
 1909: 	for ($i=0;$i<=$#ids;$i++) {
 1910: 	    if ($answer[$i]) {
 1911: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1912: 	    }
 1913: 	}
 1914:     }
 1915:     return %returnhash;
 1916: }
 1917: 
 1918: # ------------------------------------- Find the IDs behind a list of usernames
 1919: 
 1920: sub idrget {
 1921:     my ($udom,@unames)=@_;
 1922:     my %returnhash=();
 1923:     foreach my $uname (@unames) {
 1924:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1925:     }
 1926:     return %returnhash;
 1927: }
 1928: 
 1929: # Store away a list of names and associated student/employee IDs or clicker IDs
 1930: 
 1931: sub idput {
 1932:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1933:     my %servers=();
 1934:     my %ids=();
 1935:     my %byid = ();
 1936:     if (ref($idsref) eq 'HASH') {
 1937:         %ids=%{$idsref};
 1938:     }
 1939:     if ($namespace eq '') {
 1940:         $namespace = 'ids'; 
 1941:     }
 1942:     foreach my $uname (keys(%ids)) {
 1943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1944:         if ($uhom eq '') {
 1945:             $uhom=&homeserver($uname,$udom);
 1946:         }
 1947:         if ($uhom ne 'no_host') {
 1948:             my $esc_unam=&escape($uname);
 1949:             if ($namespace eq 'ids') {
 1950:                 my $id=&escape($ids{$uname});
 1951:                 $id=~tr/A-Z/a-z/;
 1952:                 my $esc_unam=&escape($uname);
 1953:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1954:             } else {
 1955:                 my @currids = split(/,/,$ids{$uname});
 1956:                 foreach my $id (@currids) {
 1957:                     $byid{$uhom}{$id} .= $uname.',';
 1958:                 }
 1959:             }
 1960:         }
 1961:     }
 1962:     if ($namespace eq 'clickers') {
 1963:         foreach my $server (keys(%byid)) {
 1964:             if (ref($byid{$server}) eq 'HASH') {
 1965:                 foreach my $id (keys(%{$byid{$server}})) {
 1966:                     $byid{$server} =~ s/,$//;
 1967:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1968:                 }
 1969:             }
 1970:         }
 1971:     }
 1972:     foreach my $server (keys(%servers)) {
 1973:         $servers{$server} =~ s/\&$//;
 1974:         if ($namespace eq 'ids') {     
 1975:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1976:         } else {
 1977:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1978:         }
 1979:     }
 1980: }
 1981: 
 1982: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1983: 
 1984: sub iddel {
 1985:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1986:     my %result=();
 1987:     my %ids=();
 1988:     my %byid = ();
 1989:     if (ref($idshashref) eq 'HASH') {
 1990:         %ids=%{$idshashref};
 1991:     } else {
 1992:         return %result;
 1993:     }
 1994:     if ($namespace eq '') {
 1995:         $namespace = 'ids';
 1996:     }
 1997:     my %servers=();
 1998:     while (my ($id,$unamestr) = each(%ids)) {
 1999:         if ($namespace eq 'ids') {
 2000:             my $uhom = $uhome;
 2001:             if ($uhom eq '') { 
 2002:                 $uhom=&homeserver($unamestr,$udom);
 2003:             }
 2004:             if ($uhom ne 'no_host') {
 2005:                 $servers{$uhom}.='&'.&escape($id);
 2006:             }
 2007:          } else {
 2008:             my @curritems = split(/,/,$ids{$id});
 2009:             foreach my $uname (@curritems) {
 2010:                 my $uhom = $uhome;
 2011:                 if ($uhom eq '') {
 2012:                     $uhom=&homeserver($uname,$udom);
 2013:                 }
 2014:                 if ($uhom ne 'no_host') { 
 2015:                     $byid{$uhom}{$id} .= $uname.',';
 2016:                 }
 2017:             }
 2018:         }
 2019:     }
 2020:     if ($namespace eq 'clickers') {
 2021:         foreach my $server (keys(%byid)) {
 2022:             if (ref($byid{$server}) eq 'HASH') {
 2023:                 foreach my $id (keys(%{$byid{$server}})) {
 2024:                     $byid{$server}{$id} =~ s/,$//;
 2025:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2026:                 }
 2027:             }
 2028:         }
 2029:     }
 2030:     foreach my $server (keys(%servers)) {
 2031:         $servers{$server} =~ s/\&$//;
 2032:         if ($namespace eq 'ids') {
 2033:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2034:         } elsif ($namespace eq 'clickers') {
 2035:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2036:         }
 2037:     }
 2038:     return %result;
 2039: }
 2040: 
 2041: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2042: 
 2043: sub updateclickers {
 2044:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2045:     my %clickers;
 2046:     if (ref($idshashref) eq 'HASH') {
 2047:         %clickers=%{$idshashref};
 2048:     } else {
 2049:         return;
 2050:     }
 2051:     my $items='';
 2052:     foreach my $item (keys(%clickers)) {
 2053:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2054:     }
 2055:     $items=~s/\&$//;
 2056:     my $request = "updateclickers:$udom:$action:$items";
 2057:     if ($critical) {
 2058:         return &critical($request,$uhome);
 2059:     } else {
 2060:         return &reply($request,$uhome);
 2061:     }
 2062: }
 2063: 
 2064: # ------------------------------dump from db file owned by domainconfig user
 2065: sub dump_dom {
 2066:     my ($namespace, $udom, $regexp) = @_;
 2067: 
 2068:     $udom ||= $env{'user.domain'};
 2069: 
 2070:     return () unless $udom;
 2071: 
 2072:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2073: }
 2074: 
 2075: # ------------------------------------------ get items from domain db files   
 2076: 
 2077: sub get_dom {
 2078:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2079:     return if ($udom eq 'public');
 2080:     my $items='';
 2081:     foreach my $item (@$storearr) {
 2082:         $items.=&escape($item).'&';
 2083:     }
 2084:     $items=~s/\&$//;
 2085:     if (!$udom) {
 2086:         $udom=$env{'user.domain'};
 2087:         return if ($udom eq 'public');
 2088:         if (defined(&domain($udom,'primary'))) {
 2089:             $uhome=&domain($udom,'primary');
 2090:         } else {
 2091:             undef($uhome);
 2092:         }
 2093:     } else {
 2094:         if (!$uhome) {
 2095:             if (defined(&domain($udom,'primary'))) {
 2096:                 $uhome=&domain($udom,'primary');
 2097:             }
 2098:         }
 2099:     }
 2100:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2101:         my $rep;
 2102:         if ($namespace =~ /^enc/) {
 2103:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2104:         } else {
 2105:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2106:         }
 2107:         my %returnhash;
 2108:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2109:             return %returnhash;
 2110:         }
 2111:         my @pairs=split(/\&/,$rep);
 2112:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2113:             return @pairs;
 2114:         }
 2115:         my $i=0;
 2116:         foreach my $item (@$storearr) {
 2117:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2118:             $i++;
 2119:         }
 2120:         return %returnhash;
 2121:     } else {
 2122:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2123:     }
 2124: }
 2125: 
 2126: # -------------------------------------------- put items in domain db files 
 2127: 
 2128: sub put_dom {
 2129:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2130:     if (!$udom) {
 2131:         $udom=$env{'user.domain'};
 2132:         if (defined(&domain($udom,'primary'))) {
 2133:             $uhome=&domain($udom,'primary');
 2134:         } else {
 2135:             undef($uhome);
 2136:         }
 2137:     } else {
 2138:         if (!$uhome) {
 2139:             if (defined(&domain($udom,'primary'))) {
 2140:                 $uhome=&domain($udom,'primary');
 2141:             }
 2142:         }
 2143:     } 
 2144:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2145:         my $items='';
 2146:         foreach my $item (keys(%$storehash)) {
 2147:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2148:         }
 2149:         $items=~s/\&$//;
 2150:         if ($namespace =~ /^enc/) {
 2151:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2152:         } else {
 2153:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2154:         }
 2155:     } else {
 2156:         &logthis("put_dom failed - no homeserver and/or domain");
 2157:     }
 2158: }
 2159: 
 2160: # --------------------- newput for items in db file owned by domainconfig user
 2161: sub newput_dom {
 2162:     my ($namespace,$storehash,$udom) = @_;
 2163:     my $result;
 2164:     if (!$udom) {
 2165:         $udom=$env{'user.domain'};
 2166:     }
 2167:     if ($udom) {
 2168:         my $uname = &get_domainconfiguser($udom);
 2169:         $result = &newput($namespace,$storehash,$udom,$uname);
 2170:     }
 2171:     return $result;
 2172: }
 2173: 
 2174: # --------------------- delete for items in db file owned by domainconfig user
 2175: sub del_dom {
 2176:     my ($namespace,$storearr,$udom)=@_;
 2177:     if (ref($storearr) eq 'ARRAY') {
 2178:         if (!$udom) {
 2179:             $udom=$env{'user.domain'};
 2180:         }
 2181:         if ($udom) {
 2182:             my $uname = &get_domainconfiguser($udom); 
 2183:             return &del($namespace,$storearr,$udom,$uname);
 2184:         }
 2185:     }
 2186: }
 2187: 
 2188: # ----------------------------------construct domainconfig user for a domain 
 2189: sub get_domainconfiguser {
 2190:     my ($udom) = @_;
 2191:     return $udom.'-domainconfig';
 2192: }
 2193: 
 2194: sub retrieve_inst_usertypes {
 2195:     my ($udom) = @_;
 2196:     my (%returnhash,@order);
 2197:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2198:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2199:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2200:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2201:     } else {
 2202:         if (defined(&domain($udom,'primary'))) {
 2203:             my $uhome=&domain($udom,'primary');
 2204:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2205:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2206:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2207:                 return (\%returnhash,\@order);
 2208:             }
 2209:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2210:             my @pairs=split(/\&/,$hashitems);
 2211:             foreach my $item (@pairs) {
 2212:                 my ($key,$value)=split(/=/,$item,2);
 2213:                 $key = &unescape($key);
 2214:                 next if ($key =~ /^error: 2 /);
 2215:                 $returnhash{$key}=&thaw_unescape($value);
 2216:             }
 2217:             my @esc_order = split(/\&/,$orderitems);
 2218:             foreach my $item (@esc_order) {
 2219:                 push(@order,&unescape($item));
 2220:             }
 2221:         } else {
 2222:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2223:         }
 2224:         return (\%returnhash,\@order);
 2225:     }
 2226: }
 2227: 
 2228: sub is_domainimage {
 2229:     my ($url) = @_;
 2230:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2231:         if (&domain($1) ne '') {
 2232:             return '1';
 2233:         }
 2234:     }
 2235:     return;
 2236: }
 2237: 
 2238: sub inst_directory_query {
 2239:     my ($srch) = @_;
 2240:     my $udom = $srch->{'srchdomain'};
 2241:     my %results;
 2242:     my $homeserver = &domain($udom,'primary');
 2243:     my $outcome;
 2244:     if ($homeserver ne '') {
 2245:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2246:             if ($srch->{'srchby'} eq 'email') {
 2247:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2248:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2249:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2250:                     (($major == 2) && ($minor < 12))) {
 2251:                     return;
 2252:                 }
 2253:             }
 2254:         }
 2255: 	my $queryid=&reply("querysend:instdirsearch:".
 2256: 			   &escape($srch->{'srchby'}).':'.
 2257: 			   &escape($srch->{'srchterm'}).':'.
 2258: 			   &escape($srch->{'srchtype'}),$homeserver);
 2259: 	my $host=&hostname($homeserver);
 2260: 	if ($queryid !~/^\Q$host\E\_/) {
 2261: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2262: 	    return;
 2263: 	}
 2264: 	my $response = &get_query_reply($queryid);
 2265: 	my $maxtries = 5;
 2266: 	my $tries = 1;
 2267: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2268: 	    $response = &get_query_reply($queryid);
 2269: 	    $tries ++;
 2270: 	}
 2271: 
 2272:         if (!&error($response) && $response ne 'refused') {
 2273:             if ($response eq 'unavailable') {
 2274:                 $outcome = $response;
 2275:             } else {
 2276:                 $outcome = 'ok';
 2277:                 my @matches = split(/\n/,$response);
 2278:                 foreach my $match (@matches) {
 2279:                     my ($key,$value) = split(/=/,$match);
 2280:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2281:                 }
 2282:             }
 2283:         }
 2284:     }
 2285:     return ($outcome,%results);
 2286: }
 2287: 
 2288: sub usersearch {
 2289:     my ($srch) = @_;
 2290:     my $dom = $srch->{'srchdomain'};
 2291:     my %results;
 2292:     my %libserv = &all_library();
 2293:     my $query = 'usersearch';
 2294:     foreach my $tryserver (keys(%libserv)) {
 2295:         if (&host_domain($tryserver) eq $dom) {
 2296:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2297:                 if ($srch->{'srchby'} eq 'email') {
 2298:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2299:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2300:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2301:                              (($major == 2) && ($minor < 12)));
 2302:                 }
 2303:             }
 2304:             my $host=&hostname($tryserver);
 2305:             my $queryid=
 2306:                 &reply("querysend:".&escape($query).':'.
 2307:                        &escape($srch->{'srchby'}).':'.
 2308:                        &escape($srch->{'srchtype'}).':'.
 2309:                        &escape($srch->{'srchterm'}),$tryserver);
 2310:             if ($queryid !~/^\Q$host\E\_/) {
 2311:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2312:                 next;
 2313:             }
 2314:             my $reply = &get_query_reply($queryid);
 2315:             my $maxtries = 1;
 2316:             my $tries = 1;
 2317:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2318:                 $reply = &get_query_reply($queryid);
 2319:                 $tries ++;
 2320:             }
 2321:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2322:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2323:             } else {
 2324:                 my @matches;
 2325:                 if ($reply =~ /\n/) {
 2326:                     @matches = split(/\n/,$reply);
 2327:                 } else {
 2328:                     @matches = split(/\&/,$reply);
 2329:                 }
 2330:                 foreach my $match (@matches) {
 2331:                     my ($uname,$udom,%userhash);
 2332:                     foreach my $entry (split(/:/,$match)) {
 2333:                         my ($key,$value) =
 2334:                             map {&unescape($_);} split(/=/,$entry);
 2335:                         $userhash{$key} = $value;
 2336:                         if ($key eq 'username') {
 2337:                             $uname = $value;
 2338:                         } elsif ($key eq 'domain') {
 2339:                             $udom = $value;
 2340:                         }
 2341:                     }
 2342:                     $results{$uname.':'.$udom} = \%userhash;
 2343:                 }
 2344:             }
 2345:         }
 2346:     }
 2347:     return %results;
 2348: }
 2349: 
 2350: sub get_instuser {
 2351:     my ($udom,$uname,$id) = @_;
 2352:     my $homeserver = &domain($udom,'primary');
 2353:     my ($outcome,%results);
 2354:     if ($homeserver ne '') {
 2355:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2356:                            &escape($id).':'.&escape($udom),$homeserver);
 2357:         my $host=&hostname($homeserver);
 2358:         if ($queryid !~/^\Q$host\E\_/) {
 2359:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2360:             return;
 2361:         }
 2362:         my $response = &get_query_reply($queryid);
 2363:         my $maxtries = 5;
 2364:         my $tries = 1;
 2365:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2366:             $response = &get_query_reply($queryid);
 2367:             $tries ++;
 2368:         }
 2369:         if (!&error($response) && $response ne 'refused') {
 2370:             if ($response eq 'unavailable') {
 2371:                 $outcome = $response;
 2372:             } else {
 2373:                 $outcome = 'ok';
 2374:                 my @matches = split(/\n/,$response);
 2375:                 foreach my $match (@matches) {
 2376:                     my ($key,$value) = split(/=/,$match);
 2377:                     $results{&unescape($key)} = &thaw_unescape($value);
 2378:                 }
 2379:             }
 2380:         }
 2381:     }
 2382:     my %userinfo;
 2383:     if (ref($results{$uname}) eq 'HASH') {
 2384:         %userinfo = %{$results{$uname}};
 2385:     } 
 2386:     return ($outcome,%userinfo);
 2387: }
 2388: 
 2389: sub get_multiple_instusers {
 2390:     my ($udom,$users,$caller) = @_;
 2391:     my ($outcome,$results);
 2392:     if (ref($users) eq 'HASH') {
 2393:         my $count = keys(%{$users}); 
 2394:         my $requested = &freeze_escape($users);
 2395:         my $homeserver = &domain($udom,'primary');
 2396:         if ($homeserver ne '') {
 2397:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2398:             my $host=&hostname($homeserver);
 2399:             if ($queryid !~/^\Q$host\E\_/) {
 2400:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2401:                          ' for host: '.$homeserver.'in domain '.$udom);
 2402:                 return ($outcome,$results);
 2403:             }
 2404:             my $response = &get_query_reply($queryid);
 2405:             my $maxtries = 5;
 2406:             if ($count > 100) {
 2407:                 $maxtries = 1+int($count/20);
 2408:             }
 2409:             my $tries = 1;
 2410:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2411:                 $response = &get_query_reply($queryid);
 2412:                 $tries ++;
 2413:             }
 2414:             if ($response eq '') {
 2415:                 $results = {};
 2416:                 foreach my $key (keys(%{$users})) {
 2417:                     my ($uname,$id);
 2418:                     if ($caller eq 'id') {
 2419:                         $id = $key;
 2420:                     } else {
 2421:                         $uname = $key;
 2422:                     }
 2423:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2424:                     $outcome = $resp;
 2425:                     if ($resp eq 'ok') {
 2426:                         %{$results} = (%{$results}, %info);
 2427:                     } else {
 2428:                         last;
 2429:                     }
 2430:                 }
 2431:             } elsif(!&error($response) && ($response ne 'refused')) {
 2432:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2433:                     $outcome = $response;
 2434:                 } else {
 2435:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2436:                     if ($outcome eq 'ok') {
 2437:                         $results = &thaw_unescape($userdata); 
 2438:                     }
 2439:                 }
 2440:             }
 2441:         }
 2442:     }
 2443:     return ($outcome,$results);
 2444: }
 2445: 
 2446: sub inst_rulecheck {
 2447:     my ($udom,$uname,$id,$item,$rules) = @_;
 2448:     my %returnhash;
 2449:     if ($udom ne '') {
 2450:         if (ref($rules) eq 'ARRAY') {
 2451:             @{$rules} = map {&escape($_);} (@{$rules});
 2452:             my $rulestr = join(':',@{$rules});
 2453:             my $homeserver=&domain($udom,'primary');
 2454:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2455:                 my $response;
 2456:                 if ($item eq 'username') {                
 2457:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2458:                                               ':'.&escape($uname).':'.$rulestr,
 2459:                                               $homeserver));
 2460:                 } elsif ($item eq 'id') {
 2461:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2462:                                               ':'.&escape($id).':'.$rulestr,
 2463:                                               $homeserver));
 2464:                 } elsif ($item eq 'selfcreate') {
 2465:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2466:                                                &escape($udom).':'.&escape($uname).
 2467:                                               ':'.$rulestr,$homeserver));
 2468:                 }
 2469:                 if ($response ne 'refused') {
 2470:                     my @pairs=split(/\&/,$response);
 2471:                     foreach my $item (@pairs) {
 2472:                         my ($key,$value)=split(/=/,$item,2);
 2473:                         $key = &unescape($key);
 2474:                         next if ($key =~ /^error: 2 /);
 2475:                         $returnhash{$key}=&thaw_unescape($value);
 2476:                     }
 2477:                 }
 2478:             }
 2479:         }
 2480:     }
 2481:     return %returnhash;
 2482: }
 2483: 
 2484: sub inst_userrules {
 2485:     my ($udom,$check) = @_;
 2486:     my (%ruleshash,@ruleorder);
 2487:     if ($udom ne '') {
 2488:         my $homeserver=&domain($udom,'primary');
 2489:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2490:             my $response;
 2491:             if ($check eq 'id') {
 2492:                 $response=&reply('instidrules:'.&escape($udom),
 2493:                                  $homeserver);
 2494:             } elsif ($check eq 'email') {
 2495:                 $response=&reply('instemailrules:'.&escape($udom),
 2496:                                  $homeserver);
 2497:             } else {
 2498:                 $response=&reply('instuserrules:'.&escape($udom),
 2499:                                  $homeserver);
 2500:             }
 2501:             if (($response ne 'refused') && ($response ne 'error') && 
 2502:                 ($response ne 'unknown_cmd') && 
 2503:                 ($response ne 'no_such_host')) {
 2504:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2505:                 my @pairs=split(/\&/,$hashitems);
 2506:                 foreach my $item (@pairs) {
 2507:                     my ($key,$value)=split(/=/,$item,2);
 2508:                     $key = &unescape($key);
 2509:                     next if ($key =~ /^error: 2 /);
 2510:                     $ruleshash{$key}=&thaw_unescape($value);
 2511:                 }
 2512:                 my @esc_order = split(/\&/,$orderitems);
 2513:                 foreach my $item (@esc_order) {
 2514:                     push(@ruleorder,&unescape($item));
 2515:                 }
 2516:             }
 2517:         }
 2518:     }
 2519:     return (\%ruleshash,\@ruleorder);
 2520: }
 2521: 
 2522: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2523: 
 2524: sub get_domain_defaults {
 2525:     my ($domain,$ignore_cache) = @_;
 2526:     return if (($domain eq '') || ($domain eq 'public'));
 2527:     my $cachetime = 60*60*24;
 2528:     unless ($ignore_cache) {
 2529:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2530:         if (defined($cached)) {
 2531:             if (ref($result) eq 'HASH') {
 2532:                 return %{$result};
 2533:             }
 2534:         }
 2535:     }
 2536:     my %domdefaults;
 2537:     my %domconfig =
 2538:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2539:                                   'requestcourses','inststatus',
 2540:                                   'coursedefaults','usersessions',
 2541:                                   'requestauthor','selfenrollment',
 2542:                                   'coursecategories','ssl','autoenroll',
 2543:                                   'trust','helpsettings'],$domain);
 2544:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2545:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2546:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2547:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2548:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2549:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2550:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2551:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2552:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2553:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2554:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2555:     } else {
 2556:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2557:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2558:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2559:     }
 2560:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2561:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2562:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2563:         } else {
 2564:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2565:         }
 2566:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2567:         foreach my $item (@usertools) {
 2568:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2569:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2570:             }
 2571:         }
 2572:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2573:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2574:         }
 2575:     }
 2576:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2577:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2578:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2579:         }
 2580:     }
 2581:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2582:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2583:     }
 2584:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2585:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2586:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2587:         }
 2588:     }
 2589:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2590:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2591:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2592:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2593:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2594:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2595:         }
 2596:         foreach my $type (@coursetypes) {
 2597:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2598:                 unless ($type eq 'community') {
 2599:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2600:                 }
 2601:             }
 2602:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2603:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2604:             }
 2605:             if ($domdefaults{'postsubmit'} eq 'on') {
 2606:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2607:                     $domdefaults{$type.'postsubtimeout'} = 
 2608:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2609:                 }
 2610:             }
 2611:         }
 2612:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2613:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2614:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2615:                 if (@clonecodes) {
 2616:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2617:                 }
 2618:             }
 2619:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2620:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2621:         }
 2622:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2623:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2624:         } 
 2625:     }
 2626:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2627:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2628:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2629:         }
 2630:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2631:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2632:         }
 2633:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2634:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2635:         }
 2636:     }
 2637:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2638:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2639:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2640:                             'approval','limit');
 2641:             foreach my $type (@coursetypes) {
 2642:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2643:                     my @mgrdc = ();
 2644:                     foreach my $item (@settings) {
 2645:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2646:                             push(@mgrdc,$item);
 2647:                         }
 2648:                     }
 2649:                     if (@mgrdc) {
 2650:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2651:                     }
 2652:                 }
 2653:             }
 2654:         }
 2655:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2656:             foreach my $type (@coursetypes) {
 2657:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2658:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2659:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2660:                     }
 2661:                 }
 2662:             }
 2663:         }
 2664:     }
 2665:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2666:         $domdefaults{'catauth'} = 'std';
 2667:         $domdefaults{'catunauth'} = 'std';
 2668:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2669:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2670:         }
 2671:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2672:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2673:         }
 2674:     }
 2675:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2676:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2677:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2678:         }
 2679:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2680:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2681:         }
 2682:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2683:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2684:         }
 2685:     }
 2686:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2687:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2688:         foreach my $prefix (@prefixes) {
 2689:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2690:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2691:             }
 2692:         }
 2693:     }
 2694:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2695:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2696:     }
 2697:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2698:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2699:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2700:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2701:         }
 2702:     }
 2703:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2704:     return %domdefaults;
 2705: }
 2706: 
 2707: sub course_portal_url {
 2708:     my ($cnum,$cdom) = @_;
 2709:     my $chome = &homeserver($cnum,$cdom);
 2710:     my $hostname = &hostname($chome);
 2711:     my $protocol = $protocol{$chome};
 2712:     $protocol = 'http' if ($protocol ne 'https');
 2713:     my %domdefaults = &get_domain_defaults($cdom);
 2714:     my $firsturl;
 2715:     if ($domdefaults{'portal_def'}) {
 2716:         $firsturl = $domdefaults{'portal_def'};
 2717:     } else {
 2718:         $firsturl = $protocol.'://'.$hostname;
 2719:     }
 2720:     return $firsturl;
 2721: }
 2722: 
 2723: # --------------------------------------------------- Assign a key to a student
 2724: 
 2725: sub assign_access_key {
 2726: #
 2727: # a valid key looks like uname:udom#comments
 2728: # comments are being appended
 2729: #
 2730:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2731:     $kdom=
 2732:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2733:     $knum=
 2734:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2735:     $cdom=
 2736:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2737:     $cnum=
 2738:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2739:     $udom=$env{'user.name'} unless (defined($udom));
 2740:     $uname=$env{'user.domain'} unless (defined($uname));
 2741:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2742:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2743:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2744:                                                   # assigned to this person
 2745:                                                   # - this should not happen,
 2746:                                                   # unless something went wrong
 2747:                                                   # the first time around
 2748: # ready to assign
 2749:         $logentry=$1.'; '.$logentry;
 2750:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2751:                                                  $kdom,$knum) eq 'ok') {
 2752: # key now belongs to user
 2753: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2754:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2755:                 &appenv({'environment.'.$envkey => $ckey});
 2756:                 return 'ok';
 2757:             } else {
 2758:                 return 
 2759:   'error: Count not permanently assign key, will need to be re-entered later.';
 2760: 	    }
 2761:         } else {
 2762:             return 'error: Could not assign key, try again later.';
 2763:         }
 2764:     } elsif (!$existing{$ckey}) {
 2765: # the key does not exist
 2766: 	return 'error: The key does not exist';
 2767:     } else {
 2768: # the key is somebody else's
 2769: 	return 'error: The key is already in use';
 2770:     }
 2771: }
 2772: 
 2773: # ------------------------------------------ put an additional comment on a key
 2774: 
 2775: sub comment_access_key {
 2776: #
 2777: # a valid key looks like uname:udom#comments
 2778: # comments are being appended
 2779: #
 2780:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2781:     $cdom=
 2782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2783:     $cnum=
 2784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2785:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2786:     if ($existing{$ckey}) {
 2787:         $existing{$ckey}.='; '.$logentry;
 2788: # ready to assign
 2789:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2790:                                                  $cdom,$cnum) eq 'ok') {
 2791: 	    return 'ok';
 2792:         } else {
 2793: 	    return 'error: Count not store comment.';
 2794:         }
 2795:     } else {
 2796: # the key does not exist
 2797: 	return 'error: The key does not exist';
 2798:     }
 2799: }
 2800: 
 2801: # ------------------------------------------------------ Generate a set of keys
 2802: 
 2803: sub generate_access_keys {
 2804:     my ($number,$cdom,$cnum,$logentry)=@_;
 2805:     $cdom=
 2806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2807:     $cnum=
 2808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2809:     unless (&allowed('mky',$cdom)) { return 0; }
 2810:     unless (($cdom) && ($cnum)) { return 0; }
 2811:     if ($number>10000) { return 0; }
 2812:     sleep(2); # make sure don't get same seed twice
 2813:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2814:     my $total=0;
 2815:     for (my $i=1;$i<=$number;$i++) {
 2816:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2817:                   sprintf("%lx",int(100000*rand)).'-'.
 2818:                   sprintf("%lx",int(100000*rand));
 2819:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2820:        $newkey=~s/0/h/g; # and also 0 and O
 2821:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2822:        if ($existing{$newkey}) {
 2823:            $i--;
 2824:        } else {
 2825: 	  if (&put('accesskeys',
 2826:               { $newkey => '# generated '.localtime().
 2827:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2828:                            '; '.$logentry },
 2829: 		   $cdom,$cnum) eq 'ok') {
 2830:               $total++;
 2831: 	  }
 2832:        }
 2833:     }
 2834:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2835:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2836:     return $total;
 2837: }
 2838: 
 2839: # ------------------------------------------------------- Validate an accesskey
 2840: 
 2841: sub validate_access_key {
 2842:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2843:     $cdom=
 2844:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2845:     $cnum=
 2846:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2847:     $udom=$env{'user.domain'} unless (defined($udom));
 2848:     $uname=$env{'user.name'} unless (defined($uname));
 2849:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2850:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2851: }
 2852: 
 2853: # ------------------------------------- Find the section of student in a course
 2854: sub devalidate_getsection_cache {
 2855:     my ($udom,$unam,$courseid)=@_;
 2856:     my $hashid="$udom:$unam:$courseid";
 2857:     &devalidate_cache_new('getsection',$hashid);
 2858: }
 2859: 
 2860: sub courseid_to_courseurl {
 2861:     my ($courseid) = @_;
 2862:     #already url style courseid
 2863:     return $courseid if ($courseid =~ m{^/});
 2864: 
 2865:     if (exists($env{'course.'.$courseid.'.num'})) {
 2866: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2867: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2868: 	return "/$cdom/$cnum";
 2869:     }
 2870: 
 2871:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2872:     if (exists($courseinfo{'num'})) {
 2873: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2874:     }
 2875: 
 2876:     return undef;
 2877: }
 2878: 
 2879: sub getsection {
 2880:     my ($udom,$unam,$courseid)=@_;
 2881:     my $cachetime=1800;
 2882: 
 2883:     my $hashid="$udom:$unam:$courseid";
 2884:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2885:     if (defined($cached)) { return $result; }
 2886: 
 2887:     my %Pending; 
 2888:     my %Expired;
 2889:     #
 2890:     # Each role can either have not started yet (pending), be active, 
 2891:     #    or have expired.
 2892:     #
 2893:     # If there is an active role, we are done.
 2894:     #
 2895:     # If there is more than one role which has not started yet, 
 2896:     #     choose the one which will start sooner
 2897:     # If there is one role which has not started yet, return it.
 2898:     #
 2899:     # If there is more than one expired role, choose the one which ended last.
 2900:     # If there is a role which has expired, return it.
 2901:     #
 2902:     $courseid = &courseid_to_courseurl($courseid);
 2903:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2904:     foreach my $key (keys(%roleshash)) {
 2905:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2906:         my $section=$1;
 2907:         if ($key eq $courseid.'_st') { $section=''; }
 2908:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2909:         my $now=time;
 2910:         if (defined($end) && $end && ($now > $end)) {
 2911:             $Expired{$end}=$section;
 2912:             next;
 2913:         }
 2914:         if (defined($start) && $start && ($now < $start)) {
 2915:             $Pending{$start}=$section;
 2916:             next;
 2917:         }
 2918:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2919:     }
 2920:     #
 2921:     # Presumedly there will be few matching roles from the above
 2922:     # loop and the sorting time will be negligible.
 2923:     if (scalar(keys(%Pending))) {
 2924:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2925:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2926:     } 
 2927:     if (scalar(keys(%Expired))) {
 2928:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2929:         my $time = pop(@sorted);
 2930:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2931:     }
 2932:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2933: }
 2934: 
 2935: sub save_cache {
 2936:     &purge_remembered();
 2937:     #&Apache::loncommon::validate_page();
 2938:     undef(%env);
 2939:     undef($env_loaded);
 2940: }
 2941: 
 2942: my $to_remember=-1;
 2943: my %remembered;
 2944: my %accessed;
 2945: my $kicks=0;
 2946: my $hits=0;
 2947: sub make_key {
 2948:     my ($name,$id) = @_;
 2949:     if (length($id) > 65 
 2950: 	&& length(&escape($id)) > 200) {
 2951: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2952:     }
 2953:     return &escape($name.':'.$id);
 2954: }
 2955: 
 2956: sub devalidate_cache_new {
 2957:     my ($name,$id,$debug) = @_;
 2958:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2959:     my $remembered_id=$name.':'.$id;
 2960:     $id=&make_key($name,$id);
 2961:     $memcache->delete($id);
 2962:     delete($remembered{$remembered_id});
 2963:     delete($accessed{$remembered_id});
 2964: }
 2965: 
 2966: sub is_cached_new {
 2967:     my ($name,$id,$debug) = @_;
 2968:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2969:     if (exists($remembered{$remembered_id})) {
 2970: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2971: 	$accessed{$remembered_id}=[&gettimeofday()];
 2972: 	$hits++;
 2973: 	return ($remembered{$remembered_id},1);
 2974:     }
 2975:     $id=&make_key($name,$id);
 2976:     my $value = $memcache->get($id);
 2977:     if (!(defined($value))) {
 2978: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2979: 	return (undef,undef);
 2980:     }
 2981:     if ($value eq '__undef__') {
 2982: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2983: 	$value=undef;
 2984:     }
 2985:     &make_room($remembered_id,$value,$debug);
 2986:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2987:     return ($value,1);
 2988: }
 2989: 
 2990: sub do_cache_new {
 2991:     my ($name,$id,$value,$time,$debug) = @_;
 2992:     my $remembered_id=$name.':'.$id;
 2993:     $id=&make_key($name,$id);
 2994:     my $setvalue=$value;
 2995:     if (!defined($setvalue)) {
 2996: 	$setvalue='__undef__';
 2997:     }
 2998:     if (!defined($time) ) {
 2999: 	$time=600;
 3000:     }
 3001:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3002:     my $result = $memcache->set($id,$setvalue,$time);
 3003:     if (! $result) {
 3004: 	&logthis("caching of id -> $id  failed");
 3005: 	$memcache->disconnect_all();
 3006:     }
 3007:     # need to make a copy of $value
 3008:     &make_room($remembered_id,$value,$debug);
 3009:     return $value;
 3010: }
 3011: 
 3012: sub make_room {
 3013:     my ($remembered_id,$value,$debug)=@_;
 3014: 
 3015:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3016:                                     : $value;
 3017:     if ($to_remember<0) { return; }
 3018:     $accessed{$remembered_id}=[&gettimeofday()];
 3019:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3020:     my $to_kick;
 3021:     my $max_time=0;
 3022:     foreach my $other (keys(%accessed)) {
 3023: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3024: 	    $to_kick=$other;
 3025: 	    $max_time=&tv_interval($accessed{$other});
 3026: 	}
 3027:     }
 3028:     delete($remembered{$to_kick});
 3029:     delete($accessed{$to_kick});
 3030:     $kicks++;
 3031:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3032:     return;
 3033: }
 3034: 
 3035: sub purge_remembered {
 3036:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3037:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3038:     undef(%remembered);
 3039:     undef(%accessed);
 3040: }
 3041: # ------------------------------------- Read an entry from a user's environment
 3042: 
 3043: sub userenvironment {
 3044:     my ($udom,$unam,@what)=@_;
 3045:     my $items;
 3046:     foreach my $item (@what) {
 3047:         $items.=&escape($item).'&';
 3048:     }
 3049:     $items=~s/\&$//;
 3050:     my %returnhash=();
 3051:     my $uhome = &homeserver($unam,$udom);
 3052:     unless ($uhome eq 'no_host') {
 3053:         my @answer=split(/\&/, 
 3054:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3055:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3056:             return %returnhash;
 3057:         }
 3058:         my $i;
 3059:         for ($i=0;$i<=$#what;$i++) {
 3060: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3061:         }
 3062:     }
 3063:     return %returnhash;
 3064: }
 3065: 
 3066: # ---------------------------------------------------------- Get a studentphoto
 3067: sub studentphoto {
 3068:     my ($udom,$unam,$ext) = @_;
 3069:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3070:     if (defined($env{'request.course.id'})) {
 3071:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3072:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3073:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3074:             } else {
 3075:                 my ($result,$perm_reqd)=
 3076: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3077:                 if ($result eq 'ok') {
 3078:                     if (!($perm_reqd eq 'yes')) {
 3079:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3080:                     }
 3081:                 }
 3082:             }
 3083:         }
 3084:     } else {
 3085:         my ($result,$perm_reqd) = 
 3086: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3087:         if ($result eq 'ok') {
 3088:             if (!($perm_reqd eq 'yes')) {
 3089:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3090:             }
 3091:         }
 3092:     }
 3093:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3094: }
 3095: 
 3096: sub retrievestudentphoto {
 3097:     my ($udom,$unam,$ext,$type) = @_;
 3098:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3099:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3100:     if ($ret eq 'ok') {
 3101:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3102:         if ($type eq 'thumbnail') {
 3103:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3104:         }
 3105:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3106:         return $tokenurl;
 3107:     } else {
 3108:         if ($type eq 'thumbnail') {
 3109:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3110:         } else { 
 3111:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3112:         }
 3113:     }
 3114: }
 3115: 
 3116: # -------------------------------------------------------------------- New chat
 3117: 
 3118: sub chatsend {
 3119:     my ($newentry,$anon,$group)=@_;
 3120:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3122:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3123:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3124: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3125: 		   &escape($newentry)).':'.$group,$chome);
 3126: }
 3127: 
 3128: # ------------------------------------------ Find current version of a resource
 3129: 
 3130: sub getversion {
 3131:     my $fname=&clutter(shift);
 3132:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3133:     return &currentversion(&filelocation('',$fname));
 3134: }
 3135: 
 3136: sub currentversion {
 3137:     my $fname=shift;
 3138:     my $author=$fname;
 3139:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3140:     my ($udom,$uname)=split(/\//,$author);
 3141:     my $home=&homeserver($uname,$udom);
 3142:     if ($home eq 'no_host') { 
 3143:         return -1; 
 3144:     }
 3145:     my $answer=&reply("currentversion:$fname",$home);
 3146:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3147: 	return -1;
 3148:     }
 3149:     return $answer;
 3150: }
 3151: 
 3152: #
 3153: # Return special version number of resource if set by override, empty otherwise
 3154: #
 3155: sub usedversion {
 3156:     my $fname=shift;
 3157:     unless ($fname) { $fname=$env{'request.uri'}; }
 3158:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3159:     if ($urlversion) { return $urlversion; }
 3160:     return '';
 3161: }
 3162: 
 3163: # ----------------------------- Subscribe to a resource, return URL if possible
 3164: 
 3165: sub subscribe {
 3166:     my $fname=shift;
 3167:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3168:     $fname=~s/[\n\r]//g;
 3169:     my $author=$fname;
 3170:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3171:     my ($udom,$uname)=split(/\//,$author);
 3172:     my $home=homeserver($uname,$udom);
 3173:     if ($home eq 'no_host') {
 3174:         return 'not_found';
 3175:     }
 3176:     my $answer=reply("sub:$fname",$home);
 3177:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3178: 	$answer.=' by '.$home;
 3179:     }
 3180:     return $answer;
 3181: }
 3182:     
 3183: # -------------------------------------------------------------- Replicate file
 3184: 
 3185: sub repcopy {
 3186:     my $filename=shift;
 3187:     $filename=~s/\/+/\//g;
 3188:     my $londocroot = $perlvar{'lonDocRoot'};
 3189:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3190:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3191:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3192: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3193: 	return &repcopy_userfile($filename);
 3194:     }
 3195:     $filename=~s/[\n\r]//g;
 3196:     my $transname="$filename.in.transfer";
 3197: # FIXME: this should flock
 3198:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3199:     my $remoteurl=subscribe($filename);
 3200:     if ($remoteurl =~ /^con_lost by/) {
 3201: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3202:            return 'unavailable';
 3203:     } elsif ($remoteurl eq 'not_found') {
 3204: 	   #&logthis("Subscribe returned not_found: $filename");
 3205: 	   return 'not_found';
 3206:     } elsif ($remoteurl =~ /^rejected by/) {
 3207: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3208:            return 'forbidden';
 3209:     } elsif ($remoteurl eq 'directory') {
 3210:            return 'ok';
 3211:     } else {
 3212:         my $author=$filename;
 3213:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3214:         my ($udom,$uname)=split(/\//,$author);
 3215:         my $home=homeserver($uname,$udom);
 3216:         unless ($home eq $perlvar{'lonHostID'}) {
 3217:            my @parts=split(/\//,$filename);
 3218:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3219:            if ($path ne "$londocroot/res") {
 3220:                &logthis("Malconfiguration for replication: $filename");
 3221: 	       return 'bad_request';
 3222:            }
 3223:            my $count;
 3224:            for ($count=5;$count<$#parts;$count++) {
 3225:                $path.="/$parts[$count]";
 3226:                if ((-e $path)!=1) {
 3227: 		   mkdir($path,0777);
 3228:                }
 3229:            }
 3230:            my $request=new HTTP::Request('GET',"$remoteurl");
 3231:            my $response;
 3232:            if ($remoteurl =~ m{/raw/}) {
 3233:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3234:            } else {
 3235:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3236:            }
 3237:            if ($response->is_error()) {
 3238: 	       unlink($transname);
 3239:                my $message=$response->status_line;
 3240:                &logthis("<font color=\"blue\">WARNING:"
 3241:                        ." LWP get: $message: $filename</font>");
 3242:                return 'unavailable';
 3243:            } else {
 3244: 	       if ($remoteurl!~/\.meta$/) {
 3245:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3246:                   my $mresponse;
 3247:                   if ($remoteurl =~ m{/raw/}) {
 3248:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3249:                   } else {
 3250:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3251:                   }
 3252:                   if ($mresponse->is_error()) {
 3253: 		      unlink($filename.'.meta');
 3254:                       &logthis(
 3255:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3256:                   }
 3257: 	       }
 3258:                rename($transname,$filename);
 3259:                return 'ok';
 3260:            }
 3261:        }
 3262:     }
 3263: }
 3264: 
 3265: # ------------------------------------------------ Get server side include body
 3266: sub ssi_body {
 3267:     my ($filelink,%form)=@_;
 3268:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3269:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3270:     }
 3271:     my $output='';
 3272:     my $response;
 3273:     if ($filelink=~/^https?\:/) {
 3274:        ($output,$response)=&externalssi($filelink);
 3275:     } else {
 3276:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3277:        $filelink .= 'inhibitmenu=yes';
 3278:        ($output,$response)=&ssi($filelink,%form);
 3279:     }
 3280:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3281:     $output=~s/^.*?\<body[^\>]*\>//si;
 3282:     $output=~s/\<\/body\s*\>.*?$//si;
 3283:     if (wantarray) {
 3284:         return ($output, $response);
 3285:     } else {
 3286:         return $output;
 3287:     }
 3288: }
 3289: 
 3290: # --------------------------------------------------------- Server Side Include
 3291: 
 3292: sub absolute_url {
 3293:     my ($host_name) = @_;
 3294:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3295:     if ($host_name eq '') {
 3296: 	$host_name = $ENV{'SERVER_NAME'};
 3297:     }
 3298:     return $protocol.$host_name;
 3299: }
 3300: 
 3301: #
 3302: #   Server side include.
 3303: # Parameters:
 3304: #  fn     Possibly encrypted resource name/id.
 3305: #  form   Hash that describes how the rendering should be done
 3306: #         and other things.
 3307: # Returns:
 3308: #   Scalar context: The content of the response.
 3309: #   Array context:  2 element list of the content and the full response object.
 3310: #     
 3311: sub ssi {
 3312: 
 3313:     my ($fn,%form)=@_;
 3314:     my $request;
 3315: 
 3316:     $form{'no_update_last_known'}=1;
 3317:     &Apache::lonenc::check_encrypt(\$fn);
 3318:     if (%form) {
 3319:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3320:       $request->content(join('&',map { 
 3321:             my $name = escape($_);
 3322:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3323:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3324:             : &escape($form{$_}) );    
 3325:         } keys(%form)));
 3326:     } else {
 3327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3328:     }
 3329: 
 3330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3331:     my $lonhost = $perlvar{'lonHostID'};
 3332:     my $islocal;
 3333:     if (($env{'request.course.id'}) &&
 3334:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3335:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3336:         ($form{'grade_symb'} ne '') &&
 3337:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3338:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3339:         $islocal = 1;
 3340:     }
 3341:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3342:                                                 '','','',$islocal);
 3343: 
 3344:     if (wantarray) {
 3345: 	return ($response->content, $response);
 3346:     } else {
 3347: 	return $response->content;
 3348:     }
 3349: }
 3350: 
 3351: sub externalssi {
 3352:     my ($url)=@_;
 3353:     my $request=new HTTP::Request('GET',$url);
 3354:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3355:     if (wantarray) {
 3356:         return ($response->content, $response);
 3357:     } else {
 3358:         return $response->content;
 3359:     }
 3360: }
 3361: 
 3362: 
 3363: # If the local copy of a replicated resource is outdated, trigger a  
 3364: # connection from the homeserver to flush the delayed queue. If no update 
 3365: # happens, remove local copies of outdated resource (and corresponding
 3366: # metadata file).
 3367: 
 3368: sub remove_stale_resfile {
 3369:     my ($url) = @_;
 3370:     my $removed;
 3371:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3372:         my $audom = $1;
 3373:         my $auname = $2;
 3374:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3375:             my $homeserver = &homeserver($auname,$audom);
 3376:             unless (($homeserver eq 'no_host') ||
 3377:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3378:                 my $fname = &filelocation('',$url);
 3379:                 if (-e $fname) {
 3380:                     my $hostname = &hostname($homeserver);
 3381:                     if ($hostname) {
 3382:                         my $protocol = $protocol{$homeserver};
 3383:                         $protocol = 'http' if ($protocol ne 'https');
 3384:                         my $uri = &declutter($url);
 3385:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3386:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3387:                         if ($response->is_success()) {
 3388:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3389:                             my $locmodtime = (stat($fname))[9];
 3390:                             if ($locmodtime < $remmodtime) {
 3391:                                 my $stale;
 3392:                                 my $answer = &reply('pong',$homeserver);
 3393:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3394:                                     sleep(0.2);
 3395:                                     $locmodtime = (stat($fname))[9];
 3396:                                     if ($locmodtime < $remmodtime) {
 3397:                                         my $posstransfer = $fname.'.in.transfer';
 3398:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3399:                                             $removed = 1;
 3400:                                         } else {
 3401:                                             $stale = 1;
 3402:                                         }
 3403:                                     } else {
 3404:                                         $removed = 1;
 3405:                                     }
 3406:                                 } else {
 3407:                                     $stale = 1;
 3408:                                 }
 3409:                                 if ($stale) {
 3410:                                     unlink($fname);
 3411:                                     if ($uri!~/\.meta$/) {
 3412:                                         unlink($fname.'.meta');
 3413:                                     }
 3414:                                     &reply("unsub:$fname",$homeserver);
 3415:                                     $removed = 1;
 3416:                                 }
 3417:                             }
 3418:                         }
 3419:                     }
 3420:                 }
 3421:             }
 3422:         }
 3423:     }
 3424:     return $removed;
 3425: }
 3426: 
 3427: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3428: 
 3429: sub allowuploaded {
 3430:     my ($srcurl,$url)=@_;
 3431:     $url=&clutter(&declutter($url));
 3432:     my $dir=$url;
 3433:     $dir=~s/\/[^\/]+$//;
 3434:     my %httpref=();
 3435:     my $httpurl=&hreflocation('',$url);
 3436:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3437:     &Apache::lonnet::appenv(\%httpref);
 3438: }
 3439: 
 3440: #
 3441: # Determine if the current user should be able to edit a particular resource,
 3442: # when viewing in course context.
 3443: # (a) When viewing resource used to determine if "Edit" item is included in 
 3444: #     Functions.
 3445: # (b) When displaying folder contents in course editor, used to determine if
 3446: #     "Edit" link will be displayed alongside resource.
 3447: #
 3448: #  input: six args -- filename (decluttered), course number, course domain,
 3449: #                   url, symb (if registered) and group (if this is a group
 3450: #                   item -- e.g., bulletin board, group page etc.).
 3451: #  output: array of five scalars -- 
 3452: #          $cfile -- url for file editing if editable on current server
 3453: #          $home -- homeserver of resource (i.e., for author if published,
 3454: #                                           or course if uploaded.).
 3455: #          $switchserver --  1 if server switch will be needed.
 3456: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3457: #          $forceview -- 1 if icon/link should be to go to view mode
 3458: #
 3459: 
 3460: sub can_edit_resource {
 3461:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3462:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3463: #
 3464: # For aboutme pages user can only edit his/her own.
 3465: #
 3466:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3467:         my ($sdom,$sname) = ($1,$2);
 3468:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3469:             $home = $env{'user.home'};
 3470:             $cfile = $resurl;
 3471:             if ($env{'form.forceedit'}) {
 3472:                 $forceview = 1;
 3473:             } else {
 3474:                 $forceedit = 1;
 3475:             }
 3476:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3477:         } else {
 3478:             return;
 3479:         }
 3480:     }
 3481: 
 3482:     if ($env{'request.course.id'}) {
 3483:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3484:         if ($group ne '') {
 3485: # if this is a group homepage or group bulletin board, check group privs
 3486:             my $allowed = 0;
 3487:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3488:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3489:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3490:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3491:                     $allowed = 1;
 3492:                 }
 3493:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3494:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3495:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3496:                     $allowed = 1;
 3497:                 }
 3498:             }
 3499:             if ($allowed) {
 3500:                 $home=&homeserver($cnum,$cdom);
 3501:                 if ($env{'form.forceedit'}) {
 3502:                     $forceview = 1;
 3503:                 } else {
 3504:                     $forceedit = 1;
 3505:                 }
 3506:                 $cfile = $resurl;
 3507:             } else {
 3508:                 return;
 3509:             }
 3510:         } else {
 3511:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3512:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3513:                     return;
 3514:                 }
 3515:             } elsif (!$crsedit) {
 3516: #
 3517: # No edit allowed where CC has switched to student role.
 3518: #
 3519:                 return;
 3520:             }
 3521:         }
 3522:     }
 3523: 
 3524:     if ($file ne '') {
 3525:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3526:             if (&is_course_upload($file,$cnum,$cdom)) {
 3527:                 $uploaded = 1;
 3528:                 $incourse = 1;
 3529:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3530:                     $cfile = &hreflocation('',$file);
 3531:                     if ($env{'form.forceedit'}) {
 3532:                         $forceview = 1;
 3533:                     } else {
 3534:                         $forceedit = 1;
 3535:                     }
 3536:                 }
 3537:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3538:                 $incourse = 1;
 3539:                 if ($env{'form.forceedit'}) {
 3540:                     $forceview = 1;
 3541:                 } else {
 3542:                     $forceedit = 1;
 3543:                 }
 3544:                 $cfile = $resurl;
 3545:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3546:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3547:                     $incourse = 1;
 3548:                     if ($env{'form.forceedit'}) {
 3549:                         $forceview = 1;
 3550:                     } else {
 3551:                         $forceedit = 1;
 3552:                     }
 3553:                     $cfile = $resurl;
 3554:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3555:                     $incourse = 1;
 3556:                     $cfile = $resurl.'/smpedit';
 3557:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3558:                     $incourse = 1;
 3559:                     if ($env{'form.forceedit'}) {
 3560:                         $forceview = 1;
 3561:                     } else {
 3562:                         $forceedit = 1;
 3563:                     }
 3564:                     $cfile = $resurl;
 3565:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3566:                     $incourse = 1;
 3567:                     if ($env{'form.forceedit'}) {
 3568:                         $forceview = 1;
 3569:                     } else {
 3570:                         $forceedit = 1;
 3571:                     }
 3572:                     $cfile = $resurl;
 3573:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3574:                     $incourse = 1;
 3575:                     if ($env{'form.forceedit'}) {
 3576:                         $forceview = 1;
 3577:                     } else {
 3578:                         $forceedit = 1;
 3579:                     }
 3580:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3581:                 }
 3582:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3583:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3584:                 if (&is_on_map($template)) { 
 3585:                     $incourse = 1;
 3586:                     $forceview = 1;
 3587:                     $cfile = $template;
 3588:                 }
 3589:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3590:                     $incourse = 1;
 3591:                     if ($env{'form.forceedit'}) {
 3592:                         $forceview = 1;
 3593:                     } else {
 3594:                         $forceedit = 1;
 3595:                     }
 3596:                     $cfile = $resurl;
 3597:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3598:                 $incourse = 1;
 3599:                 if ($env{'form.forceedit'}) {
 3600:                     $forceview = 1;
 3601:                 } else {
 3602:                     $forceedit = 1;
 3603:                 }
 3604:                 $cfile = $resurl;
 3605:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3606:                 $incourse = 1;
 3607:                 $forceview = 1;
 3608:                 if ($symb) {
 3609:                     my ($map,$id,$res)=&decode_symb($symb);
 3610:                     $env{'request.symb'} = $symb;
 3611:                     $cfile = &clutter($res);
 3612:                 } else {
 3613:                     $cfile = $env{'form.suppurl'};
 3614:                     my $escfile = &unescape($cfile);
 3615:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3616:                         $cfile = '/adm/wrapper'.$escfile;
 3617:                     } else {
 3618:                         $escfile =~ s{^http://}{};
 3619:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3620:                     }
 3621:                 }
 3622:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3623:                 if ($env{'form.forceedit'}) {
 3624:                     $forceview = 1;
 3625:                 } else {
 3626:                     $forceedit = 1;
 3627:                 }
 3628:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3629:             }
 3630:         }
 3631:         if ($uploaded || $incourse) {
 3632:             $home=&homeserver($cnum,$cdom);
 3633:         } elsif ($file !~ m{/$}) {
 3634:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3635:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3636:             # Check that the user has permission to edit this resource
 3637:             my $setpriv = 1;
 3638:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3639:             if (defined($cfudom)) {
 3640:                 $home=&homeserver($cfuname,$cfudom);
 3641:                 $cfile=$file;
 3642:             }
 3643:         }
 3644:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3645:             (($home ne '') && ($home ne 'no_host'))) {
 3646:             my @ids=&current_machine_ids();
 3647:             unless (grep(/^\Q$home\E$/,@ids)) {
 3648:                 $switchserver=1;
 3649:             }
 3650:         }
 3651:     }
 3652:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3653: }
 3654: 
 3655: sub is_course_upload {
 3656:     my ($file,$cnum,$cdom) = @_;
 3657:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3658:     $uploadpath =~ s{^\/}{};
 3659:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3660:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3661:         return 1;
 3662:     }
 3663:     return;
 3664: }
 3665: 
 3666: sub in_course {
 3667:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3668:     if ($hideprivileged) {
 3669:         my $skipuser;
 3670:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3671:         my @possdoms = ($cdom);  
 3672:         if ($coursehash{'checkforpriv'}) { 
 3673:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3674:         }
 3675:         if (&privileged($uname,$udom,\@possdoms)) {
 3676:             $skipuser = 1;
 3677:             if ($coursehash{'nothideprivileged'}) {
 3678:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3679:                     my $user;
 3680:                     if ($item =~ /:/) {
 3681:                         $user = $item;
 3682:                     } else {
 3683:                         $user = join(':',split(/[\@]/,$item));
 3684:                     }
 3685:                     if ($user eq $uname.':'.$udom) {
 3686:                         undef($skipuser);
 3687:                         last;
 3688:                     }
 3689:                 }
 3690:             }
 3691:             if ($skipuser) {
 3692:                 return 0;
 3693:             }
 3694:         }
 3695:     }
 3696:     $type ||= 'any';
 3697:     if (!defined($cdom) || !defined($cnum)) {
 3698:         my $cid  = $env{'request.course.id'};
 3699:         $cdom = $env{'course.'.$cid.'.domain'};
 3700:         $cnum = $env{'course.'.$cid.'.num'};
 3701:     }
 3702:     my $typesref;
 3703:     if (($type eq 'any') || ($type eq 'all')) {
 3704:         $typesref = ['active','previous','future'];
 3705:     } elsif ($type eq 'previous' || $type eq 'future') {
 3706:         $typesref = [$type];
 3707:     }
 3708:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3709:                               $typesref,undef,[$cdom]);
 3710:     my ($tmp) = keys(%roles);
 3711:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3712:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3713:     if (@course_roles > 0) {
 3714:         return 1;
 3715:     }
 3716:     return 0;
 3717: }
 3718: 
 3719: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3720: # input: action, courseID, current domain, intended
 3721: #        path to file, source of file, instruction to parse file for objects,
 3722: #        ref to hash for embedded objects,
 3723: #        ref to hash for codebase of java objects.
 3724: #        reference to scalar to accommodate mime type determined
 3725: #          from File::MMagic if $parser = parse.
 3726: #
 3727: # output: url to file (if action was uploaddoc), 
 3728: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3729: #
 3730: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3731: # course.
 3732: #
 3733: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3734: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3735: #          course's home server.
 3736: #
 3737: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3738: #          be copied from $source (current location) to 
 3739: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3740: #         and will then be copied to
 3741: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3742: #         course's home server.
 3743: #
 3744: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3745: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3746: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3747: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3748: #         in course's home server.
 3749: #
 3750: 
 3751: sub process_coursefile {
 3752:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3753:         $mimetype)=@_;
 3754:     my $fetchresult;
 3755:     my $home=&homeserver($docuname,$docudom);
 3756:     if ($action eq 'propagate') {
 3757:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3758: 			     $home);
 3759:     } else {
 3760:         my $fpath = '';
 3761:         my $fname = $file;
 3762:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3763:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3764:         my $filepath = &build_filepath($fpath);
 3765:         if ($action eq 'copy') {
 3766:             if ($source eq '') {
 3767:                 $fetchresult = 'no source file';
 3768:                 return $fetchresult;
 3769:             } else {
 3770:                 my $destination = $filepath.'/'.$fname;
 3771:                 rename($source,$destination);
 3772:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3773:                                  $home);
 3774:             }
 3775:         } elsif ($action eq 'uploaddoc') {
 3776:             open(my $fh,'>',$filepath.'/'.$fname);
 3777:             print $fh $env{'form.'.$source};
 3778:             close($fh);
 3779:             if ($parser eq 'parse') {
 3780:                 my $mm = new File::MMagic;
 3781:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3782:                 if ($type eq 'text/html') {
 3783:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3784:                     unless ($parse_result eq 'ok') {
 3785:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3786:                     }
 3787:                 }
 3788:                 if (ref($mimetype)) {
 3789:                     $$mimetype = $type;
 3790:                 } 
 3791:             }
 3792:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3793:                                  $home);
 3794:             if ($fetchresult eq 'ok') {
 3795:                 return '/uploaded/'.$fpath.'/'.$fname;
 3796:             } else {
 3797:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3798:                         ' to host '.$home.': '.$fetchresult);
 3799:                 return '/adm/notfound.html';
 3800:             }
 3801:         }
 3802:     }
 3803:     unless ( $fetchresult eq 'ok') {
 3804:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3805:              ' to host '.$home.': '.$fetchresult);
 3806:     }
 3807:     return $fetchresult;
 3808: }
 3809: 
 3810: sub build_filepath {
 3811:     my ($fpath) = @_;
 3812:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3813:     unless ($fpath eq '') {
 3814:         my @parts=split('/',$fpath);
 3815:         foreach my $part (@parts) {
 3816:             $filepath.= '/'.$part;
 3817:             if ((-e $filepath)!=1) {
 3818:                 mkdir($filepath,0777);
 3819:             }
 3820:         }
 3821:     }
 3822:     return $filepath;
 3823: }
 3824: 
 3825: sub store_edited_file {
 3826:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3827:     my $file = $primary_url;
 3828:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3829:     my $fpath = '';
 3830:     my $fname = $file;
 3831:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3832:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3833:     my $filepath = &build_filepath($fpath);
 3834:     open(my $fh,'>',$filepath.'/'.$fname);
 3835:     print $fh $content;
 3836:     close($fh);
 3837:     my $home=&homeserver($docuname,$docudom);
 3838:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3839: 			  $home);
 3840:     if ($$fetchresult eq 'ok') {
 3841:         return '/uploaded/'.$fpath.'/'.$fname;
 3842:     } else {
 3843:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3844: 		 ' to host '.$home.': '.$$fetchresult);
 3845:         return '/adm/notfound.html';
 3846:     }
 3847: }
 3848: 
 3849: sub clean_filename {
 3850:     my ($fname,$args)=@_;
 3851: # Replace Windows backslashes by forward slashes
 3852:     $fname=~s/\\/\//g;
 3853:     if (!$args->{'keep_path'}) {
 3854:         # Get rid of everything but the actual filename
 3855: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3856:     }
 3857: # Replace spaces by underscores
 3858:     $fname=~s/\s+/\_/g;
 3859: # Replace all other weird characters by nothing
 3860:     $fname=~s{[^/\w\.\-]}{}g;
 3861: # Replace all .\d. sequences with _\d. so they no longer look like version
 3862: # numbers
 3863:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3864:     return $fname;
 3865: }
 3866: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3867: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3868: # image with the same aspect ratio as the original, but with dimensions which do 
 3869: # not exceed $resizewidth and $resizeheight.
 3870:  
 3871: sub resizeImage {
 3872:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3873:     my $ima = Image::Magick->new;
 3874:     my $resized;
 3875:     if (-e $img_path) {
 3876:         $ima->Read($img_path);
 3877:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3878:             my $width = $ima->Get('width');
 3879:             my $height = $ima->Get('height');
 3880:             if ($width > $resizewidth) {
 3881: 	        my $factor = $width/$resizewidth;
 3882:                 my $newheight = $height/$factor;
 3883:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3884:                 $resized = 1;
 3885:             }
 3886:         }
 3887:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3888:             my $width = $ima->Get('width');
 3889:             my $height = $ima->Get('height');
 3890:             if ($height > $resizeheight) {
 3891:                 my $factor = $height/$resizeheight;
 3892:                 my $newwidth = $width/$factor;
 3893:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3894:                 $resized = 1;
 3895:             }
 3896:         }
 3897:         if ($resized) {
 3898:             $ima->Write($img_path);
 3899:         }
 3900:     }
 3901:     return;
 3902: }
 3903: 
 3904: # --------------- Take an uploaded file and put it into the userfiles directory
 3905: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3906: #                    the desired filename is in $env{"form.$formname.filename"}
 3907: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3908: #                                    canceloverwrite, scantron or ''.
 3909: #                   if 'coursedoc': upload to the current course
 3910: #                   if 'existingfile': write file to tmp/overwrites directory 
 3911: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3912: #                   $context is passed as argument to &finishuserfileupload
 3913: #        $subdir - directory in userfile to store the file into
 3914: #        $parser - instruction to parse file for objects ($parser = parse) or
 3915: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3916: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 3917: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3918: #        $allfiles - reference to hash for embedded objects
 3919: #        $codebase - reference to hash for codebase of java objects
 3920: #        $desuname - username for permanent storage of uploaded file
 3921: #        $dsetudom - domain for permanaent storage of uploaded file
 3922: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3923: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3924: #        $resizewidth - width (pixels) to which to resize uploaded image
 3925: #        $resizeheight - height (pixels) to which to resize uploaded image
 3926: #        $mimetype - reference to scalar to accommodate mime type determined
 3927: #                    from File::MMagic.
 3928: # 
 3929: # output: url of file in userspace, or error: <message> 
 3930: #             or /adm/notfound.html if failure to upload occurse
 3931: 
 3932: sub userfileupload {
 3933:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3934:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3935:     if (!defined($subdir)) { $subdir='unknown'; }
 3936:     my $fname=$env{'form.'.$formname.'.filename'};
 3937:     $fname=&clean_filename($fname);
 3938:     # See if there is anything left
 3939:     unless ($fname) { return 'error: no uploaded file'; }
 3940:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3941:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3942:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3943:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3944:         my $now = time;
 3945:         my $filepath;
 3946:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3947:              $filepath = 'tmp/helprequests/'.$now;
 3948:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3949:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3950:                          '_'.$env{'user.domain'}.'/pending';
 3951:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3952:             my ($docuname,$docudom);
 3953:             if ($destudom =~ /^$match_domain$/) {
 3954:                 $docudom = $destudom;
 3955:             } else {
 3956:                 $docudom = $env{'user.domain'};
 3957:             }
 3958:             if ($destuname =~ /^$match_username$/) {
 3959:                 $docuname = $destuname;
 3960:             } else {
 3961:                 $docuname = $env{'user.name'};
 3962:             }
 3963:             if (exists($env{'form.group'})) {
 3964:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3965:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3966:             }
 3967:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3968:             if ($context eq 'canceloverwrite') {
 3969:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3970:                 if (-e  $tempfile) {
 3971:                     my @info = stat($tempfile);
 3972:                     if ($info[9] eq $env{'form.timestamp'}) {
 3973:                         unlink($tempfile);
 3974:                     }
 3975:                 }
 3976:                 return;
 3977:             }
 3978:         }
 3979:         # Create the directory if not present
 3980:         my @parts=split(/\//,$filepath);
 3981:         my $fullpath = $perlvar{'lonDaemons'};
 3982:         for (my $i=0;$i<@parts;$i++) {
 3983:             $fullpath .= '/'.$parts[$i];
 3984:             if ((-e $fullpath)!=1) {
 3985:                 mkdir($fullpath,0777);
 3986:             }
 3987:         }
 3988:         open(my $fh,'>',$fullpath.'/'.$fname);
 3989:         print $fh $env{'form.'.$formname};
 3990:         close($fh);
 3991:         if ($context eq 'existingfile') {
 3992:             my @info = stat($fullpath.'/'.$fname);
 3993:             return ($fullpath.'/'.$fname,$info[9]);
 3994:         } else {
 3995:             return $fullpath.'/'.$fname;
 3996:         }
 3997:     }
 3998:     if ($subdir eq 'scantron') {
 3999:         $fname = 'scantron_orig_'.$fname;
 4000:     } else {
 4001:         $fname="$subdir/$fname";
 4002:     }
 4003:     if ($context eq 'coursedoc') {
 4004: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4005: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4006:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4007:             return &finishuserfileupload($docuname,$docudom,
 4008: 					 $formname,$fname,$parser,$allfiles,
 4009: 					 $codebase,$thumbwidth,$thumbheight,
 4010:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4011:         } else {
 4012:             if ($env{'form.folder'}) {
 4013:                 $fname=$env{'form.folder'}.'/'.$fname;
 4014:             }
 4015:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4016: 				       $fname,$formname,$parser,
 4017: 				       $allfiles,$codebase,$mimetype);
 4018:         }
 4019:     } elsif (defined($destuname)) {
 4020:         my $docuname=$destuname;
 4021:         my $docudom=$destudom;
 4022: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4023: 				     $parser,$allfiles,$codebase,
 4024:                                      $thumbwidth,$thumbheight,
 4025:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4026:     } else {
 4027:         my $docuname=$env{'user.name'};
 4028:         my $docudom=$env{'user.domain'};
 4029:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4030:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4031:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4032:         }
 4033: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4034: 				     $parser,$allfiles,$codebase,
 4035:                                      $thumbwidth,$thumbheight,
 4036:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4037:     }
 4038: }
 4039: 
 4040: sub finishuserfileupload {
 4041:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4042:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4043:     my $path=$docudom.'/'.$docuname.'/';
 4044:     my $filepath=$perlvar{'lonDocRoot'};
 4045:   
 4046:     my ($fnamepath,$file,$fetchthumb);
 4047:     $file=$fname;
 4048:     if ($fname=~m|/|) {
 4049:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4050: 	$path.=$fnamepath.'/';
 4051:     }
 4052:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4053:     my $count;
 4054:     for ($count=4;$count<=$#parts;$count++) {
 4055:         $filepath.="/$parts[$count]";
 4056:         if ((-e $filepath)!=1) {
 4057: 	    mkdir($filepath,0777);
 4058:         }
 4059:     }
 4060: 
 4061: # Save the file
 4062:     {
 4063: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4064: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4065: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4066: 	    return '/adm/notfound.html';
 4067: 	}
 4068:         if ($context eq 'overwrite') {
 4069:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4070:             my $target = $filepath.'/'.$file;
 4071:             if (-e $source) {
 4072:                 my @info = stat($source);
 4073:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4074:                     unless (&File::Copy::move($source,$target)) {
 4075:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4076:                         return "Moving from $source failed";
 4077:                     }
 4078:                 } else {
 4079:                     return "Temporary file: $source had unexpected date/time for last modification";
 4080:                 }
 4081:             } else {
 4082:                 return "Temporary file: $source missing";
 4083:             }
 4084:         } elsif (!print FH ($env{'form.'.$formname})) {
 4085: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4086: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4087: 	    return '/adm/notfound.html';
 4088: 	}
 4089: 	close(FH);
 4090:         if ($resizewidth && $resizeheight) {
 4091:             my $mm = new File::MMagic;
 4092:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4093:             if ($mime_type =~ m{^image/}) {
 4094: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4095:             }  
 4096: 	}
 4097:     }
 4098:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4099:         if (ref($mimetype)) {
 4100:             if ($$mimetype eq '') {
 4101:                 my $mm = new File::MMagic;
 4102:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4103:                 $$mimetype = $type;
 4104:             }
 4105:         }
 4106:     }
 4107:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4108:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4109:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4110:                                                        $allfiles,$codebase);
 4111:             unless ($parse_result eq 'ok') {
 4112:                 &logthis('Failed to parse '.$filepath.$file.
 4113: 	   	         ' for embedded media: '.$parse_result); 
 4114:             }
 4115:         }
 4116:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4117:         my $format = $env{'form.scantron_format'};
 4118:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4119:     }
 4120:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4121:         my $input = $filepath.'/'.$file;
 4122:         my $output = $filepath.'/'.'tn-'.$file;
 4123:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4124:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4125:         system({$args[0]} @args);
 4126:         if (-e $filepath.'/'.'tn-'.$file) {
 4127:             $fetchthumb  = 1; 
 4128:         }
 4129:     }
 4130:  
 4131: # Notify homeserver to grep it
 4132: #
 4133:     my $docuhome=&homeserver($docuname,$docudom);	
 4134:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4135:     if ($fetchresult eq 'ok') {
 4136:         if ($fetchthumb) {
 4137:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4138:             if ($thumbresult ne 'ok') {
 4139:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4140:                          $docuhome.': '.$thumbresult);
 4141:             }
 4142:         }
 4143: #
 4144: # Return the URL to it
 4145:         return '/uploaded/'.$path.$file;
 4146:     } else {
 4147:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4148: 		 ': '.$fetchresult);
 4149:         return '/adm/notfound.html';
 4150:     }
 4151: }
 4152: 
 4153: sub extract_embedded_items {
 4154:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4155:     my @state = ();
 4156:     my (%lastids,%related,%shockwave,%flashvars);
 4157:     my %javafiles = (
 4158:                       codebase => '',
 4159:                       code => '',
 4160:                       archive => ''
 4161:                     );
 4162:     my %mediafiles = (
 4163:                       src => '',
 4164:                       movie => '',
 4165:                      );
 4166:     my $p;
 4167:     if ($content) {
 4168:         $p = HTML::LCParser->new($content);
 4169:     } else {
 4170:         $p = HTML::LCParser->new($fullpath);
 4171:     }
 4172:     while (my $t=$p->get_token()) {
 4173: 	if ($t->[0] eq 'S') {
 4174: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4175: 	    push(@state, $tagname);
 4176:             if (lc($tagname) eq 'allow') {
 4177:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4178:             }
 4179: 	    if (lc($tagname) eq 'img') {
 4180: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4181: 	    }
 4182: 	    if (lc($tagname) eq 'a') {
 4183:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4184:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4185:                 }
 4186: 	    }
 4187:             if (lc($tagname) eq 'script') {
 4188:                 my $src;
 4189:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4190:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4191:                 } else {
 4192:                     if ($attr->{'src'} ne '') {
 4193:                         $src = $attr->{'src'};
 4194:                         &add_filetype($allfiles,$src,'src');
 4195:                     }
 4196:                 }
 4197:                 my $text = $p->get_trimmed_text();
 4198:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4199:                     my @swfargs = split(/,/,$1);
 4200:                     foreach my $item (@swfargs) {
 4201:                         $item =~ s/["']//g;
 4202:                         $item =~ s/^\s+//;
 4203:                         $item =~ s/\s+$//;
 4204:                     }
 4205:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4206:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4207:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4208:                         } else {
 4209:                             $related{$swfargs[0]} = [$swfargs[2]];
 4210:                         }
 4211:                     }
 4212:                 }
 4213:             }
 4214:             if (lc($tagname) eq 'link') {
 4215:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4216:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4217:                 }
 4218:             }
 4219: 	    if (lc($tagname) eq 'object' ||
 4220: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4221: 		foreach my $item (keys(%javafiles)) {
 4222: 		    $javafiles{$item} = '';
 4223: 		}
 4224:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4225:                     $lastids{lc($tagname)} = $attr->{'id'};
 4226:                 }
 4227: 	    }
 4228: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4229: 		my $name = lc($attr->{'name'});
 4230: 		foreach my $item (keys(%javafiles)) {
 4231: 		    if ($name eq $item) {
 4232: 			$javafiles{$item} = $attr->{'value'};
 4233: 			last;
 4234: 		    }
 4235: 		}
 4236:                 my $pathfrom;
 4237: 		foreach my $item (keys(%mediafiles)) {
 4238: 		    if ($name eq $item) {
 4239:                         $pathfrom = $attr->{'value'};
 4240:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4241: 			&add_filetype($allfiles,$pathfrom,$name);
 4242: 			last;
 4243: 		    }
 4244: 		}
 4245:                 if ($name eq 'flashvars') {
 4246:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4247:                 }
 4248:                 if ($pathfrom ne '') {
 4249:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4250:                                          $pathfrom);
 4251:                 }
 4252: 	    }
 4253: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4254: 		foreach my $item (keys(%javafiles)) {
 4255: 		    if ($attr->{$item}) {
 4256: 			$javafiles{$item} = $attr->{$item};
 4257: 			last;
 4258: 		    }
 4259: 		}
 4260: 		foreach my $item (keys(%mediafiles)) {
 4261: 		    if ($attr->{$item}) {
 4262: 			&add_filetype($allfiles,$attr->{$item},$item);
 4263: 			last;
 4264: 		    }
 4265: 		}
 4266:                 if (lc($tagname) eq 'embed') {
 4267:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4268:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4269:                                              $attr->{'src'});
 4270:                     }
 4271:                 }
 4272: 	    }
 4273:             if (lc($tagname) eq 'iframe') {
 4274:                 my $src = $attr->{'src'} ;
 4275:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4276:                     &add_filetype($allfiles,$src,'src');
 4277:                 } elsif ($src =~ m{^/}) {
 4278:                     if ($env{'request.course.id'}) {
 4279:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4280:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4281:                         my $url = &hreflocation('',$fullpath);
 4282:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4283:                             my $relpath = $1;
 4284:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4285:                                 &add_filetype($allfiles,$1,'src');
 4286:                             }
 4287:                         }
 4288:                     }
 4289:                 }
 4290:             }
 4291:             if ($t->[4] =~ m{/>$}) {
 4292:                 pop(@state);
 4293:             }
 4294: 	} elsif ($t->[0] eq 'E') {
 4295: 	    my ($tagname) = ($t->[1]);
 4296: 	    if ($javafiles{'codebase'} ne '') {
 4297: 		$javafiles{'codebase'} .= '/';
 4298: 	    }  
 4299: 	    if (lc($tagname) eq 'applet' ||
 4300: 		lc($tagname) eq 'object' ||
 4301: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4302: 		) {
 4303: 		foreach my $item (keys(%javafiles)) {
 4304: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4305: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4306: 			&add_filetype($allfiles,$file,$item);
 4307: 		    }
 4308: 		}
 4309: 	    } 
 4310: 	    pop @state;
 4311: 	}
 4312:     }
 4313:     foreach my $id (sort(keys(%flashvars))) {
 4314:         if ($shockwave{$id} ne '') {
 4315:             my @pairs = split(/\&/,$flashvars{$id});
 4316:             foreach my $pair (@pairs) {
 4317:                 my ($key,$value) = split(/\=/,$pair);
 4318:                 if ($key eq 'thumb') {
 4319:                     &add_filetype($allfiles,$value,$key);
 4320:                 } elsif ($key eq 'content') {
 4321:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4322:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4323:                     if ($ext ne '') {
 4324:                         &add_filetype($allfiles,$path.$value,$ext);
 4325:                     }
 4326:                 }
 4327:             }
 4328:         }
 4329:     }
 4330:     return 'ok';
 4331: }
 4332: 
 4333: sub add_filetype {
 4334:     my ($allfiles,$file,$type)=@_;
 4335:     if (exists($allfiles->{$file})) {
 4336: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4337: 	    push(@{$allfiles->{$file}}, &escape($type));
 4338: 	}
 4339:     } else {
 4340: 	@{$allfiles->{$file}} = (&escape($type));
 4341:     }
 4342: }
 4343: 
 4344: sub embedded_dependency {
 4345:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4346:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4347:         if (($identifier ne '') &&
 4348:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4349:             ($pathfrom ne '')) {
 4350:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4351:             foreach my $dep (@{$related->{$identifier}}) {
 4352:                 &add_filetype($allfiles,$path.$dep,'object');
 4353:             }
 4354:         }
 4355:     }
 4356:     return;
 4357: }
 4358: 
 4359: sub bubblesheet_converter {
 4360:     my ($cdom,$fullpath,$config,$format) = @_;
 4361:     if ((&domain($cdom) ne '') &&
 4362:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/$match_courseid/scantron_orig}) &&
 4363:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4364:         my %csvcols = %{$config};
 4365:         my %csvbynum = reverse(%csvcols);
 4366:         my %scantronconf = &get_scantron_config($format,$cdom);
 4367:         if (keys(%scantronconf)) {
 4368:             my %bynum = (
 4369:                           $scantronconf{CODEstart} => 'CODEstart',
 4370:                           $scantronconf{IDstart}   => 'IDstart',
 4371:                           $scantronconf{PaperID}   => 'PaperID',
 4372:                           $scantronconf{FirstName} => 'FirstName',
 4373:                           $scantronconf{LastName}  => 'LastName',
 4374:                           $scantronconf{Qstart}    => 'Qstart',
 4375:                         );
 4376:             my @ordered;
 4377:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4378:                 push (@ordered,$bynum{$item}));
 4379:             }
 4380:             my %mapstart = (
 4381:                               CODEstart => 'CODE',
 4382:                               IDstart   => 'ID',
 4383:                               PaperID   => 'PaperID',
 4384:                               FirstName => 'FirstName',
 4385:                               LastName  => 'LastName',
 4386:                               Qstart    => 'FirstQuestion',
 4387:                            );
 4388:             my %maplength = (
 4389:                               CODEstart => 'CODElength',
 4390:                               IDstart   => 'IDlength',
 4391:                               PaperID   => 'PaperIDlength',
 4392:                               FirstName => 'FirstNamelength',
 4393:                               LastName  => 'LastNamelength',
 4394:             );
 4395:             if (open(my $fh,'<',$fullpath)) {
 4396:                 my $output;
 4397:                 while (my $line=<$fh>) {
 4398:                     $line =~ s{[\r\n]+$}{};
 4399:                     my %found;
 4400:                     my @values = split(/,/,$line);
 4401:                     my ($qstart,$record);
 4402:                     for (my $i=0; $i<@values; $i++) {
 4403:                         if (($qstart ne '') && ($i > $qstart)) {
 4404:                             $found{'FirstQuestion'} .= $values[$i];
 4405:                         } elsif (exists($csvbynum{$i})) {
 4406:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4407:                                 $qstart = $i;
 4408:                             } else {
 4409:                                 $values[$i] =~ s/^\s+//;
 4410:                                 if ($csvbynum{$i} eq 'PaperID') {
 4411:                                     while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4412:                                         $values[$i] = '0'.$values[$i];
 4413:                                     }
 4414:                                 }
 4415:                             }
 4416:                             $found{$csvbynum{$i}} = $values[$i];
 4417:                         }
 4418:                     }
 4419:                     foreach my $item (@ordered) {
 4420:                         my $currlength = 1+length($record);
 4421:                         my $numspaces = $scantronconf{$item} - $currlength;
 4422:                         if ($numspaces > 0) {
 4423:                             $record .= (' ' x $numspaces);
 4424:                         }
 4425:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4426:                             unless ($item eq 'Qstart') {
 4427:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4428:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4429:                                 }
 4430:                             }
 4431:                             $record .= $found{$mapstart{$item}};
 4432:                         }
 4433:                     }
 4434:                     $output .= "$record\n";
 4435:                 }
 4436:                 close($fh);
 4437:                 if ($output) {
 4438:                     if (open(my $fh,'>',$fullpath)) {
 4439:                         print $fh $output;
 4440:                         close($fh);
 4441:                     }
 4442:                 }
 4443:             }
 4444:         }
 4445:         return;
 4446:     }
 4447: }
 4448: 
 4449: sub get_scantron_config {
 4450:     my ($which,$cdom) = @_;
 4451:     my @lines = &get_scantronformat_file($cdom);
 4452:     my %config;
 4453:     #FIXME probably should move to XML it has already gotten a bit much now
 4454:     foreach my $line (@lines) {
 4455:         my ($name,$descrip)=split(/:/,$line);
 4456:         if ($name ne $which ) { next; }
 4457:         chomp($line);
 4458:         my @config=split(/:/,$line);
 4459:         $config{'name'}=$config[0];
 4460:         $config{'description'}=$config[1];
 4461:         $config{'CODElocation'}=$config[2];
 4462:         $config{'CODEstart'}=$config[3];
 4463:         $config{'CODElength'}=$config[4];
 4464:         $config{'IDstart'}=$config[5];
 4465:         $config{'IDlength'}=$config[6];
 4466:         $config{'Qstart'}=$config[7];
 4467:         $config{'Qlength'}=$config[8];
 4468:         $config{'Qoff'}=$config[9];
 4469:         $config{'Qon'}=$config[10];
 4470:         $config{'PaperID'}=$config[11];
 4471:         $config{'PaperIDlength'}=$config[12];
 4472:         $config{'FirstName'}=$config[13];
 4473:         $config{'FirstNamelength'}=$config[14];
 4474:         $config{'LastName'}=$config[15];
 4475:         $config{'LastNamelength'}=$config[16];
 4476:         $config{'BubblesPerRow'}=$config[17];
 4477:         last;
 4478:     }
 4479:     return %config;
 4480: }
 4481: 
 4482: sub get_scantronformat_file {
 4483:     my ($cdom) = @_;
 4484:     if ($cdom eq '') {
 4485:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4486:     }
 4487:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4488:     my $gottab = 0;
 4489:     my @lines;
 4490:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4491:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4492:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4493:             if ($formatfile ne '-1') {
 4494:                 @lines = split("\n",$formatfile,-1);
 4495:                 $gottab = 1;
 4496:             }
 4497:         }
 4498:     }
 4499:     if (!$gottab) {
 4500:         my $confname = $cdom.'-domainconfig';
 4501:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4502:         my $formatfile = &getfile($default);
 4503:         if ($formatfile ne '-1') {
 4504:             @lines = split("\n",$formatfile,-1);
 4505:             $gottab = 1;
 4506:         }
 4507:     }
 4508:     if (!$gottab) {
 4509:         my @domains = &current_machine_domains();
 4510:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4511:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4512:                 @lines = <$fh>;
 4513:                 close($fh);
 4514:             }  
 4515:         } else {
 4516:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4517:                 @lines = <$fh>;
 4518:                 close($fh);
 4519:             }
 4520:         }
 4521:     }
 4522:     return @lines;
 4523: }
 4524: 
 4525: sub removeuploadedurl {
 4526:     my ($url)=@_;	
 4527:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4528:     return &removeuserfile($uname,$udom,$fname);
 4529: }
 4530: 
 4531: sub removeuserfile {
 4532:     my ($docuname,$docudom,$fname)=@_;
 4533:     my $home=&homeserver($docuname,$docudom);    
 4534:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4535:     if ($result eq 'ok') {	
 4536:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4537:             my $metafile = $fname.'.meta';
 4538:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4539: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4540:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4541:             my $sqlresult = 
 4542:                 &update_portfolio_table($docuname,$docudom,$file,
 4543:                                         'portfolio_metadata',$group,
 4544:                                         'delete');
 4545:         }
 4546:     }
 4547:     return $result;
 4548: }
 4549: 
 4550: sub mkdiruserfile {
 4551:     my ($docuname,$docudom,$dir)=@_;
 4552:     my $home=&homeserver($docuname,$docudom);
 4553:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4554: }
 4555: 
 4556: sub renameuserfile {
 4557:     my ($docuname,$docudom,$old,$new)=@_;
 4558:     my $home=&homeserver($docuname,$docudom);
 4559:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4560:                         &escape("$old").':'.&escape("$new"),$home);
 4561:     if ($result eq 'ok') {
 4562:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4563:             my $oldmeta = $old.'.meta';
 4564:             my $newmeta = $new.'.meta';
 4565:             my $metaresult = 
 4566:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4567: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4568:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4569:             my $sqlresult = 
 4570:                 &update_portfolio_table($docuname,$docudom,$file,
 4571:                                         'portfolio_metadata',$group,
 4572:                                         'delete');
 4573:         }
 4574:     }
 4575:     return $result;
 4576: }
 4577: 
 4578: # ------------------------------------------------------------------------- Log
 4579: 
 4580: sub log {
 4581:     my ($dom,$nam,$hom,$what)=@_;
 4582:     return critical("log:$dom:$nam:$what",$hom);
 4583: }
 4584: 
 4585: # ------------------------------------------------------------------ Course Log
 4586: #
 4587: # This routine flushes several buffers of non-mission-critical nature
 4588: #
 4589: 
 4590: sub flushcourselogs {
 4591:     &logthis('Flushing log buffers');
 4592: #
 4593: # course logs
 4594: # This is a log of all transactions in a course, which can be used
 4595: # for data mining purposes
 4596: #
 4597: # It also collects the courseid database, which lists last transaction
 4598: # times and course titles for all courseids
 4599: #
 4600:     my %courseidbuffer=();
 4601:     foreach my $crsid (keys(%courselogs)) {
 4602:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4603: 		          &escape($courselogs{$crsid}),
 4604: 		          $coursehombuf{$crsid}) eq 'ok') {
 4605: 	    delete $courselogs{$crsid};
 4606:         } else {
 4607:             &logthis('Failed to flush log buffer for '.$crsid);
 4608:             if (length($courselogs{$crsid})>40000) {
 4609:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4610:                         " exceeded maximum size, deleting.</font>");
 4611:                delete $courselogs{$crsid};
 4612:             }
 4613:         }
 4614:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4615:             'description' => $coursedescrbuf{$crsid},
 4616:             'inst_code'    => $courseinstcodebuf{$crsid},
 4617:             'type'        => $coursetypebuf{$crsid},
 4618:             'owner'       => $courseownerbuf{$crsid},
 4619:         };
 4620:     }
 4621: #
 4622: # Write course id database (reverse lookup) to homeserver of courses 
 4623: # Is used in pickcourse
 4624: #
 4625:     foreach my $crs_home (keys(%courseidbuffer)) {
 4626:         my $response = &courseidput(&host_domain($crs_home),
 4627:                                     $courseidbuffer{$crs_home},
 4628:                                     $crs_home,'timeonly');
 4629:     }
 4630: #
 4631: # File accesses
 4632: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4633: #
 4634:     foreach my $entry (keys(%accesshash)) {
 4635:         if ($entry =~ /___count$/) {
 4636:             my ($dom,$name);
 4637:             ($dom,$name,undef)=
 4638: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4639:             if (! defined($dom) || $dom eq '' || 
 4640:                 ! defined($name) || $name eq '') {
 4641:                 my $cid = $env{'request.course.id'};
 4642:                 $dom  = $env{'request.'.$cid.'.domain'};
 4643:                 $name = $env{'request.'.$cid.'.num'};
 4644:             }
 4645:             my $value = $accesshash{$entry};
 4646:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4647:             my %temphash=($url => $value);
 4648:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4649:             if ($result eq 'ok') {
 4650:                 delete $accesshash{$entry};
 4651:             }
 4652:         } else {
 4653:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4654:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4655:             my %temphash=($entry => $accesshash{$entry});
 4656:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4657:                 delete $accesshash{$entry};
 4658:             }
 4659:         }
 4660:     }
 4661: #
 4662: # Roles
 4663: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4664: #
 4665:     foreach my $entry (keys(%userrolehash)) {
 4666:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4667: 	    split(/\:/,$entry);
 4668:         if (&Apache::lonnet::put('nohist_userroles',
 4669:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4670:                 $rudom,$runame) eq 'ok') {
 4671: 	    delete $userrolehash{$entry};
 4672:         }
 4673:     }
 4674: #
 4675: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4676: #
 4677:     my %domrolebuffer = ();
 4678:     foreach my $entry (keys(%domainrolehash)) {
 4679:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4680:         if ($domrolebuffer{$rudom}) {
 4681:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4682:                       '='.&escape($domainrolehash{$entry});
 4683:         } else {
 4684:             $domrolebuffer{$rudom}.=&escape($entry).
 4685:                       '='.&escape($domainrolehash{$entry});
 4686:         }
 4687:         delete $domainrolehash{$entry};
 4688:     }
 4689:     foreach my $dom (keys(%domrolebuffer)) {
 4690: 	my %servers;
 4691: 	if (defined(&domain($dom,'primary'))) {
 4692: 	    my $primary=&domain($dom,'primary');
 4693: 	    my $hostname=&hostname($primary);
 4694: 	    $servers{$primary} = $hostname;
 4695: 	} else { 
 4696: 	    %servers = &get_servers($dom,'library');
 4697: 	}
 4698: 	foreach my $tryserver (keys(%servers)) {
 4699: 	    if (&reply('domroleput:'.$dom.':'.
 4700: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4701: 		last;
 4702: 	    } else {  
 4703: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4704: 	    }
 4705:         }
 4706:     }
 4707:     $dumpcount++;
 4708: }
 4709: 
 4710: sub courselog {
 4711:     my $what=shift;
 4712:     $what=time.':'.$what;
 4713:     unless ($env{'request.course.id'}) { return ''; }
 4714:     $coursedombuf{$env{'request.course.id'}}=
 4715:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4716:     $coursenumbuf{$env{'request.course.id'}}=
 4717:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4718:     $coursehombuf{$env{'request.course.id'}}=
 4719:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4720:     $coursedescrbuf{$env{'request.course.id'}}=
 4721:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4722:     $courseinstcodebuf{$env{'request.course.id'}}=
 4723:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4724:     $courseownerbuf{$env{'request.course.id'}}=
 4725:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4726:     $coursetypebuf{$env{'request.course.id'}}=
 4727:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4728:     if (defined $courselogs{$env{'request.course.id'}}) {
 4729: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4730:     } else {
 4731: 	$courselogs{$env{'request.course.id'}}.=$what;
 4732:     }
 4733:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4734: 	&flushcourselogs();
 4735:     }
 4736: }
 4737: 
 4738: sub courseacclog {
 4739:     my $fnsymb=shift;
 4740:     unless ($env{'request.course.id'}) { return ''; }
 4741:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4742:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4743:         $what.=':POST';
 4744:         # FIXME: Probably ought to escape things....
 4745: 	foreach my $key (keys(%env)) {
 4746:             if ($key=~/^form\.(.*)/) {
 4747:                 my $formitem = $1;
 4748:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4749:                     $what.=':'.$formitem.'='.$env{$key};
 4750:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4751:                     $what.=':'.$formitem.'='.$env{$key};
 4752:                 }
 4753:             }
 4754:         }
 4755:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4756:         # FIXME: We should not be depending on a form parameter that someone
 4757:         # editing lonsearchcat.pm might change in the future.
 4758:         if ($env{'form.phase'} eq 'course_search') {
 4759:             $what.= ':POST';
 4760:             # FIXME: Probably ought to escape things....
 4761:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4762:                                  'crsdiscuss') {
 4763:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4764:             }
 4765:         }
 4766:     }
 4767:     &courselog($what);
 4768: }
 4769: 
 4770: sub countacc {
 4771:     my $url=&declutter(shift);
 4772:     return if (! defined($url) || $url eq '');
 4773:     unless ($env{'request.course.id'}) { return ''; }
 4774: #
 4775: # Mark that this url was used in this course
 4776: #
 4777:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4778: #
 4779: # Increase the access count for this resource in this child process
 4780: #
 4781:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4782:     $accesshash{$key}++;
 4783: }
 4784: 
 4785: sub linklog {
 4786:     my ($from,$to)=@_;
 4787:     $from=&declutter($from);
 4788:     $to=&declutter($to);
 4789:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4790:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4791: }
 4792: 
 4793: sub statslog {
 4794:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4795:     if ($users<2) { return; }
 4796:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4797:             'course'       => $env{'request.course.id'},
 4798:             'sections'     => '"all"',
 4799:             'num_students' => $users,
 4800:             'part'         => $part,
 4801:             'symb'         => $symb,
 4802:             'mean_tries'   => $av_attempts,
 4803:             'deg_of_diff'  => $degdiff});
 4804:     foreach my $key (keys(%dynstore)) {
 4805:         $accesshash{$key}=$dynstore{$key};
 4806:     }
 4807: }
 4808:   
 4809: sub userrolelog {
 4810:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4811:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4812:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4813:        $userrolehash
 4814:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4815:                     =$tend.':'.$tstart;
 4816:     }
 4817:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4818:        $userrolehash
 4819:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4820:                     =$tend.':'.$tstart;
 4821:     }
 4822:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4823:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4824:        $domainrolehash
 4825:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4826:                     = $tend.':'.$tstart;
 4827:     }
 4828: }
 4829: 
 4830: sub courserolelog {
 4831:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4832:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4833:         my $cdom = $1;
 4834:         my $cnum = $2;
 4835:         my $sec = $3;
 4836:         my $namespace = 'rolelog';
 4837:         my %storehash = (
 4838:                            role    => $trole,
 4839:                            start   => $tstart,
 4840:                            end     => $tend,
 4841:                            selfenroll => $selfenroll,
 4842:                            context    => $context,
 4843:                         );
 4844:         if ($trole eq 'gr') {
 4845:             $namespace = 'groupslog';
 4846:             $storehash{'group'} = $sec;
 4847:         } else {
 4848:             $storehash{'section'} = $sec;
 4849:         }
 4850:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4851:                    $domain,$cnum,$cdom);
 4852:         if (($trole ne 'st') || ($sec ne '')) {
 4853:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4854:         }
 4855:     }
 4856:     return;
 4857: }
 4858: 
 4859: sub domainrolelog {
 4860:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4861:     if ($area =~ m{^/($match_domain)/$}) {
 4862:         my $cdom = $1;
 4863:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4864:         my $namespace = 'rolelog';
 4865:         my %storehash = (
 4866:                            role    => $trole,
 4867:                            start   => $tstart,
 4868:                            end     => $tend,
 4869:                            context => $context,
 4870:                         );
 4871:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4872:                    $domain,$domconfiguser,$cdom);
 4873:     }
 4874:     return;
 4875: 
 4876: }
 4877: 
 4878: sub coauthorrolelog {
 4879:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4880:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4881:         my $audom = $1;
 4882:         my $auname = $2;
 4883:         my $namespace = 'rolelog';
 4884:         my %storehash = (
 4885:                            role    => $trole,
 4886:                            start   => $tstart,
 4887:                            end     => $tend,
 4888:                            context => $context,
 4889:                         );
 4890:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4891:                    $domain,$auname,$audom);
 4892:     }
 4893:     return;
 4894: }
 4895: 
 4896: sub get_course_adv_roles {
 4897:     my ($cid,$codes) = @_;
 4898:     $cid=$env{'request.course.id'} unless (defined($cid));
 4899:     my %coursehash=&coursedescription($cid);
 4900:     my $crstype = &Apache::loncommon::course_type($cid);
 4901:     my %nothide=();
 4902:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4903:         if ($user !~ /:/) {
 4904: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4905:         } else {
 4906:             $nothide{$user}=1;
 4907:         }
 4908:     }
 4909:     my @possdoms = ($coursehash{'domain'});
 4910:     if ($coursehash{'checkforpriv'}) {
 4911:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4912:     }
 4913:     my %returnhash=();
 4914:     my %dumphash=
 4915:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4916:     my $now=time;
 4917:     my %privileged;
 4918:     foreach my $entry (keys(%dumphash)) {
 4919: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4920:         if (($tstart) && ($tstart<0)) { next; }
 4921:         if (($tend) && ($tend<$now)) { next; }
 4922:         if (($tstart) && ($now<$tstart)) { next; }
 4923:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4924: 	if ($username eq '' || $domain eq '') { next; }
 4925:         if ((&privileged($username,$domain,\@possdoms)) &&
 4926:             (!$nothide{$username.':'.$domain})) { next; }
 4927: 	if ($role eq 'cr') { next; }
 4928:         if ($codes) {
 4929:             if ($section) { $role .= ':'.$section; }
 4930:             if ($returnhash{$role}) {
 4931:                 $returnhash{$role}.=','.$username.':'.$domain;
 4932:             } else {
 4933:                 $returnhash{$role}=$username.':'.$domain;
 4934:             }
 4935:         } else {
 4936:             my $key=&plaintext($role,$crstype);
 4937:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4938:             if ($returnhash{$key}) {
 4939: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4940:             } else {
 4941:                 $returnhash{$key}=$username.':'.$domain;
 4942:             }
 4943:         }
 4944:     }
 4945:     return %returnhash;
 4946: }
 4947: 
 4948: sub get_my_roles {
 4949:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4950:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4951:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4952:     my (%dumphash,%nothide);
 4953:     if ($context eq 'userroles') {
 4954:         %dumphash = &dump('roles',$udom,$uname);
 4955:     } else {
 4956:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4957:         if ($hidepriv) {
 4958:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4959:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4960:                 if ($user !~ /:/) {
 4961:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4962:                 } else {
 4963:                     $nothide{$user} = 1;
 4964:                 }
 4965:             }
 4966:         }
 4967:     }
 4968:     my %returnhash=();
 4969:     my $now=time;
 4970:     my %privileged;
 4971:     foreach my $entry (keys(%dumphash)) {
 4972:         my ($role,$tend,$tstart);
 4973:         if ($context eq 'userroles') {
 4974:             next if ($entry =~ /^rolesdef/);
 4975: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4976:         } else {
 4977:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4978:         }
 4979:         if (($tstart) && ($tstart<0)) { next; }
 4980:         my $status = 'active';
 4981:         if (($tend) && ($tend<=$now)) {
 4982:             $status = 'previous';
 4983:         } 
 4984:         if (($tstart) && ($now<$tstart)) {
 4985:             $status = 'future';
 4986:         }
 4987:         if (ref($types) eq 'ARRAY') {
 4988:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4989:                 next;
 4990:             } 
 4991:         } else {
 4992:             if ($status ne 'active') {
 4993:                 next;
 4994:             }
 4995:         }
 4996:         my ($rolecode,$username,$domain,$section,$area);
 4997:         if ($context eq 'userroles') {
 4998:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4999:             (undef,$domain,$username,$section) = split(/\//,$area);
 5000:         } else {
 5001:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5002:         }
 5003:         if (ref($roledoms) eq 'ARRAY') {
 5004:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5005:                 next;
 5006:             }
 5007:         }
 5008:         if (ref($roles) eq 'ARRAY') {
 5009:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5010:                 if ($role =~ /^cr\//) {
 5011:                     if (!grep(/^cr$/,@{$roles})) {
 5012:                         next;
 5013:                     }
 5014:                 } elsif ($role =~ /^gr\//) {
 5015:                     if (!grep(/^gr$/,@{$roles})) {
 5016:                         next;
 5017:                     }
 5018:                 } else {
 5019:                     next;
 5020:                 }
 5021:             }
 5022:         }
 5023:         if ($hidepriv) {
 5024:             my @privroles = ('dc','su');
 5025:             if ($context eq 'userroles') {
 5026:                 next if (grep(/^\Q$role\E$/,@privroles));
 5027:             } else {
 5028:                 my $possdoms = [$domain];
 5029:                 if (ref($roledoms) eq 'ARRAY') {
 5030:                    push(@{$possdoms},@{$roledoms}); 
 5031:                 }
 5032:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5033:                     if (!$nothide{$username.':'.$domain}) {
 5034:                         next;
 5035:                     }
 5036:                 }
 5037:             }
 5038:         }
 5039:         if ($withsec) {
 5040:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5041:                 $tstart.':'.$tend;
 5042:         } else {
 5043:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5044:         }
 5045:     }
 5046:     return %returnhash;
 5047: }
 5048: 
 5049: sub get_all_adhocroles {
 5050:     my ($dom) = @_;
 5051:     my @roles_by_num = ();
 5052:     my %domdefaults = &get_domain_defaults($dom);
 5053:     my (%description,%access_in_dom,%access_info);
 5054:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5055:         my $count = 0;
 5056:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5057:         my %ordered;
 5058:         foreach my $role (sort(keys(%domcurrent))) {
 5059:             my ($order,$desc,$access_in_dom);
 5060:             if (ref($domcurrent{$role}) eq 'HASH') {
 5061:                 $order = $domcurrent{$role}{'order'};
 5062:                 $desc = $domcurrent{$role}{'desc'};
 5063:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5064:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5065:             }
 5066:             if ($order eq '') {
 5067:                 $order = $count;
 5068:             }
 5069:             $ordered{$order} = $role;
 5070:             if ($desc ne '') {
 5071:                 $description{$role} = $desc;
 5072:             } else {
 5073:                 $description{$role}= $role;
 5074:             }
 5075:             $count++;
 5076:         }
 5077:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5078:             push(@roles_by_num,$ordered{$item});
 5079:         }
 5080:     }
 5081:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5082: }
 5083: 
 5084: sub get_my_adhocroles {
 5085:     my ($cid,$checkreg) = @_;
 5086:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5087:     if ($env{'request.course.id'} eq $cid) {
 5088:         $cdom = $env{'course.'.$cid.'.domain'};
 5089:         $cnum = $env{'course.'.$cid.'.num'};
 5090:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5091:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5092:         $cdom = $1;
 5093:         $cnum = $2;
 5094:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5095:                                      $cdom,$cnum);
 5096:     }
 5097:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5098:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5099:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5100:         if ($rosterhash{$user} ne '') {
 5101:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5102:             return ([],{}) if ($type eq 'auto');
 5103:         }
 5104:     }
 5105:     if (($cdom ne '') && ($cnum ne ''))  {
 5106:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5107:             my $then=$env{'user.login.time'};
 5108:             my $update=$env{'user.update.time'};
 5109:             if (!$update) {
 5110:                 $update = $then;
 5111:             }
 5112:             my @liveroles;
 5113:             foreach my $role ('dh','da') {
 5114:                 if ($env{"user.role.$role./$cdom/"}) {
 5115:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5116:                     my $limit = $update;
 5117:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5118:                         $limit = $then;
 5119:                     }
 5120:                     my $activerole = 1;
 5121:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5122:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5123:                     if ($activerole) {
 5124:                         push(@liveroles,$role);
 5125:                     }
 5126:                 }
 5127:             }
 5128:             if (@liveroles) {
 5129:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5130:                     my ($accessref,$accessinfo,%access_in_dom);
 5131:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5132:                     if (ref($roles_by_num) eq 'ARRAY') {
 5133:                         if (@{$roles_by_num}) {
 5134:                             my %settings;
 5135:                             if ($env{'request.course.id'} eq $cid) {
 5136:                                 foreach my $envkey (keys(%env)) {
 5137:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5138:                                         $settings{$1} = $env{$envkey};
 5139:                                     }
 5140:                                 }
 5141:                             } else {
 5142:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5143:                             }
 5144:                             my %setincrs;
 5145:                             if ($settings{'internal.adhocaccess'}) {
 5146:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5147:                             }
 5148:                             my @statuses;
 5149:                             if ($env{'environment.inststatus'}) {
 5150:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5151:                             }
 5152:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5153:                             if (ref($accessref) eq 'HASH') {
 5154:                                 %access_in_dom = %{$accessref};
 5155:                             }
 5156:                             foreach my $role (@{$roles_by_num}) {
 5157:                                 my ($curraccess,@okstatus,@personnel);
 5158:                                 if ($setincrs{$role}) {
 5159:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5160:                                     if ($curraccess eq 'status') {
 5161:                                         @okstatus = split(/\&/,$rest);
 5162:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5163:                                         @personnel = split(/\&/,$rest);
 5164:                                     }
 5165:                                 } else {
 5166:                                     $curraccess = $access_in_dom{$role};
 5167:                                     if (ref($accessinfo) eq 'HASH') {
 5168:                                         if ($curraccess eq 'status') {
 5169:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5170:                                                 @okstatus = @{$accessinfo->{$role}};
 5171:                                             }
 5172:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5173:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5174:                                                 @personnel = @{$accessinfo->{$role}};
 5175:                                             }
 5176:                                         }
 5177:                                     }
 5178:                                 }
 5179:                                 if ($curraccess eq 'none') {
 5180:                                     next;
 5181:                                 } elsif ($curraccess eq 'all') {
 5182:                                     push(@possroles,$role);
 5183:                                 } elsif ($curraccess eq 'dh') {
 5184:                                     if (grep(/^dh$/,@liveroles)) {
 5185:                                         push(@possroles,$role);
 5186:                                     } else {
 5187:                                         next;
 5188:                                     }
 5189:                                 } elsif ($curraccess eq 'da') {
 5190:                                     if (grep(/^da$/,@liveroles)) {
 5191:                                         push(@possroles,$role);
 5192:                                     } else {
 5193:                                         next;
 5194:                                     }
 5195:                                 } elsif ($curraccess eq 'status') {
 5196:                                     if (@okstatus) {
 5197:                                         if (!@statuses) {
 5198:                                             if (grep(/^default$/,@okstatus)) {
 5199:                                                 push(@possroles,$role);
 5200:                                             }
 5201:                                         } else {
 5202:                                             foreach my $status (@okstatus) {
 5203:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5204:                                                     push(@possroles,$role);
 5205:                                                     last;
 5206:                                                 }
 5207:                                             }
 5208:                                         }
 5209:                                     }
 5210:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5211:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5212:                                         if ($curraccess eq 'exc') {
 5213:                                             push(@possroles,$role);
 5214:                                         }
 5215:                                     } elsif ($curraccess eq 'inc') {
 5216:                                         push(@possroles,$role);
 5217:                                     }
 5218:                                 }
 5219:                             }
 5220:                         }
 5221:                     }
 5222:                 }
 5223:             }
 5224:         }
 5225:     }
 5226:     unless (ref($description) eq 'HASH') {
 5227:         if (ref($roles_by_num) eq 'ARRAY') {
 5228:             my %desc;
 5229:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5230:             $description = \%desc;
 5231:         } else {
 5232:             $description = {};
 5233:         }
 5234:     }
 5235:     return (\@possroles,$description);
 5236: }
 5237: 
 5238: # ----------------------------------------------------- Frontpage Announcements
 5239: #
 5240: #
 5241: 
 5242: sub postannounce {
 5243:     my ($server,$text)=@_;
 5244:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5245:     unless ($text=~/\w/) { $text=''; }
 5246:     return &reply('setannounce:'.&escape($text),$server);
 5247: }
 5248: 
 5249: sub getannounce {
 5250: 
 5251:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5252: 	my $announcement='';
 5253: 	while (my $line = <$fh>) { $announcement .= $line; }
 5254: 	close($fh);
 5255: 	if ($announcement=~/\w/) { 
 5256: 	    return 
 5257:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5258:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5259: 	} else {
 5260: 	    return '';
 5261: 	}
 5262:     } else {
 5263: 	return '';
 5264:     }
 5265: }
 5266: 
 5267: # ---------------------------------------------------------- Course ID routines
 5268: # Deal with domain's nohist_courseid.db files
 5269: #
 5270: 
 5271: sub courseidput {
 5272:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5273:     return unless (ref($storehash) eq 'HASH');
 5274:     my $outcome;
 5275:     if ($caller eq 'timeonly') {
 5276:         my $cids = '';
 5277:         foreach my $item (keys(%$storehash)) {
 5278:             $cids.=&escape($item).'&';
 5279:         }
 5280:         $cids=~s/\&$//;
 5281:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5282:                           $coursehome);       
 5283:     } else {
 5284:         my $items = '';
 5285:         foreach my $item (keys(%$storehash)) {
 5286:             $items.= &escape($item).'='.
 5287:                      &freeze_escape($$storehash{$item}).'&';
 5288:         }
 5289:         $items=~s/\&$//;
 5290:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5291:                           $coursehome);
 5292:     }
 5293:     if ($outcome eq 'unknown_cmd') {
 5294:         my $what;
 5295:         foreach my $cid (keys(%$storehash)) {
 5296:             $what .= &escape($cid).'=';
 5297:             foreach my $item ('description','inst_code','owner','type') {
 5298:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5299:             }
 5300:             $what =~ s/\:$/&/;
 5301:         }
 5302:         $what =~ s/\&$//;  
 5303:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5304:     } else {
 5305:         return $outcome;
 5306:     }
 5307: }
 5308: 
 5309: sub courseiddump {
 5310:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5311:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5312:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5313:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5314:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5315:     my $as_hash = 1;
 5316:     my %returnhash;
 5317:     if (!$domfilter) { $domfilter=''; }
 5318:     my %libserv = &all_library();
 5319:     foreach my $tryserver (keys(%libserv)) {
 5320:         if ( (  $hostidflag == 1 
 5321: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5322: 	     || (!defined($hostidflag)) ) {
 5323: 
 5324: 	    if (($domfilter eq '') ||
 5325: 		(&host_domain($tryserver) eq $domfilter)) {
 5326:                 my $rep;
 5327:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5328:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5329:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5330:                                 &escape($descfilter), &escape($instcodefilter), 
 5331:                                 &escape($ownerfilter), &escape($coursefilter),
 5332:                                 &escape($typefilter), &escape($regexp_ok), 
 5333:                                 $as_hash, &escape($selfenrollonly), 
 5334:                                 &escape($catfilter), $showhidden, $caller, 
 5335:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5336:                                 &escape($createdbefore), &escape($createdafter), 
 5337:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5338:                                 $reqcrsdom,&escape($reqinstcode))));
 5339:                 } else {
 5340:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5341:                              $sincefilter.':'.&escape($descfilter).':'.
 5342:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5343:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5344:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5345:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5346:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5347:                              &escape($cc_clone).':'.$cloneonly.':'.
 5348:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5349:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5350:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5351:                 }
 5352:                      
 5353:                 my @pairs=split(/\&/,$rep);
 5354:                 foreach my $item (@pairs) {
 5355:                     my ($key,$value)=split(/\=/,$item,2);
 5356:                     $key = &unescape($key);
 5357:                     next if ($key =~ /^error: 2 /);
 5358:                     my $result = &thaw_unescape($value);
 5359:                     if (ref($result) eq 'HASH') {
 5360:                         $returnhash{$key}=$result;
 5361:                     } else {
 5362:                         my @responses = split(/:/,$value);
 5363:                         my @items = ('description','inst_code','owner','type');
 5364:                         for (my $i=0; $i<@responses; $i++) {
 5365:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5366:                         }
 5367:                     }
 5368:                 }
 5369:             }
 5370:         }
 5371:     }
 5372:     return %returnhash;
 5373: }
 5374: 
 5375: sub courselastaccess {
 5376:     my ($cdom,$cnum,$hostidref) = @_;
 5377:     my %returnhash;
 5378:     if ($cdom && $cnum) {
 5379:         my $chome = &homeserver($cnum,$cdom);
 5380:         if ($chome ne 'no_host') {
 5381:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5382:             &extract_lastaccess(\%returnhash,$rep);
 5383:         }
 5384:     } else {
 5385:         if (!$cdom) { $cdom=''; }
 5386:         my %libserv = &all_library();
 5387:         foreach my $tryserver (keys(%libserv)) {
 5388:             if (ref($hostidref) eq 'ARRAY') {
 5389:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5390:             } 
 5391:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5392:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5393:                 &extract_lastaccess(\%returnhash,$rep);
 5394:             }
 5395:         }
 5396:     }
 5397:     return %returnhash;
 5398: }
 5399: 
 5400: sub extract_lastaccess {
 5401:     my ($returnhash,$rep) = @_;
 5402:     if (ref($returnhash) eq 'HASH') {
 5403:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5404:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5405:                  $rep eq '') {
 5406:             my @pairs=split(/\&/,$rep);
 5407:             foreach my $item (@pairs) {
 5408:                 my ($key,$value)=split(/\=/,$item,2);
 5409:                 $key = &unescape($key);
 5410:                 next if ($key =~ /^error: 2 /);
 5411:                 $returnhash->{$key} = &thaw_unescape($value);
 5412:             }
 5413:         }
 5414:     }
 5415:     return;
 5416: }
 5417: 
 5418: # ---------------------------------------------------------- DC e-mail
 5419: 
 5420: sub dcmailput {
 5421:     my ($domain,$msgid,$message,$server)=@_;
 5422:     my $status = &Apache::lonnet::critical(
 5423:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5424:        &escape($message),$server);
 5425:     return $status;
 5426: }
 5427: 
 5428: sub dcmaildump {
 5429:     my ($dom,$startdate,$enddate,$senders) = @_;
 5430:     my %returnhash=();
 5431: 
 5432:     if (defined(&domain($dom,'primary'))) {
 5433:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5434:                                                          &escape($enddate).':';
 5435: 	my @esc_senders=map { &escape($_)} @$senders;
 5436: 	$cmd.=&escape(join('&',@esc_senders));
 5437: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5438:             my ($key,$value) = split(/\=/,$line,2);
 5439:             if (($key) && ($value)) {
 5440:                 $returnhash{&unescape($key)} = &unescape($value);
 5441:             }
 5442:         }
 5443:     }
 5444:     return %returnhash;
 5445: }
 5446: # ---------------------------------------------------------- Domain roles
 5447: 
 5448: sub get_domain_roles {
 5449:     my ($dom,$roles,$startdate,$enddate)=@_;
 5450:     if ((!defined($startdate)) || ($startdate eq '')) {
 5451:         $startdate = '.';
 5452:     }
 5453:     if ((!defined($enddate)) || ($enddate eq '')) {
 5454:         $enddate = '.';
 5455:     }
 5456:     my $rolelist;
 5457:     if (ref($roles) eq 'ARRAY') {
 5458:         $rolelist = join('&',@{$roles});
 5459:     }
 5460:     my %personnel = ();
 5461: 
 5462:     my %servers = &get_servers($dom,'library');
 5463:     foreach my $tryserver (keys(%servers)) {
 5464: 	%{$personnel{$tryserver}}=();
 5465: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5466: 					    &escape($startdate).':'.
 5467: 					    &escape($enddate).':'.
 5468: 					    &escape($rolelist), $tryserver))) {
 5469: 	    my ($key,$value) = split(/\=/,$line,2);
 5470: 	    if (($key) && ($value)) {
 5471: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5472: 	    }
 5473: 	}
 5474:     }
 5475:     return %personnel;
 5476: }
 5477: 
 5478: sub get_active_domroles {
 5479:     my ($dom,$roles) = @_;
 5480:     return () unless (ref($roles) eq 'ARRAY');
 5481:     my $now = time;
 5482:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5483:     my %domroles;
 5484:     foreach my $server (keys(%dompersonnel)) {
 5485:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5486:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5487:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5488:         }
 5489:     }
 5490:     return %domroles;
 5491: }
 5492: 
 5493: # ----------------------------------------------------------- Interval timing 
 5494: 
 5495: {
 5496: # Caches needed for speedup of navmaps
 5497: # We don't want to cache this for very long at all (5 seconds at most)
 5498: # 
 5499: # The user for whom we cache
 5500: my $cachedkey='';
 5501: # The cached times for this user
 5502: my %cachedtimes=();
 5503: # When this was last done
 5504: my $cachedtime='';
 5505: 
 5506: sub load_all_first_access {
 5507:     my ($uname,$udom,$ignorecache)=@_;
 5508:     if (($cachedkey eq $uname.':'.$udom) &&
 5509:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5510:         (!$ignorecache)) {
 5511:         return;
 5512:     }
 5513:     $cachedtime=time;
 5514:     $cachedkey=$uname.':'.$udom;
 5515:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5516: }
 5517: 
 5518: sub get_first_access {
 5519:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5520:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5521:     if ($argsymb) { $symb=$argsymb; }
 5522:     my ($map,$id,$res)=&decode_symb($symb);
 5523:     if ($argmap) { $map = $argmap; }
 5524:     if ($type eq 'course') {
 5525: 	$res='course';
 5526:     } elsif ($type eq 'map') {
 5527: 	$res=&symbread($map);
 5528:     } else {
 5529: 	$res=$symb;
 5530:     }
 5531:     &load_all_first_access($uname,$udom,$ignorecache);
 5532:     return $cachedtimes{"$courseid\0$res"};
 5533: }
 5534: 
 5535: sub set_first_access {
 5536:     my ($type,$interval)=@_;
 5537:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5538:     my ($map,$id,$res)=&decode_symb($symb);
 5539:     if ($type eq 'course') {
 5540: 	$res='course';
 5541:     } elsif ($type eq 'map') {
 5542: 	$res=&symbread($map);
 5543:     } else {
 5544: 	$res=$symb;
 5545:     }
 5546:     $cachedkey='';
 5547:     my $firstaccess=&get_first_access($type,$symb,$map);
 5548:     if ($firstaccess) {
 5549:         &logthis("First access time already set ($firstaccess) when attempting ".
 5550:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5551:                  "in $courseid");
 5552:         return 'already_set';
 5553:     } else {
 5554:         my $start = time;
 5555: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5556:                           $udom,$uname);
 5557:         if ($putres eq 'ok') {
 5558:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5559:                  $udom,$uname); 
 5560:             &appenv(
 5561:                      {
 5562:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5563:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5564:                      }
 5565:                   );
 5566:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5567:                 $cachedtimes{"$courseid\0$res"} = $start;
 5568:             }
 5569:         } elsif ($putres ne 'refused') {
 5570:             &logthis("Result: $putres when attempting to set first access time ".
 5571:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5572:         }
 5573:         return $putres;
 5574:     }
 5575:     return 'already_set';
 5576: }
 5577: }
 5578: 
 5579: # --------------------------------------------- Set Expire Date for Spreadsheet
 5580: 
 5581: sub expirespread {
 5582:     my ($uname,$udom,$stype,$usymb)=@_;
 5583:     my $cid=$env{'request.course.id'}; 
 5584:     if ($cid) {
 5585:        my $now=time;
 5586:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5587:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5588:                             $env{'course.'.$cid.'.num'}.
 5589: 	        	    ':nohist_expirationdates:'.
 5590:                             &escape($key).'='.$now,
 5591:                             $env{'course.'.$cid.'.home'})
 5592:     }
 5593:     return 'ok';
 5594: }
 5595: 
 5596: # ----------------------------------------------------- Devalidate Spreadsheets
 5597: 
 5598: sub devalidate {
 5599:     my ($symb,$uname,$udom)=@_;
 5600:     my $cid=$env{'request.course.id'}; 
 5601:     if ($cid) {
 5602:         # delete the stored spreadsheets for
 5603:         # - the student level sheet of this user in course's homespace
 5604:         # - the assessment level sheet for this resource 
 5605:         #   for this user in user's homespace
 5606: 	# - current conditional state info
 5607: 	my $key=$uname.':'.$udom.':';
 5608:         my $status=
 5609: 	    &del('nohist_calculatedsheets',
 5610: 		 [$key.'studentcalc:'],
 5611: 		 $env{'course.'.$cid.'.domain'},
 5612: 		 $env{'course.'.$cid.'.num'})
 5613: 		.' '.
 5614: 	    &del('nohist_calculatedsheets_'.$cid,
 5615: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5616:         unless ($status eq 'ok ok') {
 5617:            &logthis('Could not devalidate spreadsheet '.
 5618:                     $uname.' at '.$udom.' for '.
 5619: 		    $symb.': '.$status);
 5620:         }
 5621: 	&delenv('user.state.'.$cid);
 5622:     }
 5623: }
 5624: 
 5625: sub get_scalar {
 5626:     my ($string,$end) = @_;
 5627:     my $value;
 5628:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5629: 	$value = $1;
 5630:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5631: 	$value = $1;
 5632:     }
 5633:     return &unescape($value);
 5634: }
 5635: 
 5636: sub array2str {
 5637:   my (@array) = @_;
 5638:   my $result=&arrayref2str(\@array);
 5639:   $result=~s/^__ARRAY_REF__//;
 5640:   $result=~s/__END_ARRAY_REF__$//;
 5641:   return $result;
 5642: }
 5643: 
 5644: sub arrayref2str {
 5645:   my ($arrayref) = @_;
 5646:   my $result='__ARRAY_REF__';
 5647:   foreach my $elem (@$arrayref) {
 5648:     if(ref($elem) eq 'ARRAY') {
 5649:       $result.=&arrayref2str($elem).'&';
 5650:     } elsif(ref($elem) eq 'HASH') {
 5651:       $result.=&hashref2str($elem).'&';
 5652:     } elsif(ref($elem)) {
 5653:       #print("Got a ref of ".(ref($elem))." skipping.");
 5654:     } else {
 5655:       $result.=&escape($elem).'&';
 5656:     }
 5657:   }
 5658:   $result=~s/\&$//;
 5659:   $result .= '__END_ARRAY_REF__';
 5660:   return $result;
 5661: }
 5662: 
 5663: sub hash2str {
 5664:   my (%hash) = @_;
 5665:   my $result=&hashref2str(\%hash);
 5666:   $result=~s/^__HASH_REF__//;
 5667:   $result=~s/__END_HASH_REF__$//;
 5668:   return $result;
 5669: }
 5670: 
 5671: sub hashref2str {
 5672:   my ($hashref)=@_;
 5673:   my $result='__HASH_REF__';
 5674:   foreach my $key (sort(keys(%$hashref))) {
 5675:     if (ref($key) eq 'ARRAY') {
 5676:       $result.=&arrayref2str($key).'=';
 5677:     } elsif (ref($key) eq 'HASH') {
 5678:       $result.=&hashref2str($key).'=';
 5679:     } elsif (ref($key)) {
 5680:       $result.='=';
 5681:       #print("Got a ref of ".(ref($key))." skipping.");
 5682:     } else {
 5683: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5684:     }
 5685: 
 5686:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5687:       $result.=&arrayref2str($hashref->{$key}).'&';
 5688:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5689:       $result.=&hashref2str($hashref->{$key}).'&';
 5690:     } elsif(ref($hashref->{$key})) {
 5691:        $result.='&';
 5692:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5693:     } else {
 5694:       $result.=&escape($hashref->{$key}).'&';
 5695:     }
 5696:   }
 5697:   $result=~s/\&$//;
 5698:   $result .= '__END_HASH_REF__';
 5699:   return $result;
 5700: }
 5701: 
 5702: sub str2hash {
 5703:     my ($string)=@_;
 5704:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5705:     return %$hash;
 5706: }
 5707: 
 5708: sub str2hashref {
 5709:   my ($string) = @_;
 5710: 
 5711:   my %hash;
 5712: 
 5713:   if($string !~ /^__HASH_REF__/) {
 5714:       if (! ($string eq '' || !defined($string))) {
 5715: 	  $hash{'error'}='Not hash reference';
 5716:       }
 5717:       return (\%hash, $string);
 5718:   }
 5719: 
 5720:   $string =~ s/^__HASH_REF__//;
 5721: 
 5722:   while($string !~ /^__END_HASH_REF__/) {
 5723:       #key
 5724:       my $key='';
 5725:       if($string =~ /^__HASH_REF__/) {
 5726:           ($key, $string)=&str2hashref($string);
 5727:           if(defined($key->{'error'})) {
 5728:               $hash{'error'}='Bad data';
 5729:               return (\%hash, $string);
 5730:           }
 5731:       } elsif($string =~ /^__ARRAY_REF__/) {
 5732:           ($key, $string)=&str2arrayref($string);
 5733:           if($key->[0] eq 'Array reference error') {
 5734:               $hash{'error'}='Bad data';
 5735:               return (\%hash, $string);
 5736:           }
 5737:       } else {
 5738:           $string =~ s/^(.*?)=//;
 5739: 	  $key=&unescape($1);
 5740:       }
 5741:       $string =~ s/^=//;
 5742: 
 5743:       #value
 5744:       my $value='';
 5745:       if($string =~ /^__HASH_REF__/) {
 5746:           ($value, $string)=&str2hashref($string);
 5747:           if(defined($value->{'error'})) {
 5748:               $hash{'error'}='Bad data';
 5749:               return (\%hash, $string);
 5750:           }
 5751:       } elsif($string =~ /^__ARRAY_REF__/) {
 5752:           ($value, $string)=&str2arrayref($string);
 5753:           if($value->[0] eq 'Array reference error') {
 5754:               $hash{'error'}='Bad data';
 5755:               return (\%hash, $string);
 5756:           }
 5757:       } else {
 5758: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5759:       }
 5760:       $string =~ s/^&//;
 5761: 
 5762:       $hash{$key}=$value;
 5763:   }
 5764: 
 5765:   $string =~ s/^__END_HASH_REF__//;
 5766: 
 5767:   return (\%hash, $string);
 5768: }
 5769: 
 5770: sub str2array {
 5771:     my ($string)=@_;
 5772:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5773:     return @$array;
 5774: }
 5775: 
 5776: sub str2arrayref {
 5777:   my ($string) = @_;
 5778:   my @array;
 5779: 
 5780:   if($string !~ /^__ARRAY_REF__/) {
 5781:       if (! ($string eq '' || !defined($string))) {
 5782: 	  $array[0]='Array reference error';
 5783:       }
 5784:       return (\@array, $string);
 5785:   }
 5786: 
 5787:   $string =~ s/^__ARRAY_REF__//;
 5788: 
 5789:   while($string !~ /^__END_ARRAY_REF__/) {
 5790:       my $value='';
 5791:       if($string =~ /^__HASH_REF__/) {
 5792:           ($value, $string)=&str2hashref($string);
 5793:           if(defined($value->{'error'})) {
 5794:               $array[0] ='Array reference error';
 5795:               return (\@array, $string);
 5796:           }
 5797:       } elsif($string =~ /^__ARRAY_REF__/) {
 5798:           ($value, $string)=&str2arrayref($string);
 5799:           if($value->[0] eq 'Array reference error') {
 5800:               $array[0] ='Array reference error';
 5801:               return (\@array, $string);
 5802:           }
 5803:       } else {
 5804: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5805:       }
 5806:       $string =~ s/^&//;
 5807: 
 5808:       push(@array, $value);
 5809:   }
 5810: 
 5811:   $string =~ s/^__END_ARRAY_REF__//;
 5812: 
 5813:   return (\@array, $string);
 5814: }
 5815: 
 5816: # -------------------------------------------------------------------Temp Store
 5817: 
 5818: sub tmpreset {
 5819:   my ($symb,$namespace,$domain,$stuname) = @_;
 5820:   if (!$symb) {
 5821:     $symb=&symbread();
 5822:     if (!$symb) { $symb= $env{'request.url'}; }
 5823:   }
 5824:   $symb=escape($symb);
 5825: 
 5826:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5827:   $namespace=~s/\//\_/g;
 5828:   $namespace=~s/\W//g;
 5829: 
 5830:   if (!$domain) { $domain=$env{'user.domain'}; }
 5831:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5832:   if ($domain eq 'public' && $stuname eq 'public') {
 5833:       $stuname=$ENV{'REMOTE_ADDR'};
 5834:   }
 5835:   my $path=LONCAPA::tempdir();
 5836:   my %hash;
 5837:   if (tie(%hash,'GDBM_File',
 5838: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5839: 	  &GDBM_WRCREAT(),0640)) {
 5840:     foreach my $key (keys(%hash)) {
 5841:       if ($key=~ /:$symb/) {
 5842: 	delete($hash{$key});
 5843:       }
 5844:     }
 5845:   }
 5846: }
 5847: 
 5848: sub tmpstore {
 5849:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5850: 
 5851:   if (!$symb) {
 5852:     $symb=&symbread();
 5853:     if (!$symb) { $symb= $env{'request.url'}; }
 5854:   }
 5855:   $symb=escape($symb);
 5856: 
 5857:   if (!$namespace) {
 5858:     # I don't think we would ever want to store this for a course.
 5859:     # it seems this will only be used if we don't have a course.
 5860:     #$namespace=$env{'request.course.id'};
 5861:     #if (!$namespace) {
 5862:       $namespace=$env{'request.state'};
 5863:     #}
 5864:   }
 5865:   $namespace=~s/\//\_/g;
 5866:   $namespace=~s/\W//g;
 5867:   if (!$domain) { $domain=$env{'user.domain'}; }
 5868:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5869:   if ($domain eq 'public' && $stuname eq 'public') {
 5870:       $stuname=$ENV{'REMOTE_ADDR'};
 5871:   }
 5872:   my $now=time;
 5873:   my %hash;
 5874:   my $path=LONCAPA::tempdir();
 5875:   if (tie(%hash,'GDBM_File',
 5876: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5877: 	  &GDBM_WRCREAT(),0640)) {
 5878:     $hash{"version:$symb"}++;
 5879:     my $version=$hash{"version:$symb"};
 5880:     my $allkeys=''; 
 5881:     foreach my $key (keys(%$storehash)) {
 5882:       $allkeys.=$key.':';
 5883:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5884:     }
 5885:     $hash{"$version:$symb:timestamp"}=$now;
 5886:     $allkeys.='timestamp';
 5887:     $hash{"$version:keys:$symb"}=$allkeys;
 5888:     if (untie(%hash)) {
 5889:       return 'ok';
 5890:     } else {
 5891:       return "error:$!";
 5892:     }
 5893:   } else {
 5894:     return "error:$!";
 5895:   }
 5896: }
 5897: 
 5898: # -----------------------------------------------------------------Temp Restore
 5899: 
 5900: sub tmprestore {
 5901:   my ($symb,$namespace,$domain,$stuname) = @_;
 5902: 
 5903:   if (!$symb) {
 5904:     $symb=&symbread();
 5905:     if (!$symb) { $symb= $env{'request.url'}; }
 5906:   }
 5907:   $symb=escape($symb);
 5908: 
 5909:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5910: 
 5911:   if (!$domain) { $domain=$env{'user.domain'}; }
 5912:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5913:   if ($domain eq 'public' && $stuname eq 'public') {
 5914:       $stuname=$ENV{'REMOTE_ADDR'};
 5915:   }
 5916:   my %returnhash;
 5917:   $namespace=~s/\//\_/g;
 5918:   $namespace=~s/\W//g;
 5919:   my %hash;
 5920:   my $path=LONCAPA::tempdir();
 5921:   if (tie(%hash,'GDBM_File',
 5922: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5923: 	  &GDBM_READER(),0640)) {
 5924:     my $version=$hash{"version:$symb"};
 5925:     $returnhash{'version'}=$version;
 5926:     my $scope;
 5927:     for ($scope=1;$scope<=$version;$scope++) {
 5928:       my $vkeys=$hash{"$scope:keys:$symb"};
 5929:       my @keys=split(/:/,$vkeys);
 5930:       my $key;
 5931:       $returnhash{"$scope:keys"}=$vkeys;
 5932:       foreach $key (@keys) {
 5933: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5934: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5935:       }
 5936:     }
 5937:     if (!(untie(%hash))) {
 5938:       return "error:$!";
 5939:     }
 5940:   } else {
 5941:     return "error:$!";
 5942:   }
 5943:   return %returnhash;
 5944: }
 5945: 
 5946: # ----------------------------------------------------------------------- Store
 5947: 
 5948: sub store {
 5949:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5950:     my $home='';
 5951: 
 5952:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5953: 
 5954:     $symb=&symbclean($symb);
 5955:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5956: 
 5957:     if (!$domain) { $domain=$env{'user.domain'}; }
 5958:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5959: 
 5960:     &devalidate($symb,$stuname,$domain);
 5961: 
 5962:     $symb=escape($symb);
 5963:     if (!$namespace) { 
 5964:        unless ($namespace=$env{'request.course.id'}) { 
 5965:           return ''; 
 5966:        } 
 5967:     }
 5968:     if (!$home) { $home=$env{'user.home'}; }
 5969: 
 5970:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5971:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5972: 
 5973:     my $namevalue='';
 5974:     foreach my $key (keys(%$storehash)) {
 5975:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5976:     }
 5977:     $namevalue=~s/\&$//;
 5978:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5979:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5980: }
 5981: 
 5982: # -------------------------------------------------------------- Critical Store
 5983: 
 5984: sub cstore {
 5985:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5986:     my $home='';
 5987: 
 5988:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5989: 
 5990:     $symb=&symbclean($symb);
 5991:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5992: 
 5993:     if (!$domain) { $domain=$env{'user.domain'}; }
 5994:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5995: 
 5996:     &devalidate($symb,$stuname,$domain);
 5997: 
 5998:     $symb=escape($symb);
 5999:     if (!$namespace) { 
 6000:        unless ($namespace=$env{'request.course.id'}) { 
 6001:           return ''; 
 6002:        } 
 6003:     }
 6004:     if (!$home) { $home=$env{'user.home'}; }
 6005: 
 6006:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6007:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6008: 
 6009:     my $namevalue='';
 6010:     foreach my $key (keys(%$storehash)) {
 6011:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6012:     }
 6013:     $namevalue=~s/\&$//;
 6014:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6015:     return critical
 6016:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6017: }
 6018: 
 6019: # --------------------------------------------------------------------- Restore
 6020: 
 6021: sub restore {
 6022:     my ($symb,$namespace,$domain,$stuname) = @_;
 6023:     my $home='';
 6024: 
 6025:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6026: 
 6027:     if (!$symb) {
 6028:         return if ($namespace eq 'courserequests');
 6029:         unless ($symb=escape(&symbread())) { return ''; }
 6030:     } else {
 6031:         unless ($namespace eq 'courserequests') {
 6032:             $symb=&escape(&symbclean($symb));
 6033:         }
 6034:     }
 6035:     if (!$namespace) { 
 6036:        unless ($namespace=$env{'request.course.id'}) { 
 6037:           return ''; 
 6038:        } 
 6039:     }
 6040:     if (!$domain) { $domain=$env{'user.domain'}; }
 6041:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6042:     if (!$home) { $home=$env{'user.home'}; }
 6043:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6044: 
 6045:     my %returnhash=();
 6046:     foreach my $line (split(/\&/,$answer)) {
 6047: 	my ($name,$value)=split(/\=/,$line);
 6048:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6049:     }
 6050:     my $version;
 6051:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6052:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6053:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6054:        }
 6055:     }
 6056:     return %returnhash;
 6057: }
 6058: 
 6059: # ---------------------------------------------------------- Course Description
 6060: #
 6061: #  
 6062: 
 6063: sub coursedescription {
 6064:     my ($courseid,$args)=@_;
 6065:     $courseid=~s/^\///;
 6066:     $courseid=~s/\_/\//g;
 6067:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6068:     my $chome=&homeserver($cnum,$cdomain);
 6069:     my $normalid=$cdomain.'_'.$cnum;
 6070:     # need to always cache even if we get errors otherwise we keep 
 6071:     # trying and trying and trying to get the course description.
 6072:     my %envhash=();
 6073:     my %returnhash=();
 6074:     
 6075:     my $expiretime=600;
 6076:     if ($env{'request.course.id'} eq $normalid) {
 6077: 	$expiretime=120;
 6078:     }
 6079: 
 6080:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6081:     if (!$args->{'freshen_cache'}
 6082: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6083: 	foreach my $key (keys(%env)) {
 6084: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6085: 	    my ($setting) = $1;
 6086: 	    $returnhash{$setting} = $env{$key};
 6087: 	}
 6088: 	return %returnhash;
 6089:     }
 6090: 
 6091:     # get the data again
 6092: 
 6093:     if (!$args->{'one_time'}) {
 6094: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6095:     }
 6096: 
 6097:     if ($chome ne 'no_host') {
 6098:        %returnhash=&dump('environment',$cdomain,$cnum);
 6099:        if (!exists($returnhash{'con_lost'})) {
 6100: 	   my $username = $env{'user.name'}; # Defult username
 6101: 	   if(defined $args->{'user'}) {
 6102: 	       $username = $args->{'user'};
 6103: 	   }
 6104:            $returnhash{'home'}= $chome;
 6105: 	   $returnhash{'domain'} = $cdomain;
 6106: 	   $returnhash{'num'} = $cnum;
 6107:            if (!defined($returnhash{'type'})) {
 6108:                $returnhash{'type'} = 'Course';
 6109:            }
 6110:            while (my ($name,$value) = each %returnhash) {
 6111:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6112:            }
 6113:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6114:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6115: 	       $username.'_'.$cdomain.'_'.$cnum;
 6116:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6117:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6118:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6119:        }
 6120:     }
 6121:     if (!$args->{'one_time'}) {
 6122: 	&appenv(\%envhash);
 6123:     }
 6124:     return %returnhash;
 6125: }
 6126: 
 6127: sub update_released_required {
 6128:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6129:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6130:         $cid = $env{'request.course.id'};
 6131:         $cdom = $env{'course.'.$cid.'.domain'};
 6132:         $cnum = $env{'course.'.$cid.'.num'};
 6133:         $chome = $env{'course.'.$cid.'.home'};
 6134:     }
 6135:     if ($needsrelease) {
 6136:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6137:         my $needsupdate;
 6138:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6139:             $needsupdate = 1;
 6140:         } else {
 6141:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6142:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6143:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6144:                 $needsupdate = 1;
 6145:             }
 6146:         }
 6147:         if ($needsupdate) {
 6148:             my %needshash = (
 6149:                              'internal.releaserequired' => $needsrelease,
 6150:                             );
 6151:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6152:             if ($putresult eq 'ok') {
 6153:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6154:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6155:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6156:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6157:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6158:                 }
 6159:             }
 6160:         }
 6161:     }
 6162:     return;
 6163: }
 6164: 
 6165: # -------------------------------------------------See if a user is privileged
 6166: 
 6167: sub privileged {
 6168:     my ($username,$domain,$possdomains,$possroles)=@_;
 6169:     my $now = time;
 6170:     my $roles;
 6171:     if (ref($possroles) eq 'ARRAY') {
 6172:         $roles = $possroles; 
 6173:     } else {
 6174:         $roles = ['dc','su'];
 6175:     }
 6176:     if (ref($possdomains) eq 'ARRAY') {
 6177:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6178:         foreach my $dom (@{$possdomains}) {
 6179:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6180:                 (ref($privileged{$dom}) eq 'HASH')) {
 6181:                 foreach my $role (@{$roles}) {
 6182:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6183:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6184:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6185:                             return 1 unless (($end && $end < $now) ||
 6186:                                              ($start && $start > $now));
 6187:                         }
 6188:                     }
 6189:                 }
 6190:             }
 6191:         }
 6192:     } else {
 6193:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6194:         my $now = time;
 6195: 
 6196:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6197:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6198:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6199:                 return 1 unless ($tend && $tend < $now) 
 6200:                         or ($tstart && $tstart > $now);
 6201:             }
 6202:         }
 6203:     }
 6204:     return 0;
 6205: }
 6206: 
 6207: sub privileged_by_domain {
 6208:     my ($domains,$roles) = @_;
 6209:     my %privileged = ();
 6210:     my $cachetime = 60*60*24;
 6211:     my $now = time;
 6212:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6213:         return %privileged;
 6214:     }
 6215:     foreach my $dom (@{$domains}) {
 6216:         next if (ref($privileged{$dom}) eq 'HASH');
 6217:         my $needroles;
 6218:         foreach my $role (@{$roles}) {
 6219:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6220:             if (defined($cached)) {
 6221:                 if (ref($result) eq 'HASH') {
 6222:                     $privileged{$dom}{$role} = $result;
 6223:                 }
 6224:             } else {
 6225:                 $needroles = 1;
 6226:             }
 6227:         }
 6228:         if ($needroles) {
 6229:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6230:             $privileged{$dom} = {};
 6231:             foreach my $server (keys(%dompersonnel)) {
 6232:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6233:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6234:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6235:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6236:                         next if ($end && $end < $now);
 6237:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6238:                             $dompersonnel{$server}{$item};
 6239:                     }
 6240:                 }
 6241:             }
 6242:             if (ref($privileged{$dom}) eq 'HASH') {
 6243:                 foreach my $role (@{$roles}) {
 6244:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6245:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6246:                     } else {
 6247:                         my %hash = ();
 6248:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6249:                     }
 6250:                 }
 6251:             }
 6252:         }
 6253:     }
 6254:     return %privileged;
 6255: }
 6256: 
 6257: # -------------------------------------------------------- Get user privileges
 6258: 
 6259: sub rolesinit {
 6260:     my ($domain, $username) = @_;
 6261:     my %userroles = ('user.login.time' => time);
 6262:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6263: 
 6264:     # firstaccess and timerinterval are related to timed maps/resources. 
 6265:     # also, blocking can be triggered by an activating timer
 6266:     # it's saved in the user's %env.
 6267:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6268:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6269:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6270:         %timerintchk, %timerintenv);
 6271: 
 6272:     foreach my $key (keys(%firstaccess)) {
 6273:         my ($cid, $rest) = split(/\0/, $key);
 6274:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6275:     }
 6276: 
 6277:     foreach my $key (keys(%timerinterval)) {
 6278:         my ($cid,$rest) = split(/\0/,$key);
 6279:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6280:     }
 6281: 
 6282:     my %allroles=();
 6283:     my %allgroups=();
 6284: 
 6285:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6286:         my $role = $rolesdump{$area};
 6287:         $area =~ s/\_\w\w$//;
 6288: 
 6289:         my ($trole, $tend, $tstart, $group_privs);
 6290: 
 6291:         if ($role =~ /^cr/) {
 6292:         # Custom role, defined by a user 
 6293:         # e.g., user.role.cr/msu/smith/mynewrole
 6294:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6295:                 $trole = $1;
 6296:                 ($tend, $tstart) = split('_', $2);
 6297:             } else {
 6298:                 $trole = $role;
 6299:             }
 6300:         } elsif ($role =~ m|^gr/|) {
 6301:         # Role of member in a group, defined within a course/community
 6302:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6303:             ($trole, $tend, $tstart) = split(/_/, $role);
 6304:             next if $tstart eq '-1';
 6305:             ($trole, $group_privs) = split(/\//, $trole);
 6306:             $group_privs = &unescape($group_privs);
 6307:         } else {
 6308:         # Just a normal role, defined in roles.tab
 6309:             ($trole, $tend, $tstart) = split(/_/,$role);
 6310:         }
 6311: 
 6312:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6313:                  $username);
 6314:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6315: 
 6316:         # role expired or not available yet?
 6317:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6318:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6319: 
 6320:         next if $area eq '' or $trole eq '';
 6321: 
 6322:         my $spec = "$trole.$area";
 6323:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6324: 
 6325:         if ($trole =~ /^cr\//) {
 6326:         # Custom role, defined by a user
 6327:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6328:         } elsif ($trole eq 'gr') {
 6329:         # Role of a member in a group, defined within a course/community
 6330:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6331:             next;
 6332:         } else {
 6333:         # Normal role, defined in roles.tab
 6334:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6335:         }
 6336: 
 6337:         my $cid = $tdomain.'_'.$trest;
 6338:         unless ($firstaccchk{$cid}) {
 6339:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6340:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6341:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6342:                         $coursetimerstarts{$cid}{$item}; 
 6343:                 }
 6344:             }
 6345:             $firstaccchk{$cid} = 1;
 6346:         }
 6347:         unless ($timerintchk{$cid}) {
 6348:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6349:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6350:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6351:                        $coursetimerintervals{$cid}{$item};
 6352:                 }
 6353:             }
 6354:             $timerintchk{$cid} = 1;
 6355:         }
 6356:     }
 6357: 
 6358:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6359:                                                           \%allroles, \%allgroups);
 6360:     $env{'user.adv'} = $userroles{'user.adv'};
 6361:     $env{'user.rar'} = $userroles{'user.rar'};
 6362: 
 6363:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6364: }
 6365: 
 6366: sub set_arearole {
 6367:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6368:     unless ($nolog) {
 6369: # log the associated role with the area
 6370:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6371:     }
 6372:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6373: }
 6374: 
 6375: sub custom_roleprivs {
 6376:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6377:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6378:     my $homsvr = &homeserver($rauthor,$rdomain);
 6379:     if (&hostname($homsvr) ne '') {
 6380:         my ($rdummy,$roledef)=
 6381:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6382:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6383:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6384:             if (defined($syspriv)) {
 6385:                 if ($trest =~ /^$match_community$/) {
 6386:                     $syspriv =~ s/bre\&S//; 
 6387:                 }
 6388:                 $$allroles{'cm./'}.=':'.$syspriv;
 6389:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6390:             }
 6391:             if ($tdomain ne '') {
 6392:                 if (defined($dompriv)) {
 6393:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6394:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6395:                 }
 6396:                 if (($trest ne '') && (defined($coursepriv))) {
 6397:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6398:                         my $rolename = $1;
 6399:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6400:                     }
 6401:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6402:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6403:                 }
 6404:             }
 6405:         }
 6406:     }
 6407: }
 6408: 
 6409: sub course_adhocrole_privs {
 6410:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6411:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6412:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6413:         my (%currprivs,%storeprivs);
 6414:         foreach my $item (split(/:/,$coursepriv)) {
 6415:             my ($priv,$restrict) = split(/\&/,$item);
 6416:             $currprivs{$priv} = $restrict;
 6417:         }
 6418:         my (%possadd,%possremove,%full);
 6419:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6420:             my ($priv,$restrict)=split(/\&/,$item);
 6421:             $full{$priv} = $restrict;
 6422:         }
 6423:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6424:              next if ($item eq '');
 6425:              my ($rule,$rest) = split(/=/,$item);
 6426:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6427:              foreach my $priv (split(/:/,$rest)) {
 6428:                  if ($priv ne '') {
 6429:                      if ($rule eq 'off') {
 6430:                          $possremove{$priv} = 1;
 6431:                      } else {
 6432:                          $possadd{$priv} = 1;
 6433:                      }
 6434:                  }
 6435:              }
 6436:          }
 6437:          foreach my $priv (sort(keys(%full))) {
 6438:              if (exists($currprivs{$priv})) {
 6439:                  unless (exists($possremove{$priv})) {
 6440:                      $storeprivs{$priv} = $currprivs{$priv};
 6441:                  }
 6442:              } elsif (exists($possadd{$priv})) {
 6443:                  $storeprivs{$priv} = $full{$priv};
 6444:              }
 6445:          }
 6446:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6447:      }
 6448:      return $coursepriv;
 6449: }
 6450: 
 6451: sub group_roleprivs {
 6452:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6453:     my $access = 1;
 6454:     my $now = time;
 6455:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6456:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6457:     if ($access) {
 6458:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6459:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6460:     }
 6461: }
 6462: 
 6463: sub standard_roleprivs {
 6464:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6465:     if (defined($pr{$trole.':s'})) {
 6466:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6467:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6468:     }
 6469:     if ($tdomain ne '') {
 6470:         if (defined($pr{$trole.':d'})) {
 6471:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6472:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6473:         }
 6474:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6475:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6476:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6477:         }
 6478:     }
 6479: }
 6480: 
 6481: sub set_userprivs {
 6482:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6483:     my $author=0;
 6484:     my $adv=0;
 6485:     my $rar=0;
 6486:     my %grouproles = ();
 6487:     if (keys(%{$allgroups}) > 0) {
 6488:         my @groupkeys; 
 6489:         foreach my $role (keys(%{$allroles})) {
 6490:             push(@groupkeys,$role);
 6491:         }
 6492:         if (ref($groups_roles) eq 'HASH') {
 6493:             foreach my $key (keys(%{$groups_roles})) {
 6494:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6495:                     push(@groupkeys,$key);
 6496:                 }
 6497:             }
 6498:         }
 6499:         if (@groupkeys > 0) {
 6500:             foreach my $role (@groupkeys) {
 6501:                 my ($trole,$area,$sec,$extendedarea);
 6502:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6503:                     $trole = $1;
 6504:                     $area = $2;
 6505:                     $sec = $3;
 6506:                     $extendedarea = $area.$sec;
 6507:                     if (exists($$allgroups{$area})) {
 6508:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6509:                             my $spec = $trole.'.'.$extendedarea;
 6510:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6511:                                                 $$allgroups{$area}{$group};
 6512:                         }
 6513:                     }
 6514:                 }
 6515:             }
 6516:         }
 6517:     }
 6518:     foreach my $group (keys(%grouproles)) {
 6519:         $$allroles{$group} = $grouproles{$group};
 6520:     }
 6521:     foreach my $role (keys(%{$allroles})) {
 6522:         my %thesepriv;
 6523:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6524:         foreach my $item (split(/:/,$$allroles{$role})) {
 6525:             if ($item ne '') {
 6526:                 my ($privilege,$restrictions)=split(/&/,$item);
 6527:                 if ($restrictions eq '') {
 6528:                     $thesepriv{$privilege}='F';
 6529:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6530:                     $thesepriv{$privilege}.=$restrictions;
 6531:                 }
 6532:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6533:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6534:             }
 6535:         }
 6536:         my $thesestr='';
 6537:         foreach my $priv (sort(keys(%thesepriv))) {
 6538: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6539: 	}
 6540:         $userroles->{'user.priv.'.$role} = $thesestr;
 6541:     }
 6542:     return ($author,$adv,$rar);
 6543: }
 6544: 
 6545: sub role_status {
 6546:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6547:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6548:         my ($one,$two) = split(m{\./},$rolekey,2);
 6549:         (undef,undef,$$role) = split(/\./,$one,3);
 6550:         unless (!defined($$role) || $$role eq '') {
 6551:             $$where = '/'.$two;
 6552:             $$trolecode=$$role.'.'.$$where;
 6553:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6554:             $$tstatus='is';
 6555:             if ($$tstart && $$tstart>$update) {
 6556:                 $$tstatus='future';
 6557:                 if ($$tstart<$now) {
 6558:                     if ($$tstart && $$tstart>$refresh) {
 6559:                         if (($$where ne '') && ($$role ne '')) {
 6560:                             my (%allroles,%allgroups,$group_privs,
 6561:                                 %groups_roles,@rolecodes);
 6562:                             my %userroles = (
 6563:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6564:                             );
 6565:                             @rolecodes = ('cm'); 
 6566:                             my $spec=$$role.'.'.$$where;
 6567:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6568:                             if ($$role =~ /^cr\//) {
 6569:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6570:                                 push(@rolecodes,'cr');
 6571:                             } elsif ($$role eq 'gr') {
 6572:                                 push(@rolecodes,$$role);
 6573:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6574:                                                     $env{'user.name'});
 6575:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6576:                                 (undef,my $group_privs) = split(/\//,$trole);
 6577:                                 $group_privs = &unescape($group_privs);
 6578:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6579:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6580:                                 &get_groups_roles($tdomain,$trest,
 6581:                                                   \%course_roles,\@rolecodes,
 6582:                                                   \%groups_roles);
 6583:                             } else {
 6584:                                 push(@rolecodes,$$role);
 6585:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6586:                             }
 6587:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6588:                                                                    \%groups_roles);
 6589:                             &appenv(\%userroles,\@rolecodes);
 6590:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6591:                         }
 6592:                     }
 6593:                     $$tstatus = 'is';
 6594:                 }
 6595:             }
 6596:             if ($$tend) {
 6597:                 if ($$tend<$update) {
 6598:                     $$tstatus='expired';
 6599:                 } elsif ($$tend<$now) {
 6600:                     $$tstatus='will_not';
 6601:                 }
 6602:             }
 6603:         }
 6604:     }
 6605: }
 6606: 
 6607: sub get_groups_roles {
 6608:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6609:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6610:                   (ref($rolecodes) eq 'ARRAY') && 
 6611:                   (ref($groups_roles) eq 'HASH')); 
 6612:     if (keys(%{$cdom_courseroles}) > 0) {
 6613:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6614:         if ($cdom ne '' && $cnum ne '') {
 6615:             foreach my $key (keys(%{$cdom_courseroles})) {
 6616:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6617:                     my $crsrole = $1;
 6618:                     my $crssec = $2;
 6619:                     if ($crsrole =~ /^cr/) {
 6620:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6621:                             push(@{$rolecodes},'cr');
 6622:                         }
 6623:                     } else {
 6624:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6625:                             push(@{$rolecodes},$crsrole);
 6626:                         }
 6627:                     }
 6628:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6629:                     if ($crssec ne '') {
 6630:                         $rolekey .= "/$crssec";
 6631:                     }
 6632:                     $rolekey .= './';
 6633:                     $groups_roles->{$rolekey} = $rolecodes;
 6634:                 }
 6635:             }
 6636:         }
 6637:     }
 6638:     return;
 6639: }
 6640: 
 6641: sub delete_env_groupprivs {
 6642:     my ($where,$courseroles,$possroles) = @_;
 6643:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6644:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6645:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6646:         %{$courseroles->{$udom}} =
 6647:             &get_my_roles('','','userroles',['active'],
 6648:                           $possroles,[$udom],1);
 6649:     }
 6650:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6651:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6652:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6653:             my $area = '/'.$cdom.'/'.$cnum;
 6654:             my $privkey = "user.priv.$crsrole.$area";
 6655:             if ($crssec ne '') {
 6656:                 $privkey .= '/'.$crssec;
 6657:             }
 6658:             $privkey .= ".$area/$group";
 6659:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6660:         }
 6661:     }
 6662:     return;
 6663: }
 6664: 
 6665: sub check_adhoc_privs {
 6666:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6667:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6668:     if ($sec) {
 6669:         $cckey .= '/'.$sec;
 6670:     } 
 6671:     my $setprivs;
 6672:     if ($env{$cckey}) {
 6673:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6674:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6675:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6676:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6677:             $setprivs = 1;
 6678:         }
 6679:     } else {
 6680:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6681:         $setprivs = 1;
 6682:     }
 6683:     return $setprivs;
 6684: }
 6685: 
 6686: sub set_adhoc_privileges {
 6687: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6688:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6689:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6690:     if ($sec ne '') {
 6691:         $area .= '/'.$sec;
 6692:     }
 6693:     my $spec = $role.'.'.$area;
 6694:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6695:                                   $env{'user.name'},1);
 6696:     my %rolehash = ();
 6697:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6698:         my $rolename = $1;
 6699:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6700:         my %domdef = &get_domain_defaults($dcdom);
 6701:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6702:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6703:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6704:             }
 6705:         }
 6706:     } else {
 6707:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6708:     }
 6709:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6710:     &appenv(\%userroles,[$role,'cm']);
 6711:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6712:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6713:         &appenv( {'request.role'        => $spec,
 6714:                   'request.role.domain' => $dcdom,
 6715:                   'request.course.sec'  => $sec,
 6716:                  }
 6717:                );
 6718:         my $tadv=0;
 6719:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6720:         &appenv({'request.role.adv'    => $tadv});
 6721:     }
 6722: }
 6723: 
 6724: # --------------------------------------------------------------- get interface
 6725: 
 6726: sub get {
 6727:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6728:    my $items='';
 6729:    foreach my $item (@$storearr) {
 6730:        $items.=&escape($item).'&';
 6731:    }
 6732:    $items=~s/\&$//;
 6733:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6734:    if (!$uname) { $uname=$env{'user.name'}; }
 6735:    my $uhome=&homeserver($uname,$udomain);
 6736: 
 6737:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6738:    my @pairs=split(/\&/,$rep);
 6739:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6740:      return @pairs;
 6741:    }
 6742:    my %returnhash=();
 6743:    my $i=0;
 6744:    foreach my $item (@$storearr) {
 6745:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6746:       $i++;
 6747:    }
 6748:    return %returnhash;
 6749: }
 6750: 
 6751: # --------------------------------------------------------------- del interface
 6752: 
 6753: sub del {
 6754:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6755:    my $items='';
 6756:    foreach my $item (@$storearr) {
 6757:        $items.=&escape($item).'&';
 6758:    }
 6759: 
 6760:    $items=~s/\&$//;
 6761:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6762:    if (!$uname) { $uname=$env{'user.name'}; }
 6763:    my $uhome=&homeserver($uname,$udomain);
 6764:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6765: }
 6766: 
 6767: # -------------------------------------------------------------- dump interface
 6768: 
 6769: sub unserialize {
 6770:     my ($rep, $escapedkeys) = @_;
 6771: 
 6772:     return {} if $rep =~ /^error/;
 6773: 
 6774:     my %returnhash=();
 6775: 	foreach my $item (split(/\&/,$rep)) {
 6776: 	    my ($key, $value) = split(/=/, $item, 2);
 6777: 	    $key = unescape($key) unless $escapedkeys;
 6778: 	    next if $key =~ /^error: 2 /;
 6779: 	    $returnhash{$key} = &thaw_unescape($value);
 6780: 	}
 6781:     #return %returnhash;
 6782:     return \%returnhash;
 6783: }        
 6784: 
 6785: # see Lond::dump_with_regexp
 6786: # if $escapedkeys hash keys won't get unescaped.
 6787: sub dump {
 6788:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6789:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6790:     if (!$uname) { $uname=$env{'user.name'}; }
 6791:     my $uhome=&homeserver($uname,$udomain);
 6792: 
 6793:     if ($regexp) {
 6794:         $regexp=&escape($regexp);
 6795:     } else {
 6796:         $regexp='.';
 6797:     }
 6798:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6799:         # user is hosted on this machine
 6800:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6801:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6802:         return %{unserialize($reply, $escapedkeys)};
 6803:     }
 6804:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6805:     my @pairs=split(/\&/,$rep);
 6806:     my %returnhash=();
 6807:     if (!($rep =~ /^error/ )) {
 6808: 	foreach my $item (@pairs) {
 6809: 	    my ($key,$value)=split(/=/,$item,2);
 6810:         $key = unescape($key) unless $escapedkeys;
 6811:         #$key = &unescape($key);
 6812: 	    next if ($key =~ /^error: 2 /);
 6813: 	    $returnhash{$key}=&thaw_unescape($value);
 6814: 	}
 6815:     }
 6816:     return %returnhash;
 6817: }
 6818: 
 6819: 
 6820: # --------------------------------------------------------- dumpstore interface
 6821: 
 6822: sub dumpstore {
 6823:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6824:    # same as dump but keys must be escaped. They may contain colon separated
 6825:    # lists of values that may themself contain colons (e.g. symbs).
 6826:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6827: }
 6828: 
 6829: # -------------------------------------------------------------- keys interface
 6830: 
 6831: sub getkeys {
 6832:    my ($namespace,$udomain,$uname)=@_;
 6833:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6834:    if (!$uname) { $uname=$env{'user.name'}; }
 6835:    my $uhome=&homeserver($uname,$udomain);
 6836:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6837:    my @keyarray=();
 6838:    foreach my $key (split(/\&/,$rep)) {
 6839:       next if ($key =~ /^error: 2 /);
 6840:       push(@keyarray,&unescape($key));
 6841:    }
 6842:    return @keyarray;
 6843: }
 6844: 
 6845: # --------------------------------------------------------------- currentdump
 6846: sub currentdump {
 6847:    my ($courseid,$sdom,$sname)=@_;
 6848:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6849:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6850:    $sname    = $env{'user.name'}         if (! defined($sname));
 6851:    my $uhome = &homeserver($sname,$sdom);
 6852:    my $rep;
 6853: 
 6854:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6855:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6856:                    $courseid)));
 6857:    } else {
 6858:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6859:    }
 6860: 
 6861:    return if ($rep =~ /^(error:|no_such_host)/);
 6862:    #
 6863:    my %returnhash=();
 6864:    #
 6865:    if ($rep eq 'unknown_cmd') {
 6866:        # an old lond will not know currentdump
 6867:        # Do a dump and make it look like a currentdump
 6868:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6869:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6870:        my %hash = @tmp;
 6871:        @tmp=();
 6872:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6873:    } else {
 6874:        my @pairs=split(/\&/,$rep);
 6875:        foreach my $pair (@pairs) {
 6876:            my ($key,$value)=split(/=/,$pair,2);
 6877:            my ($symb,$param) = split(/:/,$key);
 6878:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6879:                                                         &thaw_unescape($value);
 6880:        }
 6881:    }
 6882:    return %returnhash;
 6883: }
 6884: 
 6885: sub convert_dump_to_currentdump{
 6886:     my %hash = %{shift()};
 6887:     my %returnhash;
 6888:     # Code ripped from lond, essentially.  The only difference
 6889:     # here is the unescaping done by lonnet::dump().  Conceivably
 6890:     # we might run in to problems with parameter names =~ /^v\./
 6891:     while (my ($key,$value) = each(%hash)) {
 6892:         my ($v,$symb,$param) = split(/:/,$key);
 6893: 	$symb  = &unescape($symb);
 6894: 	$param = &unescape($param);
 6895:         next if ($v eq 'version' || $symb eq 'keys');
 6896:         next if (exists($returnhash{$symb}) &&
 6897:                  exists($returnhash{$symb}->{$param}) &&
 6898:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6899:         $returnhash{$symb}->{$param}=$value;
 6900:         $returnhash{$symb}->{'v.'.$param}=$v;
 6901:     }
 6902:     #
 6903:     # Remove all of the keys in the hashes which keep track of
 6904:     # the version of the parameter.
 6905:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6906:         # use a foreach because we are going to delete from the hash.
 6907:         foreach my $key (keys(%$param_hash)) {
 6908:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6909:         }
 6910:     }
 6911:     return \%returnhash;
 6912: }
 6913: 
 6914: # ------------------------------------------------------ critical inc interface
 6915: 
 6916: sub cinc {
 6917:     return &inc(@_,'critical');
 6918: }
 6919: 
 6920: # --------------------------------------------------------------- inc interface
 6921: 
 6922: sub inc {
 6923:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6924:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6925:     if (!$uname) { $uname=$env{'user.name'}; }
 6926:     my $uhome=&homeserver($uname,$udomain);
 6927:     my $items='';
 6928:     if (! ref($store)) {
 6929:         # got a single value, so use that instead
 6930:         $items = &escape($store).'=&';
 6931:     } elsif (ref($store) eq 'SCALAR') {
 6932:         $items = &escape($$store).'=&';        
 6933:     } elsif (ref($store) eq 'ARRAY') {
 6934:         $items = join('=&',map {&escape($_);} @{$store});
 6935:     } elsif (ref($store) eq 'HASH') {
 6936:         while (my($key,$value) = each(%{$store})) {
 6937:             $items.= &escape($key).'='.&escape($value).'&';
 6938:         }
 6939:     }
 6940:     $items=~s/\&$//;
 6941:     if ($critical) {
 6942: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6943:     } else {
 6944: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6945:     }
 6946: }
 6947: 
 6948: # --------------------------------------------------------------- put interface
 6949: 
 6950: sub put {
 6951:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6952:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6953:    if (!$uname) { $uname=$env{'user.name'}; }
 6954:    my $uhome=&homeserver($uname,$udomain);
 6955:    my $items='';
 6956:    foreach my $item (keys(%$storehash)) {
 6957:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6958:    }
 6959:    $items=~s/\&$//;
 6960:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6961: }
 6962: 
 6963: # ------------------------------------------------------------ newput interface
 6964: 
 6965: sub newput {
 6966:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6967:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6968:    if (!$uname) { $uname=$env{'user.name'}; }
 6969:    my $uhome=&homeserver($uname,$udomain);
 6970:    my $items='';
 6971:    foreach my $key (keys(%$storehash)) {
 6972:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6973:    }
 6974:    $items=~s/\&$//;
 6975:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6976: }
 6977: 
 6978: # ---------------------------------------------------------  putstore interface
 6979: 
 6980: sub putstore {
 6981:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6982:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6983:    if (!$uname) { $uname=$env{'user.name'}; }
 6984:    my $uhome=&homeserver($uname,$udomain);
 6985:    my $items='';
 6986:    foreach my $key (keys(%$storehash)) {
 6987:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6988:    }
 6989:    $items=~s/\&$//;
 6990:    my $esc_symb=&escape($symb);
 6991:    my $esc_v=&escape($version);
 6992:    my $reply =
 6993:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6994: 	      $uhome);
 6995:    if (($tolog) && ($reply eq 'ok')) {
 6996:        my $namevalue='';
 6997:        foreach my $key (keys(%{$storehash})) {
 6998:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6999:        }
 7000:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7001:                      '&host='.&escape($perlvar{'lonHostID'}).
 7002:                      '&version='.$esc_v.
 7003:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7004:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7005:    }
 7006:    if ($reply eq 'unknown_cmd') {
 7007:        # gfall back to way things use to be done
 7008:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7009: 			    $uname);
 7010:    }
 7011:    return $reply;
 7012: }
 7013: 
 7014: sub old_putstore {
 7015:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7016:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7017:     if (!$uname) { $uname=$env{'user.name'}; }
 7018:     my $uhome=&homeserver($uname,$udomain);
 7019:     my %newstorehash;
 7020:     foreach my $item (keys(%$storehash)) {
 7021: 	my $key = $version.':'.&escape($symb).':'.$item;
 7022: 	$newstorehash{$key} = $storehash->{$item};
 7023:     }
 7024:     my $items='';
 7025:     my %allitems = ();
 7026:     foreach my $item (keys(%newstorehash)) {
 7027: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7028: 	    my $key = $1.':keys:'.$2;
 7029: 	    $allitems{$key} .= $3.':';
 7030: 	}
 7031: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7032:     }
 7033:     foreach my $item (keys(%allitems)) {
 7034: 	$allitems{$item} =~ s/\:$//;
 7035: 	$items.= $item.'='.$allitems{$item}.'&';
 7036:     }
 7037:     $items=~s/\&$//;
 7038:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7039: }
 7040: 
 7041: # ------------------------------------------------------ critical put interface
 7042: 
 7043: sub cput {
 7044:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7045:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7046:    if (!$uname) { $uname=$env{'user.name'}; }
 7047:    my $uhome=&homeserver($uname,$udomain);
 7048:    my $items='';
 7049:    foreach my $item (keys(%$storehash)) {
 7050:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7051:    }
 7052:    $items=~s/\&$//;
 7053:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7054: }
 7055: 
 7056: # -------------------------------------------------------------- eget interface
 7057: 
 7058: sub eget {
 7059:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7060:    my $items='';
 7061:    foreach my $item (@$storearr) {
 7062:        $items.=&escape($item).'&';
 7063:    }
 7064:    $items=~s/\&$//;
 7065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7066:    if (!$uname) { $uname=$env{'user.name'}; }
 7067:    my $uhome=&homeserver($uname,$udomain);
 7068:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7069:    my @pairs=split(/\&/,$rep);
 7070:    my %returnhash=();
 7071:    my $i=0;
 7072:    foreach my $item (@$storearr) {
 7073:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7074:       $i++;
 7075:    }
 7076:    return %returnhash;
 7077: }
 7078: 
 7079: # ------------------------------------------------------------ tmpput interface
 7080: sub tmpput {
 7081:     my ($storehash,$server,$context)=@_;
 7082:     my $items='';
 7083:     foreach my $item (keys(%$storehash)) {
 7084: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7085:     }
 7086:     $items=~s/\&$//;
 7087:     if (defined($context)) {
 7088:         $items .= ':'.&escape($context);
 7089:     }
 7090:     return &reply("tmpput:$items",$server);
 7091: }
 7092: 
 7093: # ------------------------------------------------------------ tmpget interface
 7094: sub tmpget {
 7095:     my ($token,$server)=@_;
 7096:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7097:     my $rep=&reply("tmpget:$token",$server);
 7098:     my %returnhash;
 7099:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7100:         return %returnhash;
 7101:     }
 7102:     foreach my $item (split(/\&/,$rep)) {
 7103: 	my ($key,$value)=split(/=/,$item);
 7104: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7105:     }
 7106:     return %returnhash;
 7107: }
 7108: 
 7109: # ------------------------------------------------------------ tmpdel interface
 7110: sub tmpdel {
 7111:     my ($token,$server)=@_;
 7112:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7113:     return &reply("tmpdel:$token",$server);
 7114: }
 7115: 
 7116: # ------------------------------------------------------------ get_timebased_id 
 7117: 
 7118: sub get_timebased_id {
 7119:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7120:         $maxtries) = @_;
 7121:     my ($newid,$error,$dellock);
 7122:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7123:         return ('','ok','invalid call to get suffix');
 7124:     }
 7125: 
 7126: # set defaults for any optional args for which values were not supplied
 7127:     if ($who eq '') {
 7128:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7129:     }
 7130:     if (!$locktries) {
 7131:         $locktries = 3;
 7132:     }
 7133:     if (!$maxtries) {
 7134:         $maxtries = 10;
 7135:     }
 7136:     
 7137:     if (($cdom eq '') || ($cnum eq '')) {
 7138:         if ($env{'request.course.id'}) {
 7139:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7140:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7141:         }
 7142:         if (($cdom eq '') || ($cnum eq '')) {
 7143:             return ('','ok','call to get suffix not in course context');
 7144:         }
 7145:     }
 7146: 
 7147: # construct locking item
 7148:     my $lockhash = {
 7149:                       $prefix."\0".'locked_'.$keyid => $who,
 7150:                    };
 7151:     my $tries = 0;
 7152: 
 7153: # attempt to get lock on nohist_$namespace file
 7154:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7155:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7156:         $tries ++;
 7157:         sleep 1;
 7158:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7159:     }
 7160: 
 7161: # attempt to get unique identifier, based on current timestamp
 7162:     if ($gotlock eq 'ok') {
 7163:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7164:         my $id = time;
 7165:         $newid = $id;
 7166:         if ($idtype eq 'addcode') {
 7167:             $newid .= &sixnum_code();
 7168:         }
 7169:         my $idtries = 0;
 7170:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7171:             if ($idtype eq 'concat') {
 7172:                 $newid = $id.$idtries;
 7173:             } elsif ($idtype eq 'addcode') {
 7174:                 $newid = $newid.&sixnum_code();
 7175:             } else {
 7176:                 $newid ++;
 7177:             }
 7178:             $idtries ++;
 7179:         }
 7180:         if (!exists($inuse{$prefix."\0".$newid})) {
 7181:             my %new_item =  (
 7182:                               $prefix."\0".$newid => $who,
 7183:                             );
 7184:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7185:                                                  $cdom,$cnum);
 7186:             if ($putresult ne 'ok') {
 7187:                 undef($newid);
 7188:                 $error = 'error saving new item: '.$putresult;
 7189:             }
 7190:         } else {
 7191:              undef($newid);
 7192:              $error = ('error: no unique suffix available for the new item ');
 7193:         }
 7194: #  remove lock
 7195:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7196:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7197:     } else {
 7198:         $error = "error: could not obtain lockfile\n";
 7199:         $dellock = 'ok';
 7200:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7201:             $dellock = 'nolock';
 7202:         }
 7203:     }
 7204:     return ($newid,$dellock,$error);
 7205: }
 7206: 
 7207: sub sixnum_code {
 7208:     my $code;
 7209:     for (0..6) {
 7210:         $code .= int( rand(9) );
 7211:     }
 7212:     return $code;
 7213: }
 7214: 
 7215: # -------------------------------------------------- portfolio access checking
 7216: 
 7217: sub portfolio_access {
 7218:     my ($requrl,$clientip) = @_;
 7219:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7220:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7221:     if ($result) {
 7222:         my %setters;
 7223:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7224:             my ($startblock,$endblock) =
 7225:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7226:             if ($startblock && $endblock) {
 7227:                 return 'B';
 7228:             }
 7229:         } else {
 7230:             my ($startblock,$endblock) =
 7231:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7232:             if ($startblock && $endblock) {
 7233:                 return 'B';
 7234:             }
 7235:         }
 7236:     }
 7237:     if ($result eq 'ok') {
 7238:        return 'F';
 7239:     } elsif ($result =~ /^[^:]+:guest_/) {
 7240:        return 'A';
 7241:     }
 7242:     return '';
 7243: }
 7244: 
 7245: sub get_portfolio_access {
 7246:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7247: 
 7248:     if (!ref($access_hash)) {
 7249: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7250: 	my %access_controls = &get_access_controls($current_perms,$group,
 7251: 						   $file_name);
 7252: 	$access_hash = $access_controls{$file_name};
 7253:     }
 7254: 
 7255:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7256:     my $now = time;
 7257:     if (ref($access_hash) eq 'HASH') {
 7258:         foreach my $key (keys(%{$access_hash})) {
 7259:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7260:             if ($start > $now) {
 7261:                 next;
 7262:             }
 7263:             if ($end && $end<$now) {
 7264:                 next;
 7265:             }
 7266:             if ($scope eq 'public') {
 7267:                 $public = $key;
 7268:                 last;
 7269:             } elsif ($scope eq 'guest') {
 7270:                 $guest = $key;
 7271:             } elsif ($scope eq 'domains') {
 7272:                 push(@domains,$key);
 7273:             } elsif ($scope eq 'users') {
 7274:                 push(@users,$key);
 7275:             } elsif ($scope eq 'course') {
 7276:                 push(@courses,$key);
 7277:             } elsif ($scope eq 'group') {
 7278:                 push(@groups,$key);
 7279:             } elsif ($scope eq 'ip') {
 7280:                 push(@ips,$key);
 7281:             }
 7282:         }
 7283:         if ($public) {
 7284:             return 'ok';
 7285:         } elsif (@ips > 0) {
 7286:             my $allowed;
 7287:             foreach my $ipkey (@ips) {
 7288:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7289:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7290:                         $allowed = 1;
 7291:                         last; 
 7292:                     }
 7293:                 }
 7294:             }
 7295:             if ($allowed) {
 7296:                 return 'ok';
 7297:             }
 7298:         }
 7299:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7300:             if ($guest) {
 7301:                 return $guest;
 7302:             }
 7303:         } else {
 7304:             if (@domains > 0) {
 7305:                 foreach my $domkey (@domains) {
 7306:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7307:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7308:                             return 'ok';
 7309:                         }
 7310:                     }
 7311:                 }
 7312:             }
 7313:             if (@users > 0) {
 7314:                 foreach my $userkey (@users) {
 7315:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7316:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7317:                             if (ref($item) eq 'HASH') {
 7318:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7319:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7320:                                     return 'ok';
 7321:                                 }
 7322:                             }
 7323:                         }
 7324:                     } 
 7325:                 }
 7326:             }
 7327:             my %roleshash;
 7328:             my @courses_and_groups = @courses;
 7329:             push(@courses_and_groups,@groups); 
 7330:             if (@courses_and_groups > 0) {
 7331:                 my (%allgroups,%allroles); 
 7332:                 my ($start,$end,$role,$sec,$group);
 7333:                 foreach my $envkey (%env) {
 7334:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7335:                         my $cid = $2.'_'.$3; 
 7336:                         if ($1 eq 'gr') {
 7337:                             $group = $4;
 7338:                             $allgroups{$cid}{$group} = $env{$envkey};
 7339:                         } else {
 7340:                             if ($4 eq '') {
 7341:                                 $sec = 'none';
 7342:                             } else {
 7343:                                 $sec = $4;
 7344:                             }
 7345:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7346:                         }
 7347:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7348:                         my $cid = $2.'_'.$3;
 7349:                         if ($4 eq '') {
 7350:                             $sec = 'none';
 7351:                         } else {
 7352:                             $sec = $4;
 7353:                         }
 7354:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7355:                     }
 7356:                 }
 7357:                 if (keys(%allroles) == 0) {
 7358:                     return;
 7359:                 }
 7360:                 foreach my $key (@courses_and_groups) {
 7361:                     my %content = %{$$access_hash{$key}};
 7362:                     my $cnum = $content{'number'};
 7363:                     my $cdom = $content{'domain'};
 7364:                     my $cid = $cdom.'_'.$cnum;
 7365:                     if (!exists($allroles{$cid})) {
 7366:                         next;
 7367:                     }    
 7368:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7369:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7370:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7371:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7372:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7373:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7374:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7375:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7376:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7377:                                         if (grep/^all$/,@sections) {
 7378:                                             return 'ok';
 7379:                                         } else {
 7380:                                             if (grep/^$sec$/,@sections) {
 7381:                                                 return 'ok';
 7382:                                             }
 7383:                                         }
 7384:                                     }
 7385:                                 }
 7386:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7387:                                     if (grep/^none$/,@groups) {
 7388:                                         return 'ok';
 7389:                                     }
 7390:                                 } else {
 7391:                                     if (grep/^all$/,@groups) {
 7392:                                         return 'ok';
 7393:                                     } 
 7394:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7395:                                         if (grep/^$group$/,@groups) {
 7396:                                             return 'ok';
 7397:                                         }
 7398:                                     }
 7399:                                 } 
 7400:                             }
 7401:                         }
 7402:                     }
 7403:                 }
 7404:             }
 7405:             if ($guest) {
 7406:                 return $guest;
 7407:             }
 7408:         }
 7409:     }
 7410:     return;
 7411: }
 7412: 
 7413: sub course_group_datechecker {
 7414:     my ($dates,$now,$status) = @_;
 7415:     my ($start,$end) = split(/\./,$dates);
 7416:     if (!$start && !$end) {
 7417:         return 'ok';
 7418:     }
 7419:     if (grep/^active$/,@{$status}) {
 7420:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7421:             return 'ok';
 7422:         }
 7423:     }
 7424:     if (grep/^previous$/,@{$status}) {
 7425:         if ($end > $now ) {
 7426:             return 'ok';
 7427:         }
 7428:     }
 7429:     if (grep/^future$/,@{$status}) {
 7430:         if ($start > $now) {
 7431:             return 'ok';
 7432:         }
 7433:     }
 7434:     return; 
 7435: }
 7436: 
 7437: sub parse_portfolio_url {
 7438:     my ($url) = @_;
 7439: 
 7440:     my ($type,$udom,$unum,$group,$file_name);
 7441:     
 7442:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7443: 	$type = 1;
 7444:         $udom = $1;
 7445:         $unum = $2;
 7446:         $file_name = $3;
 7447:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7448: 	$type = 2;
 7449:         $udom = $1;
 7450:         $unum = $2;
 7451:         $group = $3;
 7452:         $file_name = $3.'/'.$4;
 7453:     }
 7454:     if (wantarray) {
 7455: 	return ($type,$udom,$unum,$file_name,$group);
 7456:     }
 7457:     return $type;
 7458: }
 7459: 
 7460: sub is_portfolio_url {
 7461:     my ($url) = @_;
 7462:     return scalar(&parse_portfolio_url($url));
 7463: }
 7464: 
 7465: sub is_portfolio_file {
 7466:     my ($file) = @_;
 7467:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7468:         return 1;
 7469:     }
 7470:     return;
 7471: }
 7472: 
 7473: sub usertools_access {
 7474:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7475:     my ($access,%tools);
 7476:     if ($context eq '') {
 7477:         $context = 'tools';
 7478:     }
 7479:     if ($context eq 'requestcourses') {
 7480:         %tools = (
 7481:                       official   => 1,
 7482:                       unofficial => 1,
 7483:                       community  => 1,
 7484:                       textbook   => 1,
 7485:                       placement  => 1,
 7486:                       lti        => 1,
 7487:                  );
 7488:     } elsif ($context eq 'requestauthor') {
 7489:         %tools = (
 7490:                       requestauthor => 1,
 7491:                  );
 7492:     } else {
 7493:         %tools = (
 7494:                       aboutme   => 1,
 7495:                       blog      => 1,
 7496:                       webdav    => 1,
 7497:                       portfolio => 1,
 7498:                  );
 7499:     }
 7500:     return if (!defined($tools{$tool}));
 7501: 
 7502:     if (($udom eq '') || ($uname eq '')) {
 7503:         $udom = $env{'user.domain'};
 7504:         $uname = $env{'user.name'};
 7505:     }
 7506: 
 7507:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7508:         if ($action ne 'reload') {
 7509:             if ($context eq 'requestcourses') {
 7510:                 return $env{'environment.canrequest.'.$tool};
 7511:             } elsif ($context eq 'requestauthor') {
 7512:                 return $env{'environment.canrequest.author'};
 7513:             } else {
 7514:                 return $env{'environment.availabletools.'.$tool};
 7515:             }
 7516:         }
 7517:     }
 7518: 
 7519:     my ($toolstatus,$inststatus,$envkey);
 7520:     if ($context eq 'requestauthor') {
 7521:         $envkey = $context; 
 7522:     } else {
 7523:         $envkey = $context.'.'.$tool;
 7524:     }
 7525: 
 7526:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7527:          ($action ne 'reload')) {
 7528:         $toolstatus = $env{'environment.'.$envkey};
 7529:         $inststatus = $env{'environment.inststatus'};
 7530:     } else {
 7531:         if (ref($userenvref) eq 'HASH') {
 7532:             $toolstatus = $userenvref->{$envkey};
 7533:             $inststatus = $userenvref->{'inststatus'};
 7534:         } else {
 7535:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7536:             $toolstatus = $userenv{$envkey};
 7537:             $inststatus = $userenv{'inststatus'};
 7538:         }
 7539:     }
 7540: 
 7541:     if ($toolstatus ne '') {
 7542:         if ($toolstatus) {
 7543:             $access = 1;
 7544:         } else {
 7545:             $access = 0;
 7546:         }
 7547:         return $access;
 7548:     }
 7549: 
 7550:     my ($is_adv,%domdef);
 7551:     if (ref($is_advref) eq 'HASH') {
 7552:         $is_adv = $is_advref->{'is_adv'};
 7553:     } else {
 7554:         $is_adv = &is_advanced_user($udom,$uname);
 7555:     }
 7556:     if (ref($domdefref) eq 'HASH') {
 7557:         %domdef = %{$domdefref};
 7558:     } else {
 7559:         %domdef = &get_domain_defaults($udom);
 7560:     }
 7561:     if (ref($domdef{$tool}) eq 'HASH') {
 7562:         if ($is_adv) {
 7563:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7564:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7565:                     $access = 1;
 7566:                 } else {
 7567:                     $access = 0;
 7568:                 }
 7569:                 return $access;
 7570:             }
 7571:         }
 7572:         if ($inststatus ne '') {
 7573:             my ($hasaccess,$hasnoaccess);
 7574:             foreach my $affiliation (split(/:/,$inststatus)) {
 7575:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7576:                     if ($domdef{$tool}{$affiliation}) {
 7577:                         $hasaccess = 1;
 7578:                     } else {
 7579:                         $hasnoaccess = 1;
 7580:                     }
 7581:                 }
 7582:             }
 7583:             if ($hasaccess || $hasnoaccess) {
 7584:                 if ($hasaccess) {
 7585:                     $access = 1;
 7586:                 } elsif ($hasnoaccess) {
 7587:                     $access = 0; 
 7588:                 }
 7589:                 return $access;
 7590:             }
 7591:         } else {
 7592:             if ($domdef{$tool}{'default'} ne '') {
 7593:                 if ($domdef{$tool}{'default'}) {
 7594:                     $access = 1;
 7595:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7596:                     $access = 0;
 7597:                 }
 7598:                 return $access;
 7599:             }
 7600:         }
 7601:     } else {
 7602:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7603:             $access = 1;
 7604:         } else {
 7605:             $access = 0;
 7606:         }
 7607:         return $access;
 7608:     }
 7609: }
 7610: 
 7611: sub is_course_owner {
 7612:     my ($cdom,$cnum,$udom,$uname) = @_;
 7613:     if (($udom eq '') || ($uname eq '')) {
 7614:         $udom = $env{'user.domain'};
 7615:         $uname = $env{'user.name'};
 7616:     }
 7617:     unless (($udom eq '') || ($uname eq '')) {
 7618:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7619:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7620:                 return 1;
 7621:             } else {
 7622:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7623:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7624:                     return 1;
 7625:                 }
 7626:             }
 7627:         }
 7628:     }
 7629:     return;
 7630: }
 7631: 
 7632: sub is_advanced_user {
 7633:     my ($udom,$uname) = @_;
 7634:     if ($udom ne '' && $uname ne '') {
 7635:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7636:             if (wantarray) {
 7637:                 return ($env{'user.adv'},$env{'user.author'});
 7638:             } else {
 7639:                 return $env{'user.adv'};
 7640:             }
 7641:         }
 7642:     }
 7643:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7644:     my %allroles;
 7645:     my ($is_adv,$is_author);
 7646:     foreach my $role (keys(%roleshash)) {
 7647:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7648:         my $area = '/'.$tdomain.'/'.$trest;
 7649:         if ($sec ne '') {
 7650:             $area .= '/'.$sec;
 7651:         }
 7652:         if (($area ne '') && ($trole ne '')) {
 7653:             my $spec=$trole.'.'.$area;
 7654:             if ($trole =~ /^cr\//) {
 7655:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7656:             } elsif ($trole ne 'gr') {
 7657:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7658:             }
 7659:             if ($trole eq 'au') {
 7660:                 $is_author = 1;
 7661:             }
 7662:         }
 7663:     }
 7664:     foreach my $role (keys(%allroles)) {
 7665:         last if ($is_adv);
 7666:         foreach my $item (split(/:/,$allroles{$role})) {
 7667:             if ($item ne '') {
 7668:                 my ($privilege,$restrictions)=split(/&/,$item);
 7669:                 if ($privilege eq 'adv') {
 7670:                     $is_adv = 1;
 7671:                     last;
 7672:                 }
 7673:             }
 7674:         }
 7675:     }
 7676:     if (wantarray) {
 7677:         return ($is_adv,$is_author);
 7678:     }
 7679:     return $is_adv;
 7680: }
 7681: 
 7682: sub check_can_request {
 7683:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7684:     my $canreq = 0;
 7685:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7686:         $uname = $env{'user.name'};
 7687:         $udom = $env{'user.domain'};
 7688:     }
 7689:     my ($types,$typename) = &Apache::loncommon::course_types();
 7690:     my @options = ('approval','validate','autolimit');
 7691:     my $optregex = join('|',@options);
 7692:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7693:         foreach my $type (@{$types}) {
 7694:             if (&usertools_access($uname,$udom,$type,undef,
 7695:                                   'requestcourses')) {
 7696:                 $canreq ++;
 7697:                 if (ref($request_domains) eq 'HASH') {
 7698:                     push(@{$request_domains->{$type}},$udom);
 7699:                 }
 7700:                 if ($dom eq $udom) {
 7701:                     $can_request->{$type} = 1;
 7702:                 }
 7703:             }
 7704:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7705:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7706:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7707:                 if (@curr > 0) {
 7708:                     foreach my $item (@curr) {
 7709:                         if (ref($request_domains) eq 'HASH') {
 7710:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7711:                             if ($otherdom ne '') {
 7712:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7713:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7714:                                         push(@{$request_domains->{$type}},$otherdom);
 7715:                                     }
 7716:                                 } else {
 7717:                                     push(@{$request_domains->{$type}},$otherdom);
 7718:                                 }
 7719:                             }
 7720:                         }
 7721:                     }
 7722:                     unless ($dom eq $env{'user.domain'}) {
 7723:                         $canreq ++;
 7724:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7725:                             $can_request->{$type} = 1;
 7726:                         }
 7727:                     }
 7728:                 }
 7729:             }
 7730:         }
 7731:     }
 7732:     return $canreq;
 7733: }
 7734: 
 7735: # ---------------------------------------------- Custom access rule evaluation
 7736: 
 7737: sub customaccess {
 7738:     my ($priv,$uri)=@_;
 7739:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7740:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7741:     $udom = &LONCAPA::clean_domain($udom);
 7742:     $ucrs = &LONCAPA::clean_username($ucrs);
 7743:     my $access=0;
 7744:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7745: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7746: 	if ($type eq 'user') {
 7747: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7748: 		my ($tdom,$tuname)=split(m{/},$scope);
 7749: 		if ($tdom) {
 7750: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7751: 		}
 7752: 		if ($tuname) {
 7753: 		    if ($tuname ne $env{'user.name'}) { next; }
 7754: 		}
 7755: 		$access=($effect eq 'allow');
 7756: 		last;
 7757: 	    }
 7758: 	} else {
 7759: 	    if ($role) {
 7760: 		if ($role ne $urole) { next; }
 7761: 	    }
 7762: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7763: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7764: 		if ($tdom) {
 7765: 		    if ($tdom ne $udom) { next; }
 7766: 		}
 7767: 		if ($tcrs) {
 7768: 		    if ($tcrs ne $ucrs) { next; }
 7769: 		}
 7770: 		if ($tsec) {
 7771: 		    if ($tsec ne $usec) { next; }
 7772: 		}
 7773: 		$access=($effect eq 'allow');
 7774: 		last;
 7775: 	    }
 7776: 	    if ($realm eq '' && $role eq '') {
 7777: 		$access=($effect eq 'allow');
 7778: 	    }
 7779: 	}
 7780:     }
 7781:     return $access;
 7782: }
 7783: 
 7784: # ------------------------------------------------- Check for a user privilege
 7785: 
 7786: sub allowed {
 7787:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7788:     my $ver_orguri=$uri;
 7789:     $uri=&deversion($uri);
 7790:     my $orguri=$uri;
 7791:     $uri=&declutter($uri);
 7792: 
 7793:     if ($priv eq 'evb') {
 7794: # Evade communication block restrictions for specified role in a course
 7795:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7796:             return $1;
 7797:         } else {
 7798:             return;
 7799:         }
 7800:     }
 7801: 
 7802:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7803: # Free bre access to adm and meta resources
 7804:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7805: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7806: 	&& ($priv eq 'bre')) {
 7807: 	return 'F';
 7808:     }
 7809: 
 7810: # Free bre access to user's own portfolio contents
 7811:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7812:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7813: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7814:         my %setters;
 7815:         my ($startblock,$endblock) = 
 7816:             &Apache::loncommon::blockcheck(\%setters,'port');
 7817:         if ($startblock && $endblock) {
 7818:             return 'B';
 7819:         } else {
 7820:             return 'F';
 7821:         }
 7822:     }
 7823: 
 7824: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7825:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7826:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7827:         if (exists($env{'request.course.id'})) {
 7828:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7829:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7830:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7831:                 my $courseprivid=$env{'request.course.id'};
 7832:                 $courseprivid=~s/\_/\//;
 7833:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7834:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7835:                     return $1; 
 7836:                 } else {
 7837:                     if ($env{'request.course.sec'}) {
 7838:                         $courseprivid.='/'.$env{'request.course.sec'};
 7839:                     }
 7840:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7841:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7842:                         return $2;
 7843:                     }
 7844:                 }
 7845:             }
 7846:         }
 7847:     }
 7848: 
 7849: # Free bre to public access
 7850: 
 7851:     if ($priv eq 'bre') {
 7852:         my $copyright;
 7853:         unless ($uri =~ /ext\.tool/) {
 7854:             $copyright=&metadata($uri,'copyright');
 7855:         }
 7856: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7857:            return 'F'; 
 7858:         }
 7859:         if ($copyright eq 'priv') {
 7860:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7861: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7862: 		return '';
 7863:             }
 7864:         }
 7865:         if ($copyright eq 'domain') {
 7866:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7867: 	    unless (($env{'user.domain'} eq $1) ||
 7868:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7869: 		return '';
 7870:             }
 7871:         }
 7872:         if ($env{'request.role'}=~ /li\.\//) {
 7873:             # Library role, so allow browsing of resources in this domain.
 7874:             return 'F';
 7875:         }
 7876:         if ($copyright eq 'custom') {
 7877: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7878:         }
 7879:     }
 7880:     # Domain coordinator is trying to create a course
 7881:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7882:         # uri is the requested domain in this case.
 7883:         # comparison to 'request.role.domain' shows if the user has selected
 7884:         # a role of dc for the domain in question.
 7885:         return 'F' if ($uri eq $env{'request.role.domain'});
 7886:     }
 7887: 
 7888:     my $thisallowed='';
 7889:     my $statecond=0;
 7890:     my $courseprivid='';
 7891: 
 7892:     my $ownaccess;
 7893:     # Community Coordinator or Assistant Co-author browsing resource space.
 7894:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7895:         if ($uri eq '') {
 7896:             $ownaccess = 1;
 7897:         } else {
 7898:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7899:                 my $udom = $env{'user.domain'};
 7900:                 my $uname = $env{'user.name'};
 7901:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7902:                     $ownaccess = 1;
 7903:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7904:                     unless ($uri =~ m{\.\./}) {
 7905:                         $ownaccess = 1;
 7906:                     }
 7907:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7908:                     my $now = time;
 7909:                     if ($uri =~ m{^([^/]+)/?$}) {
 7910:                         my $adom = $1;
 7911:                         foreach my $key (keys(%env)) {
 7912:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7913:                                 my ($start,$end) = split('.',$env{$key});
 7914:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7915:                                     $ownaccess = 1;
 7916:                                     last;
 7917:                                 }
 7918:                             }
 7919:                         }
 7920:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7921:                         my $adom = $1;
 7922:                         my $aname = $2;
 7923:                         foreach my $role ('ca','aa') { 
 7924:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7925:                                 my ($start,$end) =
 7926:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7927:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7928:                                     $ownaccess = 1;
 7929:                                     last;
 7930:                                 }
 7931:                             }
 7932:                         }
 7933:                     }
 7934:                 }
 7935:             }
 7936:         }
 7937:     }
 7938: 
 7939: # Course
 7940: 
 7941:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7942:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7943:             $thisallowed.=$1;
 7944:         }
 7945:     }
 7946: 
 7947: # Domain
 7948: 
 7949:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7950:        =~/\Q$priv\E\&([^\:]*)/) {
 7951:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7952:             $thisallowed.=$1;
 7953:         }
 7954:     }
 7955: 
 7956: # User who is not author or co-author might still be able to edit
 7957: # resource of an author in the domain (e.g., if Domain Coordinator).
 7958:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7959:         (&allowed('mdc',$env{'request.course.id'}))) {
 7960:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7961:             $thisallowed.=$1;
 7962:         }
 7963:     }
 7964: 
 7965: # Course: uri itself is a course
 7966:     my $courseuri=$uri;
 7967:     $courseuri=~s/\_(\d)/\/$1/;
 7968:     $courseuri=~s/^([^\/])/\/$1/;
 7969: 
 7970:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7971:        =~/\Q$priv\E\&([^\:]*)/) {
 7972:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7973:             $thisallowed.=$1;
 7974:         }
 7975:     }
 7976: 
 7977: # URI is an uploaded document for this course, default permissions don't matter
 7978: # not allowing 'edit' access (editupload) to uploaded course docs
 7979:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7980: 	$thisallowed='';
 7981:         my ($match)=&is_on_map($uri);
 7982:         if ($match) {
 7983:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7984:                   =~/\Q$priv\E\&([^\:]*)/) {
 7985:                 my $value = $1;
 7986:                 if ($noblockcheck) {
 7987:                     $thisallowed.=$value;
 7988:                 } else {
 7989:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7990:                     if (@blockers > 0) {
 7991:                         $thisallowed = 'B';
 7992:                     } else {
 7993:                         $thisallowed.=$value;
 7994:                     }
 7995:                 }
 7996:             }
 7997:         } else {
 7998:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7999:             if ($refuri) {
 8000:                 if ($refuri =~ m|^/adm/|) {
 8001:                     $thisallowed='F';
 8002:                 } else {
 8003:                     $refuri=&declutter($refuri);
 8004:                     my ($match) = &is_on_map($refuri);
 8005:                     if ($match) {
 8006:                         if ($noblockcheck) {
 8007:                             $thisallowed='F';
 8008:                         } else {
 8009:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8010:                             if (@blockers > 0) {
 8011:                                 $thisallowed = 'B';
 8012:                             } else {
 8013:                                 $thisallowed='F';
 8014:                             }
 8015:                         }
 8016:                     }
 8017:                 }
 8018:             }
 8019:         }
 8020:     }
 8021: 
 8022:     if ($priv eq 'bre'
 8023: 	&& $thisallowed ne 'F' 
 8024: 	&& $thisallowed ne '2'
 8025: 	&& &is_portfolio_url($uri)) {
 8026: 	$thisallowed = &portfolio_access($uri,$clientip);
 8027:     }
 8028: 
 8029: # Full access at system, domain or course-wide level? Exit.
 8030:     if ($thisallowed=~/F/) {
 8031: 	return 'F';
 8032:     }
 8033: 
 8034: # If this is generating or modifying users, exit with special codes
 8035: 
 8036:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8037: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8038: 	    my ($audom,$auname)=split('/',$uri);
 8039: # no author name given, so this just checks on the general right to make a co-author in this domain
 8040: 	    unless ($auname) { return $thisallowed; }
 8041: # an author name is given, so we are about to actually make a co-author for a certain account
 8042: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8043: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8044: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8045: 	}
 8046: 	return $thisallowed;
 8047:     }
 8048: #
 8049: # Gathered so far: system, domain and course wide privileges
 8050: #
 8051: # Course: See if uri or referer is an individual resource that is part of 
 8052: # the course
 8053: 
 8054:     if ($env{'request.course.id'}) {
 8055: 
 8056:        $courseprivid=$env{'request.course.id'};
 8057:        if ($env{'request.course.sec'}) {
 8058:           $courseprivid.='/'.$env{'request.course.sec'};
 8059:        }
 8060:        $courseprivid=~s/\_/\//;
 8061:        my $checkreferer=1;
 8062:        my ($match,$cond)=&is_on_map($uri);
 8063:        if ($match) {
 8064:            $statecond=$cond;
 8065:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8066:                =~/\Q$priv\E\&([^\:]*)/) {
 8067:                my $value = $1;
 8068:                if ($priv eq 'bre') {
 8069:                    if ($noblockcheck) {
 8070:                        $thisallowed.=$value;
 8071:                    } else {
 8072:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8073:                        if (@blockers > 0) {
 8074:                            $thisallowed = 'B';
 8075:                        } else {
 8076:                            $thisallowed.=$value;
 8077:                        }
 8078:                    }
 8079:                } else {
 8080:                    $thisallowed.=$value;
 8081:                }
 8082:                $checkreferer=0;
 8083:            }
 8084:        }
 8085:        
 8086:        if ($checkreferer) {
 8087: 	  my $refuri=$env{'httpref.'.$orguri};
 8088:             unless ($refuri) {
 8089:                 foreach my $key (keys(%env)) {
 8090: 		    if ($key=~/^httpref\..*\*/) {
 8091: 			my $pattern=$key;
 8092:                         $pattern=~s/^httpref\.\/res\///;
 8093:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8094:                         $pattern=~s/\//\\\//g;
 8095:                         if ($orguri=~/$pattern/) {
 8096: 			    $refuri=$env{$key};
 8097:                         }
 8098:                     }
 8099:                 }
 8100:             }
 8101: 
 8102:          if ($refuri) { 
 8103: 	  $refuri=&declutter($refuri);
 8104:           my ($match,$cond)=&is_on_map($refuri);
 8105:             if ($match) {
 8106:               my $refstatecond=$cond;
 8107:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8108:                   =~/\Q$priv\E\&([^\:]*)/) {
 8109:                   my $value = $1;
 8110:                   if ($priv eq 'bre') {
 8111:                       if ($noblockcheck) {
 8112:                           $thisallowed.=$value;
 8113:                       } else {
 8114:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8115:                           if (@blockers > 0) {
 8116:                               $thisallowed = 'B';
 8117:                           } else {
 8118:                               $thisallowed.=$value;
 8119:                           }
 8120:                       }
 8121:                   } else {
 8122:                       $thisallowed.=$value;
 8123:                   }
 8124:                   $uri=$refuri;
 8125:                   $statecond=$refstatecond;
 8126:               }
 8127:           }
 8128:         }
 8129:        }
 8130:    }
 8131: 
 8132: #
 8133: # Gathered now: all privileges that could apply, and condition number
 8134: # 
 8135: #
 8136: # Full or no access?
 8137: #
 8138: 
 8139:     if ($thisallowed=~/F/) {
 8140: 	return 'F';
 8141:     }
 8142: 
 8143:     unless ($thisallowed) {
 8144:         return '';
 8145:     }
 8146: 
 8147: # Restrictions exist, deal with them
 8148: #
 8149: #   C:according to course preferences
 8150: #   R:according to resource settings
 8151: #   L:unless locked
 8152: #   X:according to user session state
 8153: #
 8154: 
 8155: # Possibly locked functionality, check all courses
 8156: # Locks might take effect only after 10 minutes cache expiration for other
 8157: # courses, and 2 minutes for current course
 8158: 
 8159:     my $envkey;
 8160:     if ($thisallowed=~/L/) {
 8161:         foreach $envkey (keys(%env)) {
 8162:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8163:                my $courseid=$2;
 8164:                my $roleid=$1.'.'.$2;
 8165:                $courseid=~s/^\///;
 8166:                my $expiretime=600;
 8167:                if ($env{'request.role'} eq $roleid) {
 8168: 		  $expiretime=120;
 8169:                }
 8170: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8171:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8172:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8173: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8174:                }
 8175:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8176:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8177: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8178:                        &log($env{'user.domain'},$env{'user.name'},
 8179:                             $env{'user.home'},
 8180:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8181:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8182:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8183: 		       return '';
 8184:                    }
 8185:                }
 8186:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8187:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8188: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8189:                        &log($env{'user.domain'},$env{'user.name'},
 8190:                             $env{'user.home'},
 8191:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8192:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8193:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8194: 		       return '';
 8195:                    }
 8196:                }
 8197: 	   }
 8198:        }
 8199:     }
 8200:    
 8201: #
 8202: # Rest of the restrictions depend on selected course
 8203: #
 8204: 
 8205:     unless ($env{'request.course.id'}) {
 8206: 	if ($thisallowed eq 'A') {
 8207: 	    return 'A';
 8208:         } elsif ($thisallowed eq 'B') {
 8209:             return 'B';
 8210: 	} else {
 8211: 	    return '1';
 8212: 	}
 8213:     }
 8214: 
 8215: #
 8216: # Now user is definitely in a course
 8217: #
 8218: 
 8219: 
 8220: # Course preferences
 8221: 
 8222:    if ($thisallowed=~/C/) {
 8223:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8224:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8225:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8226: 	   =~/\Q$rolecode\E/) {
 8227: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8228: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8229: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8230: 			$env{'request.course.id'});
 8231: 	   }
 8232:            return '';
 8233:        }
 8234: 
 8235:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8236: 	   =~/\Q$unamedom\E/) {
 8237: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8238: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8239: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8240: 			$env{'request.course.id'});
 8241: 	   }
 8242:            return '';
 8243:        }
 8244:    }
 8245: 
 8246: # Resource preferences
 8247: 
 8248:    if ($thisallowed=~/R/) {
 8249:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8250:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8251: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8252: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8253: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8254: 	   }
 8255: 	   return '';
 8256:        }
 8257:    }
 8258: 
 8259: # Restricted by state or randomout?
 8260: 
 8261:    if ($thisallowed=~/X/) {
 8262:       if ($env{'acc.randomout'}) {
 8263: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8264:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8265:             return ''; 
 8266:          }
 8267:       }
 8268:       if (&condval($statecond)) {
 8269: 	 return '2';
 8270:       } else {
 8271:          return '';
 8272:       }
 8273:    }
 8274: 
 8275:     if ($thisallowed eq 'A') {
 8276: 	return 'A';
 8277:     } elsif ($thisallowed eq 'B') {
 8278:         return 'B';
 8279:     }
 8280:    return 'F';
 8281: }
 8282: 
 8283: # ------------------------------------------- Check construction space access
 8284: 
 8285: sub constructaccess {
 8286:     my ($url,$setpriv)=@_;
 8287: 
 8288: # We do not allow editing of previous versions of files
 8289:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8290: 
 8291: # Get username and domain from URL
 8292:     my ($ownername,$ownerdomain,$ownerhome);
 8293: 
 8294:     ($ownerdomain,$ownername) =
 8295:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8296: 
 8297: # The URL does not really point to any authorspace, forget it
 8298:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8299: 
 8300: # Now we need to see if the user has access to the authorspace of
 8301: # $ownername at $ownerdomain
 8302: 
 8303:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8304: # Real author for this?
 8305:        $ownerhome = $env{'user.home'};
 8306:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8307:           return ($ownername,$ownerdomain,$ownerhome);
 8308:        }
 8309:     } else {
 8310: # Co-author for this?
 8311:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8312:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8313:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8314:             return ($ownername,$ownerdomain,$ownerhome);
 8315:         }
 8316:         if ($env{'request.course.id'}) {
 8317:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8318:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8319:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8320:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8321:                     return ($ownername,$ownerdomain,$ownerhome);
 8322:                 }
 8323:             }
 8324:         }
 8325:     }
 8326: 
 8327: # We don't have any access right now. If we are not possibly going to do anything about this,
 8328: # we might as well leave
 8329:    unless ($setpriv) { return ''; }
 8330: 
 8331: # Backdoor access?
 8332:     my $allowed=&allowed('eco',$ownerdomain);
 8333: # Nope
 8334:     unless ($allowed) { return ''; }
 8335: # Looks like we may have access, but could be locked by the owner of the construction space
 8336:     if ($allowed eq 'U') {
 8337:         my %blocked=&get('environment',['domcoord.author'],
 8338:                          $ownerdomain,$ownername);
 8339: # Is blocked by owner
 8340:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8341:     }
 8342:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8343: # Grant temporary access
 8344:         my $then=$env{'user.login.time'};
 8345:         my $update=$env{'user.update.time'};
 8346:         if (!$update) { $update = $then; }
 8347:         my $refresh=$env{'user.refresh.time'};
 8348:         if (!$refresh) { $refresh = $update; }
 8349:         my $now = time;
 8350:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8351:                            $now,'ca','constructaccess');
 8352:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8353:         return($ownername,$ownerdomain,$ownerhome);
 8354:     }
 8355: # No business here
 8356:     return '';
 8357: }
 8358: 
 8359: # ----------------------------------------------------------- Content Blocking
 8360: 
 8361: {
 8362: # Caches for faster Course Contents display where content blocking
 8363: # is in operation (i.e., interval param set) for timed quiz.
 8364: #
 8365: # User for whom data are being temporarily cached.
 8366: my $cacheduser='';
 8367: # Cached blockers for this user (a hash of blocking items). 
 8368: my %cachedblockers=();
 8369: # When the data were last cached.
 8370: my $cachedlast='';
 8371: 
 8372: sub load_all_blockers {
 8373:     my ($uname,$udom,$blocks)=@_;
 8374:     if (($uname ne '') && ($udom ne '')) { 
 8375:         if (($cacheduser eq $uname.':'.$udom) &&
 8376:             (abs($cachedlast-time)<5)) {
 8377:             return;
 8378:         }
 8379:     }
 8380:     $cachedlast=time;
 8381:     $cacheduser=$uname.':'.$udom;
 8382:     %cachedblockers = &get_commblock_resources($blocks);
 8383: }
 8384: 
 8385: sub get_comm_blocks {
 8386:     my ($cdom,$cnum) = @_;
 8387:     if ($cdom eq '' || $cnum eq '') {
 8388:         return unless ($env{'request.course.id'});
 8389:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8390:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8391:     }
 8392:     my %commblocks;
 8393:     my $hashid=$cdom.'_'.$cnum;
 8394:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8395:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8396:         %commblocks = %{$blocksref};
 8397:     } else {
 8398:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8399:         my $cachetime = 600;
 8400:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8401:     }
 8402:     return %commblocks;
 8403: }
 8404: 
 8405: sub get_commblock_resources {
 8406:     my ($blocks) = @_;
 8407:     my %blockers = ();
 8408:     return %blockers unless ($env{'request.course.id'});
 8409:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8410:     my %commblocks;
 8411:     if (ref($blocks) eq 'HASH') {
 8412:         %commblocks = %{$blocks};
 8413:     } else {
 8414:         %commblocks = &get_comm_blocks();
 8415:     }
 8416:     return %blockers unless (keys(%commblocks) > 0); 
 8417:     my $navmap = Apache::lonnavmaps::navmap->new();
 8418:     return %blockers unless (ref($navmap));
 8419:     my $now = time;
 8420:     foreach my $block (keys(%commblocks)) {
 8421:         if ($block =~ /^(\d+)____(\d+)$/) {
 8422:             my ($start,$end) = ($1,$2);
 8423:             if ($start <= $now && $end >= $now) {
 8424:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8425:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8426:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8427:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8428:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8429:                             }
 8430:                         }
 8431:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8432:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8433:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8434:                             }
 8435:                         }
 8436:                     }
 8437:                 }
 8438:             }
 8439:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8440:             my $item = $1;
 8441:             my @to_test;
 8442:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8443:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8444:                     my @interval;
 8445:                     my $type = 'map';
 8446:                     if ($item eq 'course') {
 8447:                         $type = 'course';
 8448:                         @interval=&EXT("resource.0.interval");
 8449:                     } else {
 8450:                         if ($item =~ /___\d+___/) {
 8451:                             $type = 'resource';
 8452:                             @interval=&EXT("resource.0.interval",$item);
 8453:                             if (ref($navmap)) {                        
 8454:                                 my $res = $navmap->getBySymb($item); 
 8455:                                 push(@to_test,$res);
 8456:                             }
 8457:                         } else {
 8458:                             my $mapsymb = &symbread($item,1);
 8459:                             if ($mapsymb) {
 8460:                                 if (ref($navmap)) {
 8461:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8462:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8463:                                     foreach my $res (@to_test) {
 8464:                                         my $symb = $res->symb();
 8465:                                         next if ($symb eq $mapsymb);
 8466:                                         if ($symb ne '') {
 8467:                                             @interval=&EXT("resource.0.interval",$symb);
 8468:                                             if ($interval[1] eq 'map') {
 8469:                                                 last;
 8470:                                             }
 8471:                                         }
 8472:                                     }
 8473:                                 }
 8474:                             }
 8475:                         }
 8476:                     }
 8477:                     if ($interval[0] =~ /^(\d+)/) {
 8478:                         my $timelimit = $1; 
 8479:                         my $first_access;
 8480:                         if ($type eq 'resource') {
 8481:                             $first_access=&get_first_access($interval[1],$item);
 8482:                         } elsif ($type eq 'map') {
 8483:                             $first_access=&get_first_access($interval[1],undef,$item);
 8484:                         } else {
 8485:                             $first_access=&get_first_access($interval[1]);
 8486:                         }
 8487:                         if ($first_access) {
 8488:                             my $timesup = $first_access+$timelimit;
 8489:                             if ($timesup > $now) {
 8490:                                 my $activeblock;
 8491:                                 foreach my $res (@to_test) {
 8492:                                     if ($res->answerable()) {
 8493:                                         $activeblock = 1;
 8494:                                         last;
 8495:                                     }
 8496:                                 }
 8497:                                 if ($activeblock) {
 8498:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8499:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8500:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8501:                                          }
 8502:                                     }
 8503:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8504:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8505:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8506:                                         }
 8507:                                     }
 8508:                                 }
 8509:                             }
 8510:                         }
 8511:                     }
 8512:                 }
 8513:             }
 8514:         }
 8515:     }
 8516:     return %blockers;
 8517: }
 8518: 
 8519: sub has_comm_blocking {
 8520:     my ($priv,$symb,$uri,$blocks) = @_;
 8521:     my @blockers;
 8522:     return unless ($env{'request.course.id'});
 8523:     return unless ($priv eq 'bre');
 8524:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8525:     return if ($env{'request.state'} eq 'construct');
 8526:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8527:     return unless (keys(%cachedblockers) > 0);
 8528:     my (%possibles,@symbs);
 8529:     if (!$symb) {
 8530:         $symb = &symbread($uri,1,1,1,\%possibles);
 8531:     }
 8532:     if ($symb) {
 8533:         @symbs = ($symb);
 8534:     } elsif (keys(%possibles)) { 
 8535:         @symbs = keys(%possibles);
 8536:     }
 8537:     my $noblock;
 8538:     foreach my $symb (@symbs) {
 8539:         last if ($noblock);
 8540:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8541:         foreach my $block (keys(%cachedblockers)) {
 8542:             if ($block =~ /^firstaccess____(.+)$/) {
 8543:                 my $item = $1;
 8544:                 if (($item eq $map) || ($item eq $symb)) {
 8545:                     $noblock = 1;
 8546:                     last;
 8547:                 }
 8548:             }
 8549:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8550:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8551:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8552:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8553:                             push(@blockers,$block);
 8554:                         }
 8555:                     }
 8556:                 }
 8557:             }
 8558:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8559:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8560:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8561:                         push(@blockers,$block);
 8562:                     }
 8563:                 }
 8564:             }
 8565:         }
 8566:     }
 8567:     return if ($noblock);
 8568:     return @blockers;
 8569: }
 8570: }
 8571: 
 8572: # -------------------------------- Deversion and split uri into path an filename   
 8573: 
 8574: #
 8575: #   Removes the version from a URI and
 8576: #   splits it in to its filename and path to the filename.
 8577: #   Seems like File::Basename could have done this more clearly.
 8578: #   Parameters:
 8579: #      $uri   - input URI
 8580: #   Returns:
 8581: #     Two element list consisting of 
 8582: #     $pathname  - the URI up to and excluding the trailing /
 8583: #     $filename  - The part of the URI following the last /
 8584: #  NOTE:
 8585: #    Another realization of this is simply:
 8586: #    use File::Basename;
 8587: #    ...
 8588: #    $uri = shift;
 8589: #    $filename = basename($uri);
 8590: #    $path     = dirname($uri);
 8591: #    return ($filename, $path);
 8592: #
 8593: #     The implementation below is probably faster however.
 8594: #
 8595: sub split_uri_for_cond {
 8596:     my $uri=&deversion(&declutter(shift));
 8597:     my @uriparts=split(/\//,$uri);
 8598:     my $filename=pop(@uriparts);
 8599:     my $pathname=join('/',@uriparts);
 8600:     return ($pathname,$filename);
 8601: }
 8602: # --------------------------------------------------- Is a resource on the map?
 8603: 
 8604: sub is_on_map {
 8605:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8606:     #Trying to find the conditional for the file
 8607:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8608: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8609:     if ($match) {
 8610: 	return (1,$1);
 8611:     } else {
 8612: 	return (0,0);
 8613:     }
 8614: }
 8615: 
 8616: # --------------------------------------------------------- Get symb from alias
 8617: 
 8618: sub get_symb_from_alias {
 8619:     my $symb=shift;
 8620:     my ($map,$resid,$url)=&decode_symb($symb);
 8621: # Already is a symb
 8622:     if ($url) { return $symb; }
 8623: # Must be an alias
 8624:     my $aliassymb='';
 8625:     my %bighash;
 8626:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8627:                             &GDBM_READER(),0640)) {
 8628:         my $rid=$bighash{'mapalias_'.$symb};
 8629: 	if ($rid) {
 8630: 	    my ($mapid,$resid)=split(/\./,$rid);
 8631: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8632: 				    $resid,$bighash{'src_'.$rid});
 8633: 	}
 8634:         untie %bighash;
 8635:     }
 8636:     return $aliassymb;
 8637: }
 8638: 
 8639: # ----------------------------------------------------------------- Define Role
 8640: 
 8641: sub definerole {
 8642:   if (allowed('mcr','/')) {
 8643:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8644:     foreach my $role (split(':',$sysrole)) {
 8645: 	my ($crole,$cqual)=split(/\&/,$role);
 8646:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8647:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8648: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8649:                return "refused:s:$crole&$cqual"; 
 8650:             }
 8651:         }
 8652:     }
 8653:     foreach my $role (split(':',$domrole)) {
 8654: 	my ($crole,$cqual)=split(/\&/,$role);
 8655:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8656:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8657: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8658:                return "refused:d:$crole&$cqual"; 
 8659:             }
 8660:         }
 8661:     }
 8662:     foreach my $role (split(':',$courole)) {
 8663: 	my ($crole,$cqual)=split(/\&/,$role);
 8664:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8665:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8666: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8667:                return "refused:c:$crole&$cqual"; 
 8668:             }
 8669:         }
 8670:     }
 8671:     my $uhome;
 8672:     if (($uname ne '') && ($udom ne '')) {
 8673:         $uhome = &homeserver($uname,$udom);
 8674:         return $uhome if ($uhome eq 'no_host');
 8675:     } else {
 8676:         $uname = $env{'user.name'};
 8677:         $udom = $env{'user.domain'};
 8678:         $uhome = $env{'user.home'};
 8679:     }
 8680:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8681:                 "$udom:$uname:rolesdef_$rolename=".
 8682:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8683:     return reply($command,$uhome);
 8684:   } else {
 8685:     return 'refused';
 8686:   }
 8687: }
 8688: 
 8689: # ---------------- Make a metadata query against the network of library servers
 8690: 
 8691: sub metadata_query {
 8692:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8693:     my %rhash;
 8694:     my %libserv = &all_library();
 8695:     my @server_list = (defined($server_array) ? @$server_array
 8696:                                               : keys(%libserv) );
 8697:     for my $server (@server_list) {
 8698:         my $domains = ''; 
 8699:         if (ref($domains_hash) eq 'HASH') {
 8700:             $domains = $domains_hash->{$server}; 
 8701:         }
 8702: 	unless ($custom or $customshow) {
 8703: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8704: 	    $rhash{$server}=$reply;
 8705: 	}
 8706: 	else {
 8707: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8708: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8709: 			     $server);
 8710: 	    $rhash{$server}=$reply;
 8711: 	}
 8712:     }
 8713:     return \%rhash;
 8714: }
 8715: 
 8716: # ----------------------------------------- Send log queries and wait for reply
 8717: 
 8718: sub log_query {
 8719:     my ($uname,$udom,$query,%filters)=@_;
 8720:     my $uhome=&homeserver($uname,$udom);
 8721:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8722:     my $uhost=&hostname($uhome);
 8723:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8724:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8725:                        $uhome);
 8726:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8727:     return get_query_reply($queryid);
 8728: }
 8729: 
 8730: # -------------------------- Update MySQL table for portfolio file
 8731: 
 8732: sub update_portfolio_table {
 8733:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8734:     if ($group ne '') {
 8735:         $file_name =~s /^\Q$group\E//;
 8736:     }
 8737:     my $homeserver = &homeserver($uname,$udom);
 8738:     my $queryid=
 8739:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8740:                ':'.&escape($file_name).':'.$action,$homeserver);
 8741:     my $reply = &get_query_reply($queryid);
 8742:     return $reply;
 8743: }
 8744: 
 8745: # -------------------------- Update MySQL allusers table
 8746: 
 8747: sub update_allusers_table {
 8748:     my ($uname,$udom,$names) = @_;
 8749:     my $homeserver = &homeserver($uname,$udom);
 8750:     my $queryid=
 8751:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8752:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8753:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8754:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8755:                'generation='.&escape($names->{'generation'}).'%%'.
 8756:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8757:                'id='.&escape($names->{'id'}),$homeserver);
 8758:     return;
 8759: }
 8760: 
 8761: # ------- Request retrieval of institutional classlists for course(s)
 8762: 
 8763: sub fetch_enrollment_query {
 8764:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8765:     my ($homeserver,$sleep,$loopmax);
 8766:     my $maxtries = 1;
 8767:     if ($context eq 'automated') {
 8768:         $homeserver = $perlvar{'lonHostID'};
 8769:         $sleep = 2;
 8770:         $loopmax = 100;
 8771:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8772:     } else {
 8773:         $homeserver = &homeserver($cnum,$dom);
 8774:     }
 8775:     my $host=&hostname($homeserver);
 8776:     my $cmd = '';
 8777:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8778:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8779:     }
 8780:     $cmd =~ s/%%$//;
 8781:     $cmd = &escape($cmd);
 8782:     my $query = 'fetchenrollment';
 8783:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8784:     unless ($queryid=~/^\Q$host\E\_/) { 
 8785:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8786:         return 'error: '.$queryid;
 8787:     }
 8788:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8789:     my $tries = 1;
 8790:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8791:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8792:         $tries ++;
 8793:     }
 8794:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8795:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8796:     } else {
 8797:         my @responses = split(/:/,$reply);
 8798:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8799:             foreach my $line (@responses) {
 8800:                 my ($key,$value) = split(/=/,$line,2);
 8801:                 $$replyref{$key} = $value;
 8802:             }
 8803:         } else {
 8804:             my $pathname = LONCAPA::tempdir();
 8805:             foreach my $line (@responses) {
 8806:                 my ($key,$value) = split(/=/,$line);
 8807:                 $$replyref{$key} = $value;
 8808:                 if ($value > 0) {
 8809:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8810:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8811:                         my $destname = $pathname.'/'.$filename;
 8812:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8813:                         if ($xml_classlist =~ /^error/) {
 8814:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8815:                         } else {
 8816:                             if ( open(FILE,">",$destname) ) {
 8817:                                 print FILE &unescape($xml_classlist);
 8818:                                 close(FILE);
 8819:                             } else {
 8820:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8821:                             }
 8822:                         }
 8823:                     }
 8824:                 }
 8825:             }
 8826:         }
 8827:         return 'ok';
 8828:     }
 8829:     return 'error';
 8830: }
 8831: 
 8832: sub get_query_reply {
 8833:     my ($queryid,$sleep,$loopmax) = @_;;
 8834:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8835:         $sleep = 0.2;
 8836:     }
 8837:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8838:         $loopmax = 100;
 8839:     }
 8840:     my $replyfile=LONCAPA::tempdir().$queryid;
 8841:     my $reply='';
 8842:     for (1..$loopmax) {
 8843: 	sleep($sleep);
 8844:         if (-e $replyfile.'.end') {
 8845: 	    if (open(my $fh,"<",$replyfile)) {
 8846: 		$reply = join('',<$fh>);
 8847: 		close($fh);
 8848: 	   } else { return 'error: reply_file_error'; }
 8849:            return &unescape($reply);
 8850: 	}
 8851:     }
 8852:     return 'timeout:'.$queryid;
 8853: }
 8854: 
 8855: sub courselog_query {
 8856: #
 8857: # possible filters:
 8858: # url: url or symb
 8859: # username
 8860: # domain
 8861: # action: view, submit, grade
 8862: # start: timestamp
 8863: # end: timestamp
 8864: #
 8865:     my (%filters)=@_;
 8866:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8867:     if ($filters{'url'}) {
 8868: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8869:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8870:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8871:     }
 8872:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8873:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8874:     return &log_query($cname,$cdom,'courselog',%filters);
 8875: }
 8876: 
 8877: sub userlog_query {
 8878: #
 8879: # possible filters:
 8880: # action: log check role
 8881: # start: timestamp
 8882: # end: timestamp
 8883: #
 8884:     my ($uname,$udom,%filters)=@_;
 8885:     return &log_query($uname,$udom,'userlog',%filters);
 8886: }
 8887: 
 8888: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8889: 
 8890: sub auto_run {
 8891:     my ($cnum,$cdom) = @_;
 8892:     my $response = 0;
 8893:     my $settings;
 8894:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8895:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8896:         $settings = $domconfig{'autoenroll'};
 8897:         if ($settings->{'run'} eq '1') {
 8898:             $response = 1;
 8899:         }
 8900:     } else {
 8901:         my $homeserver;
 8902:         if (&is_course($cdom,$cnum)) {
 8903:             $homeserver = &homeserver($cnum,$cdom);
 8904:         } else {
 8905:             $homeserver = &domain($cdom,'primary');
 8906:         }
 8907:         if ($homeserver ne 'no_host') {
 8908:             $response = &reply('autorun:'.$cdom,$homeserver);
 8909:         }
 8910:     }
 8911:     return $response;
 8912: }
 8913: 
 8914: sub auto_get_sections {
 8915:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8916:     my $homeserver;
 8917:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8918:         $homeserver = &homeserver($cnum,$cdom);
 8919:     }
 8920:     if (!defined($homeserver)) { 
 8921:         if ($cdom =~ /^$match_domain$/) {
 8922:             $homeserver = &domain($cdom,'primary');
 8923:         }
 8924:     }
 8925:     my @secs;
 8926:     if (defined($homeserver)) {
 8927:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8928:         unless ($response eq 'refused') {
 8929:             @secs = split(/:/,$response);
 8930:         }
 8931:     }
 8932:     return @secs;
 8933: }
 8934: 
 8935: sub auto_new_course {
 8936:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8937:     my $homeserver = &homeserver($cnum,$cdom);
 8938:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8939:     return $response;
 8940: }
 8941: 
 8942: sub auto_validate_courseID {
 8943:     my ($cnum,$cdom,$inst_course_id) = @_;
 8944:     my $homeserver = &homeserver($cnum,$cdom);
 8945:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8946:     return $response;
 8947: }
 8948: 
 8949: sub auto_validate_instcode {
 8950:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8951:     my ($homeserver,$response);
 8952:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8953:         $homeserver = &homeserver($cnum,$cdom);
 8954:     }
 8955:     if (!defined($homeserver)) {
 8956:         if ($cdom =~ /^$match_domain$/) {
 8957:             $homeserver = &domain($cdom,'primary');
 8958:         }
 8959:     }
 8960:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8961:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8962:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8963:     return ($outcome,$description,$defaultcredits);
 8964: }
 8965: 
 8966: sub auto_create_password {
 8967:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8968:     my ($homeserver,$response);
 8969:     my $create_passwd = 0;
 8970:     my $authchk = '';
 8971:     if ($udom =~ /^$match_domain$/) {
 8972:         $homeserver = &domain($udom,'primary');
 8973:     }
 8974:     if ($homeserver eq '') {
 8975:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8976:             $homeserver = &homeserver($cnum,$cdom);
 8977:         }
 8978:     }
 8979:     if ($homeserver eq '') {
 8980:         $authchk = 'nodomain';
 8981:     } else {
 8982:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8983:         if ($response eq 'refused') {
 8984:             $authchk = 'refused';
 8985:         } else {
 8986:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8987:         }
 8988:     }
 8989:     return ($authparam,$create_passwd,$authchk);
 8990: }
 8991: 
 8992: sub auto_photo_permission {
 8993:     my ($cnum,$cdom,$students) = @_;
 8994:     my $homeserver = &homeserver($cnum,$cdom);
 8995:     my ($outcome,$perm_reqd,$conditions) = 
 8996: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8997:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8998: 	return (undef,undef);
 8999:     }
 9000:     return ($outcome,$perm_reqd,$conditions);
 9001: }
 9002: 
 9003: sub auto_checkphotos {
 9004:     my ($uname,$udom,$pid) = @_;
 9005:     my $homeserver = &homeserver($uname,$udom);
 9006:     my ($result,$resulttype);
 9007:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9008: 				   &escape($uname).':'.&escape($pid),
 9009: 				   $homeserver));
 9010:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9011: 	return (undef,undef);
 9012:     }
 9013:     if ($outcome) {
 9014:         ($result,$resulttype) = split(/:/,$outcome);
 9015:     } 
 9016:     return ($result,$resulttype);
 9017: }
 9018: 
 9019: sub auto_photochoice {
 9020:     my ($cnum,$cdom) = @_;
 9021:     my $homeserver = &homeserver($cnum,$cdom);
 9022:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9023: 						       &escape($cdom),
 9024: 						       $homeserver)));
 9025:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9026: 	return (undef,undef);
 9027:     }
 9028:     return ($update,$comment);
 9029: }
 9030: 
 9031: sub auto_photoupdate {
 9032:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9033:     my $homeserver = &homeserver($cnum,$dom);
 9034:     my $host=&hostname($homeserver);
 9035:     my $cmd = '';
 9036:     my $maxtries = 1;
 9037:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9038:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9039:     }
 9040:     $cmd =~ s/%%$//;
 9041:     $cmd = &escape($cmd);
 9042:     my $query = 'institutionalphotos';
 9043:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9044:     unless ($queryid=~/^\Q$host\E\_/) {
 9045:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9046:         return 'error: '.$queryid;
 9047:     }
 9048:     my $reply = &get_query_reply($queryid);
 9049:     my $tries = 1;
 9050:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9051:         $reply = &get_query_reply($queryid);
 9052:         $tries ++;
 9053:     }
 9054:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9055:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9056:     } else {
 9057:         my @responses = split(/:/,$reply);
 9058:         my $outcome = shift(@responses); 
 9059:         foreach my $item (@responses) {
 9060:             my ($key,$value) = split(/=/,$item);
 9061:             $$photo{$key} = $value;
 9062:         }
 9063:         return $outcome;
 9064:     }
 9065:     return 'error';
 9066: }
 9067: 
 9068: sub auto_instcode_format {
 9069:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9070: 	$cat_order) = @_;
 9071:     my $courses = '';
 9072:     my @homeservers;
 9073:     if ($caller eq 'global') {
 9074: 	my %servers = &get_servers($codedom,'library');
 9075: 	foreach my $tryserver (keys(%servers)) {
 9076: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9077: 		push(@homeservers,$tryserver);
 9078: 	    }
 9079:         }
 9080:     } elsif ($caller eq 'requests') {
 9081:         if ($codedom =~ /^$match_domain$/) {
 9082:             my $chome = &domain($codedom,'primary');
 9083:             unless ($chome eq 'no_host') {
 9084:                 push(@homeservers,$chome);
 9085:             }
 9086:         }
 9087:     } else {
 9088:         push(@homeservers,&homeserver($caller,$codedom));
 9089:     }
 9090:     foreach my $code (keys(%{$instcodes})) {
 9091:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9092:     }
 9093:     chop($courses);
 9094:     my $ok_response = 0;
 9095:     my $response;
 9096:     while (@homeservers > 0 && $ok_response == 0) {
 9097:         my $server = shift(@homeservers); 
 9098:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9099:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9100:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9101: 		split(/:/,$response);
 9102:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9103:             push(@{$codetitles},&str2array($codetitles_str));
 9104:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9105:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9106:             $ok_response = 1;
 9107:         }
 9108:     }
 9109:     if ($ok_response) {
 9110:         return 'ok';
 9111:     } else {
 9112:         return $response;
 9113:     }
 9114: }
 9115: 
 9116: sub auto_instcode_defaults {
 9117:     my ($domain,$returnhash,$code_order) = @_;
 9118:     my @homeservers;
 9119: 
 9120:     my %servers = &get_servers($domain,'library');
 9121:     foreach my $tryserver (keys(%servers)) {
 9122: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9123: 	    push(@homeservers,$tryserver);
 9124: 	}
 9125:     }
 9126: 
 9127:     my $response;
 9128:     foreach my $server (@homeservers) {
 9129:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9130:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9131: 	
 9132: 	foreach my $pair (split(/\&/,$response)) {
 9133: 	    my ($name,$value)=split(/\=/,$pair);
 9134: 	    if ($name eq 'code_order') {
 9135: 		@{$code_order} = split(/\&/,&unescape($value));
 9136: 	    } else {
 9137: 		$returnhash->{&unescape($name)}=&unescape($value);
 9138: 	    }
 9139: 	}
 9140: 	return 'ok';
 9141:     }
 9142: 
 9143:     return $response;
 9144: }
 9145: 
 9146: sub auto_possible_instcodes {
 9147:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9148:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9149:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9150:         return;
 9151:     }
 9152:     my (@homeservers,$uhome);
 9153:     if (defined(&domain($domain,'primary'))) {
 9154:         $uhome=&domain($domain,'primary');
 9155:         push(@homeservers,&domain($domain,'primary'));
 9156:     } else {
 9157:         my %servers = &get_servers($domain,'library');
 9158:         foreach my $tryserver (keys(%servers)) {
 9159:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9160:                 push(@homeservers,$tryserver);
 9161:             }
 9162:         }
 9163:     }
 9164:     my $response;
 9165:     foreach my $server (@homeservers) {
 9166:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9167:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9168:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9169:             split(':',$response);
 9170:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9171:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9172:         foreach my $item (split('&',$cat_title)) {   
 9173:             my ($name,$value)=split('=',$item);
 9174:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9175:         }
 9176:         foreach my $item (split('&',$cat_order)) {
 9177:             my ($name,$value)=split('=',$item);
 9178:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9179:         }
 9180:         return 'ok';
 9181:     }
 9182:     return $response;
 9183: }
 9184: 
 9185: sub auto_courserequest_checks {
 9186:     my ($dom) = @_;
 9187:     my ($homeserver,%validations);
 9188:     if ($dom =~ /^$match_domain$/) {
 9189:         $homeserver = &domain($dom,'primary');
 9190:     }
 9191:     unless ($homeserver eq 'no_host') {
 9192:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9193:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9194:             my @items = split(/&/,$response);
 9195:             foreach my $item (@items) {
 9196:                 my ($key,$value) = split('=',$item);
 9197:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9198:             }
 9199:         }
 9200:     }
 9201:     return %validations; 
 9202: }
 9203: 
 9204: sub auto_courserequest_validation {
 9205:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9206:     my ($homeserver,$response);
 9207:     if ($dom =~ /^$match_domain$/) {
 9208:         $homeserver = &domain($dom,'primary');
 9209:     }
 9210:     unless ($homeserver eq 'no_host') {
 9211:         my $customdata;
 9212:         if (ref($custominfo) eq 'HASH') {
 9213:             $customdata = &freeze_escape($custominfo);
 9214:         }
 9215:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9216:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9217:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9218:                                     $customdata,$homeserver));
 9219:     }
 9220:     return $response;
 9221: }
 9222: 
 9223: sub auto_validate_class_sec {
 9224:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9225:     my $homeserver = &homeserver($cnum,$cdom);
 9226:     my $ownerlist;
 9227:     if (ref($owners) eq 'ARRAY') {
 9228:         $ownerlist = join(',',@{$owners});
 9229:     } else {
 9230:         $ownerlist = $owners;
 9231:     }
 9232:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9233:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9234:     return $response;
 9235: }
 9236: 
 9237: sub auto_validate_instclasses {
 9238:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9239:     my ($homeserver,%validations);
 9240:     $homeserver = &homeserver($cnum,$cdom);
 9241:     unless ($homeserver eq 'no_host') {
 9242:         my $ownerlist;
 9243:         if (ref($owners) eq 'ARRAY') {
 9244:             $ownerlist = join(',',@{$owners});
 9245:         } else {
 9246:             $ownerlist = $owners;
 9247:         }
 9248:         if (ref($classesref) eq 'HASH') {
 9249:             my $classes = &freeze_escape($classesref);
 9250:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9251:                                 ':'.$cdom.':'.$classes,$homeserver);
 9252:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9253:                 my @items = split(/&/,$response);
 9254:                 foreach my $item (@items) {
 9255:                     my ($key,$value) = split('=',$item);
 9256:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9257:                 }
 9258:             }
 9259:         }
 9260:     }
 9261:     return %validations;
 9262: }
 9263: 
 9264: sub auto_crsreq_update {
 9265:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9266:         $code,$accessstart,$accessend,$inbound) = @_;
 9267:     my ($homeserver,%crsreqresponse);
 9268:     if ($cdom =~ /^$match_domain$/) {
 9269:         $homeserver = &domain($cdom,'primary');
 9270:     }
 9271:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9272:         my $info;
 9273:         if (ref($inbound) eq 'HASH') {
 9274:             $info = &freeze_escape($inbound);
 9275:         }
 9276:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9277:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9278:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9279:                             &escape($title).':'.&escape($code).':'.
 9280:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9281:                             $homeserver);
 9282:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9283:             my @items = split(/&/,$response);
 9284:             foreach my $item (@items) {
 9285:                 my ($key,$value) = split('=',$item);
 9286:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9287:             }
 9288:         }
 9289:     }
 9290:     return \%crsreqresponse;
 9291: }
 9292: 
 9293: sub auto_export_grades {
 9294:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9295:     my ($homeserver,%exportresponse);
 9296:     if ($cdom =~ /^$match_domain$/) {
 9297:         $homeserver = &domain($cdom,'primary');
 9298:     }
 9299:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9300:         my $info;
 9301:         if (ref($inforef) eq 'HASH') {
 9302:             $info = &freeze_escape($inforef);
 9303:         }
 9304:         if (ref($gradesref) eq 'HASH') {
 9305:             my $grades = &freeze_escape($gradesref);
 9306:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9307:                                 $info.':'.$grades,$homeserver);
 9308:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9309:                 my @items = split(/&/,$response);
 9310:                 foreach my $item (@items) {
 9311:                     my ($key,$value) = split('=',$item);
 9312:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9313:                 }
 9314:             }
 9315:         }
 9316:     }
 9317:     return \%exportresponse;
 9318: }
 9319: 
 9320: sub check_instcode_cloning {
 9321:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9322:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9323:         return;
 9324:     }
 9325:     my $canclone;
 9326:     if (@{$code_order} > 0) {
 9327:         my $instcoderegexp ='^';
 9328:         my @clonecodes = split(/\&/,$cloner);
 9329:         foreach my $item (@{$code_order}) {
 9330:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9331:                 foreach my $pair (@clonecodes) {
 9332:                     my ($key,$val) = split(/\=/,$pair,2);
 9333:                     $val = &unescape($val);
 9334:                     if ($key eq $item) {
 9335:                         $instcoderegexp .= '('.$val.')';
 9336:                         last;
 9337:                     }
 9338:                 }
 9339:             } else {
 9340:                 $instcoderegexp .= $codedefaults->{$item};
 9341:             }
 9342:         }
 9343:         $instcoderegexp .= '$';
 9344:         my (@from,@to);
 9345:         eval {
 9346:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9347:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9348:         };
 9349:         if ((@from > 0) && (@to > 0)) {
 9350:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9351:             if (!@diffs) {
 9352:                 $canclone = 1;
 9353:             }
 9354:         }
 9355:     }
 9356:     return $canclone;
 9357: }
 9358: 
 9359: sub default_instcode_cloning {
 9360:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9361:     my (%codedefaults,@code_order,$canclone);
 9362:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9363:         %codedefaults = %{$codedefaultsref};
 9364:         @code_order = @{$codeorderref};
 9365:     } elsif ($clonedom) {
 9366:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9367:     }
 9368:     if (($domdefclone) && (@code_order)) {
 9369:         my @clonecodes = split(/\+/,$domdefclone);
 9370:         my $instcoderegexp ='^';
 9371:         foreach my $item (@code_order) {
 9372:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9373:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9374:             } else {
 9375:                 $instcoderegexp .= $codedefaults{$item};
 9376:             }
 9377:         }
 9378:         $instcoderegexp .= '$';
 9379:         my (@from,@to);
 9380:         eval {
 9381:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9382:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9383:         };
 9384:         if ((@from > 0) && (@to > 0)) {
 9385:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9386:             if (!@diffs) {
 9387:                 $canclone = 1;
 9388:             }
 9389:         }
 9390:     }
 9391:     return $canclone;
 9392: }
 9393: 
 9394: # ------------------------------------------------------- Course Group routines
 9395: 
 9396: sub get_coursegroups {
 9397:     my ($cdom,$cnum,$group,$namespace) = @_;
 9398:     return(&dump($namespace,$cdom,$cnum,$group));
 9399: }
 9400: 
 9401: sub modify_coursegroup {
 9402:     my ($cdom,$cnum,$groupsettings) = @_;
 9403:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9404: }
 9405: 
 9406: sub toggle_coursegroup_status {
 9407:     my ($cdom,$cnum,$group,$action) = @_;
 9408:     my ($from_namespace,$to_namespace);
 9409:     if ($action eq 'delete') {
 9410:         $from_namespace = 'coursegroups';
 9411:         $to_namespace = 'deleted_groups';
 9412:     } else {
 9413:         $from_namespace = 'deleted_groups';
 9414:         $to_namespace = 'coursegroups';
 9415:     }
 9416:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9417:     if (my $tmp = &error(%curr_group)) {
 9418:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9419:         return ('read error',$tmp);
 9420:     } else {
 9421:         my %savedsettings = %curr_group; 
 9422:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9423:         my $deloutcome;
 9424:         if ($result eq 'ok') {
 9425:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9426:         } else {
 9427:             return ('write error',$result);
 9428:         }
 9429:         if ($deloutcome eq 'ok') {
 9430:             return 'ok';
 9431:         } else {
 9432:             return ('delete error',$deloutcome);
 9433:         }
 9434:     }
 9435: }
 9436: 
 9437: sub modify_group_roles {
 9438:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9439:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9440:     my $role = 'gr/'.&escape($userprivs);
 9441:     my ($uname,$udom) = split(/:/,$user);
 9442:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9443:     if ($result eq 'ok') {
 9444:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9445:     }
 9446:     return $result;
 9447: }
 9448: 
 9449: sub modify_coursegroup_membership {
 9450:     my ($cdom,$cnum,$membership) = @_;
 9451:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9452:     return $result;
 9453: }
 9454: 
 9455: sub get_active_groups {
 9456:     my ($udom,$uname,$cdom,$cnum) = @_;
 9457:     my $now = time;
 9458:     my %groups = ();
 9459:     foreach my $key (keys(%env)) {
 9460:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9461:             my ($start,$end) = split(/\./,$env{$key});
 9462:             if (($end!=0) && ($end<$now)) { next; }
 9463:             if (($start!=0) && ($start>$now)) { next; }
 9464:             if ($1 eq $cdom && $2 eq $cnum) {
 9465:                 $groups{$3} = $env{$key} ;
 9466:             }
 9467:         }
 9468:     }
 9469:     return %groups;
 9470: }
 9471: 
 9472: sub get_group_membership {
 9473:     my ($cdom,$cnum,$group) = @_;
 9474:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9475: }
 9476: 
 9477: sub get_users_groups {
 9478:     my ($udom,$uname,$courseid) = @_;
 9479:     my @usersgroups;
 9480:     my $cachetime=1800;
 9481: 
 9482:     my $hashid="$udom:$uname:$courseid";
 9483:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9484:     if (defined($cached)) {
 9485:         @usersgroups = split(/:/,$grouplist);
 9486:     } else {  
 9487:         $grouplist = '';
 9488:         my $courseurl = &courseid_to_courseurl($courseid);
 9489:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9490:         my $access_end = $env{'course.'.$courseid.
 9491:                               '.default_enrollment_end_date'};
 9492:         my $now = time;
 9493:         foreach my $key (keys(%roleshash)) {
 9494:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9495:                 my $group = $1;
 9496:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9497:                     my $start = $2;
 9498:                     my $end = $1;
 9499:                     if ($start == -1) { next; } # deleted from group
 9500:                     if (($start!=0) && ($start>$now)) { next; }
 9501:                     if (($end!=0) && ($end<$now)) {
 9502:                         if ($access_end && $access_end < $now) {
 9503:                             if ($access_end - $end < 86400) {
 9504:                                 push(@usersgroups,$group);
 9505:                             }
 9506:                         }
 9507:                         next;
 9508:                     }
 9509:                     push(@usersgroups,$group);
 9510:                 }
 9511:             }
 9512:         }
 9513:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9514:         $grouplist = join(':',@usersgroups);
 9515:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9516:     }
 9517:     return @usersgroups;
 9518: }
 9519: 
 9520: sub devalidate_getgroups_cache {
 9521:     my ($udom,$uname,$cdom,$cnum)=@_;
 9522:     my $courseid = $cdom.'_'.$cnum;
 9523: 
 9524:     my $hashid="$udom:$uname:$courseid";
 9525:     &devalidate_cache_new('getgroups',$hashid);
 9526: }
 9527: 
 9528: # ------------------------------------------------------------------ Plain Text
 9529: 
 9530: sub plaintext {
 9531:     my ($short,$type,$cid,$forcedefault) = @_;
 9532:     if ($short =~ m{^cr/}) {
 9533: 	return (split('/',$short))[-1];
 9534:     }
 9535:     if (!defined($cid)) {
 9536:         $cid = $env{'request.course.id'};
 9537:     }
 9538:     my %rolenames = (
 9539:                       Course    => 'std',
 9540:                       Community => 'alt1',
 9541:                       Placement => 'std',
 9542:                     );
 9543:     if ($cid ne '') {
 9544:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9545:             unless ($forcedefault) {
 9546:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9547:                 &Apache::lonlocal::mt_escape(\$roletext);
 9548:                 return &Apache::lonlocal::mt($roletext);
 9549:             }
 9550:         }
 9551:     }
 9552:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9553:         (defined($rolenames{$type})) && 
 9554:         (defined($prp{$short}{$rolenames{$type}}))) {
 9555:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9556:     } elsif ($cid ne '') {
 9557:         my $crstype = $env{'course.'.$cid.'.type'};
 9558:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9559:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9560:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9561:         }
 9562:     }
 9563:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9564: }
 9565: 
 9566: # ----------------------------------------------------------------- Assign Role
 9567: 
 9568: sub assignrole {
 9569:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9570:         $context)=@_;
 9571:     my $mrole;
 9572:     if ($role =~ /^cr\//) {
 9573:         my $cwosec=$url;
 9574:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9575: 	unless (&allowed('ccr',$cwosec)) {
 9576:            my $refused = 1;
 9577:            if ($context eq 'requestcourses') {
 9578:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9579:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9580:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9581:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9582:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9583:                            if ($crsenv{'internal.courseowner'} eq
 9584:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9585:                                $refused = '';
 9586:                            }
 9587:                        }
 9588:                    }
 9589:                }
 9590:            }
 9591:            if ($refused) {
 9592:                &logthis('Refused custom assignrole: '.
 9593:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9594:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9595:                return 'refused';
 9596:            }
 9597:         }
 9598:         $mrole='cr';
 9599:     } elsif ($role =~ /^gr\//) {
 9600:         my $cwogrp=$url;
 9601:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9602:         unless (&allowed('mdg',$cwogrp)) {
 9603:             &logthis('Refused group assignrole: '.
 9604:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9605:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9606:             return 'refused';
 9607:         }
 9608:         $mrole='gr';
 9609:     } else {
 9610:         my $cwosec=$url;
 9611:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9612:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9613:             my $refused;
 9614:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9615:                 if (!(&allowed('c'.$role,$url))) {
 9616:                     $refused = 1;
 9617:                 }
 9618:             } else {
 9619:                 $refused = 1;
 9620:             }
 9621:             if ($refused) {
 9622:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9623:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9624:                     my %crsenv;
 9625:                     if ($role eq 'cc' || $role eq 'co') {
 9626:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9627:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9628:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9629:                                 if ($crsenv{'internal.courseowner'} eq 
 9630:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9631:                                     $refused = '';
 9632:                                 }
 9633:                             }
 9634:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9635:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9636:                                 if ($crsenv{'internal.courseowner'} eq 
 9637:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9638:                                     $refused = '';
 9639:                                 }
 9640:                             }
 9641:                         }
 9642:                     }
 9643:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9644:                     if ($role eq 'st') {
 9645:                         $refused = '';
 9646:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9647:                         $refused = '';
 9648:                     }
 9649:                 } elsif ($context eq 'requestcourses') {
 9650:                     my @possroles = ('st','ta','ep','in','cc','co');
 9651:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9652:                         my $wrongcc;
 9653:                         if ($cnum =~ /^$match_community$/) {
 9654:                             $wrongcc = 1 if ($role eq 'cc');
 9655:                         } else {
 9656:                             $wrongcc = 1 if ($role eq 'co');
 9657:                         }
 9658:                         unless ($wrongcc) {
 9659:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9660:                             if ($crsenv{'internal.courseowner'} eq 
 9661:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9662:                                 $refused = '';
 9663:                             }
 9664:                         }
 9665:                     }
 9666:                 } elsif ($context eq 'requestauthor') {
 9667:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9668:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9669:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9670:                             $refused = '';
 9671:                         } else {
 9672:                             my %domdefaults = &get_domain_defaults($udom);
 9673:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9674:                                 my $checkbystatus;
 9675:                                 if ($env{'user.adv'}) { 
 9676:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9677:                                     if ($disposition eq 'automatic') {
 9678:                                         $refused = '';
 9679:                                     } elsif ($disposition eq '') {
 9680:                                         $checkbystatus = 1;
 9681:                                     } 
 9682:                                 } else {
 9683:                                     $checkbystatus = 1;
 9684:                                 }
 9685:                                 if ($checkbystatus) {
 9686:                                     if ($env{'environment.inststatus'}) {
 9687:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9688:                                         foreach my $type (@inststatuses) {
 9689:                                             if (($type ne '') &&
 9690:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9691:                                                 $refused = '';
 9692:                                             }
 9693:                                         }
 9694:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9695:                                         $refused = '';
 9696:                                     }
 9697:                                 }
 9698:                             }
 9699:                         }
 9700:                     }
 9701:                 }
 9702:                 if ($refused) {
 9703:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9704:                              ' '.$role.' '.$end.' '.$start.' by '.
 9705: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9706:                     return 'refused';
 9707:                 }
 9708:             }
 9709:         } elsif ($role eq 'au') {
 9710:             if ($url ne '/'.$udom.'/') {
 9711:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9712:                          ' to assign author role for '.$uname.':'.$udom.
 9713:                          ' in domain: '.$url.' refused (wrong domain).');
 9714:                 return 'refused';
 9715:             }
 9716:         }
 9717:         $mrole=$role;
 9718:     }
 9719:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9720:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9721:     if ($end) { $command.='_'.$end; }
 9722:     if ($start) {
 9723: 	if ($end) { 
 9724:            $command.='_'.$start; 
 9725:         } else {
 9726:            $command.='_0_'.$start;
 9727:         }
 9728:     }
 9729:     my $origstart = $start;
 9730:     my $origend = $end;
 9731:     my $delflag;
 9732: # actually delete
 9733:     if ($deleteflag) {
 9734: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9735: # modify command to delete the role
 9736:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9737:                 "$udom:$uname:$url".'_'."$mrole";
 9738: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9739: # set start and finish to negative values for userrolelog
 9740:            $start=-1;
 9741:            $end=-1;
 9742:            $delflag = 1;
 9743:         }
 9744:     }
 9745: # send command
 9746:     my $answer=&reply($command,&homeserver($uname,$udom));
 9747: # log new user role if status is ok
 9748:     if ($answer eq 'ok') {
 9749: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9750:         if (($role eq 'cc') || ($role eq 'in') ||
 9751:             ($role eq 'ep') || ($role eq 'ad') ||
 9752:             ($role eq 'ta') || ($role eq 'st') ||
 9753:             ($role=~/^cr/) || ($role eq 'gr') ||
 9754:             ($role eq 'co')) {
 9755: # for course roles, perform group memberships changes triggered by role change.
 9756:             unless ($role =~ /^gr/) {
 9757:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9758:                                                  $origstart,$selfenroll,$context);
 9759:             }
 9760:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9761:                            $selfenroll,$context);
 9762:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9763:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9764:                  ($role eq 'da')) {
 9765:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9766:                            $context);
 9767:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9768:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9769:                              $context); 
 9770:         }
 9771:         if ($role eq 'cc') {
 9772:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9773:         }
 9774:     }
 9775:     return $answer;
 9776: }
 9777: 
 9778: sub autoupdate_coowners {
 9779:     my ($url,$end,$start,$uname,$udom) = @_;
 9780:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9781:     if (($cdom ne '') && ($cnum ne '')) {
 9782:         my $now = time;
 9783:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9784:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9785:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9786:             my $instcode = $coursehash{'internal.coursecode'};
 9787:             if ($instcode ne '') {
 9788:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9789:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9790:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9791:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9792:                         if ($result eq 'valid') {
 9793:                             if ($coursehash{'internal.co-owners'}) {
 9794:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9795:                                     push(@newcoowners,$coowner);
 9796:                                 }
 9797:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9798:                                     push(@newcoowners,$uname.':'.$udom);
 9799:                                 }
 9800:                                 @newcoowners = sort(@newcoowners);
 9801:                             } else {
 9802:                                 push(@newcoowners,$uname.':'.$udom);
 9803:                             }
 9804:                         } else {
 9805:                             if ($coursehash{'internal.co-owners'}) {
 9806:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9807:                                     unless ($coowner eq $uname.':'.$udom) {
 9808:                                         push(@newcoowners,$coowner);
 9809:                                     }
 9810:                                 }
 9811:                                 unless (@newcoowners > 0) {
 9812:                                     $delcoowners = 1;
 9813:                                     $coowners = '';
 9814:                                 }
 9815:                             }
 9816:                         }
 9817:                         if (@newcoowners || $delcoowners) {
 9818:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9819:                                             $delcoowners,@newcoowners);
 9820:                         }
 9821:                     }
 9822:                 }
 9823:             }
 9824:         }
 9825:     }
 9826: }
 9827: 
 9828: sub store_coowners {
 9829:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9830:     my $cid = $cdom.'_'.$cnum;
 9831:     my ($coowners,$delresult,$putresult);
 9832:     if (@newcoowners) {
 9833:         $coowners = join(',',@newcoowners);
 9834:         my %coownershash = (
 9835:                             'internal.co-owners' => $coowners,
 9836:                            );
 9837:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9838:         if ($putresult eq 'ok') {
 9839:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9840:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9841:             }
 9842:         }
 9843:     }
 9844:     if ($delcoowners) {
 9845:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9846:         if ($delresult eq 'ok') {
 9847:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9848:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9849:             }
 9850:         }
 9851:     }
 9852:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9853:         my %crsinfo =
 9854:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9855:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9856:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9857:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9858:         }
 9859:     }
 9860: }
 9861: 
 9862: # -------------------------------------------------- Modify user authentication
 9863: # Overrides without validation
 9864: 
 9865: sub modifyuserauth {
 9866:     my ($udom,$uname,$umode,$upass)=@_;
 9867:     my $uhome=&homeserver($uname,$udom);
 9868:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9869:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9870:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9871:              ' in domain '.$env{'request.role.domain'});  
 9872:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9873: 		     &escape($upass),$uhome);
 9874:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9875:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9876:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9877:     &log($udom,,$uname,$uhome,
 9878:         'Authentication changed by '.$env{'user.domain'}.', '.
 9879:                                      $env{'user.name'}.', '.$umode.
 9880:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9881:     unless ($reply eq 'ok') {
 9882:         &logthis('Authentication mode error: '.$reply);
 9883: 	return 'error: '.$reply;
 9884:     }   
 9885:     return 'ok';
 9886: }
 9887: 
 9888: # --------------------------------------------------------------- Modify a user
 9889: 
 9890: sub modifyuser {
 9891:     my ($udom,    $uname, $uid,
 9892:         $umode,   $upass, $first,
 9893:         $middle,  $last,  $gene,
 9894:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9895:     $udom= &LONCAPA::clean_domain($udom);
 9896:     $uname=&LONCAPA::clean_username($uname);
 9897:     my $showcandelete = 'none';
 9898:     if (ref($candelete) eq 'ARRAY') {
 9899:         if (@{$candelete} > 0) {
 9900:             $showcandelete = join(', ',@{$candelete});
 9901:         }
 9902:     }
 9903:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9904:              $umode.', '.$first.', '.$middle.', '.
 9905: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9906:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9907:                                      ' desiredhome not specified'). 
 9908:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9909:              ' in domain '.$env{'request.role.domain'});
 9910:     my $uhome=&homeserver($uname,$udom,'true');
 9911:     my $newuser;
 9912:     if ($uhome eq 'no_host') {
 9913:         $newuser = 1;
 9914:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9915:                 ($umode eq 'lti')) {
 9916:             return 'error: more information needed to create new user';
 9917:         }
 9918:     }
 9919: # ----------------------------------------------------------------- Create User
 9920:     if (($uhome eq 'no_host') && 
 9921: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9922:         my $unhome='';
 9923:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9924:             $unhome = $desiredhome;
 9925: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9926: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9927:         } else { # load balancing routine for determining $unhome
 9928:             my $loadm=10000000;
 9929: 	    my %servers = &get_servers($udom,'library');
 9930: 	    foreach my $tryserver (keys(%servers)) {
 9931: 		my $answer=reply('load',$tryserver);
 9932: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9933: 		    $loadm=$answer;
 9934: 		    $unhome=$tryserver;
 9935: 		}
 9936: 	    }
 9937:         }
 9938:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9939: 	    return 'error: unable to find a home server for '.$uname.
 9940:                    ' in domain '.$udom;
 9941:         }
 9942:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9943:                          &escape($upass),$unhome);
 9944: 	unless ($reply eq 'ok') {
 9945:             return 'error: '.$reply;
 9946:         }   
 9947:         $uhome=&homeserver($uname,$udom,'true');
 9948:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9949: 	    return 'error: unable verify users home machine.';
 9950:         }
 9951:     }   # End of creation of new user
 9952: # ---------------------------------------------------------------------- Add ID
 9953:     if ($uid) {
 9954:        $uid=~tr/A-Z/a-z/;
 9955:        my %uidhash=&idrget($udom,$uname);
 9956:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9957:          && (!$forceid)) {
 9958: 	  unless ($uid eq $uidhash{$uname}) {
 9959: 	      return 'error: user id "'.$uid.'" does not match '.
 9960:                   'current user id "'.$uidhash{$uname}.'".';
 9961:           }
 9962:        } else {
 9963: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9964:        }
 9965:     }
 9966: # -------------------------------------------------------------- Add names, etc
 9967:     my @tmp=&get('environment',
 9968: 		   ['firstname','middlename','lastname','generation','id',
 9969:                     'permanentemail','inststatus'],
 9970: 		   $udom,$uname);
 9971:     my (%names,%oldnames);
 9972:     if ($tmp[0] =~ m/^error:.*/) { 
 9973:         %names=(); 
 9974:     } else {
 9975:         %names = @tmp;
 9976:         %oldnames = %names;
 9977:     }
 9978: #
 9979: # If name, email and/or uid are blank (e.g., because an uploaded file
 9980: # of users did not contain them), do not overwrite existing values
 9981: # unless field is in $candelete array ref.  
 9982: #
 9983: 
 9984:     my @fields = ('firstname','middlename','lastname','generation',
 9985:                   'permanentemail','id');
 9986:     my %newvalues;
 9987:     if (ref($candelete) eq 'ARRAY') {
 9988:         foreach my $field (@fields) {
 9989:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9990:                 if ($field eq 'firstname') {
 9991:                     $names{$field} = $first;
 9992:                 } elsif ($field eq 'middlename') {
 9993:                     $names{$field} = $middle;
 9994:                 } elsif ($field eq 'lastname') {
 9995:                     $names{$field} = $last;
 9996:                 } elsif ($field eq 'generation') { 
 9997:                     $names{$field} = $gene;
 9998:                 } elsif ($field eq 'permanentemail') {
 9999:                     $names{$field} = $email;
10000:                 } elsif ($field eq 'id') {
10001:                     $names{$field}  = $uid;
10002:                 }
10003:             }
10004:         }
10005:     }
10006:     if ($first)  { $names{'firstname'}  = $first; }
10007:     if (defined($middle)) { $names{'middlename'} = $middle; }
10008:     if ($last)   { $names{'lastname'}   = $last; }
10009:     if (defined($gene))   { $names{'generation'} = $gene; }
10010:     if ($email) {
10011:        $email=~s/[^\w\@\.\-\,]//gs;
10012:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10013:     }
10014:     if ($uid) { $names{'id'}  = $uid; }
10015:     if (defined($inststatus)) {
10016:         $names{'inststatus'} = '';
10017:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10018:         if (ref($usertypes) eq 'HASH') {
10019:             my @okstatuses; 
10020:             foreach my $item (split(/:/,$inststatus)) {
10021:                 if (defined($usertypes->{$item})) {
10022:                     push(@okstatuses,$item);  
10023:                 }
10024:             }
10025:             if (@okstatuses) {
10026:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10027:             }
10028:         }
10029:     }
10030:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10031:                  $umode.', '.$first.', '.$middle.', '.
10032:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10033:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10034:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10035:     } else {
10036:         $logmsg .= ' during self creation';
10037:     }
10038:     my $changed;
10039:     if ($newuser) {
10040:         $changed = 1;
10041:     } else {
10042:         foreach my $field (@fields) {
10043:             if ($names{$field} ne $oldnames{$field}) {
10044:                 $changed = 1;
10045:                 last;
10046:             }
10047:         }
10048:     }
10049:     unless ($changed) {
10050:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10051:         &logthis($logmsg);
10052:         return 'ok';
10053:     }
10054:     my $reply = &put('environment', \%names, $udom,$uname);
10055:     if ($reply ne 'ok') { 
10056:         return 'error: '.$reply;
10057:     }
10058:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10059:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10060:     }
10061:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10062:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10063:     $logmsg = 'Success modifying user '.$logmsg;
10064:     &logthis($logmsg);
10065:     return 'ok';
10066: }
10067: 
10068: # -------------------------------------------------------------- Modify student
10069: 
10070: sub modifystudent {
10071:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10072:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10073:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10074:     if (!$cid) {
10075: 	unless ($cid=$env{'request.course.id'}) {
10076: 	    return 'not_in_class';
10077: 	}
10078:     }
10079: # --------------------------------------------------------------- Make the user
10080:     my $reply=&modifyuser
10081: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10082:          $desiredhome,$email,$inststatus);
10083:     unless ($reply eq 'ok') { return $reply; }
10084:     # This will cause &modify_student_enrollment to get the uid from the
10085:     # student's environment
10086:     $uid = undef if (!$forceid);
10087:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10088:                                         $gene,$usec,$end,$start,$type,$locktype,
10089:                                         $cid,$selfenroll,$context,$credits,$instsec);
10090:     return $reply;
10091: }
10092: 
10093: sub modify_student_enrollment {
10094:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10095:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10096:     my ($cdom,$cnum,$chome);
10097:     if (!$cid) {
10098: 	unless ($cid=$env{'request.course.id'}) {
10099: 	    return 'not_in_class';
10100: 	}
10101: 	$cdom=$env{'course.'.$cid.'.domain'};
10102: 	$cnum=$env{'course.'.$cid.'.num'};
10103:     } else {
10104: 	($cdom,$cnum)=split(/_/,$cid);
10105:     }
10106:     $chome=$env{'course.'.$cid.'.home'};
10107:     if (!$chome) {
10108: 	$chome=&homeserver($cnum,$cdom);
10109:     }
10110:     if (!$chome) { return 'unknown_course'; }
10111:     # Make sure the user exists
10112:     my $uhome=&homeserver($uname,$udom);
10113:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10114: 	return 'error: no such user';
10115:     }
10116:     # Get student data if we were not given enough information
10117:     if (!defined($first)  || $first  eq '' || 
10118:         !defined($last)   || $last   eq '' || 
10119:         !defined($uid)    || $uid    eq '' || 
10120:         !defined($middle) || $middle eq '' || 
10121:         !defined($gene)   || $gene   eq '') {
10122:         # They did not supply us with enough data to enroll the student, so
10123:         # we need to pick up more information.
10124:         my %tmp = &get('environment',
10125:                        ['firstname','middlename','lastname', 'generation','id']
10126:                        ,$udom,$uname);
10127: 
10128:         #foreach my $key (keys(%tmp)) {
10129:         #    &logthis("key $key = ".$tmp{$key});
10130:         #}
10131:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10132:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10133:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10134:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10135:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10136:     }
10137:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10138:     my $user = "$uname:$udom";
10139:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10140:     my $reply=cput('classlist',
10141: 		   {$user => 
10142: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10143: 		   $cdom,$cnum);
10144:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10145:         &devalidate_getsection_cache($udom,$uname,$cid);
10146:     } else { 
10147: 	return 'error: '.$reply;
10148:     }
10149:     # Add student role to user
10150:     my $uurl='/'.$cid;
10151:     $uurl=~s/\_/\//g;
10152:     if ($usec) {
10153: 	$uurl.='/'.$usec;
10154:     }
10155:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10156:                              $selfenroll,$context);
10157:     if ($result ne 'ok') {
10158:         if ($old_entry{$user} ne '') {
10159:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10160:         } else {
10161:             $reply = &del('classlist',[$user],$cdom,$cnum);
10162:         }
10163:     }
10164:     return $result; 
10165: }
10166: 
10167: sub format_name {
10168:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10169:     my $name;
10170:     if ($first ne 'lastname') {
10171: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10172:     } else {
10173: 	if ($lastname=~/\S/) {
10174: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10175: 	    $name=~s/\s+,/,/;
10176: 	} else {
10177: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10178: 	}
10179:     }
10180:     $name=~s/^\s+//;
10181:     $name=~s/\s+$//;
10182:     $name=~s/\s+/ /g;
10183:     return $name;
10184: }
10185: 
10186: # ------------------------------------------------- Write to course preferences
10187: 
10188: sub writecoursepref {
10189:     my ($courseid,%prefs)=@_;
10190:     $courseid=~s/^\///;
10191:     $courseid=~s/\_/\//g;
10192:     my ($cdomain,$cnum)=split(/\//,$courseid);
10193:     my $chome=homeserver($cnum,$cdomain);
10194:     if (($chome eq '') || ($chome eq 'no_host')) { 
10195: 	return 'error: no such course';
10196:     }
10197:     my $cstring='';
10198:     foreach my $pref (keys(%prefs)) {
10199: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10200:     }
10201:     $cstring=~s/\&$//;
10202:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10203: }
10204: 
10205: # ---------------------------------------------------------- Make/modify course
10206: 
10207: sub createcourse {
10208:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10209:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10210:     $url=&declutter($url);
10211:     my $cid='';
10212:     if ($context eq 'requestcourses') {
10213:         my $can_create = 0;
10214:         my ($ownername,$ownerdom) = split(':',$course_owner);
10215:         if ($udom eq $ownerdom) {
10216:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10217:                                   $context)) {
10218:                 $can_create = 1;
10219:             }
10220:         } else {
10221:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10222:                                            $category);
10223:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10224:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10225:                 if (@curr > 0) {
10226:                     my @options = qw(approval validate autolimit);
10227:                     my $optregex = join('|',@options);
10228:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10229:                         $can_create = 1;
10230:                     }
10231:                 }
10232:             }
10233:         }
10234:         if ($can_create) {
10235:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10236:                 unless (&allowed('ccc',$udom)) {
10237:                     return 'refused'; 
10238:                 }
10239:             }
10240:         } else {
10241:             return 'refused';
10242:         }
10243:     } elsif (!&allowed('ccc',$udom)) {
10244:         return 'refused';
10245:     }
10246: # --------------------------------------------------------------- Get Unique ID
10247:     my $uname;
10248:     if ($cnum =~ /^$match_courseid$/) {
10249:         my $chome=&homeserver($cnum,$udom,'true');
10250:         if (($chome eq '') || ($chome eq 'no_host')) {
10251:             $uname = $cnum;
10252:         } else {
10253:             $uname = &generate_coursenum($udom,$crstype);
10254:         }
10255:     } else {
10256:         $uname = &generate_coursenum($udom,$crstype);
10257:     }
10258:     return $uname if ($uname =~ /^error/);
10259: # -------------------------------------------------- Check supplied server name
10260:     if (!defined($course_server)) {
10261:         if (defined(&domain($udom,'primary'))) {
10262:             $course_server = &domain($udom,'primary');
10263:         } else {
10264:             $course_server = $env{'user.home'}; 
10265:         }
10266:     }
10267:     my %host_servers =
10268:         &Apache::lonnet::get_servers($udom,'library');
10269:     unless ($host_servers{$course_server}) {
10270:         return 'error: invalid home server for course: '.$course_server;
10271:     }
10272: # ------------------------------------------------------------- Make the course
10273:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10274:                       $course_server);
10275:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10276:     my $uhome=&homeserver($uname,$udom,'true');
10277:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10278: 	return 'error: no such course';
10279:     }
10280: # ----------------------------------------------------------------- Course made
10281: # log existence
10282:     my $now = time;
10283:     my $newcourse = {
10284:                     $udom.'_'.$uname => {
10285:                                      description => $description,
10286:                                      inst_code   => $inst_code,
10287:                                      owner       => $course_owner,
10288:                                      type        => $crstype,
10289:                                      creator     => $env{'user.name'}.':'.
10290:                                                     $env{'user.domain'},
10291:                                      created     => $now,
10292:                                      context     => $context,
10293:                                                 },
10294:                     };
10295:     &courseidput($udom,$newcourse,$uhome,'notime');
10296: # set toplevel url
10297:     my $topurl=$url;
10298:     unless ($nonstandard) {
10299: # ------------------------------------------ For standard courses, make top url
10300:         my $mapurl=&clutter($url);
10301:         if ($mapurl eq '/res/') { $mapurl=''; }
10302:         $env{'form.initmap'}=(<<ENDINITMAP);
10303: <map>
10304: <resource id="1" type="start"></resource>
10305: <resource id="2" src="$mapurl"></resource>
10306: <resource id="3" type="finish"></resource>
10307: <link index="1" from="1" to="2"></link>
10308: <link index="2" from="2" to="3"></link>
10309: </map>
10310: ENDINITMAP
10311:         $topurl=&declutter(
10312:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10313:                           );
10314:     }
10315: # ----------------------------------------------------------- Write preferences
10316:     &writecoursepref($udom.'_'.$uname,
10317:                      ('description'              => $description,
10318:                       'url'                      => $topurl,
10319:                       'internal.creator'         => $env{'user.name'}.':'.
10320:                                                     $env{'user.domain'},
10321:                       'internal.created'         => $now,
10322:                       'internal.creationcontext' => $context)
10323:                     );
10324:     return '/'.$udom.'/'.$uname;
10325: }
10326: 
10327: # ------------------------------------------------------------------- Create ID
10328: sub generate_coursenum {
10329:     my ($udom,$crstype) = @_;
10330:     my $domdesc = &domain($udom);
10331:     return 'error: invalid domain' if ($domdesc eq '');
10332:     my $first;
10333:     if ($crstype eq 'Community') {
10334:         $first = '0';
10335:     } else {
10336:         $first = int(1+rand(9)); 
10337:     } 
10338:     my $uname=$first.
10339:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10340:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10341:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10342: # ----------------------------------------------- Make sure that does not exist
10343:     my $uhome=&homeserver($uname,$udom,'true');
10344:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10345:         if ($crstype eq 'Community') {
10346:             $first = '0';
10347:         } else {
10348:             $first = int(1+rand(9));
10349:         }
10350:         $uname=$first.
10351:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10352:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10353:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10354:         $uhome=&homeserver($uname,$udom,'true');
10355:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10356:             return 'error: unable to generate unique course-ID';
10357:         }
10358:     }
10359:     return $uname;
10360: }
10361: 
10362: sub is_course {
10363:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10364:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10365: 
10366:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10367:     my $uhome=&homeserver($cnum,$cdom);
10368:     my $iscourse;
10369:     if (grep { $_ eq $uhome } current_machine_ids()) {
10370:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10371:     } else {
10372:         my $hashid = $cdom.':'.$cnum;
10373:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10374:         unless (defined($cached)) {
10375:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10376:                                         $cnum,undef,undef,'.');
10377:             $iscourse = 0;
10378:             if (exists($courses{$cdom.'_'.$cnum})) {
10379:                 $iscourse = 1;
10380:             }
10381:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10382:         }
10383:     }
10384:     return unless ($iscourse);
10385:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10386: }
10387: 
10388: sub store_userdata {
10389:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10390:     my $result;
10391:     if ($datakey ne '') {
10392:         if (ref($storehash) eq 'HASH') {
10393:             if ($udom eq '' || $uname eq '') {
10394:                 $udom = $env{'user.domain'};
10395:                 $uname = $env{'user.name'};
10396:             }
10397:             my $uhome=&homeserver($uname,$udom);
10398:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10399:                 $result = 'error: no_host';
10400:             } else {
10401:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10402:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10403: 
10404:                 my $namevalue='';
10405:                 foreach my $key (keys(%{$storehash})) {
10406:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10407:                 }
10408:                 $namevalue=~s/\&$//;
10409:                 unless ($namespace eq 'courserequests') {
10410:                     $datakey = &escape($datakey);
10411:                 }
10412:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10413:                                   $namevalue,$uhome);
10414:             }
10415:         } else {
10416:             $result = 'error: data to store was not a hash reference'; 
10417:         }
10418:     } else {
10419:         $result= 'error: invalid requestkey'; 
10420:     }
10421:     return $result;
10422: }
10423: 
10424: # ---------------------------------------------------------- Assign Custom Role
10425: 
10426: sub assigncustomrole {
10427:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10428:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10429:                        $end,$start,$deleteflag,$selfenroll,$context);
10430: }
10431: 
10432: # ----------------------------------------------------------------- Revoke Role
10433: 
10434: sub revokerole {
10435:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10436:     my $now=time;
10437:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10438: }
10439: 
10440: # ---------------------------------------------------------- Revoke Custom Role
10441: 
10442: sub revokecustomrole {
10443:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10444:     my $now=time;
10445:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10446:            $deleteflag,$selfenroll,$context);
10447: }
10448: 
10449: # ------------------------------------------------------------ Disk usage
10450: sub diskusage {
10451:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10452:     $directorypath =~ s/\/$//;
10453:     my $listing=&reply('du2:'.&escape($directorypath).':'
10454:                        .&escape($getpropath).':'.&escape($uname).':'
10455:                        .&escape($udom),homeserver($uname,$udom));
10456:     if ($listing eq 'unknown_cmd') {
10457:         if ($getpropath) {
10458:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10459:         }
10460:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10461:     }
10462:     return $listing;
10463: }
10464: 
10465: sub is_locked {
10466:     my ($file_name, $domain, $user, $which) = @_;
10467:     my @check;
10468:     my $is_locked;
10469:     push (@check,$file_name);
10470:     my %locked = &get('file_permissions',\@check,
10471: 		      $env{'user.domain'},$env{'user.name'});
10472:     my ($tmp)=keys(%locked);
10473:     if ($tmp=~/^error:/) { undef(%locked); }
10474:     
10475:     if (ref($locked{$file_name}) eq 'ARRAY') {
10476:         $is_locked = 'false';
10477:         foreach my $entry (@{$locked{$file_name}}) {
10478:            if (ref($entry) eq 'ARRAY') {
10479:                $is_locked = 'true';
10480:                if (ref($which) eq 'ARRAY') {
10481:                    push(@{$which},$entry);
10482:                } else {
10483:                    last;
10484:                }
10485:            }
10486:        }
10487:     } else {
10488:         $is_locked = 'false';
10489:     }
10490:     return $is_locked;
10491: }
10492: 
10493: sub declutter_portfile {
10494:     my ($file) = @_;
10495:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10496:     return $file;
10497: }
10498: 
10499: # ------------------------------------------------------------- Mark as Read Only
10500: 
10501: sub mark_as_readonly {
10502:     my ($domain,$user,$files,$what) = @_;
10503:     my %current_permissions = &dump('file_permissions',$domain,$user);
10504:     my ($tmp)=keys(%current_permissions);
10505:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10506:     foreach my $file (@{$files}) {
10507: 	$file = &declutter_portfile($file);
10508:         push(@{$current_permissions{$file}},$what);
10509:     }
10510:     &put('file_permissions',\%current_permissions,$domain,$user);
10511:     return;
10512: }
10513: 
10514: # ------------------------------------------------------------Save Selected Files
10515: 
10516: sub save_selected_files {
10517:     my ($user, $path, @files) = @_;
10518:     my $filename = $user."savedfiles";
10519:     my @other_files = &files_not_in_path($user, $path);
10520:     open (OUT,'>',LONCAPA::tempdir().$filename);
10521:     foreach my $file (@files) {
10522:         print (OUT $env{'form.currentpath'}.$file."\n");
10523:     }
10524:     foreach my $file (@other_files) {
10525:         print (OUT $file."\n");
10526:     }
10527:     close (OUT);
10528:     return 'ok';
10529: }
10530: 
10531: sub clear_selected_files {
10532:     my ($user) = @_;
10533:     my $filename = $user."savedfiles";
10534:     open (OUT,'>',LONCAPA::tempdir().$filename);
10535:     print (OUT undef);
10536:     close (OUT);
10537:     return ("ok");    
10538: }
10539: 
10540: sub files_in_path {
10541:     my ($user, $path) = @_;
10542:     my $filename = $user."savedfiles";
10543:     my %return_files;
10544:     open (IN,'<',LONCAPA::tempdir().$filename);
10545:     while (my $line_in = <IN>) {
10546:         chomp ($line_in);
10547:         my @paths_and_file = split (m!/!, $line_in);
10548:         my $file_part = pop (@paths_and_file);
10549:         my $path_part = join ('/', @paths_and_file);
10550:         $path_part.='/';
10551:         my $path_and_file = $path_part.$file_part;
10552:         if ($path_part eq $path) {
10553:             $return_files{$file_part}= 'selected';
10554:         }
10555:     }
10556:     close (IN);
10557:     return (\%return_files);
10558: }
10559: 
10560: # called in portfolio select mode, to show files selected NOT in current directory
10561: sub files_not_in_path {
10562:     my ($user, $path) = @_;
10563:     my $filename = $user."savedfiles";
10564:     my @return_files;
10565:     my $path_part;
10566:     open(IN, '<',LONCAPA::tempdir().$filename);
10567:     while (my $line = <IN>) {
10568:         #ok, I know it's clunky, but I want it to work
10569:         my @paths_and_file = split(m|/|, $line);
10570:         my $file_part = pop(@paths_and_file);
10571:         chomp($file_part);
10572:         my $path_part = join('/', @paths_and_file);
10573:         $path_part .= '/';
10574:         my $path_and_file = $path_part.$file_part;
10575:         if ($path_part ne $path) {
10576:             push(@return_files, ($path_and_file));
10577:         }
10578:     }
10579:     close(OUT);
10580:     return (@return_files);
10581: }
10582: 
10583: #------------------------------Submitted/Handedback Portfolio Files Versioning
10584:  
10585: sub portfiles_versioning {
10586:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10587:     my $portfolio_root = '/userfiles/portfolio';
10588:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10589:     foreach my $file (@{$portfiles}) {
10590:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10591:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10592:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10593:         my $getpropath = 1;
10594:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10595:                                              $stu_name,$getpropath);
10596:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10597:         my $new_answer = 
10598:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10599:         if ($new_answer ne 'problem getting file') {
10600:             push(@{$versioned_portfiles}, $directory.$new_answer);
10601:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10602:                               [$symb,$env{'request.course.id'},'graded']);
10603:         }
10604:     }
10605: }
10606: 
10607: sub get_next_version {
10608:     my ($answer_name, $answer_ext, $dir_list) = @_;
10609:     my $version;
10610:     if (ref($dir_list) eq 'ARRAY') {
10611:         foreach my $row (@{$dir_list}) {
10612:             my ($file) = split(/\&/,$row,2);
10613:             my ($file_name,$file_version,$file_ext) =
10614:                 &file_name_version_ext($file);
10615:             if (($file_name eq $answer_name) &&
10616:                 ($file_ext eq $answer_ext)) {
10617:                      # gets here if filename and extension match,
10618:                      # regardless of version
10619:                 if ($file_version ne '') {
10620:                     # a versioned file is found  so save it for later
10621:                     if ($file_version > $version) {
10622:                         $version = $file_version;
10623:                     }
10624:                 }
10625:             }
10626:         }
10627:     }
10628:     $version ++;
10629:     return($version);
10630: }
10631: 
10632: sub version_selected_portfile {
10633:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10634:     my ($answer_name,$answer_ver,$answer_ext) =
10635:         &file_name_version_ext($file_name);
10636:     my $new_answer;
10637:     $env{'form.copy'} =
10638:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10639:     if($env{'form.copy'} eq '-1') {
10640:         $new_answer = 'problem getting file';
10641:     } else {
10642:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10643:         my $copy_result = 
10644:             &finishuserfileupload($stu_name,$domain,'copy',
10645:                                   '/portfolio'.$directory.$new_answer);
10646:     }
10647:     undef($env{'form.copy'});
10648:     return ($new_answer);
10649: }
10650: 
10651: sub file_name_version_ext {
10652:     my ($file)=@_;
10653:     my @file_parts = split(/\./, $file);
10654:     my ($name,$version,$ext);
10655:     if (@file_parts > 1) {
10656:         $ext=pop(@file_parts);
10657:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10658:             $version=pop(@file_parts);
10659:         }
10660:         $name=join('.',@file_parts);
10661:     } else {
10662:         $name=join('.',@file_parts);
10663:     }
10664:     return($name,$version,$ext);
10665: }
10666: 
10667: #----------------------------------------------Get portfolio file permissions
10668: 
10669: sub get_portfile_permissions {
10670:     my ($domain,$user) = @_;
10671:     my %current_permissions = &dump('file_permissions',$domain,$user);
10672:     my ($tmp)=keys(%current_permissions);
10673:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10674:     return \%current_permissions;
10675: }
10676: 
10677: #---------------------------------------------Get portfolio file access controls
10678: 
10679: sub get_access_controls {
10680:     my ($current_permissions,$group,$file) = @_;
10681:     my %access;
10682:     my $real_file = $file;
10683:     $file =~ s/\.meta$//;
10684:     if (defined($file)) {
10685:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10686:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10687:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10688:             }
10689:         }
10690:     } else {
10691:         foreach my $key (keys(%{$current_permissions})) {
10692:             if ($key =~ /\0accesscontrol$/) {
10693:                 if (defined($group)) {
10694:                     if ($key !~ m-^\Q$group\E/-) {
10695:                         next;
10696:                     }
10697:                 }
10698:                 my ($fullpath) = split(/\0/,$key);
10699:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10700:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10701:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10702:                     }
10703:                 }
10704:             }
10705:         }
10706:     }
10707:     return %access;
10708: }
10709: 
10710: sub modify_access_controls {
10711:     my ($file_name,$changes,$domain,$user)=@_;
10712:     my ($outcome,$deloutcome);
10713:     my %store_permissions;
10714:     my %new_values;
10715:     my %new_control;
10716:     my %translation;
10717:     my @deletions = ();
10718:     my $now = time;
10719:     if (exists($$changes{'activate'})) {
10720:         if (ref($$changes{'activate'}) eq 'HASH') {
10721:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10722:             my $numnew = scalar(@newitems);
10723:             for (my $i=0; $i<$numnew; $i++) {
10724:                 my $newkey = $newitems[$i];
10725:                 my $newid = &Apache::loncommon::get_cgi_id();
10726:                 if ($newkey =~ /^\d+:/) { 
10727:                     $newkey =~ s/^(\d+)/$newid/;
10728:                     $translation{$1} = $newid;
10729:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10730:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10731:                     $translation{$1} = $newid;
10732:                 }
10733:                 $new_values{$file_name."\0".$newkey} = 
10734:                                           $$changes{'activate'}{$newitems[$i]};
10735:                 $new_control{$newkey} = $now;
10736:             }
10737:         }
10738:     }
10739:     my %todelete;
10740:     my %changed_items;
10741:     foreach my $action ('delete','update') {
10742:         if (exists($$changes{$action})) {
10743:             if (ref($$changes{$action}) eq 'HASH') {
10744:                 foreach my $key (keys(%{$$changes{$action}})) {
10745:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10746:                     if ($action eq 'delete') { 
10747:                         $todelete{$itemnum} = 1;
10748:                     } else {
10749:                         $changed_items{$itemnum} = $key;
10750:                     }
10751:                 }
10752:             }
10753:         }
10754:     }
10755:     # get lock on access controls for file.
10756:     my $lockhash = {
10757:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10758:                                                        ':'.$env{'user.domain'},
10759:                    }; 
10760:     my $tries = 0;
10761:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10762:    
10763:     while (($gotlock ne 'ok') && $tries < 10) {
10764:         $tries ++;
10765:         sleep(0.1);
10766:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10767:     }
10768:     if ($gotlock eq 'ok') {
10769:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10770:         my ($tmp)=keys(%curr_permissions);
10771:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10772:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10773:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10774:             if (ref($curr_controls) eq 'HASH') {
10775:                 foreach my $control_item (keys(%{$curr_controls})) {
10776:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10777:                     if (defined($todelete{$itemnum})) {
10778:                         push(@deletions,$file_name."\0".$control_item);
10779:                     } else {
10780:                         if (defined($changed_items{$itemnum})) {
10781:                             $new_control{$changed_items{$itemnum}} = $now;
10782:                             push(@deletions,$file_name."\0".$control_item);
10783:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10784:                         } else {
10785:                             $new_control{$control_item} = $$curr_controls{$control_item};
10786:                         }
10787:                     }
10788:                 }
10789:             }
10790:         }
10791:         my ($group);
10792:         if (&is_course($domain,$user)) {
10793:             ($group,my $file) = split(/\//,$file_name,2);
10794:         }
10795:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10796:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10797:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10798:         #  remove lock
10799:         my @del_lock = ($file_name."\0".'locked_access_records');
10800:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10801:         my $sqlresult =
10802:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10803:                                     $group);
10804:     } else {
10805:         $outcome = "error: could not obtain lockfile\n";  
10806:     }
10807:     return ($outcome,$deloutcome,\%new_values,\%translation);
10808: }
10809: 
10810: sub make_public_indefinitely {
10811:     my (@requrl) = @_;
10812:     return &automated_portfile_access('public',\@requrl);
10813: }
10814: 
10815: sub automated_portfile_access {
10816:     my ($accesstype,$addsref,$delsref,$info) = @_;
10817:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10818:         return 'invalid';
10819:     }
10820:     my %urls;
10821:     if (ref($addsref) eq 'ARRAY') {
10822:         foreach my $requrl (@{$addsref}) {
10823:             if (&is_portfolio_url($requrl)) {
10824:                 unless (exists($urls{$requrl})) {
10825:                     $urls{$requrl} = 'add';
10826:                 }
10827:             }
10828:         }
10829:     }
10830:     if (ref($delsref) eq 'ARRAY') {
10831:         foreach my $requrl (@{$delsref}) { 
10832:             if (&is_portfolio_url($requrl)) {
10833:                 unless (exists($urls{$requrl})) {
10834:                     $urls{$requrl} = 'delete'; 
10835:                 }
10836:             }
10837:         }
10838:     }
10839:     unless (keys(%urls)) {
10840:         return 'invalid';
10841:     }
10842:     my $ip;
10843:     if ($accesstype eq 'ip') {
10844:         if (ref($info) eq 'HASH') {
10845:             if ($info->{'ip'} ne '') {
10846:                 $ip = $info->{'ip'};
10847:             }
10848:         }
10849:         if ($ip eq '') {
10850:             return 'invalid';
10851:         }
10852:     }
10853:     my $errors;
10854:     my $now = time;
10855:     my %current_perms;
10856:     foreach my $requrl (sort(keys(%urls))) {
10857:         my $action;
10858:         if ($urls{$requrl} eq 'add') {
10859:             $action = 'activate';
10860:         } else {
10861:             $action = 'none';
10862:         }
10863:         my $aclnum = 0;
10864:         my (undef,$udom,$unum,$file_name,$group) =
10865:             &parse_portfolio_url($requrl);
10866:         unless (exists($current_perms{$unum.':'.$udom})) {
10867:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10868:         }
10869:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10870:                                                    $group,$file_name);
10871:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10872:             my ($num,$scope,$end,$start) = 
10873:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10874:             if ($scope eq $accesstype) {
10875:                 if (($start <= $now) && ($end == 0)) {
10876:                     if ($accesstype eq 'ip') {
10877:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10878:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10879:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10880:                                     if ($urls{$requrl} eq 'add') {
10881:                                         $action = 'none';
10882:                                         last;
10883:                                     } else {
10884:                                         $action = 'delete';
10885:                                         $aclnum = $num;
10886:                                         last;
10887:                                     }
10888:                                 }
10889:                             }
10890:                         }
10891:                     } elsif ($accesstype eq 'public') {
10892:                         if ($urls{$requrl} eq 'add') {
10893:                             $action = 'none';
10894:                             last;
10895:                         } else {
10896:                             $action = 'delete';
10897:                             $aclnum = $num;
10898:                             last;
10899:                         }
10900:                     }
10901:                 } elsif ($accesstype eq 'public') {
10902:                     $action = 'update';
10903:                     $aclnum = $num;
10904:                     last;
10905:                 }
10906:             }
10907:         }
10908:         if ($action eq 'none') {
10909:             next;
10910:         } else {
10911:             my %changes;
10912:             my $newend = 0;
10913:             my $newstart = $now;
10914:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10915:             $changes{$action}{$newkey} = {
10916:                 type => $accesstype,
10917:                 time => {
10918:                     start => $newstart,
10919:                     end   => $newend,
10920:                 },
10921:             };
10922:             if ($accesstype eq 'ip') {
10923:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10924:             }
10925:             my ($outcome,$deloutcome,$new_values,$translation) =
10926:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10927:             unless ($outcome eq 'ok') {
10928:                 $errors .= $outcome.' ';
10929:             }
10930:         }
10931:     }
10932:     if ($errors) {
10933:         $errors =~ s/\s$//;
10934:         return $errors;
10935:     } else {
10936:         return 'ok';
10937:     }
10938: }
10939: 
10940: #------------------------------------------------------Get Marked as Read Only
10941: 
10942: sub get_marked_as_readonly {
10943:     my ($domain,$user,$what,$group) = @_;
10944:     my $current_permissions = &get_portfile_permissions($domain,$user);
10945:     my @readonly_files;
10946:     my $cmp1=$what;
10947:     if (ref($what)) { $cmp1=join('',@{$what}) };
10948:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10949:         if (defined($group)) {
10950:             if ($file_name !~ m-^\Q$group\E/-) {
10951:                 next;
10952:             }
10953:         }
10954:         if (ref($value) eq "ARRAY"){
10955:             foreach my $stored_what (@{$value}) {
10956:                 my $cmp2=$stored_what;
10957:                 if (ref($stored_what) eq 'ARRAY') {
10958:                     $cmp2=join('',@{$stored_what});
10959:                 }
10960:                 if ($cmp1 eq $cmp2) {
10961:                     push(@readonly_files, $file_name);
10962:                     last;
10963:                 } elsif (!defined($what)) {
10964:                     push(@readonly_files, $file_name);
10965:                     last;
10966:                 }
10967:             }
10968:         }
10969:     }
10970:     return @readonly_files;
10971: }
10972: #-----------------------------------------------------------Get Marked as Read Only Hash
10973: 
10974: sub get_marked_as_readonly_hash {
10975:     my ($current_permissions,$group,$what) = @_;
10976:     my %readonly_files;
10977:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10978:         if (defined($group)) {
10979:             if ($file_name !~ m-^\Q$group\E/-) {
10980:                 next;
10981:             }
10982:         }
10983:         if (ref($value) eq "ARRAY"){
10984:             foreach my $stored_what (@{$value}) {
10985:                 if (ref($stored_what) eq 'ARRAY') {
10986:                     foreach my $lock_descriptor(@{$stored_what}) {
10987:                         if ($lock_descriptor eq 'graded') {
10988:                             $readonly_files{$file_name} = 'graded';
10989:                         } elsif ($lock_descriptor eq 'handback') {
10990:                             $readonly_files{$file_name} = 'handback';
10991:                         } else {
10992:                             if (!exists($readonly_files{$file_name})) {
10993:                                 $readonly_files{$file_name} = 'locked';
10994:                             }
10995:                         }
10996:                     }
10997:                 } 
10998:             }
10999:         } 
11000:     }
11001:     return %readonly_files;
11002: }
11003: # ------------------------------------------------------------ Unmark as Read Only
11004: 
11005: sub unmark_as_readonly {
11006:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11007:     # for portfolio submissions, $what contains [$symb,$crsid] 
11008:     my ($domain,$user,$what,$file_name,$group) = @_;
11009:     $file_name = &declutter_portfile($file_name);
11010:     my $symb_crs = $what;
11011:     if (ref($what)) { $symb_crs=join('',@$what); }
11012:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11013:     my ($tmp)=keys(%current_permissions);
11014:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11015:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11016:     foreach my $file (@readonly_files) {
11017: 	my $clean_file = &declutter_portfile($file);
11018: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11019: 	my $current_locks = $current_permissions{$file};
11020:         my @new_locks;
11021:         my @del_keys;
11022:         if (ref($current_locks) eq "ARRAY"){
11023:             foreach my $locker (@{$current_locks}) {
11024:                 my $compare=$locker;
11025:                 if (ref($locker) eq 'ARRAY') {
11026:                     $compare=join('',@{$locker});
11027:                     if ($compare ne $symb_crs) {
11028:                         push(@new_locks, $locker);
11029:                     }
11030:                 }
11031:             }
11032:             if (scalar(@new_locks) > 0) {
11033:                 $current_permissions{$file} = \@new_locks;
11034:             } else {
11035:                 push(@del_keys, $file);
11036:                 &del('file_permissions',\@del_keys, $domain, $user);
11037:                 delete($current_permissions{$file});
11038:             }
11039:         }
11040:     }
11041:     &put('file_permissions',\%current_permissions,$domain,$user);
11042:     return;
11043: }
11044: 
11045: # ------------------------------------------------------------ Directory lister
11046: 
11047: sub dirlist {
11048:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11049:     $uri=~s/^\///;
11050:     $uri=~s/\/$//;
11051:     my ($udom, $uname);
11052:     if ($getuserdir) {
11053:         $udom = $userdomain;
11054:         $uname = $username;
11055:     } else {
11056:         (undef,$udom,$uname)=split(/\//,$uri);
11057:         if(defined($userdomain)) {
11058:             $udom = $userdomain;
11059:         }
11060:         if(defined($username)) {
11061:             $uname = $username;
11062:         }
11063:     }
11064:     my ($dirRoot,$listing,@listing_results);
11065: 
11066:     $dirRoot = $perlvar{'lonDocRoot'};
11067:     if (defined($getpropath)) {
11068:         $dirRoot = &propath($udom,$uname);
11069:         $dirRoot =~ s/\/$//;
11070:     } elsif (defined($getuserdir)) {
11071:         my $subdir=$uname.'__';
11072:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11073:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11074:                    ."/$udom/$subdir/$uname";
11075:     } elsif (defined($alternateRoot)) {
11076:         $dirRoot = $alternateRoot;
11077:     }
11078: 
11079:     if($udom) {
11080:         if($uname) {
11081:             my $uhome = &homeserver($uname,$udom);
11082:             if ($uhome eq 'no_host') {
11083:                 return ([],'no_host');
11084:             }
11085:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11086:                               .$getuserdir.':'.&escape($dirRoot)
11087:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11088:             if ($listing eq 'unknown_cmd') {
11089:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11090:             } else {
11091:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11092:             }
11093:             if ($listing eq 'unknown_cmd') {
11094:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11095:                 @listing_results = split(/:/,$listing);
11096:             } else {
11097:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11098:             }
11099:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11100:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11101:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11102:                 return ([],$listing);
11103:             } else {
11104:                 return (\@listing_results);
11105:             }
11106:         } elsif(!$alternateRoot) {
11107:             my (%allusers,%listerror);
11108: 	    my %servers = &get_servers($udom,'library');
11109:  	    foreach my $tryserver (keys(%servers)) {
11110:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11111:                                   &escape($udom),$tryserver);
11112:                 if ($listing eq 'unknown_cmd') {
11113: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11114: 				      $udom, $tryserver);
11115:                 } else {
11116:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11117:                 }
11118: 		if ($listing eq 'unknown_cmd') {
11119: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11120: 				      $udom, $tryserver);
11121: 		    @listing_results = split(/:/,$listing);
11122: 		} else {
11123: 		    @listing_results =
11124: 			map { &unescape($_); } split(/:/,$listing);
11125: 		}
11126:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11127:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11128:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11129:                     $listerror{$tryserver} = $listing;
11130:                 } else {
11131: 		    foreach my $line (@listing_results) {
11132: 			my ($entry) = split(/&/,$line,2);
11133: 			$allusers{$entry} = 1;
11134: 		    }
11135: 		}
11136:             }
11137:             my @alluserslist=();
11138:             foreach my $user (sort(keys(%allusers))) {
11139:                 push(@alluserslist,$user.'&user');
11140:             }
11141: 
11142:             if (!%listerror) {
11143:                 # no errors
11144:                 return (\@alluserslist);
11145:             } elsif (scalar(keys(%servers)) == 1) {
11146:                 # one library server, one error 
11147:                 my ($key) = keys(%listerror);
11148:                 return (\@alluserslist, $listerror{$key});
11149:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11150:                 # con_lost indicates that we might miss data from at least one
11151:                 # library server
11152:                 return (\@alluserslist, 'con_lost');
11153:             } else {
11154:                 # multiple library servers and no con_lost -> data should be
11155:                 # complete. 
11156:                 return (\@alluserslist);
11157:             }
11158: 
11159:         } else {
11160:             return ([],'missing username');
11161:         }
11162:     } elsif(!defined($getpropath)) {
11163:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11164:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11165:         return (\@all_domains);
11166:     } else {
11167:         return ([],'missing domain');
11168:     }
11169: }
11170: 
11171: # --------------------------------------------- GetFileTimestamp
11172: # This function utilizes dirlist and returns the date stamp for
11173: # when it was last modified.  It will also return an error of -1
11174: # if an error occurs
11175: 
11176: sub GetFileTimestamp {
11177:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11178:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11179:     $studentName   = &LONCAPA::clean_username($studentName);
11180:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11181:                                     undef,$getuserdir);
11182:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11183:         return -1;
11184:     }
11185:     if (ref($fileref) eq 'ARRAY') {
11186:         my @stats = split('&',$fileref->[0]);
11187:         # @stats contains first the filename, then the stat output
11188:         return $stats[10]; # so this is 10 instead of 9.
11189:     } else {
11190:         return -1;
11191:     }
11192: }
11193: 
11194: sub stat_file {
11195:     my ($uri) = @_;
11196:     $uri = &clutter_with_no_wrapper($uri);
11197: 
11198:     my ($udom,$uname,$file);
11199:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11200: 	($udom,$uname,$file) =
11201: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11202: 	$file = 'userfiles/'.$file;
11203:     }
11204:     if ($uri =~ m-^/res/-) {
11205: 	($udom,$uname) = 
11206: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11207: 	$file = $uri;
11208:     }
11209: 
11210:     if (!$udom || !$uname || !$file) {
11211: 	# unable to handle the uri
11212: 	return ();
11213:     }
11214:     my $getpropath;
11215:     if ($file =~ /^userfiles\//) {
11216:         $getpropath = 1;
11217:     }
11218:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11219:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11220:         return ();
11221:     } else {
11222:         if (ref($listref) eq 'ARRAY') {
11223:             my @stats = split('&',$listref->[0]);
11224: 	    shift(@stats); #filename is first
11225: 	    return @stats;
11226:         }
11227:     }
11228:     return ();
11229: }
11230: 
11231: # --------------------------------------------------------- recursedirs
11232: # Recursive function to traverse either a specific user's Authoring Space
11233: # or corresponding Published Resource Space, and populate the hash ref:
11234: # $dirhashref with URLs of all directories, and if $filehashref hash
11235: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11236: # or .rights files in resource space, and .meta, .save, .log, and .bak
11237: # files in Authoring Space.
11238: #
11239: # Inputs:
11240: #
11241: # $is_home - true if current server is home server for user's space
11242: # $context - either: priv, or res respectively for Authoring or Resource Space.
11243: # $docroot - Document root (i.e., /home/httpd/html
11244: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11245: # $relpath - Current path (relative to top level).
11246: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11247: # $filehashref - reference to hash to populate with URLs of files (Optional)
11248: #
11249: # Returns: nothing
11250: #
11251: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11252: #
11253: # Currently used by interface/londocs.pm to create linked select boxes for
11254: # directory and filename to import a Course "Author" resource into a course, and
11255: # also to create linked select boxes for Authoring Space and Directory to choose
11256: # save location for creation of a new "standard" problem from the Course Editor.
11257: #
11258: 
11259: sub recursedirs {
11260:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11261:     return unless (ref($dirhashref) eq 'HASH');
11262:     my $currpath = $docroot.$toppath;
11263:     if ($relpath) {
11264:         $currpath .= "/$relpath";
11265:     }
11266:     my $savefile;
11267:     if (ref($filehashref)) {
11268:         $savefile = 1;
11269:     }
11270:     if ($is_home) {
11271:         if (opendir(my $dirh,$currpath)) {
11272:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11273:                 next if ($item eq '');
11274:                 if (-d "$currpath/$item") {
11275:                     my $newpath;
11276:                     if ($relpath) {
11277:                         $newpath = "$relpath/$item";
11278:                     } else {
11279:                         $newpath = $item;
11280:                     }
11281:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11282:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11283:                 } elsif ($savefile) {
11284:                     if ($context eq 'priv') {
11285:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11286:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11287:                         }
11288:                     } else {
11289:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11290:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11291:                         }
11292:                     }
11293:                 }
11294:             }
11295:             closedir($dirh);
11296:         }
11297:     } else {
11298:         my ($dirlistref,$listerror) =
11299:             &dirlist($toppath.$relpath);
11300:         my @dir_lines;
11301:         my $dirptr=16384;
11302:         if (ref($dirlistref) eq 'ARRAY') {
11303:             foreach my $dir_line (sort
11304:                               {
11305:                                   my ($afile)=split('&',$a,2);
11306:                                   my ($bfile)=split('&',$b,2);
11307:                                   return (lc($afile) cmp lc($bfile));
11308:                               } (@{$dirlistref})) {
11309:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11310:                     split(/\&/,$dir_line,16);
11311:                 $item =~ s/\s+$//;
11312:                 next if (($item =~ /^\.\.?$/) || ($obs));
11313:                 if ($dirptr&$testdir) {
11314:                     my $newpath;
11315:                     if ($relpath) {
11316:                         $newpath = "$relpath/$item";
11317:                     } else {
11318:                         $relpath = '/';
11319:                         $newpath = $item;
11320:                     }
11321:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11322:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11323:                 } elsif ($savefile) {
11324:                     if ($context eq 'priv') {
11325:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11326:                             $filehashref->{$relpath}{$item} = 1;
11327:                         }
11328:                     } else {
11329:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11330:                             $filehashref->{$relpath}{$item} = 1;
11331:                         }
11332:                     }
11333:                 }
11334:             }
11335:         }
11336:     }
11337:     return;
11338: }
11339: 
11340: # -------------------------------------------------------- Value of a Condition
11341: 
11342: # gets the value of a specific preevaluated condition
11343: #    stored in the string  $env{user.state.<cid>}
11344: # or looks up a condition reference in the bighash and if if hasn't
11345: # already been evaluated recurses into docondval to get the value of
11346: # the condition, then memoizing it to 
11347: #   $env{user.state.<cid>.<condition>}
11348: sub directcondval {
11349:     my $number=shift;
11350:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11351: 	&Apache::lonuserstate::evalstate();
11352:     }
11353:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11354: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11355:     } elsif ($number =~ /^_/) {
11356: 	my $sub_condition;
11357: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11358: 		&GDBM_READER(),0640)) {
11359: 	    $sub_condition=$bighash{'conditions'.$number};
11360: 	    untie(%bighash);
11361: 	}
11362: 	my $value = &docondval($sub_condition);
11363: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11364: 	return $value;
11365:     }
11366:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11367:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11368:     } else {
11369:        return 2;
11370:     }
11371: }
11372: 
11373: # get the collection of conditions for this resource
11374: sub condval {
11375:     my $condidx=shift;
11376:     my $allpathcond='';
11377:     foreach my $cond (split(/\|/,$condidx)) {
11378: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11379: 	    $allpathcond.=
11380: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11381: 	}
11382:     }
11383:     $allpathcond=~s/\|$//;
11384:     return &docondval($allpathcond);
11385: }
11386: 
11387: #evaluates an expression of conditions
11388: sub docondval {
11389:     my ($allpathcond) = @_;
11390:     my $result=0;
11391:     if ($env{'request.course.id'}
11392: 	&& defined($allpathcond)) {
11393: 	my $operand='|';
11394: 	my @stack;
11395: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11396: 	    if ($chunk eq '(') {
11397: 		push @stack,($operand,$result);
11398: 	    } elsif ($chunk eq ')') {
11399: 		my $before=pop @stack;
11400: 		if (pop @stack eq '&') {
11401: 		    $result=$result>$before?$before:$result;
11402: 		} else {
11403: 		    $result=$result>$before?$result:$before;
11404: 		}
11405: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11406: 		$operand=$chunk;
11407: 	    } else {
11408: 		my $new=directcondval($chunk);
11409: 		if ($operand eq '&') {
11410: 		    $result=$result>$new?$new:$result;
11411: 		} else {
11412: 		    $result=$result>$new?$result:$new;
11413: 		}
11414: 	    }
11415: 	}
11416:     }
11417:     return $result;
11418: }
11419: 
11420: # ---------------------------------------------------- Devalidate courseresdata
11421: 
11422: sub devalidatecourseresdata {
11423:     my ($coursenum,$coursedomain)=@_;
11424:     my $hashid=$coursenum.':'.$coursedomain;
11425:     &devalidate_cache_new('courseres',$hashid);
11426: }
11427: 
11428: 
11429: # --------------------------------------------------- Course Resourcedata Query
11430: #
11431: #  Parameters:
11432: #      $coursenum    - Number of the course.
11433: #      $coursedomain - Domain at which the course was created.
11434: #  Returns:
11435: #     A hash of the course parameters along (I think) with timestamps
11436: #     and version info.
11437: 
11438: sub get_courseresdata {
11439:     my ($coursenum,$coursedomain)=@_;
11440:     my $coursehom=&homeserver($coursenum,$coursedomain);
11441:     my $hashid=$coursenum.':'.$coursedomain;
11442:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11443:     my %dumpreply;
11444:     unless (defined($cached)) {
11445: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11446: 	$result=\%dumpreply;
11447: 	my ($tmp) = keys(%dumpreply);
11448: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11449: 	    &do_cache_new('courseres',$hashid,$result,600);
11450: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11451: 	    return $tmp;
11452: 	} elsif ($tmp =~ /^(error)/) {
11453: 	    $result=undef;
11454: 	    &do_cache_new('courseres',$hashid,$result,600);
11455: 	}
11456:     }
11457:     return $result;
11458: }
11459: 
11460: sub devalidateuserresdata {
11461:     my ($uname,$udom)=@_;
11462:     my $hashid="$udom:$uname";
11463:     &devalidate_cache_new('userres',$hashid);
11464: }
11465: 
11466: sub get_userresdata {
11467:     my ($uname,$udom)=@_;
11468:     #most student don\'t have any data set, check if there is some data
11469:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11470: 
11471:     my $hashid="$udom:$uname";
11472:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11473:     if (!defined($cached)) {
11474: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11475: 	$result=\%resourcedata;
11476: 	&do_cache_new('userres',$hashid,$result,600);
11477:     }
11478:     my ($tmp)=keys(%$result);
11479:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11480: 	return $result;
11481:     }
11482:     #error 2 occurs when the .db doesn't exist
11483:     if ($tmp!~/error: 2 /) {
11484:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11485: 	    &logthis("<font color=\"blue\">WARNING:".
11486: 		     " Trying to get resource data for ".
11487: 		     $uname." at ".$udom.": ".
11488: 		     $tmp."</font>");
11489:         }
11490:     } elsif ($tmp=~/error: 2 /) {
11491: 	#&EXT_cache_set($udom,$uname);
11492: 	&do_cache_new('userres',$hashid,undef,600);
11493: 	undef($tmp); # not really an error so don't send it back
11494:     }
11495:     return $tmp;
11496: }
11497: #----------------------------------------------- resdata - return resource data
11498: #  Purpose:
11499: #    Return resource data for either users or for a course.
11500: #  Parameters:
11501: #     $name      - Course/user name.
11502: #     $domain    - Name of the domain the user/course is registered on.
11503: #     $type      - Type of thing $name is (must be 'course' or 'user')
11504: #     $mapp      - decluttered URL of enclosing map  
11505: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11506: #     $recurseup - Ref to array of map URLs, starting with map containing
11507: #                  $mapp up through hierarchy of nested maps to top level map.  
11508: #     $courseid  - CourseID (first part of param identifier).
11509: #     $modifier  - Middle part of param identifier.
11510: #     $what      - Last part of param identifier.
11511: #     @which     - Array of names of resources desired.
11512: #  Returns:
11513: #     The value of the first reasource in @which that is found in the
11514: #     resource hash.
11515: #  Exceptional Conditions:
11516: #     If the $type passed in is not valid (not the string 'course' or 
11517: #     'user', an undefined  reference is returned.
11518: #     If none of the resources are found, an undef is returned
11519: sub resdata {
11520:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11521:         $modifier,$what,@which)=@_;
11522:     my $result;
11523:     if ($type eq 'course') {
11524: 	$result=&get_courseresdata($name,$domain);
11525:     } elsif ($type eq 'user') {
11526: 	$result=&get_userresdata($name,$domain);
11527:     }
11528:     if (!ref($result)) { return $result; }    
11529:     foreach my $item (@which) {
11530:         if ($item->[1] eq 'course') {
11531:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11532:                 unless ($$recursed) {
11533:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11534:                     $$recursed = 1;
11535:                 }
11536:                 foreach my $item (@${recurseup}) {
11537:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11538:                     last if (defined($result->{$norecursechk}));
11539:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11540:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11541:                 }
11542:             }
11543:         }
11544:         if (defined($result->{$item->[0]})) {
11545: 	    return [$result->{$item->[0]},$item->[1]];
11546: 	}
11547:     }
11548:     return undef;
11549: }
11550: 
11551: sub get_domain_lti {
11552:     my ($cdom,$context) = @_;
11553:     my ($name,%lti);
11554:     if ($context eq 'consumer') {
11555:         $name = 'ltitools';
11556:     } elsif ($context eq 'provider') {
11557:         $name = 'lti';
11558:     } else {
11559:         return %lti;
11560:     }
11561:     my ($result,$cached)=&is_cached_new($name,$cdom);
11562:     if (defined($cached)) {
11563:         if (ref($result) eq 'HASH') {
11564:             %lti = %{$result};
11565:         }
11566:     } else {
11567:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11568:         if (ref($domconfig{$name}) eq 'HASH') {
11569:             %lti = %{$domconfig{$name}};
11570:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11571:             if (ref($encdomconfig{$name}) eq 'HASH') {
11572:                 foreach my $id (keys(%lti)) {
11573:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11574:                         foreach my $item ('key','secret') {
11575:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11576:                         }
11577:                     }
11578:                 }
11579:             }
11580:         }
11581:         my $cachetime = 24*60*60;
11582:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11583:     }
11584:     return %lti;
11585: }
11586: 
11587: sub get_numsuppfiles {
11588:     my ($cnum,$cdom,$ignorecache)=@_;
11589:     my $hashid=$cnum.':'.$cdom;
11590:     my ($suppcount,$cached);
11591:     unless ($ignorecache) {
11592:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11593:     }
11594:     unless (defined($cached)) {
11595:         my $chome=&homeserver($cnum,$cdom);
11596:         unless ($chome eq 'no_host') {
11597:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11598:             my $suppmap = 'supplemental.sequence';
11599:             ($suppcount,$supptools,$errors) =
11600:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11601:                                                          $supptools,$errors);
11602:         }
11603:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11604:     }
11605:     return $suppcount;
11606: }
11607: 
11608: #
11609: # EXT resource caching routines
11610: #
11611: 
11612: {
11613: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11614: #
11615: # The course for which we cache
11616: my $cachedmapkey='';
11617: # The cached recursive maps for this course
11618: my %cachedmaps=();
11619: # When this was last done
11620: my $cachedmaptime='';
11621: 
11622: sub clear_EXT_cache_status {
11623:     &delenv('cache.EXT.');
11624: }
11625: 
11626: sub EXT_cache_status {
11627:     my ($target_domain,$target_user) = @_;
11628:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11629:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11630:         # We know already the user has no data
11631:         return 1;
11632:     } else {
11633:         return 0;
11634:     }
11635: }
11636: 
11637: sub EXT_cache_set {
11638:     my ($target_domain,$target_user) = @_;
11639:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11640:     #&appenv({$cachename => time});
11641: }
11642: 
11643: # --------------------------------------------------------- Value of a Variable
11644: sub EXT {
11645: 
11646:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11647:     unless ($varname) { return ''; }
11648:     #get real user name/domain, courseid and symb
11649:     my $courseid;
11650:     my $publicuser;
11651:     if ($symbparm) {
11652: 	$symbparm=&get_symb_from_alias($symbparm);
11653:     }
11654:     if (!($uname && $udom)) {
11655:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11656:       if (!$symbparm) {	$symbparm=$cursymb; }
11657:     } else {
11658: 	$courseid=$env{'request.course.id'};
11659:     }
11660:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11661:     my $rest;
11662:     if (defined($therest[0])) {
11663:        $rest=join('.',@therest);
11664:     } else {
11665:        $rest='';
11666:     }
11667: 
11668:     my $qualifierrest=$qualifier;
11669:     if ($rest) { $qualifierrest.='.'.$rest; }
11670:     my $spacequalifierrest=$space;
11671:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11672:     if ($realm eq 'user') {
11673: # --------------------------------------------------------------- user.resource
11674: 	if ($space eq 'resource') {
11675: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11676: 		  || defined($Apache::lonhomework::parsing_a_task))
11677: 		 &&
11678: 		 ($symbparm eq &symbread()) ) {	
11679: 		# if we are in the middle of processing the resource the
11680: 		# get the value we are planning on committing
11681:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11682:                     return $Apache::lonhomework::results{$qualifierrest};
11683:                 } else {
11684:                     return $Apache::lonhomework::history{$qualifierrest};
11685:                 }
11686: 	    } else {
11687: 		my %restored;
11688: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11689: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11690: 		} else {
11691: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11692: 		}
11693: 		return $restored{$qualifierrest};
11694: 	    }
11695: # ----------------------------------------------------------------- user.access
11696:         } elsif ($space eq 'access') {
11697: 	    # FIXME - not supporting calls for a specific user
11698:             return &allowed($qualifier,$rest);
11699: # ------------------------------------------ user.preferences, user.environment
11700:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11701: 	    if (($uname eq $env{'user.name'}) &&
11702: 		($udom eq $env{'user.domain'})) {
11703: 		return $env{join('.',('environment',$qualifierrest))};
11704: 	    } else {
11705: 		my %returnhash;
11706: 		if (!$publicuser) {
11707: 		    %returnhash=&userenvironment($udom,$uname,
11708: 						 $qualifierrest);
11709: 		}
11710: 		return $returnhash{$qualifierrest};
11711: 	    }
11712: # ----------------------------------------------------------------- user.course
11713:         } elsif ($space eq 'course') {
11714: 	    # FIXME - not supporting calls for a specific user
11715:             return $env{join('.',('request.course',$qualifier))};
11716: # ------------------------------------------------------------------- user.role
11717:         } elsif ($space eq 'role') {
11718: 	    # FIXME - not supporting calls for a specific user
11719:             my ($role,$where)=split(/\./,$env{'request.role'});
11720:             if ($qualifier eq 'value') {
11721: 		return $role;
11722:             } elsif ($qualifier eq 'extent') {
11723:                 return $where;
11724:             }
11725: # ----------------------------------------------------------------- user.domain
11726:         } elsif ($space eq 'domain') {
11727:             return $udom;
11728: # ------------------------------------------------------------------- user.name
11729:         } elsif ($space eq 'name') {
11730:             return $uname;
11731: # ---------------------------------------------------- Any other user namespace
11732:         } else {
11733: 	    my %reply;
11734: 	    if (!$publicuser) {
11735: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11736: 	    }
11737: 	    return $reply{$qualifierrest};
11738:         }
11739:     } elsif ($realm eq 'query') {
11740: # ---------------------------------------------- pull stuff out of query string
11741:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11742: 						[$spacequalifierrest]);
11743: 	return $env{'form.'.$spacequalifierrest}; 
11744:    } elsif ($realm eq 'request') {
11745: # ------------------------------------------------------------- request.browser
11746:         if ($space eq 'browser') {
11747:             return $env{'browser.'.$qualifier};
11748: # ------------------------------------------------------------ request.filename
11749:         } else {
11750:             return $env{'request.'.$spacequalifierrest};
11751:         }
11752:     } elsif ($realm eq 'course') {
11753: # ---------------------------------------------------------- course.description
11754:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11755:     } elsif ($realm eq 'resource') {
11756: 
11757: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11758: 	    if (!$symbparm) { $symbparm=&symbread(); }
11759: 	}
11760: 
11761:         if ($qualifier eq '') {
11762: 	    if ($space eq 'title') {
11763: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11764: 	        return &gettitle($symbparm);
11765: 	    }
11766: 	
11767: 	    if ($space eq 'map') {
11768: 	        my ($map) = &decode_symb($symbparm);
11769: 	        return &symbread($map);
11770: 	    }
11771:             if ($space eq 'maptitle') {
11772:                 my ($map) = &decode_symb($symbparm);
11773:                 return &gettitle($map);
11774:             }
11775: 	    if ($space eq 'filename') {
11776: 	        if ($symbparm) {
11777: 		    return &clutter((&decode_symb($symbparm))[2]);
11778: 	        }
11779: 	        return &hreflocation('',$env{'request.filename'});
11780: 	    }
11781: 
11782:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11783:                 if ($space eq 'visibleparts') {
11784:                     my $navmap = Apache::lonnavmaps::navmap->new();
11785:                     my $item;
11786:                     if (ref($navmap)) {
11787:                         my $res = $navmap->getBySymb($symbparm);
11788:                         my $parts = $res->parts();
11789:                         if (ref($parts) eq 'ARRAY') {
11790:                             $item = join(',',@{$parts});
11791:                         }
11792:                         undef($navmap);
11793:                     }
11794:                     return $item;
11795:                 }
11796:             }
11797:         }
11798: 
11799: 	my ($section, $group, @groups, @recurseup, $recursed);
11800: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11801:         if (($courseid eq '') && ($cid)) {
11802:             $courseid = $cid;
11803:         }
11804: 	if (($symbparm && $courseid) && 
11805: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11806: 
11807: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11808: 
11809: # ----------------------------------------------------- Cascading lookup scheme
11810: 	    my $symbp=$symbparm;
11811: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11812: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11813:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11814: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11815: 	    if (($env{'user.name'} eq $uname) &&
11816: 		($env{'user.domain'} eq $udom)) {
11817: 		$section=$env{'request.course.sec'};
11818:                 @groups = split(/:/,$env{'request.course.groups'});  
11819:                 @groups=&sort_course_groups($courseid,@groups); 
11820: 	    } else {
11821: 		if (! defined($usection)) {
11822: 		    $section=&getsection($udom,$uname,$courseid);
11823: 		} else {
11824: 		    $section = $usection;
11825: 		}
11826:                 @groups = &get_users_groups($udom,$uname,$courseid);
11827: 	    }
11828: 
11829: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11830: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11831:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11832: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11833: 
11834: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11835: 	    my $courselevelr=$courseid.'.'.$symbparm;
11836:             $courseleveli=$courseid.'.'.$recurseparm;
11837: 	    $courselevelm=$courseid.'.'.$mapparm;
11838: 
11839: # ----------------------------------------------------------- first, check user
11840: 
11841: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11842:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11843: 				       ([$courselevelr,'resource'],
11844: 					[$courselevelm,'map'     ],
11845:                                         [$courseleveli,'map'     ],
11846: 					[$courselevel, 'course'  ]));
11847: 	    if (defined($userreply)) { return &get_reply($userreply); }
11848: 
11849: # ------------------------------------------------ second, check some of course
11850:             my $coursereply;
11851:             if (@groups > 0) {
11852:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11853:                                        $recurseparm,$mapparm,$spacequalifierrest,
11854:                                        $mapp,\$recursed,\@recurseup);
11855:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11856:             }
11857: 
11858: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11859: 				  $env{'course.'.$courseid.'.domain'},
11860: 				  'course',$mapp,\$recursed,\@recurseup,
11861:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11862: 				  ([$seclevelr,   'resource'],
11863: 				   [$seclevelm,   'map'     ],
11864:                                    [$secleveli,   'map'     ],
11865: 				   [$seclevel,    'course'  ],
11866: 				   [$courselevelr,'resource']));
11867: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11868: 
11869: # ------------------------------------------------------ third, check map parms
11870: 	    my %parmhash=();
11871: 	    my $thisparm='';
11872: 	    if (tie(%parmhash,'GDBM_File',
11873: 		    $env{'request.course.fn'}.'_parms.db',
11874: 		    &GDBM_READER(),0640)) {
11875: 		$thisparm=$parmhash{$symbparm};
11876: 		untie(%parmhash);
11877: 	    }
11878: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11879: 	}
11880: # ------------------------------------------ fourth, look in resource metadata
11881:  
11882:         my $what = $spacequalifierrest;
11883: 	$what=~s/\./\_/;
11884: 	my $filename;
11885: 	if (!$symbparm) { $symbparm=&symbread(); }
11886: 	if ($symbparm) {
11887: 	    $filename=(&decode_symb($symbparm))[2];
11888: 	} else {
11889: 	    $filename=$env{'request.filename'};
11890: 	}
11891:         my $toolsymb;
11892:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11893:             $toolsymb = $symbparm;
11894:         }
11895: 	my $metadata=&metadata($filename,$what,$toolsymb);
11896: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11897: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11898: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11899: 
11900: # ----------------------------------------------- fifth, look in rest of course
11901: 	if ($symbparm && defined($courseid) && 
11902: 	    $courseid eq $env{'request.course.id'}) {
11903: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11904: 				     $env{'course.'.$courseid.'.domain'},
11905: 				     'course',$mapp,\$recursed,\@recurseup,
11906:                                      $courseid,'.',$spacequalifierrest,
11907: 				     ([$courselevelm,'map'   ],
11908:                                       [$courseleveli,'map'   ],
11909: 				      [$courselevel, 'course']));
11910: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11911: 	}
11912: # ------------------------------------------------------------------ Cascade up
11913: 	unless ($space eq '0') {
11914: 	    my @parts=split(/_/,$space);
11915: 	    my $id=pop(@parts);
11916: 	    my $part=join('_',@parts);
11917: 	    if ($part eq '') { $part='0'; }
11918: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11919: 				 $symbparm,$udom,$uname,$section,1);
11920: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11921: 	}
11922: 	if ($recurse) { return undef; }
11923: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11924: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11925: # ---------------------------------------------------- Any other user namespace
11926:     } elsif ($realm eq 'environment') {
11927: # ----------------------------------------------------------------- environment
11928: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11929: 	    return $env{'environment.'.$spacequalifierrest};
11930: 	} else {
11931: 	    if ($uname eq 'anonymous' && $udom eq '') {
11932: 		return '';
11933: 	    }
11934: 	    my %returnhash=&userenvironment($udom,$uname,
11935: 					    $spacequalifierrest);
11936: 	    return $returnhash{$spacequalifierrest};
11937: 	}
11938:     } elsif ($realm eq 'system') {
11939: # ----------------------------------------------------------------- system.time
11940: 	if ($space eq 'time') {
11941: 	    return time;
11942:         }
11943:     } elsif ($realm eq 'server') {
11944: # ----------------------------------------------------------------- system.time
11945: 	if ($space eq 'name') {
11946: 	    return $ENV{'SERVER_NAME'};
11947:         }
11948:     }
11949:     return '';
11950: }
11951: 
11952: sub get_reply {
11953:     my ($reply_value) = @_;
11954:     if (ref($reply_value) eq 'ARRAY') {
11955:         if (wantarray) {
11956: 	    return @$reply_value;
11957:         }
11958:         return $reply_value->[0];
11959:     } else {
11960:         return $reply_value;
11961:     }
11962: }
11963: 
11964: sub check_group_parms {
11965:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11966:         $recursed,$recurseupref) = @_;
11967:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11968:                   [$what,'course']);
11969:     my $coursereply;
11970:     foreach my $group (@{$groups}) {
11971:         my @groupitems = ();
11972:         foreach my $level (@levels) {
11973:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11974:              push(@groupitems,[$item,$level->[1]]);
11975:         }
11976:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11977:                                    $env{'course.'.$courseid.'.domain'},
11978:                                    'course',$mapp,$recursed,$recurseupref,
11979:                                    $courseid,'.['.$group.'].',$what,
11980:                                    @groupitems);
11981:         last if (defined($coursereply));
11982:     }
11983:     return $coursereply;
11984: }
11985: 
11986: sub get_map_hierarchy {
11987:     my ($mapname,$courseid) = @_;
11988:     my @recurseup = ();
11989:     if ($mapname) {
11990:         if (($cachedmapkey eq $courseid) &&
11991:             (abs($cachedmaptime-time)<5)) {
11992:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11993:                 return @{$cachedmaps{$mapname}};
11994:             }
11995:         }
11996:         my $navmap = Apache::lonnavmaps::navmap->new();
11997:         if (ref($navmap)) {
11998:             @recurseup = $navmap->recurseup_maps($mapname);
11999:             undef($navmap);
12000:             $cachedmaps{$mapname} = \@recurseup;
12001:             $cachedmaptime=time;
12002:             $cachedmapkey=$courseid;
12003:         }
12004:     }
12005:     return @recurseup;
12006: }
12007: 
12008: }
12009: 
12010: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12011:     my ($courseid,@groups) = @_;
12012:     @groups = sort(@groups);
12013:     return @groups;
12014: }
12015: 
12016: sub packages_tab_default {
12017:     my ($uri,$varname,$toolsymb)=@_;
12018:     my (undef,$part,$name)=split(/\./,$varname);
12019: 
12020:     my (@extension,@specifics,$do_default);
12021:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12022: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12023: 	if ($pack_type eq 'default') {
12024: 	    $do_default=1;
12025: 	} elsif ($pack_type eq 'extension') {
12026: 	    push(@extension,[$package,$pack_type,$pack_part]);
12027: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12028: 	    # only look at packages defaults for packages that this id is
12029: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12030: 	}
12031:     }
12032:     # first look for a package that matches the requested part id
12033:     foreach my $package (@specifics) {
12034: 	my (undef,$pack_type,$pack_part)=@{$package};
12035: 	next if ($pack_part ne $part);
12036: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12037: 	    return $packagetab{"$pack_type&$name&default"};
12038: 	}
12039:     }
12040:     # look for any possible matching non extension_ package
12041:     foreach my $package (@specifics) {
12042: 	my (undef,$pack_type,$pack_part)=@{$package};
12043: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12044: 	    return $packagetab{"$pack_type&$name&default"};
12045: 	}
12046: 	if ($pack_type eq 'part') { $pack_part='0'; }
12047: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12048: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12049: 	}
12050:     }
12051:     # look for any posible extension_ match
12052:     foreach my $package (@extension) {
12053: 	my ($package,$pack_type)=@{$package};
12054: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12055: 	    return $packagetab{"$pack_type&$name&default"};
12056: 	}
12057: 	if (defined($packagetab{$package."&$name&default"})) {
12058: 	    return $packagetab{$package."&$name&default"};
12059: 	}
12060:     }
12061:     # look for a global default setting
12062:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12063: 	return $packagetab{"default&$name&default"};
12064:     }
12065:     return undef;
12066: }
12067: 
12068: sub add_prefix_and_part {
12069:     my ($prefix,$part)=@_;
12070:     my $keyroot;
12071:     if (defined($prefix) && $prefix !~ /^__/) {
12072: 	# prefix that has a part already
12073: 	$keyroot=$prefix;
12074:     } elsif (defined($prefix)) {
12075: 	# prefix that is missing a part
12076: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12077:     } else {
12078: 	# no prefix at all
12079: 	if (defined($part)) { $keyroot='_'.$part; }
12080:     }
12081:     return $keyroot;
12082: }
12083: 
12084: # ---------------------------------------------------------------- Get metadata
12085: 
12086: my %metaentry;
12087: my %importedpartids;
12088: my %importedrespids;
12089: sub metadata {
12090:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12091:     $uri=&declutter($uri);
12092:     # if it is a non metadata possible uri return quickly
12093:     if (($uri eq '') || 
12094: 	(($uri =~ m|^/*adm/|) && 
12095: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12096:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12097: 	return undef;
12098:     }
12099:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12100: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12101: 	return undef;
12102:     }
12103:     my $filename=$uri;
12104:     $uri=~s/\.meta$//;
12105: #
12106: # Is the metadata already cached?
12107: # Look at timestamp of caching
12108: # Everything is cached by the main uri, libraries are never directly cached
12109: #
12110:     if (!defined($liburi)) {
12111: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12112: 	if (defined($cached)) { return $result->{':'.$what}; }
12113:     }
12114: 
12115: #
12116: # If the uri is for an external tool the file from
12117: # which metadata should be retrieved depends on whether
12118: # the tool had been configured to be gradable (set in the Course
12119: # Editor or Resource Editor).
12120: #
12121: # If a valid symb has been included as the third arg in the call
12122: # to &metadata() that can be used to retrieve the value of
12123: # parameter_0_gradable set for the resource, and included in the
12124: # uploaded map containing the tool. The value is retrieved via
12125: # &EXT(), if a valid symb is available.  Otherwise the value of
12126: # gradable in the exttool_$marker.db file for the tool instance
12127: # is retrieved via &get().
12128: #
12129: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12130: # hiddenresource and encrypturl (during course initialization)
12131: # the map-level parameter for resource.0.gradable included in the 
12132: # uploaded map containing the tool will not yet have been stored
12133: # in the user_course_parms.db file for the user's session, so in 
12134: # this case fall back to retrieving gradable status from the
12135: # exttool_$marker.db file.
12136: #
12137: # In order to avoid an infinite loop, &metadata() will return
12138: # before a call to &EXT(), if the uri is for an external tool
12139: # and the $what for which metadata is being requested is
12140: # parameter_0_gradable or 0_gradable.
12141: #
12142: 
12143:     if ($uri =~ /ext\.tool$/) {
12144:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12145:             return;
12146:         } else {
12147:             my ($checked,$use_passback);
12148:             if ($toolsymb ne '') {
12149:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12150:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12151:                     $checked = 1;
12152:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12153:                         $use_passback = 1;
12154:                     }
12155:                 }
12156:             }
12157:             unless ($checked) {
12158:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12159:                 $marker=~s/\D//g;
12160:                 if ($marker) {
12161:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12162:                     $use_passback = $toolsettings{'gradable'};
12163:                 }
12164:             }
12165:             if ($use_passback) {
12166:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12167:             } else {
12168:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12169:             }
12170:         }
12171:     }
12172: 
12173:     {
12174: # Imported parts would go here
12175:         my @origfiletagids=();
12176:         my $importedparts=0;
12177: 
12178: # Imported responseids would go here
12179:         my $importedresponses=0;
12180: #
12181: # Is this a recursive call for a library?
12182: #
12183: #	if (! exists($metacache{$uri})) {
12184: #	    $metacache{$uri}={};
12185: #	}
12186: 	my $cachetime = 60*60;
12187:         if ($liburi) {
12188: 	    $liburi=&declutter($liburi);
12189:             $filename=$liburi;
12190:         } else {
12191: 	    &devalidate_cache_new('meta',$uri);
12192: 	    undef(%metaentry);
12193: 	}
12194:         my %metathesekeys=();
12195:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12196: 	my $metastring;
12197: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12198: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12199: 	    $metastring = 
12200: 		&Apache::lonnet::ssi_body($which,
12201: 					  ('grade_target' => 'meta'));
12202: 	    $cachetime = 1; # only want this cached in the child not long term
12203: 	} elsif (($uri !~ m -^(editupload)/-) && 
12204:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12205: 	    my $file=&filelocation('',&clutter($filename));
12206: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12207: 	    $metastring=&getfile($file);
12208: 	}
12209:         my $parser=HTML::LCParser->new(\$metastring);
12210:         my $token;
12211:         undef %metathesekeys;
12212:         while ($token=$parser->get_token) {
12213: 	    if ($token->[0] eq 'S') {
12214: 		if (defined($token->[2]->{'package'})) {
12215: #
12216: # This is a package - get package info
12217: #
12218: 		    my $package=$token->[2]->{'package'};
12219: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12220: 		    if (defined($token->[2]->{'id'})) { 
12221: 			$keyroot.='_'.$token->[2]->{'id'}; 
12222: 		    }
12223: 		    if ($metaentry{':packages'}) {
12224: 			$metaentry{':packages'}.=','.$package.$keyroot;
12225: 		    } else {
12226: 			$metaentry{':packages'}=$package.$keyroot;
12227: 		    }
12228: 		    foreach my $pack_entry (keys(%packagetab)) {
12229: 			my $part=$keyroot;
12230: 			$part=~s/^\_//;
12231: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12232: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12233: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12234: 			    # ignore package.tab specified default values
12235:                             # here &package_tab_default() will fetch those
12236: 			    if ($subp eq 'default') { next; }
12237: 			    my $value=$packagetab{$pack_entry};
12238: 			    my $unikey;
12239: 			    if ($pack =~ /_0$/) {
12240: 				$unikey='parameter_0_'.$name;
12241: 				$part=0;
12242: 			    } else {
12243: 				$unikey='parameter'.$keyroot.'_'.$name;
12244: 			    }
12245: 			    if ($subp eq 'display') {
12246: 				$value.=' [Part: '.$part.']';
12247: 			    }
12248: 			    $metaentry{':'.$unikey.'.part'}=$part;
12249: 			    $metathesekeys{$unikey}=1;
12250: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12251: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12252: 			    }
12253: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12254: 				$metaentry{':'.$unikey}=
12255: 				    $metaentry{':'.$unikey.'.default'};
12256: 			    }
12257: 			}
12258: 		    }
12259: 		} else {
12260: #
12261: # This is not a package - some other kind of start tag
12262: #
12263: 		    my $entry=$token->[1];
12264: 		    my $unikey='';
12265: 
12266: 		    if ($entry eq 'import') {
12267: #
12268: # Importing a library here
12269: #
12270:                         my $location=$parser->get_text('/import');
12271:                         my $dir=$filename;
12272:                         $dir=~s|[^/]*$||;
12273:                         $location=&filelocation($dir,$location);
12274: 
12275:                         my $importid=$token->[2]->{'id'};
12276:                         my $importmode=$token->[2]->{'importmode'};
12277: #
12278: # Check metadata for imported file to
12279: # see if it contained response items
12280: #
12281:                         my ($origfile,@libfilekeys);
12282:                         my %currmetaentry = %metaentry;
12283:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12284:                                                            $depthcount+1));
12285:                         if (grep(/^responseorder$/,@libfilekeys)) {
12286:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12287:                                                              undef,$depthcount+1);
12288:                             if ($libresponseorder ne '') {
12289:                                 if ($#origfiletagids<0) {
12290:                                     undef(%importedrespids);
12291:                                     undef(%importedpartids);
12292:                                 }
12293:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12294:                                 if (@respids) {
12295:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12296:                                 }
12297:                                 if ($importedrespids{$importid} ne '') {
12298:                                     $importedresponses = 1;
12299: # We need to get the original file and the imported file to get the response order correct
12300: # Load and inspect original file
12301:                                     if ($#origfiletagids<0) {
12302:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12303:                                         $origfile=&getfile($origfilelocation);
12304:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12305:                                     }
12306:                                 }
12307:                             }
12308:                         }
12309: # Do not overwrite contents of %metaentry hash for resource itself with 
12310: # hash populated for imported library file
12311:                         %metaentry = %currmetaentry;
12312:                         undef(%currmetaentry);
12313:                         if ($importmode eq 'part') {
12314: # Import as part(s)
12315:                            $importedparts=1;
12316: # We need to get the original file and the imported file to get the part order correct
12317: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12318: # Load and inspect original file if we didn't do that already
12319:                            if ($#origfiletagids<0) {
12320:                                undef(%importedrespids);
12321:                                undef(%importedpartids);
12322:                                if ($origfile eq '') {
12323:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12324:                                    $origfile=&getfile($origfilelocation);
12325:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12326:                                }
12327:                            }
12328:                            my @impfilepartids;
12329: # If <partorder> tag is included in metadata for the imported file
12330: # get the parts in the imported file from that.
12331:                            if (grep(/^partorder$/,@libfilekeys)) {
12332:                                %currmetaentry = %metaentry;
12333:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12334:                                                             $depthcount+1);
12335:                                %metaentry = %currmetaentry;
12336:                                undef(%currmetaentry);
12337:                                if ($libpartorder ne '') {
12338:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12339:                                }
12340:                            } else {
12341: # If no <partorder> tag available, load and inspect imported file
12342:                                my $impfile=&getfile($location);
12343:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12344:                            }
12345:                            if ($#impfilepartids>=0) {
12346: # This problem had parts
12347:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12348:                            } else {
12349: # Importing by turning a single problem into a problem part
12350: # It gets the import-tags ID as part-ID
12351:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12352:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12353:                            }
12354:                         } else {
12355: # Import as problem or as normal import
12356:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12357:                             unless ($importmode eq 'problem') {
12358: # Normal import
12359:                                 if (defined($token->[2]->{'id'})) {
12360:                                     $unikey.='_'.$token->[2]->{'id'};
12361:                                 }
12362:                             }
12363: # Check metadata for imported file to
12364: # see if it contained parts
12365:                             if (grep(/^partorder$/,@libfilekeys)) {
12366:                                 %currmetaentry = %metaentry;
12367:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12368:                                                              $depthcount+1);
12369:                                 %metaentry = %currmetaentry;
12370:                                 undef(%currmetaentry);
12371:                                 if ($libpartorder ne '') {
12372:                                     $importedparts = 1;
12373:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12374:                                 }
12375:                             }
12376:                         }
12377: 			if ($depthcount<20) {
12378: 			    my $metadata = 
12379: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12380: 					  $depthcount+1);
12381: 			    foreach my $meta (split(',',$metadata)) {
12382: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12383: 				$metathesekeys{$meta}=1;
12384: 			    }
12385:                         }
12386: 		    } else {
12387: #
12388: # Not importing, some other kind of non-package, non-library start tag
12389: # 
12390:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12391:                         if (defined($token->[2]->{'id'})) {
12392:                             $unikey.='_'.$token->[2]->{'id'};
12393:                         }
12394: 			if (defined($token->[2]->{'name'})) { 
12395: 			    $unikey.='_'.$token->[2]->{'name'}; 
12396: 			}
12397: 			$metathesekeys{$unikey}=1;
12398: 			foreach my $param (@{$token->[3]}) {
12399: 			    $metaentry{':'.$unikey.'.'.$param} =
12400: 				$token->[2]->{$param};
12401: 			}
12402: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12403: 			my $default=$metaentry{':'.$unikey.'.default'};
12404: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12405: 		 # only ws inside the tag, and not in default, so use default
12406: 		 # as value
12407: 			    $metaentry{':'.$unikey}=$default;
12408: 			} elsif ( $internaltext =~ /\S/ ) {
12409: 		  # something interesting inside the tag
12410: 			    $metaentry{':'.$unikey}=$internaltext;
12411: 			} else {
12412: 		  # no interesting values, don't set a default
12413: 			}
12414: # end of not-a-package not-a-library import
12415: 		    }
12416: # end of not-a-package start tag
12417: 		}
12418: # the next is the end of "start tag"
12419: 	    }
12420: 	}
12421: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12422: 	$extension = lc($extension);
12423: 	if ($extension eq 'htm') { $extension='html'; }
12424: 
12425: 	foreach my $key (keys(%packagetab)) {
12426: 	    #no specific packages #how's our extension
12427: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12428: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12429: 					 \%metathesekeys);
12430: 	}
12431: 
12432: 	if (!exists($metaentry{':packages'})
12433: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12434: 	    foreach my $key (keys(%packagetab)) {
12435: 		#no specific packages well let's get default then
12436: 		if ($key!~/^default&/) { next; }
12437: 		&metadata_create_package_def($uri,$key,'default',
12438: 					     \%metathesekeys);
12439: 	    }
12440: 	}
12441: # are there custom rights to evaluate
12442: 	if ($metaentry{':copyright'} eq 'custom') {
12443: 
12444:     #
12445:     # Importing a rights file here
12446:     #
12447: 	    unless ($depthcount) {
12448: 		my $location=$metaentry{':customdistributionfile'};
12449: 		my $dir=$filename;
12450: 		$dir=~s|[^/]*$||;
12451: 		$location=&filelocation($dir,$location);
12452: 		my $rights_metadata =
12453: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12454: 			      $depthcount+1);
12455: 		foreach my $rights (split(',',$rights_metadata)) {
12456: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12457: 		    $metathesekeys{$rights}=1;
12458: 		}
12459: 	    }
12460: 	}
12461: 	# uniqifiy package listing
12462: 	my %seen;
12463: 	my @uniq_packages =
12464: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12465: 	$metaentry{':packages'} = join(',',@uniq_packages);
12466: 
12467:         if (($importedresponses) || ($importedparts)) {
12468:             if ($importedparts) {
12469: # We had imported parts and need to rebuild partorder
12470:                 $metaentry{':partorder'}='';
12471:                 $metathesekeys{'partorder'}=1;
12472:             }
12473:             if ($importedresponses) {
12474: # We had imported responses and need to rebuil responseorder
12475:                 $metaentry{':responseorder'}='';
12476:                 $metathesekeys{'responseorder'}=1;
12477:             }
12478:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12479:                 my $origid = $origfiletagids[$index+1];
12480:                 if ($origfiletagids[$index] eq 'part') {
12481: # Original part, part of the problem
12482:                     if ($importedparts) {
12483:                         $metaentry{':partorder'}.=','.$origid;
12484:                     }
12485:                 } elsif ($origfiletagids[$index] eq 'import') {
12486:                     if ($importedparts) {
12487: # We have imported parts at this position
12488:                         if ($importedpartids{$origid} ne '') {
12489:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12490:                         }
12491:                     }
12492:                     if ($importedresponses) {
12493: # We have imported responses at this position
12494:                         if ($importedrespids{$origid} ne '') {
12495:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12496:                         }
12497:                     }
12498:                 } else {
12499: # Original response item, part of the problem
12500:                     if ($importedresponses) {
12501:                         $metaentry{':responseorder'}.=','.$origid;
12502:                     }
12503:                 }
12504:             }
12505:             if ($importedparts) {
12506:                 $metaentry{':partorder'}=~s/^\,//;
12507:             }
12508:             if ($importedresponses) {
12509:                 $metaentry{':responseorder'}=~s/^\,//;
12510:             }
12511:         }
12512: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12513: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12514: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12515:         unless ($liburi) {
12516: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12517:         }
12518: # this is the end of "was not already recently cached
12519:     }
12520:     return $metaentry{':'.$what};
12521: }
12522: 
12523: sub metadata_create_package_def {
12524:     my ($uri,$key,$package,$metathesekeys)=@_;
12525:     my ($pack,$name,$subp)=split(/\&/,$key);
12526:     if ($subp eq 'default') { next; }
12527:     
12528:     if (defined($metaentry{':packages'})) {
12529: 	$metaentry{':packages'}.=','.$package;
12530:     } else {
12531: 	$metaentry{':packages'}=$package;
12532:     }
12533:     my $value=$packagetab{$key};
12534:     my $unikey;
12535:     $unikey='parameter_0_'.$name;
12536:     $metaentry{':'.$unikey.'.part'}=0;
12537:     $$metathesekeys{$unikey}=1;
12538:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12539: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12540:     }
12541:     if (defined($metaentry{':'.$unikey.'.default'})) {
12542: 	$metaentry{':'.$unikey}=
12543: 	    $metaentry{':'.$unikey.'.default'};
12544:     }
12545: }
12546: 
12547: sub metadata_generate_part0 {
12548:     my ($metadata,$metacache,$uri) = @_;
12549:     my %allnames;
12550:     foreach my $metakey (keys(%$metadata)) {
12551: 	if ($metakey=~/^parameter\_(.*)/) {
12552: 	  my $part=$$metacache{':'.$metakey.'.part'};
12553: 	  my $name=$$metacache{':'.$metakey.'.name'};
12554: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12555: 	    $allnames{$name}=$part;
12556: 	  }
12557: 	}
12558:     }
12559:     foreach my $name (keys(%allnames)) {
12560:       $$metadata{"parameter_0_$name"}=1;
12561:       my $key=":parameter_0_$name";
12562:       $$metacache{"$key.part"}='0';
12563:       $$metacache{"$key.name"}=$name;
12564:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12565: 					   $allnames{$name}.'_'.$name.
12566: 					   '.type'};
12567:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12568: 			     '.display'};
12569:       my $expr='[Part: '.$allnames{$name}.']';
12570:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12571:       $$metacache{"$key.display"}=$olddis;
12572:     }
12573: }
12574: 
12575: # ------------------------------------------------------ Devalidate title cache
12576: 
12577: sub devalidate_title_cache {
12578:     my ($url)=@_;
12579:     if (!$env{'request.course.id'}) { return; }
12580:     my $symb=&symbread($url);
12581:     if (!$symb) { return; }
12582:     my $key=$env{'request.course.id'}."\0".$symb;
12583:     &devalidate_cache_new('title',$key);
12584: }
12585: 
12586: # ------------------------------------------------- Get the title of a course
12587: 
12588: sub current_course_title {
12589:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12590: }
12591: # ------------------------------------------------- Get the title of a resource
12592: 
12593: sub gettitle {
12594:     my $urlsymb=shift;
12595:     my $symb=&symbread($urlsymb);
12596:     if ($symb) {
12597: 	my $key=$env{'request.course.id'}."\0".$symb;
12598: 	my ($result,$cached)=&is_cached_new('title',$key);
12599: 	if (defined($cached)) { 
12600: 	    return $result;
12601: 	}
12602: 	my ($map,$resid,$url)=&decode_symb($symb);
12603: 	my $title='';
12604: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12605: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12606: 	} else {
12607: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12608: 		    &GDBM_READER(),0640)) {
12609: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12610: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12611: 		untie(%bighash);
12612: 	    }
12613: 	}
12614: 	$title=~s/\&colon\;/\:/gs;
12615: 	if ($title) {
12616: # Remember both $symb and $title for dynamic metadata
12617:             $accesshash{$symb.'___crstitle'}=$title;
12618:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12619: # Cache this title and then return it
12620: 	    return &do_cache_new('title',$key,$title,600);
12621: 	}
12622: 	$urlsymb=$url;
12623:     }
12624:     my $title=&metadata($urlsymb,'title');
12625:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12626:     return $title;
12627: }
12628: 
12629: sub get_slot {
12630:     my ($which,$cnum,$cdom)=@_;
12631:     if (!$cnum || !$cdom) {
12632: 	(undef,my $courseid)=&whichuser();
12633: 	$cdom=$env{'course.'.$courseid.'.domain'};
12634: 	$cnum=$env{'course.'.$courseid.'.num'};
12635:     }
12636:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12637:     my %slotinfo;
12638:     if (exists($remembered{$key})) {
12639: 	$slotinfo{$which} = $remembered{$key};
12640:     } else {
12641: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12642: 	&Apache::lonhomework::showhash(%slotinfo);
12643: 	my ($tmp)=keys(%slotinfo);
12644: 	if ($tmp=~/^error:/) { return (); }
12645: 	$remembered{$key} = $slotinfo{$which};
12646:     }
12647:     if (ref($slotinfo{$which}) eq 'HASH') {
12648: 	return %{$slotinfo{$which}};
12649:     }
12650:     return $slotinfo{$which};
12651: }
12652: 
12653: sub get_reservable_slots {
12654:     my ($cnum,$cdom,$uname,$udom) = @_;
12655:     my $now = time;
12656:     my $reservable_info;
12657:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12658:     if (exists($remembered{$key})) {
12659:         $reservable_info = $remembered{$key};
12660:     } else {
12661:         my %resv;
12662:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12663:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12664:         $reservable_info = \%resv;
12665:         $remembered{$key} = $reservable_info;
12666:     }
12667:     return $reservable_info;
12668: }
12669: 
12670: sub get_course_slots {
12671:     my ($cnum,$cdom) = @_;
12672:     my $hashid=$cnum.':'.$cdom;
12673:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12674:     if (defined($cached)) {
12675:         if (ref($result) eq 'HASH') {
12676:             return %{$result};
12677:         }
12678:     } else {
12679:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12680:         my ($tmp) = keys(%slots);
12681:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12682:             &do_cache_new('allslots',$hashid,\%slots,600);
12683:             return %slots;
12684:         }
12685:     }
12686:     return;
12687: }
12688: 
12689: sub devalidate_slots_cache {
12690:     my ($cnum,$cdom)=@_;
12691:     my $hashid=$cnum.':'.$cdom;
12692:     &devalidate_cache_new('allslots',$hashid);
12693: }
12694: 
12695: sub get_coursechange {
12696:     my ($cdom,$cnum) = @_;
12697:     if ($cdom eq '' || $cnum eq '') {
12698:         return unless ($env{'request.course.id'});
12699:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12700:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12701:     }
12702:     my $hashid=$cdom.'_'.$cnum;
12703:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12704:     if ((defined($cached)) && ($change ne '')) {
12705:         return $change;
12706:     } else {
12707:         my %crshash;
12708:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12709:         if ($crshash{'internal.contentchange'} eq '') {
12710:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12711:             if ($change eq '') {
12712:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12713:                 $change = $crshash{'internal.created'};
12714:             }
12715:         } else {
12716:             $change = $crshash{'internal.contentchange'};
12717:         }
12718:         my $cachetime = 600;
12719:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12720:     }
12721:     return $change;
12722: }
12723: 
12724: sub devalidate_coursechange_cache {
12725:     my ($cnum,$cdom)=@_;
12726:     my $hashid=$cnum.':'.$cdom;
12727:     &devalidate_cache_new('crschange',$hashid);
12728: }
12729: 
12730: # ------------------------------------------------- Update symbolic store links
12731: 
12732: sub symblist {
12733:     my ($mapname,%newhash)=@_;
12734:     $mapname=&deversion(&declutter($mapname));
12735:     my %hash;
12736:     if (($env{'request.course.fn'}) && (%newhash)) {
12737:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12738:                       &GDBM_WRCREAT(),0640)) {
12739: 	    foreach my $url (keys(%newhash)) {
12740: 		next if ($url eq 'last_known'
12741: 			 && $env{'form.no_update_last_known'});
12742: 		$hash{declutter($url)}=&encode_symb($mapname,
12743: 						    $newhash{$url}->[1],
12744: 						    $newhash{$url}->[0]);
12745:             }
12746:             if (untie(%hash)) {
12747: 		return 'ok';
12748:             }
12749:         }
12750:     }
12751:     return 'error';
12752: }
12753: 
12754: # --------------------------------------------------------------- Verify a symb
12755: 
12756: sub symbverify {
12757:     my ($symb,$thisurl,$encstate)=@_;
12758:     my $thisfn=$thisurl;
12759:     $thisfn=&declutter($thisfn);
12760: # direct jump to resource in page or to a sequence - will construct own symbs
12761:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12762: # check URL part
12763:     my ($map,$resid,$url)=&decode_symb($symb);
12764: 
12765:     unless ($url eq $thisfn) { return 0; }
12766: 
12767:     $symb=&symbclean($symb);
12768:     $thisurl=&deversion($thisurl);
12769:     $thisfn=&deversion($thisfn);
12770: 
12771:     my %bighash;
12772:     my $okay=0;
12773: 
12774:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12775:                             &GDBM_READER(),0640)) {
12776:         my $noclutter;
12777:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12778:             $thisurl =~ s/\?.+$//;
12779:             if ($map =~ m{^uploaded/.+\.page$}) {
12780:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12781:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12782:                 $noclutter = 1;
12783:             }
12784:         }
12785:         my $ids;
12786:         if ($noclutter) {
12787:             $ids=$bighash{'ids_'.$thisurl};
12788:         } else {
12789:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12790:         }
12791:         unless ($ids) {
12792:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12793:             $ids=$bighash{$idkey};
12794:         }
12795:         if ($ids) {
12796: # ------------------------------------------------------------------- Has ID(s)
12797:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12798:                 $symb =~ s/\?.+$//;
12799:             }
12800: 	    foreach my $id (split(/\,/,$ids)) {
12801: 	       my ($mapid,$resid)=split(/\./,$id);
12802:                if (
12803:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12804:    eq $symb) {
12805:                    if (ref($encstate)) {
12806:                        $$encstate = $bighash{'encrypted_'.$id};
12807:                    }
12808: 		   if (($env{'request.role.adv'}) ||
12809: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12810:                        ($thisurl eq '/adm/navmaps')) {
12811: 		       $okay=1;
12812:                        last;
12813: 		   }
12814: 	       }
12815: 	   }
12816:         }
12817: 	untie(%bighash);
12818:     }
12819:     return $okay;
12820: }
12821: 
12822: # --------------------------------------------------------------- Clean-up symb
12823: 
12824: sub symbclean {
12825:     my $symb=shift;
12826:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12827: # remove version from map
12828:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12829: 
12830: # remove version from URL
12831:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12832: 
12833: # remove wrapper
12834: 
12835:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12836:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12837:     return $symb;
12838: }
12839: 
12840: # ---------------------------------------------- Split symb to find map and url
12841: 
12842: sub encode_symb {
12843:     my ($map,$resid,$url)=@_;
12844:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12845: }
12846: 
12847: sub decode_symb {
12848:     my $symb=shift;
12849:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12850:     my ($map,$resid,$url)=split(/___/,$symb);
12851:     return (&fixversion($map),$resid,&fixversion($url));
12852: }
12853: 
12854: sub fixversion {
12855:     my $fn=shift;
12856:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12857:     my %bighash;
12858:     my $uri=&clutter($fn);
12859:     my $key=$env{'request.course.id'}.'_'.$uri;
12860: # is this cached?
12861:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12862:     if (defined($cached)) { return $result; }
12863: # unfortunately not cached, or expired
12864:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12865: 	    &GDBM_READER(),0640)) {
12866:  	if ($bighash{'version_'.$uri}) {
12867:  	    my $version=$bighash{'version_'.$uri};
12868:  	    unless (($version eq 'mostrecent') || 
12869: 		    ($version==&getversion($uri))) {
12870:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12871:  	    }
12872:  	}
12873:  	untie %bighash;
12874:     }
12875:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12876: }
12877: 
12878: sub deversion {
12879:     my $url=shift;
12880:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12881:     return $url;
12882: }
12883: 
12884: # ------------------------------------------------------ Return symb list entry
12885: 
12886: sub symbread {
12887:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12888:     my $cache_str='request.symbread.cached.'.$thisfn;
12889:     if (defined($env{$cache_str})) {
12890:         if ($ignorecachednull) {
12891:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12892:         } else {
12893:             return $env{$cache_str};
12894:         }
12895:     }
12896: # no filename provided? try from environment
12897:     unless ($thisfn) {
12898:         if ($env{'request.symb'}) {
12899: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12900: 	}
12901: 	$thisfn=$env{'request.filename'};
12902:     }
12903:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12904: # is that filename actually a symb? Verify, clean, and return
12905:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12906: 	if (&symbverify($thisfn,$1)) {
12907: 	    return $env{$cache_str}=&symbclean($thisfn);
12908: 	}
12909:     }
12910:     $thisfn=declutter($thisfn);
12911:     my %hash;
12912:     my %bighash;
12913:     my $syval='';
12914:     if (($env{'request.course.fn'}) && ($thisfn)) {
12915:         my $targetfn = $thisfn;
12916:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12917:             $targetfn = 'adm/wrapper/'.$thisfn;
12918:         }
12919: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12920: 	    $targetfn=$1;
12921: 	}
12922:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12923:                       &GDBM_READER(),0640)) {
12924: 	    $syval=$hash{$targetfn};
12925:             untie(%hash);
12926:         }
12927: # ---------------------------------------------------------- There was an entry
12928:         if ($syval) {
12929: 	    #unless ($syval=~/\_\d+$/) {
12930: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12931: 		    #&appenv({'request.ambiguous' => $thisfn});
12932: 		    #return $env{$cache_str}='';
12933: 		#}    
12934: 		#$syval.=$1;
12935: 	    #}
12936:         } else {
12937: # ------------------------------------------------------- Was not in symb table
12938:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12939:                             &GDBM_READER(),0640)) {
12940: # ---------------------------------------------- Get ID(s) for current resource
12941:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12942:               unless ($ids) { 
12943:                  $ids=$bighash{'ids_/'.$thisfn};
12944:               }
12945:               unless ($ids) {
12946: # alias?
12947: 		  $ids=$bighash{'mapalias_'.$thisfn};
12948:               }
12949:               if ($ids) {
12950: # ------------------------------------------------------------------- Has ID(s)
12951:                  my @possibilities=split(/\,/,$ids);
12952:                  if ($#possibilities==0) {
12953: # ----------------------------------------------- There is only one possibility
12954: 		     my ($mapid,$resid)=split(/\./,$ids);
12955: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12956: 						    $resid,$thisfn);
12957:                      if (ref($possibles) eq 'HASH') {
12958:                          $possibles->{$syval} = 1;    
12959:                      }
12960:                      if ($checkforblock) {
12961:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12962:                          if (@blockers) {
12963:                              $syval = '';
12964:                              return;
12965:                          }
12966:                      }
12967:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12968: # ------------------------------------------ There is more than one possibility
12969:                      my $realpossible=0;
12970:                      foreach my $id (@possibilities) {
12971: 			 my $file=$bighash{'src_'.$id};
12972:                          my $canaccess;
12973:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12974:                              $canaccess = 1;
12975:                          } else { 
12976:                              $canaccess = &allowed('bre',$file);
12977:                          }
12978:                          if ($canaccess) {
12979:          		     my ($mapid,$resid)=split(/\./,$id);
12980:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12981:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12982: 						             $resid,$thisfn);
12983:                                  if (ref($possibles) eq 'HASH') {
12984:                                      $possibles->{$syval} = 1;
12985:                                  }
12986:                                  if ($checkforblock) {
12987:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12988:                                      unless (@blockers > 0) {
12989:                                          $syval = $poss_syval;
12990:                                          $realpossible++;
12991:                                      }
12992:                                  } else {
12993:                                      $syval = $poss_syval;
12994:                                      $realpossible++;
12995:                                  }
12996:                              }
12997: 			 }
12998:                      }
12999: 		     if ($realpossible!=1) { $syval=''; }
13000:                  } else {
13001:                      $syval='';
13002:                  }
13003: 	      }
13004:               untie(%bighash);
13005:            }
13006:         }
13007:         if ($syval) {
13008: 	    return $env{$cache_str}=$syval;
13009:         }
13010:     }
13011:     &appenv({'request.ambiguous' => $thisfn});
13012:     return $env{$cache_str}='';
13013: }
13014: 
13015: # ---------------------------------------------------------- Return random seed
13016: 
13017: sub numval {
13018:     my $txt=shift;
13019:     $txt=~tr/A-J/0-9/;
13020:     $txt=~tr/a-j/0-9/;
13021:     $txt=~tr/K-T/0-9/;
13022:     $txt=~tr/k-t/0-9/;
13023:     $txt=~tr/U-Z/0-5/;
13024:     $txt=~tr/u-z/0-5/;
13025:     $txt=~s/\D//g;
13026:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13027:     return int($txt);
13028: }
13029: 
13030: sub numval2 {
13031:     my $txt=shift;
13032:     $txt=~tr/A-J/0-9/;
13033:     $txt=~tr/a-j/0-9/;
13034:     $txt=~tr/K-T/0-9/;
13035:     $txt=~tr/k-t/0-9/;
13036:     $txt=~tr/U-Z/0-5/;
13037:     $txt=~tr/u-z/0-5/;
13038:     $txt=~s/\D//g;
13039:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13040:     my $total;
13041:     foreach my $val (@txts) { $total+=$val; }
13042:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13043:     return int($total);
13044: }
13045: 
13046: sub numval3 {
13047:     use integer;
13048:     my $txt=shift;
13049:     $txt=~tr/A-J/0-9/;
13050:     $txt=~tr/a-j/0-9/;
13051:     $txt=~tr/K-T/0-9/;
13052:     $txt=~tr/k-t/0-9/;
13053:     $txt=~tr/U-Z/0-5/;
13054:     $txt=~tr/u-z/0-5/;
13055:     $txt=~s/\D//g;
13056:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13057:     my $total;
13058:     foreach my $val (@txts) { $total+=$val; }
13059:     if ($_64bit) { $total=(($total<<32)>>32); }
13060:     return $total;
13061: }
13062: 
13063: sub digest {
13064:     my ($data)=@_;
13065:     my $digest=&Digest::MD5::md5($data);
13066:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13067:     my ($e,$f);
13068:     {
13069:         use integer;
13070:         $e=($a+$b);
13071:         $f=($c+$d);
13072:         if ($_64bit) {
13073:             $e=(($e<<32)>>32);
13074:             $f=(($f<<32)>>32);
13075:         }
13076:     }
13077:     if (wantarray) {
13078: 	return ($e,$f);
13079:     } else {
13080: 	my $g;
13081: 	{
13082: 	    use integer;
13083: 	    $g=($e+$f);
13084: 	    if ($_64bit) {
13085: 		$g=(($g<<32)>>32);
13086: 	    }
13087: 	}
13088: 	return $g;
13089:     }
13090: }
13091: 
13092: sub latest_rnd_algorithm_id {
13093:     return '64bit5';
13094: }
13095: 
13096: sub get_rand_alg {
13097:     my ($courseid)=@_;
13098:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13099:     if ($courseid) {
13100: 	return $env{"course.$courseid.rndseed"};
13101:     }
13102:     return &latest_rnd_algorithm_id();
13103: }
13104: 
13105: sub validCODE {
13106:     my ($CODE)=@_;
13107:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13108:     return 0;
13109: }
13110: 
13111: sub getCODE {
13112:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13113:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13114: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13115: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13116: 	return $Apache::lonhomework::history{'resource.CODE'};
13117:     }
13118:     return undef;
13119: }
13120: #
13121: #  Determines the random seed for a specific context:
13122: #
13123: # parameters:
13124: #   symb      - in course context the symb for the seed.
13125: #   course_id - The course id of the form domain_coursenum.
13126: #   domain    - Domain for the user.
13127: #   course    - Course for the user.
13128: #   cenv      - environment of the course.
13129: #
13130: # NOTE:
13131: #   All parameters are picked out of the environment if missing
13132: #   or not defined.
13133: #   If a symb cannot be determined the current time is used instead.
13134: #
13135: #  For a given well defined symb, courside, domain, username,
13136: #  and course environment, the seed is reproducible.
13137: #
13138: sub rndseed {
13139:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13140:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13141:     if (!defined($symb)) {
13142: 	unless ($symb=$wsymb) { return time; }
13143:     }
13144:     if (!defined $courseid) { 
13145: 	$courseid=$wcourseid; 
13146:     }
13147:     if (!defined $domain) { $domain=$wdomain; }
13148:     if (!defined $username) { $username=$wusername }
13149: 
13150:     my $which;
13151:     if (defined($cenv->{'rndseed'})) {
13152: 	$which = $cenv->{'rndseed'};
13153:     } else {
13154: 	$which =&get_rand_alg($courseid);
13155:     }
13156:     if (defined(&getCODE())) {
13157: 
13158: 	if ($which eq '64bit5') {
13159: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13160: 	} elsif ($which eq '64bit4') {
13161: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13162: 	} else {
13163: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13164: 	}
13165:     } elsif ($which eq '64bit5') {
13166: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13167:     } elsif ($which eq '64bit4') {
13168: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13169:     } elsif ($which eq '64bit3') {
13170: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13171:     } elsif ($which eq '64bit2') {
13172: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13173:     } elsif ($which eq '64bit') {
13174: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13175:     }
13176:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13177: }
13178: 
13179: sub rndseed_32bit {
13180:     my ($symb,$courseid,$domain,$username)=@_;
13181:     {
13182: 	use integer;
13183: 	my $symbchck=unpack("%32C*",$symb) << 27;
13184: 	my $symbseed=numval($symb) << 22;
13185: 	my $namechck=unpack("%32C*",$username) << 17;
13186: 	my $nameseed=numval($username) << 12;
13187: 	my $domainseed=unpack("%32C*",$domain) << 7;
13188: 	my $courseseed=unpack("%32C*",$courseid);
13189: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13190: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13191: 	#&logthis("rndseed :$num:$symb");
13192: 	if ($_64bit) { $num=(($num<<32)>>32); }
13193: 	return $num;
13194:     }
13195: }
13196: 
13197: sub rndseed_64bit {
13198:     my ($symb,$courseid,$domain,$username)=@_;
13199:     {
13200: 	use integer;
13201: 	my $symbchck=unpack("%32S*",$symb) << 21;
13202: 	my $symbseed=numval($symb) << 10;
13203: 	my $namechck=unpack("%32S*",$username);
13204: 	
13205: 	my $nameseed=numval($username) << 21;
13206: 	my $domainseed=unpack("%32S*",$domain) << 10;
13207: 	my $courseseed=unpack("%32S*",$courseid);
13208: 	
13209: 	my $num1=$symbchck+$symbseed+$namechck;
13210: 	my $num2=$nameseed+$domainseed+$courseseed;
13211: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13212: 	#&logthis("rndseed :$num:$symb");
13213: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13214: 	return "$num1,$num2";
13215:     }
13216: }
13217: 
13218: sub rndseed_64bit2 {
13219:     my ($symb,$courseid,$domain,$username)=@_;
13220:     {
13221: 	use integer;
13222: 	# strings need to be an even # of cahracters long, it it is odd the
13223:         # last characters gets thrown away
13224: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13225: 	my $symbseed=numval($symb) << 10;
13226: 	my $namechck=unpack("%32S*",$username.' ');
13227: 	
13228: 	my $nameseed=numval($username) << 21;
13229: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13230: 	my $courseseed=unpack("%32S*",$courseid.' ');
13231: 	
13232: 	my $num1=$symbchck+$symbseed+$namechck;
13233: 	my $num2=$nameseed+$domainseed+$courseseed;
13234: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13235: 	#&logthis("rndseed :$num:$symb");
13236: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13237: 	return "$num1,$num2";
13238:     }
13239: }
13240: 
13241: sub rndseed_64bit3 {
13242:     my ($symb,$courseid,$domain,$username)=@_;
13243:     {
13244: 	use integer;
13245: 	# strings need to be an even # of cahracters long, it it is odd the
13246:         # last characters gets thrown away
13247: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13248: 	my $symbseed=numval2($symb) << 10;
13249: 	my $namechck=unpack("%32S*",$username.' ');
13250: 	
13251: 	my $nameseed=numval2($username) << 21;
13252: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13253: 	my $courseseed=unpack("%32S*",$courseid.' ');
13254: 	
13255: 	my $num1=$symbchck+$symbseed+$namechck;
13256: 	my $num2=$nameseed+$domainseed+$courseseed;
13257: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13258: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13259: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13260: 	
13261: 	return "$num1:$num2";
13262:     }
13263: }
13264: 
13265: sub rndseed_64bit4 {
13266:     my ($symb,$courseid,$domain,$username)=@_;
13267:     {
13268: 	use integer;
13269: 	# strings need to be an even # of cahracters long, it it is odd the
13270:         # last characters gets thrown away
13271: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13272: 	my $symbseed=numval3($symb) << 10;
13273: 	my $namechck=unpack("%32S*",$username.' ');
13274: 	
13275: 	my $nameseed=numval3($username) << 21;
13276: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13277: 	my $courseseed=unpack("%32S*",$courseid.' ');
13278: 	
13279: 	my $num1=$symbchck+$symbseed+$namechck;
13280: 	my $num2=$nameseed+$domainseed+$courseseed;
13281: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13282: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13283: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13284: 	
13285: 	return "$num1:$num2";
13286:     }
13287: }
13288: 
13289: sub rndseed_64bit5 {
13290:     my ($symb,$courseid,$domain,$username)=@_;
13291:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13292:     return "$num1:$num2";
13293: }
13294: 
13295: sub rndseed_CODE_64bit {
13296:     my ($symb,$courseid,$domain,$username)=@_;
13297:     {
13298: 	use integer;
13299: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13300: 	my $symbseed=numval2($symb);
13301: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13302: 	my $CODEseed=numval(&getCODE());
13303: 	my $courseseed=unpack("%32S*",$courseid.' ');
13304: 	my $num1=$symbseed+$CODEchck;
13305: 	my $num2=$CODEseed+$courseseed+$symbchck;
13306: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13307: 	#&logthis("rndseed :$num1:$num2:$symb");
13308: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13309: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13310: 	return "$num1:$num2";
13311:     }
13312: }
13313: 
13314: sub rndseed_CODE_64bit4 {
13315:     my ($symb,$courseid,$domain,$username)=@_;
13316:     {
13317: 	use integer;
13318: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13319: 	my $symbseed=numval3($symb);
13320: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13321: 	my $CODEseed=numval3(&getCODE());
13322: 	my $courseseed=unpack("%32S*",$courseid.' ');
13323: 	my $num1=$symbseed+$CODEchck;
13324: 	my $num2=$CODEseed+$courseseed+$symbchck;
13325: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13326: 	#&logthis("rndseed :$num1:$num2:$symb");
13327: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13328: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13329: 	return "$num1:$num2";
13330:     }
13331: }
13332: 
13333: sub rndseed_CODE_64bit5 {
13334:     my ($symb,$courseid,$domain,$username)=@_;
13335:     my $code = &getCODE();
13336:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13337:     return "$num1:$num2";
13338: }
13339: 
13340: sub setup_random_from_rndseed {
13341:     my ($rndseed)=@_;
13342:     if ($rndseed =~/([,:])/) {
13343:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13344:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13345:             &Math::Random::random_set_seed_from_phrase($rndseed);
13346:         } else {
13347:             &Math::Random::random_set_seed($num1,$num2);
13348:         }
13349:     } else {
13350: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13351:     }
13352: }
13353: 
13354: sub latest_receipt_algorithm_id {
13355:     return 'receipt3';
13356: }
13357: 
13358: sub recunique {
13359:     my $fucourseid=shift;
13360:     my $unique;
13361:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13362: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13363: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13364:     } else {
13365: 	$unique=$perlvar{'lonReceipt'};
13366:     }
13367:     return unpack("%32C*",$unique);
13368: }
13369: 
13370: sub recprefix {
13371:     my $fucourseid=shift;
13372:     my $prefix;
13373:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13374: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13375: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13376:     } else {
13377: 	$prefix=$perlvar{'lonHostID'};
13378:     }
13379:     return unpack("%32C*",$prefix);
13380: }
13381: 
13382: sub ireceipt {
13383:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13384: 
13385:     my $return =&recprefix($fucourseid).'-';
13386: 
13387:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13388: 	$env{'request.state'} eq 'construct') {
13389: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13390: 	return $return;
13391:     }
13392: 
13393:     my $cuname=unpack("%32C*",$funame);
13394:     my $cudom=unpack("%32C*",$fudom);
13395:     my $cucourseid=unpack("%32C*",$fucourseid);
13396:     my $cusymb=unpack("%32C*",$fusymb);
13397:     my $cunique=&recunique($fucourseid);
13398:     my $cpart=unpack("%32S*",$part);
13399:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13400: 
13401: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13402: 			       
13403: 	$return.= ($cunique%$cuname+
13404: 		   $cunique%$cudom+
13405: 		   $cusymb%$cuname+
13406: 		   $cusymb%$cudom+
13407: 		   $cucourseid%$cuname+
13408: 		   $cucourseid%$cudom+
13409: 		   $cpart%$cuname+
13410: 		   $cpart%$cudom);
13411:     } else {
13412: 	$return.= ($cunique%$cuname+
13413: 		   $cunique%$cudom+
13414: 		   $cusymb%$cuname+
13415: 		   $cusymb%$cudom+
13416: 		   $cucourseid%$cuname+
13417: 		   $cucourseid%$cudom);
13418:     }
13419:     return $return;
13420: }
13421: 
13422: sub receipt {
13423:     my ($part)=@_;
13424:     my ($symb,$courseid,$domain,$name) = &whichuser();
13425:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13426: }
13427: 
13428: sub whichuser {
13429:     my ($passedsymb)=@_;
13430:     my ($symb,$courseid,$domain,$name,$publicuser);
13431:     if (defined($env{'form.grade_symb'})) {
13432: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13433: 	my $allowed=&allowed('vgr',$tmp_courseid);
13434: 	if (!$allowed &&
13435: 	    exists($env{'request.course.sec'}) &&
13436: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13437: 	    $allowed=&allowed('vgr',$tmp_courseid.
13438: 			      '/'.$env{'request.course.sec'});
13439: 	}
13440: 	if ($allowed) {
13441: 	    ($symb)=&get_env_multiple('form.grade_symb');
13442: 	    $courseid=$tmp_courseid;
13443: 	    ($domain)=&get_env_multiple('form.grade_domain');
13444: 	    ($name)=&get_env_multiple('form.grade_username');
13445: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13446: 	}
13447:     }
13448:     if (!$passedsymb) {
13449: 	$symb=&symbread();
13450:     } else {
13451: 	$symb=$passedsymb;
13452:     }
13453:     $courseid=$env{'request.course.id'};
13454:     $domain=$env{'user.domain'};
13455:     $name=$env{'user.name'};
13456:     if ($name eq 'public' && $domain eq 'public') {
13457: 	if (!defined($env{'form.username'})) {
13458: 	    $env{'form.username'}.=time.rand(10000000);
13459: 	}
13460: 	$name.=$env{'form.username'};
13461:     }
13462:     return ($symb,$courseid,$domain,$name,$publicuser);
13463: 
13464: }
13465: 
13466: # ------------------------------------------------------------ Serves up a file
13467: # returns either the contents of the file or 
13468: # -1 if the file doesn't exist
13469: #
13470: # if the target is a file that was uploaded via DOCS, 
13471: # a check will be made to see if a current copy exists on the local server,
13472: # if it does this will be served, otherwise a copy will be retrieved from
13473: # the home server for the course and stored in /home/httpd/html/userfiles on
13474: # the local server.   
13475: 
13476: sub getfile {
13477:     my ($file) = @_;
13478:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13479:     &repcopy($file);
13480:     return &readfile($file);
13481: }
13482: 
13483: sub repcopy_userfile {
13484:     my ($file)=@_;
13485:     my $londocroot = $perlvar{'lonDocRoot'};
13486:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13487:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13488:     my ($cdom,$cnum,$filename) = 
13489: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13490:     my $uri="/uploaded/$cdom/$cnum/$filename";
13491:     if (-e "$file") {
13492: # we already have a local copy, check it out
13493: 	my @fileinfo = stat($file);
13494: 	my $rtncode;
13495: 	my $info;
13496: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13497: 	if ($lwpresp ne 'ok') {
13498: # there is no such file anymore, even though we had a local copy
13499: 	    if ($rtncode eq '404') {
13500: 		unlink($file);
13501: 	    }
13502: 	    return -1;
13503: 	}
13504: 	if ($info < $fileinfo[9]) {
13505: # nice, the file we have is up-to-date, just say okay
13506: 	    return 'ok';
13507: 	} else {
13508: # the file is outdated, get rid of it
13509: 	    unlink($file);
13510: 	}
13511:     }
13512: # one way or the other, at this point, we don't have the file
13513: # construct the correct path for the file
13514:     my @parts = ($cdom,$cnum); 
13515:     if ($filename =~ m|^(.+)/[^/]+$|) {
13516: 	push @parts, split(/\//,$1);
13517:     }
13518:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13519:     foreach my $part (@parts) {
13520: 	$path .= '/'.$part;
13521: 	if (!-e $path) {
13522: 	    mkdir($path,0770);
13523: 	}
13524:     }
13525: # now the path exists for sure
13526: # get a user agent
13527:     my $transferfile=$file.'.in.transfer';
13528: # FIXME: this should flock
13529:     if (-e $transferfile) { return 'ok'; }
13530:     my $request;
13531:     $uri=~s/^\///;
13532:     my $homeserver = &homeserver($cnum,$cdom);
13533:     my $hostname = &hostname($homeserver);
13534:     my $protocol = $protocol{$homeserver};
13535:     $protocol = 'http' if ($protocol ne 'https');
13536:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13537:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13538: # did it work?
13539:     if ($response->is_error()) {
13540: 	unlink($transferfile);
13541: 	&logthis("Userfile repcopy failed for $uri");
13542: 	return -1;
13543:     }
13544: # worked, rename the transfer file
13545:     rename($transferfile,$file);
13546:     return 'ok';
13547: }
13548: 
13549: sub tokenwrapper {
13550:     my $uri=shift;
13551:     $uri=~s|^https?\://([^/]+)||;
13552:     $uri=~s|^/||;
13553:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13554:     my $token=$1;
13555:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13556:     if ($udom && $uname && $file) {
13557: 	$file=~s|(\?\.*)*$||;
13558:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13559:         my $homeserver = &homeserver($uname,$udom);
13560:         my $hostname = &hostname($homeserver);
13561:         my $protocol = $protocol{$homeserver};
13562:         $protocol = 'http' if ($protocol ne 'https');
13563:         return $protocol.'://'.$hostname.'/'.$uri.
13564:                (($uri=~/\?/)?'&':'?').'token='.$token.
13565:                                '&tokenissued='.$perlvar{'lonHostID'};
13566:     } else {
13567:         return '/adm/notfound.html';
13568:     }
13569: }
13570: 
13571: # call with reqtype HEAD: get last modification time
13572: # call with reqtype GET: get the file contents
13573: # Do not call this with reqtype GET for large files! It loads everything into memory
13574: #
13575: sub getuploaded {
13576:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13577:     $uri=~s/^\///;
13578:     my $homeserver = &homeserver($cnum,$cdom);
13579:     my $hostname = &hostname($homeserver);
13580:     my $protocol = $protocol{$homeserver};
13581:     $protocol = 'http' if ($protocol ne 'https');
13582:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13583:     my $request=new HTTP::Request($reqtype,$uri);
13584:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13585:     $$rtncode = $response->code;
13586:     if (! $response->is_success()) {
13587: 	return 'failed';
13588:     }      
13589:     if ($reqtype eq 'HEAD') {
13590: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13591:     } elsif ($reqtype eq 'GET') {
13592: 	$$info = $response->content;
13593:     }
13594:     return 'ok';
13595: }
13596: 
13597: sub readfile {
13598:     my $file = shift;
13599:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13600:     my $fh;
13601:     open($fh,"<",$file);
13602:     my $a='';
13603:     while (my $line = <$fh>) { $a .= $line; }
13604:     return $a;
13605: }
13606: 
13607: sub filelocation {
13608:     my ($dir,$file) = @_;
13609:     my $location;
13610:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13611: 
13612:     if ($file =~ m-^/adm/-) {
13613: 	$file=~s-^/adm/wrapper/-/-;
13614: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13615:     }
13616: 
13617:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13618:         $location = $file;
13619:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13620:         my ($udom,$uname,$filename)=
13621:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13622:         my $home=&homeserver($uname,$udom);
13623:         my $is_me=0;
13624:         my @ids=&current_machine_ids();
13625:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13626:         if ($is_me) {
13627:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13628:         } else {
13629:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13630:   	      $udom.'/'.$uname.'/'.$filename;
13631:         }
13632:     } elsif ($file =~ m-^/adm/-) {
13633: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13634:     } else {
13635:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13636:         $file=~s:^/(res|priv)/:/:;
13637:         my $space=$1;
13638:         if ( !( $file =~ m:^/:) ) {
13639:             $location = $dir. '/'.$file;
13640:         } else {
13641:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13642:         }
13643:     }
13644:     $location=~s://+:/:g; # remove duplicate /
13645:     while ($location=~m{/\.\./}) {
13646: 	if ($location =~ m{/[^/]+/\.\./}) {
13647: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13648: 	} else {
13649: 	    $location=~ s{/\.\./}{/}g;
13650: 	}
13651:     } #remove dir/..
13652:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13653:     return $location;
13654: }
13655: 
13656: sub hreflocation {
13657:     my ($dir,$file)=@_;
13658:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13659: 	$file=filelocation($dir,$file);
13660:     } elsif ($file=~m-^/adm/-) {
13661: 	$file=~s-^/adm/wrapper/-/-;
13662: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13663:     }
13664:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13665: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13666:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13667: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13668: 	        {/uploaded/$1/$2/}x;
13669:     }
13670:     if ($file=~ m{^/userfiles/}) {
13671: 	$file =~ s{^/userfiles/}{/uploaded/};
13672:     }
13673:     return $file;
13674: }
13675: 
13676: 
13677: 
13678: 
13679: 
13680: sub current_machine_domains {
13681:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13682: }
13683: 
13684: sub machine_domains {
13685:     my ($hostname) = @_;
13686:     my @domains;
13687:     my %hostname = &all_hostnames();
13688:     while( my($id, $name) = each(%hostname)) {
13689: #	&logthis("-$id-$name-$hostname-");
13690: 	if ($hostname eq $name) {
13691: 	    push(@domains,&host_domain($id));
13692: 	}
13693:     }
13694:     return @domains;
13695: }
13696: 
13697: sub current_machine_ids {
13698:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13699: }
13700: 
13701: sub machine_ids {
13702:     my ($hostname) = @_;
13703:     $hostname ||= &hostname($perlvar{'lonHostID'});
13704:     my @ids;
13705:     my %name_to_host = &all_names();
13706:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13707: 	return @{ $name_to_host{$hostname} };
13708:     }
13709:     return;
13710: }
13711: 
13712: sub additional_machine_domains {
13713:     my @domains;
13714:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13715:     while( my $line = <$fh>) {
13716:         $line =~ s/\s//g;
13717:         push(@domains,$line);
13718:     }
13719:     return @domains;
13720: }
13721: 
13722: sub default_login_domain {
13723:     my $domain = $perlvar{'lonDefDomain'};
13724:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13725:     foreach my $posdom (&current_machine_domains(),
13726:                         &additional_machine_domains()) {
13727:         if (lc($posdom) eq lc($testdomain)) {
13728:             $domain=$posdom;
13729:             last;
13730:         }
13731:     }
13732:     return $domain;
13733: }
13734: 
13735: sub uses_sts {
13736:     my ($ignore_cache) = @_;
13737:     my $lonhost = $perlvar{'lonHostID'};
13738:     my $hostname = &hostname($lonhost);
13739:     my $sts_on;
13740:     if ($protocol{$lonhost} eq 'https') {
13741:         my $cachetime = 12*3600;
13742:         if (!$ignore_cache) {
13743:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13744:             if (defined($cached)) {
13745:                 return $sts_on;
13746:             }
13747:         }
13748:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13749:         my $request=new HTTP::Request('HEAD',$url);
13750:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
13751:         if ($response->is_success) {
13752:             my $has_sts = $response->header('Strict-Transport-Security');
13753:             if ($has_sts eq '') {
13754:                 $sts_on = 0;
13755:             } else {
13756:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13757:                     my $maxage = $1;
13758:                     if ($maxage) {
13759:                         $sts_on = 1;
13760:                     } else {
13761:                         $sts_on = 0;
13762:                     }
13763:                 } else {
13764:                     $sts_on = 0;
13765:                 }
13766:             }
13767:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13768:         }
13769:     }
13770:     return;
13771: }
13772: 
13773: # ------------------------------------------------------------- Declutters URLs
13774: 
13775: sub declutter {
13776:     my $thisfn=shift;
13777:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13778:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13779:         $thisfn=~s{^/home/httpd/html}{};
13780:     }
13781:     $thisfn=~s/^\///;
13782:     $thisfn=~s|^adm/wrapper/||;
13783:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13784:     $thisfn=~s/^res\///;
13785:     $thisfn=~s/^priv\///;
13786:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13787:         $thisfn=~s/\?.+$//;
13788:     }
13789:     return $thisfn;
13790: }
13791: 
13792: # ------------------------------------------------------------- Clutter up URLs
13793: 
13794: sub clutter {
13795:     my $thisfn='/'.&declutter(shift);
13796:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13797: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13798:        $thisfn='/res'.$thisfn; 
13799:     }
13800:     if ($thisfn !~m|^/adm|) {
13801: 	if ($thisfn =~ m|^/ext/|) {
13802: 	    $thisfn='/adm/wrapper'.$thisfn;
13803: 	} else {
13804: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13805: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13806: 	    if ($embstyle eq 'ssi'
13807: 		|| ($embstyle eq 'hdn')
13808: 		|| ($embstyle eq 'rat')
13809: 		|| ($embstyle eq 'prv')
13810: 		|| ($embstyle eq 'ign')) {
13811: 		#do nothing with these
13812: 	    } elsif (($embstyle eq 'img') 
13813: 		|| ($embstyle eq 'emb')
13814: 		|| ($embstyle eq 'wrp')) {
13815: 		$thisfn='/adm/wrapper'.$thisfn;
13816: 	    } elsif ($embstyle eq 'unk'
13817: 		     && $thisfn!~/\.(sequence|page)$/) {
13818: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13819: 	    } else {
13820: #		&logthis("Got a blank emb style");
13821: 	    }
13822: 	}
13823:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13824:         $thisfn='/adm/wrapper'.$thisfn;
13825:     }
13826:     return $thisfn;
13827: }
13828: 
13829: sub clutter_with_no_wrapper {
13830:     my $uri = &clutter(shift);
13831:     if ($uri =~ m-^/adm/-) {
13832: 	$uri =~ s-^/adm/wrapper/-/-;
13833: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13834:     }
13835:     return $uri;
13836: }
13837: 
13838: sub freeze_escape {
13839:     my ($value)=@_;
13840:     if (ref($value)) {
13841: 	$value=&nfreeze($value);
13842: 	return '__FROZEN__'.&escape($value);
13843:     }
13844:     return &escape($value);
13845: }
13846: 
13847: 
13848: sub thaw_unescape {
13849:     my ($value)=@_;
13850:     if ($value =~ /^__FROZEN__/) {
13851: 	substr($value,0,10,undef);
13852: 	$value=&unescape($value);
13853: 	return &thaw($value);
13854:     }
13855:     return &unescape($value);
13856: }
13857: 
13858: sub correct_line_ends {
13859:     my ($result)=@_;
13860:     $$result =~s/\r\n/\n/mg;
13861:     $$result =~s/\r/\n/mg;
13862: }
13863: # ================================================================ Main Program
13864: 
13865: sub goodbye {
13866:    &logthis("Starting Shut down");
13867: #not converted to using infrastruture and probably shouldn't be
13868:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13869: #converted
13870: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13871:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13872: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13873: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13874: #1.1 only
13875: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13876: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13877: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13878: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13879:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13880:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13881:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13882:    &flushcourselogs();
13883:    &logthis("Shutting down");
13884: }
13885: 
13886: sub get_dns {
13887:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13888:     if (!$ignore_cache) {
13889: 	my ($content,$cached)=
13890: 	    &Apache::lonnet::is_cached_new('dns',$url);
13891: 	if ($cached) {
13892: 	    &$func($content,$hashref);
13893: 	    return;
13894: 	}
13895:     }
13896: 
13897:     my %alldns;
13898:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13899:         foreach my $dns (<$config>) {
13900: 	    next if ($dns !~ /^\^(\S*)/x);
13901:             my $line = $1;
13902:             my ($host,$protocol) = split(/:/,$line);
13903:             if ($protocol ne 'https') {
13904:                 $protocol = 'http';
13905:             }
13906: 	    $alldns{$host} = $protocol;
13907:         }
13908:         close($config);
13909:     }
13910:     while (%alldns) {
13911: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13912: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13913:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13914:         delete($alldns{$dns});
13915: 	next if ($response->is_error());
13916:         if ($url eq '/adm/dns/loncapaCRL') {
13917:             return &$func($response);
13918:         } else {
13919: 	    my @content = split("\n",$response->content);
13920: 	    unless ($nocache) {
13921: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13922: 	    }
13923: 	    &$func(\@content,$hashref);
13924:             return;
13925:         }
13926:     }
13927:     my $which = (split('/',$url,4))[3];
13928:     if ($which eq 'loncapaCRL') {
13929:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13930:         if (-e $diskfile) {
13931:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13932:         } else {
13933:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13934:         }
13935:     } else {
13936:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13937:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13938:             my @content = <$config>;
13939:             close($config);
13940:             &$func(\@content,$hashref);
13941:         }
13942:     }
13943:     return;
13944: }
13945: 
13946: # ------------------------------------------------------Get DNS checksums file
13947: sub parse_dns_checksums_tab {
13948:     my ($lines,$hashref) = @_;
13949:     my $lonhost = $perlvar{'lonHostID'};
13950:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13951:     my $loncaparev = &get_server_loncaparev($machine_dom);
13952:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13953:     my $webconfdir = '/etc/httpd/conf';
13954:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13955:         $webconfdir = '/etc/apache2';
13956:     } elsif ($distro =~ /^sles(\d+)$/) {
13957:         if ($1 >= 10) {
13958:             $webconfdir = '/etc/apache2';
13959:         }
13960:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13961:         if ($1 >= 10.0) {
13962:             $webconfdir = '/etc/apache2';
13963:         }
13964:     }
13965:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13966:     my (%chksum,%revnum);
13967:     if (ref($lines) eq 'ARRAY') {
13968:         chomp(@{$lines});
13969:         my $version = shift(@{$lines});
13970:         if ($version eq $release) {  
13971:             foreach my $line (@{$lines}) {
13972:                 my ($file,$version,$shasum) = split(/,/,$line);
13973:                 if ($file =~ m{^/etc/httpd/conf}) {
13974:                     if ($webconfdir eq '/etc/apache2') {
13975:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13976:                     }
13977:                 }
13978:                 $chksum{$file} = $shasum;
13979:                 $revnum{$file} = $version;
13980:             }
13981:             if (ref($hashref) eq 'HASH') {
13982:                 %{$hashref} = (
13983:                                 sums     => \%chksum,
13984:                                 versions => \%revnum,
13985:                               );
13986:             }
13987:         }
13988:     }
13989:     return;
13990: }
13991: 
13992: sub fetch_dns_checksums {
13993:     my %checksums;
13994:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13995:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13996:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13997:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13998:              \%checksums);
13999:     return \%checksums;
14000: }
14001: 
14002: sub fetch_crl_pemfile {
14003:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14004: }
14005: 
14006: sub save_crl_pem {
14007:     my ($response) = @_;
14008:     my ($msg,$hadchanges);
14009:     if (ref($response)) {
14010:         my $now = time;
14011:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14012:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14013:         if (open(my $fh,'>',"$tmpcrl")) {
14014:             print $fh $response->content;
14015:             close($fh);
14016:             if (-e $lonca) {
14017:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14018:                     my $check = <PIPE>;
14019:                     close(PIPE);
14020:                     chomp($check);
14021:                     if ($check eq 'verify OK') {
14022:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14023:                         my $backup;
14024:                         if (-e $dest) {
14025:                             if (&File::Copy::move($dest,"$dest.bak")) {
14026:                                 $backup = 'ok';
14027:                             }
14028:                         }
14029:                         if (&File::Copy::move($tmpcrl,$dest)) {
14030:                             $msg = 'ok';
14031:                             if ($backup) {
14032:                                 my (%oldnums,%newnums);
14033:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14034:                                     while (<PIPE>) {
14035:                                         $oldnums{(split(/:/))[1]} = 1;
14036:                                     }
14037:                                     close(PIPE);
14038:                                 }
14039:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14040:                                     while(<PIPE>) {
14041:                                         $newnums{(split(/:/))[1]} = 1;
14042:                                     }
14043:                                     close(PIPE);
14044:                                 }
14045:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14046:                                     unless (exists($oldnums{$key})) {
14047:                                         $hadchanges = 1;
14048:                                         last;
14049:                                     }
14050:                                 }
14051:                                 unless ($hadchanges) {
14052:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14053:                                         unless (exists($newnums{$key})) {
14054:                                             $hadchanges = 1;
14055:                                             last;
14056:                                         }
14057:                                     }
14058:                                 }
14059:                             }
14060:                         }
14061:                     } else {
14062:                         unlink($tmpcrl);
14063:                     }
14064:                 } else {
14065:                     unlink($tmpcrl);
14066:                 }
14067:             } else {
14068:                 unlink($tmpcrl);
14069:             }
14070:         }
14071:     }
14072:     return ($msg,$hadchanges);
14073: }
14074: 
14075: # ------------------------------------------------------------ Read domain file
14076: {
14077:     my $loaded;
14078:     my %domain;
14079: 
14080:     sub parse_domain_tab {
14081: 	my ($lines) = @_;
14082: 	foreach my $line (@$lines) {
14083: 	    next if ($line =~ /^(\#|\s*$ )/x);
14084: 
14085: 	    chomp($line);
14086: 	    my ($name,@elements) = split(/:/,$line,9);
14087: 	    my %this_domain;
14088: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14089: 			       'lang_def', 'city', 'longi', 'lati',
14090: 			       'primary') {
14091: 		$this_domain{$field} = shift(@elements);
14092: 	    }
14093: 	    $domain{$name} = \%this_domain;
14094: 	}
14095:     }
14096: 
14097:     sub reset_domain_info {
14098: 	undef($loaded);
14099: 	undef(%domain);
14100:     }
14101: 
14102:     sub load_domain_tab {
14103: 	my ($ignore_cache,$nocache) = @_;
14104: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14105: 	my $fh;
14106: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14107: 	    my @lines = <$fh>;
14108: 	    &parse_domain_tab(\@lines);
14109: 	}
14110: 	close($fh);
14111: 	$loaded = 1;
14112:     }
14113: 
14114:     sub domain {
14115: 	&load_domain_tab() if (!$loaded);
14116: 
14117: 	my ($name,$what) = @_;
14118: 	return if ( !exists($domain{$name}) );
14119: 
14120: 	if (!$what) {
14121: 	    return $domain{$name}{'description'};
14122: 	}
14123: 	return $domain{$name}{$what};
14124:     }
14125: 
14126:     sub domain_info {
14127:         &load_domain_tab() if (!$loaded);
14128:         return %domain;
14129:     }
14130: 
14131: }
14132: 
14133: 
14134: # ------------------------------------------------------------- Read hosts file
14135: {
14136:     my %hostname;
14137:     my %hostdom;
14138:     my %libserv;
14139:     my $loaded;
14140:     my %name_to_host;
14141:     my %internetdom;
14142:     my %LC_dns_serv;
14143: 
14144:     sub parse_hosts_tab {
14145: 	my ($file) = @_;
14146: 	foreach my $configline (@$file) {
14147: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14148:             chomp($configline);
14149: 	    if ($configline =~ /^\^/) {
14150:                 if ($configline =~ /^\^([\w.\-]+)/) {
14151:                     $LC_dns_serv{$1} = 1;
14152:                 }
14153:                 next;
14154:             }
14155: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14156: 	    $name=~s/\s//g;
14157: 	    if ($id && $domain && $role && $name) {
14158:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14159:                     my $curr = $hostname{$id};
14160:                     my $skip;
14161:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14162:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14163:                             $skip = 1;
14164:                         } else {
14165:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14166:                         }
14167:                     }
14168:                     unless ($skip) {
14169:                         push(@{$name_to_host{$name}},$id);
14170:                     }
14171:                 } else {
14172:                     push(@{$name_to_host{$name}},$id);
14173:                 }
14174: 		$hostname{$id}=$name;
14175: 		$hostdom{$id}=$domain;
14176: 		if ($role eq 'library') { $libserv{$id}=$name; }
14177:                 if (defined($protocol)) {
14178:                     if ($protocol eq 'https') {
14179:                         $protocol{$id} = $protocol;
14180:                     } else {
14181:                         $protocol{$id} = 'http'; 
14182:                     }
14183:                 } else {
14184:                     $protocol{$id} = 'http';
14185:                 }
14186:                 if (defined($intdom)) {
14187:                     $internetdom{$id} = $intdom;
14188:                 }
14189: 	    }
14190: 	}
14191:     }
14192:     
14193:     sub reset_hosts_info {
14194: 	&purge_remembered();
14195: 	&reset_domain_info();
14196: 	&reset_hosts_ip_info();
14197:         undef(%internetdom);
14198: 	undef(%name_to_host);
14199: 	undef(%hostname);
14200: 	undef(%hostdom);
14201: 	undef(%libserv);
14202: 	undef($loaded);
14203:     }
14204: 
14205:     sub load_hosts_tab {
14206: 	my ($ignore_cache,$nocache) = @_;
14207: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14208: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14209: 	my @config = <$config>;
14210: 	&parse_hosts_tab(\@config);
14211: 	close($config);
14212: 	$loaded=1;
14213:     }
14214: 
14215:     sub hostname {
14216: 	&load_hosts_tab() if (!$loaded);
14217: 
14218: 	my ($lonid) = @_;
14219: 	return $hostname{$lonid};
14220:     }
14221: 
14222:     sub all_hostnames {
14223: 	&load_hosts_tab() if (!$loaded);
14224: 
14225: 	return %hostname;
14226:     }
14227: 
14228:     sub all_names {
14229:         my ($ignore_cache,$nocache) = @_;
14230: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14231: 
14232: 	return %name_to_host;
14233:     }
14234: 
14235:     sub all_host_domain {
14236:         &load_hosts_tab() if (!$loaded);
14237:         return %hostdom;
14238:     }
14239: 
14240:     sub all_host_intdom {
14241:         &load_hosts_tab() if (!$loaded);
14242:         return %internetdom;
14243:     }
14244: 
14245:     sub is_library {
14246: 	&load_hosts_tab() if (!$loaded);
14247: 
14248: 	return exists($libserv{$_[0]});
14249:     }
14250: 
14251:     sub all_library {
14252: 	&load_hosts_tab() if (!$loaded);
14253: 
14254: 	return %libserv;
14255:     }
14256: 
14257:     sub unique_library {
14258: 	#2x reverse removes all hostnames that appear more than once
14259:         my %unique = reverse &all_library();
14260:         return reverse %unique;
14261:     }
14262: 
14263:     sub get_servers {
14264: 	&load_hosts_tab() if (!$loaded);
14265: 
14266: 	my ($domain,$type) = @_;
14267: 	my %possible_hosts = ($type eq 'library') ? %libserv
14268: 	                                          : %hostname;
14269: 	my %result;
14270: 	if (ref($domain) eq 'ARRAY') {
14271: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14272: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14273: 		    $result{$host} = $hostname;
14274: 		}
14275: 	    }
14276: 	} else {
14277: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14278: 		if ($hostdom{$host} eq $domain) {
14279: 		    $result{$host} = $hostname;
14280: 		}
14281: 	    }
14282: 	}
14283: 	return %result;
14284:     }
14285: 
14286:     sub get_unique_servers {
14287:         my %unique = reverse &get_servers(@_);
14288: 	return reverse %unique;
14289:     }
14290: 
14291:     sub host_domain {
14292: 	&load_hosts_tab() if (!$loaded);
14293: 
14294: 	my ($lonid) = @_;
14295: 	return $hostdom{$lonid};
14296:     }
14297: 
14298:     sub all_domains {
14299: 	&load_hosts_tab() if (!$loaded);
14300: 
14301: 	my %seen;
14302: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14303: 	return @uniq;
14304:     }
14305: 
14306:     sub internet_dom {
14307:         &load_hosts_tab() if (!$loaded);
14308: 
14309:         my ($lonid) = @_;
14310:         return $internetdom{$lonid};
14311:     }
14312: 
14313:     sub is_LC_dns {
14314:         &load_hosts_tab() if (!$loaded);
14315: 
14316:         my ($hostname) = @_;
14317:         return exists($LC_dns_serv{$hostname});
14318:     }
14319: 
14320: }
14321: 
14322: { 
14323:     my %iphost;
14324:     my %name_to_ip;
14325:     my %lonid_to_ip;
14326: 
14327:     sub get_hosts_from_ip {
14328: 	my ($ip) = @_;
14329: 	my %iphosts = &get_iphost();
14330: 	if (ref($iphosts{$ip})) {
14331: 	    return @{$iphosts{$ip}};
14332: 	}
14333: 	return;
14334:     }
14335:     
14336:     sub reset_hosts_ip_info {
14337: 	undef(%iphost);
14338: 	undef(%name_to_ip);
14339: 	undef(%lonid_to_ip);
14340:     }
14341: 
14342:     sub get_host_ip {
14343: 	my ($lonid) = @_;
14344: 	if (exists($lonid_to_ip{$lonid})) {
14345: 	    return $lonid_to_ip{$lonid};
14346: 	}
14347: 	my $name=&hostname($lonid);
14348:    	my $ip = gethostbyname($name);
14349: 	return if (!$ip || length($ip) ne 4);
14350: 	$ip=inet_ntoa($ip);
14351: 	$name_to_ip{$name}   = $ip;
14352: 	$lonid_to_ip{$lonid} = $ip;
14353: 	return $ip;
14354:     }
14355:     
14356:     sub get_iphost {
14357: 	my ($ignore_cache,$nocache) = @_;
14358: 
14359: 	if (!$ignore_cache) {
14360: 	    if (%iphost) {
14361: 		return %iphost;
14362: 	    }
14363: 	    my ($ip_info,$cached)=
14364: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14365: 	    if ($cached) {
14366: 		%iphost      = %{$ip_info->[0]};
14367: 		%name_to_ip  = %{$ip_info->[1]};
14368: 		%lonid_to_ip = %{$ip_info->[2]};
14369: 		return %iphost;
14370: 	    }
14371: 	}
14372: 
14373: 	# get yesterday's info for fallback
14374: 	my %old_name_to_ip;
14375: 	my ($ip_info,$cached)=
14376: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14377: 	if ($cached) {
14378: 	    %old_name_to_ip = %{$ip_info->[1]};
14379: 	}
14380: 
14381: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14382: 	foreach my $name (keys(%name_to_host)) {
14383: 	    my $ip;
14384: 	    if (!exists($name_to_ip{$name})) {
14385: 		$ip = gethostbyname($name);
14386: 		if (!$ip || length($ip) ne 4) {
14387: 		    if (defined($old_name_to_ip{$name})) {
14388: 			$ip = $old_name_to_ip{$name};
14389: 			&logthis("Can't find $name defaulting to old $ip");
14390: 		    } else {
14391: 			&logthis("Name $name no IP found");
14392: 			next;
14393: 		    }
14394: 		} else {
14395: 		    $ip=inet_ntoa($ip);
14396: 		}
14397: 		$name_to_ip{$name} = $ip;
14398: 	    } else {
14399: 		$ip = $name_to_ip{$name};
14400: 	    }
14401: 	    foreach my $id (@{ $name_to_host{$name} }) {
14402: 		$lonid_to_ip{$id} = $ip;
14403: 	    }
14404: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14405: 	}
14406:         unless ($nocache) {
14407: 	    &do_cache_new('iphost','iphost',
14408: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14409: 		          48*60*60);
14410:         }
14411: 
14412: 	return %iphost;
14413:     }
14414: 
14415:     #
14416:     #  Given a DNS returns the loncapa host name for that DNS 
14417:     # 
14418:     sub host_from_dns {
14419:         my ($dns) = @_;
14420:         my @hosts;
14421:         my $ip;
14422: 
14423:         if (exists($name_to_ip{$dns})) {
14424:             $ip = $name_to_ip{$dns};
14425:         }
14426:         if (!$ip) {
14427:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14428:             if (length($ip) == 4) { 
14429: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14430:             }
14431:         }
14432:         if ($ip) {
14433: 	    @hosts = get_hosts_from_ip($ip);
14434: 	    return $hosts[0];
14435:         }
14436:         return undef;
14437:     }
14438: 
14439:     sub get_internet_names {
14440:         my ($lonid) = @_;
14441:         return if ($lonid eq '');
14442:         my ($idnref,$cached)=
14443:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14444:         if ($cached) {
14445:             return $idnref;
14446:         }
14447:         my $ip = &get_host_ip($lonid);
14448:         my @hosts = &get_hosts_from_ip($ip);
14449:         my %iphost = &get_iphost();
14450:         my (@idns,%seen);
14451:         foreach my $id (@hosts) {
14452:             my $dom = &host_domain($id);
14453:             my $prim_id = &domain($dom,'primary');
14454:             my $prim_ip = &get_host_ip($prim_id);
14455:             next if ($seen{$prim_ip});
14456:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14457:                 foreach my $id (@{$iphost{$prim_ip}}) {
14458:                     my $intdom = &internet_dom($id);
14459:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14460:                         push(@idns,$intdom);
14461:                     }
14462:                 }
14463:             }
14464:             $seen{$prim_ip} = 1;
14465:         }
14466:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14467:     }
14468: 
14469: }
14470: 
14471: sub all_loncaparevs {
14472:     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);
14473: }
14474: 
14475: # ---------------------------------------------------------- Read loncaparev table
14476: {
14477:     sub load_loncaparevs { 
14478:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14479:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14480:                 while (my $configline=<$config>) {
14481:                     chomp($configline);
14482:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14483:                     $loncaparevs{$hostid}=$loncaparev;
14484:                 }
14485:                 close($config);
14486:             }
14487:         }
14488:     }
14489: }
14490: 
14491: # ---------------------------------------------------------- Read serverhostID table
14492: {
14493:     sub load_serverhomeIDs {
14494:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14495:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14496:                 while (my $configline=<$config>) {
14497:                     chomp($configline);
14498:                     my ($name,$id)=split(/:/,$configline);
14499:                     $serverhomeIDs{$name}=$id;
14500:                 }
14501:                 close($config);
14502:             }
14503:         }
14504:     }
14505: }
14506: 
14507: 
14508: BEGIN {
14509: 
14510: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14511:     unless ($readit) {
14512: {
14513:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14514:     %perlvar = (%perlvar,%{$configvars});
14515: }
14516: 
14517: 
14518: # ------------------------------------------------------ Read spare server file
14519: {
14520:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14521: 
14522:     while (my $configline=<$config>) {
14523:        chomp($configline);
14524:        if ($configline) {
14525: 	   my ($host,$type) = split(':',$configline,2);
14526: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14527: 	   push(@{ $spareid{$type} }, $host);
14528:        }
14529:     }
14530:     close($config);
14531: }
14532: # ------------------------------------------------------------ Read permissions
14533: {
14534:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14535: 
14536:     while (my $configline=<$config>) {
14537: 	chomp($configline);
14538: 	if ($configline) {
14539: 	    my ($role,$perm)=split(/ /,$configline);
14540: 	    if ($perm ne '') { $pr{$role}=$perm; }
14541: 	}
14542:     }
14543:     close($config);
14544: }
14545: 
14546: # -------------------------------------------- Read plain texts for permissions
14547: {
14548:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14549: 
14550:     while (my $configline=<$config>) {
14551: 	chomp($configline);
14552: 	if ($configline) {
14553: 	    my ($short,@plain)=split(/:/,$configline);
14554:             %{$prp{$short}} = ();
14555: 	    if (@plain > 0) {
14556:                 $prp{$short}{'std'} = $plain[0];
14557:                 for (my $i=1; $i<@plain; $i++) {
14558:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14559:                 }
14560:             }
14561: 	}
14562:     }
14563:     close($config);
14564: }
14565: 
14566: # ---------------------------------------------------------- Read package table
14567: {
14568:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14569: 
14570:     while (my $configline=<$config>) {
14571: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14572: 	chomp($configline);
14573: 	my ($short,$plain)=split(/:/,$configline);
14574: 	my ($pack,$name)=split(/\&/,$short);
14575: 	if ($plain ne '') {
14576: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14577: 	    $packagetab{$short}=$plain; 
14578: 	}
14579:     }
14580:     close($config);
14581: }
14582: 
14583: # ---------------------------------------------------------- Read loncaparev table
14584: 
14585: &load_loncaparevs();
14586: 
14587: # ---------------------------------------------------------- Read serverhostID table
14588: 
14589: &load_serverhomeIDs();
14590: 
14591: # ---------------------------------------------------------- Read releaseslist XML
14592: {
14593:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14594:     if (-e $file) {
14595:         my $parser = HTML::LCParser->new($file);
14596:         while (my $token = $parser->get_token()) {
14597:             if ($token->[0] eq 'S') {
14598:                 my $item = $token->[1];
14599:                 my $name = $token->[2]{'name'};
14600:                 my $value = $token->[2]{'value'};
14601:                 my $valuematch = $token->[2]{'valuematch'};
14602:                 my $namematch = $token->[2]{'namematch'};
14603:                 if ($item eq 'parameter') {
14604:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14605:                         my $release = $parser->get_text();
14606:                         $release =~ s/(^\s*|\s*$ )//gx;
14607:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14608:                     }
14609:                 } elsif ($item ne '' && $name ne '') {
14610:                     my $release = $parser->get_text();
14611:                     $release =~ s/(^\s*|\s*$ )//gx;
14612:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14613:                 }
14614:             }
14615:         }
14616:     }
14617: }
14618: 
14619: # ---------------------------------------------------------- Read managers table
14620: {
14621:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14622:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14623:             while (my $configline=<$config>) {
14624:                 chomp($configline);
14625:                 next if ($configline =~ /^\#/);
14626:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14627:                     $managerstab{$configline} = 1;
14628:                 }
14629:             }
14630:             close($config);
14631:         }
14632:     }
14633: }
14634: 
14635: # ------------- set up temporary directory
14636: {
14637:     $tmpdir = LONCAPA::tempdir();
14638: 
14639: }
14640: 
14641: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14642: 				'compress_threshold'=> 20_000,
14643:  			        });
14644: 
14645: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14646: $dumpcount=0;
14647: $locknum=0;
14648: 
14649: &logtouch();
14650: &logthis('<font color="yellow">INFO: Read configuration</font>');
14651: $readit=1;
14652:     {
14653: 	use integer;
14654: 	my $test=(2**32)+1;
14655: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14656: 	&logthis(" Detected 64bit platform ($_64bit)");
14657:     }
14658: }
14659: }
14660: 
14661: 1;
14662: __END__
14663: 
14664: =pod
14665: 
14666: =head1 NAME
14667: 
14668: Apache::lonnet - Subroutines to ask questions about things in the network.
14669: 
14670: =head1 SYNOPSIS
14671: 
14672: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14673: 
14674:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14675: 
14676: Common parameters:
14677: 
14678: =over 4
14679: 
14680: =item *
14681: 
14682: $uname : an internal username (if $cname expecting a course Id specifically)
14683: 
14684: =item *
14685: 
14686: $udom : a domain (if $cdom expecting a course's domain specifically)
14687: 
14688: =item *
14689: 
14690: $symb : a resource instance identifier
14691: 
14692: =item *
14693: 
14694: $namespace : the name of a .db file that contains the data needed or
14695: being set.
14696: 
14697: =back
14698: 
14699: =head1 OVERVIEW
14700: 
14701: lonnet provides subroutines which interact with the
14702: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14703: about classes, users, and resources.
14704: 
14705: For many of these objects you can also use this to store data about
14706: them or modify them in various ways.
14707: 
14708: =head2 Symbs
14709: 
14710: To identify a specific instance of a resource, LON-CAPA uses symbols
14711: or "symbs"X<symb>. These identifiers are built from the URL of the
14712: map, the resource number of the resource in the map, and the URL of
14713: the resource itself. The latter is somewhat redundant, but might help
14714: if maps change.
14715: 
14716: An example is
14717: 
14718:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14719: 
14720: The respective map entry is
14721: 
14722:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14723:   title="Problem 2">
14724:  </resource>
14725: 
14726: Symbs are used by the random number generator, as well as to store and
14727: restore data specific to a certain instance of for example a problem.
14728: 
14729: =head2 Storing And Retrieving Data
14730: 
14731: X<store()>X<cstore()>X<restore()>Three of the most important functions
14732: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14733: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14734: is is the non-critical message twin of cstore. These functions are for
14735: handlers to store a perl hash to a user's permanent data space in an
14736: easy manner, and to retrieve it again on another call. It is expected
14737: that a handler would use this once at the beginning to retrieve data,
14738: and then again once at the end to send only the new data back.
14739: 
14740: The data is stored in the user's data directory on the user's
14741: homeserver under the ID of the course.
14742: 
14743: The hash that is returned by restore will have all of the previous
14744: value for all of the elements of the hash.
14745: 
14746: Example:
14747: 
14748:  #creating a hash
14749:  my %hash;
14750:  $hash{'foo'}='bar';
14751: 
14752:  #storing it
14753:  &Apache::lonnet::cstore(\%hash);
14754: 
14755:  #changing a value
14756:  $hash{'foo'}='notbar';
14757: 
14758:  #adding a new value
14759:  $hash{'bar'}='foo';
14760:  &Apache::lonnet::cstore(\%hash);
14761: 
14762:  #retrieving the hash
14763:  my %history=&Apache::lonnet::restore();
14764: 
14765:  #print the hash
14766:  foreach my $key (sort(keys(%history))) {
14767:    print("\%history{$key} = $history{$key}");
14768:  }
14769: 
14770: Will print out:
14771: 
14772:  %history{1:foo} = bar
14773:  %history{1:keys} = foo:timestamp
14774:  %history{1:timestamp} = 990455579
14775:  %history{2:bar} = foo
14776:  %history{2:foo} = notbar
14777:  %history{2:keys} = foo:bar:timestamp
14778:  %history{2:timestamp} = 990455580
14779:  %history{bar} = foo
14780:  %history{foo} = notbar
14781:  %history{timestamp} = 990455580
14782:  %history{version} = 2
14783: 
14784: Note that the special hash entries C<keys>, C<version> and
14785: C<timestamp> were added to the hash. C<version> will be equal to the
14786: total number of versions of the data that have been stored. The
14787: C<timestamp> attribute will be the UNIX time the hash was
14788: stored. C<keys> is available in every historical section to list which
14789: keys were added or changed at a specific historical revision of a
14790: hash.
14791: 
14792: B<Warning>: do not store the hash that restore returns directly. This
14793: will cause a mess since it will restore the historical keys as if the
14794: were new keys. I.E. 1:foo will become 1:1:foo etc.
14795: 
14796: Calling convention:
14797: 
14798:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14799:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14800: 
14801: For more detailed information, see lonnet specific documentation.
14802: 
14803: =head1 RETURN MESSAGES
14804: 
14805: =over 4
14806: 
14807: =item * B<con_lost>: unable to contact remote host
14808: 
14809: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14810: when the connection is brought back up
14811: 
14812: =item * B<con_failed>: unable to contact remote host and unable to save message
14813: for later delivery
14814: 
14815: =item * B<error:>: an error a occurred, a description of the error follows the :
14816: 
14817: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14818: that was requested
14819: 
14820: =back
14821: 
14822: =head1 PUBLIC SUBROUTINES
14823: 
14824: =head2 Session Environment Functions
14825: 
14826: =over 4
14827: 
14828: =item * 
14829: X<appenv()>
14830: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14831: the user envirnoment file, and will be restored for each access this
14832: user makes during this session, also modifies the %env for the current
14833: process. Optional rolesarrayref - if defined contains a reference to an array
14834: of roles which are exempt from the restriction on modifying user.role entries 
14835: in the user's environment.db and in %env.    
14836: 
14837: =item *
14838: X<delenv()>
14839: B<delenv($delthis,$regexp)>: removes all items from the session
14840: environment file that begin with $delthis. If the 
14841: optional second arg - $regexp - is true, $delthis is treated as a 
14842: regular expression, otherwise \Q$delthis\E is used. 
14843: The values are also deleted from the current processes %env.
14844: 
14845: =item * get_env_multiple($name) 
14846: 
14847: gets $name from the %env hash, it seemlessly handles the cases where multiple
14848: values may be defined and end up as an array ref.
14849: 
14850: returns an array of values
14851: 
14852: =back
14853: 
14854: =head2 User Information
14855: 
14856: =over 4
14857: 
14858: =item *
14859: X<queryauthenticate()>
14860: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14861: authentication scheme
14862: 
14863: =item *
14864: X<authenticate()>
14865: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14866: authenticate user from domain's lib servers (first use the current
14867: one). C<$upass> should be the users password.
14868: $checkdefauth is optional (value is 1 if a check should be made to
14869:    authenticate user using default authentication method, and allow
14870:    account creation if username does not have account in the domain).
14871: $clientcancheckhost is optional (value is 1 if checking whether the
14872:    server can host will occur on the client side in lonauth.pm).   
14873: 
14874: =item *
14875: X<homeserver()>
14876: B<homeserver($uname,$udom)>: find the server which has
14877: the user's directory and files (there must be only one), this caches
14878: the answer, and also caches if there is a borken connection.
14879: 
14880: =item *
14881: X<idget()>
14882: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14883: a list of student/employee IDs or clicker IDs
14884: (student/employee IDs are a unique resource in a domain, there must be 
14885: only 1 ID per username, and only 1 username per ID in a specific domain).
14886: clickerIDs are not necessarily unique, as students might share clickers.
14887: (returns hash: id=>name,id=>name)
14888: 
14889: =item *
14890: X<idrget()>
14891: B<idrget($udom,@unames)>: find the IDs behind a list of
14892: usernames (returns hash: name=>id,name=>id)
14893: 
14894: =item *
14895: X<idput()>
14896: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14897: names and associated student/employee IDs or clicker IDs.
14898: 
14899: =item *
14900: X<iddel()>
14901: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14902: student/employee ID or clicker ID username look-ups from domain.
14903: The homeserver ($uhome) and namespace ($namespace) are optional.
14904: If no $uhome is provided, it will be determined usig &homeserver()
14905: for each user.  If no $namespace is provided, the default is ids.
14906: 
14907: =item *
14908: X<updateclickers()>
14909: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14910: clicker ID-to-username look-ups in clickers.db on library server.
14911: Permitted actions are add or del (i.e., add or delete). The 
14912: clickers.db contains clickerID as keys (escaped), and each corresponding
14913: value is an escaped comma-separated list of usernames (for whom the
14914: library server is the homeserver), who registered that particular ID.
14915: If $critical is true, the update will be sent via &critical, otherwise
14916: &reply() will be used.
14917: 
14918: =item *
14919: X<rolesinit()>
14920: B<rolesinit($udom,$username)>: get user privileges.
14921: returns user role, first access and timer interval hashes
14922: 
14923: =item *
14924: X<privileged()>
14925: B<privileged($username,$domain)>: returns a true if user has a
14926: privileged and active role (i.e. su or dc), false otherwise.
14927: 
14928: =item *
14929: X<getsection()>
14930: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14931: course $cname, return section name/number or '' for "not in course"
14932: and '-1' for "no section"
14933: 
14934: =item *
14935: X<userenvironment()>
14936: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14937: passed in @what from the requested user's environment, returns a hash
14938: 
14939: =item * 
14940: X<userlog_query()>
14941: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14942: activity.log file. %filters defines filters applied when parsing the
14943: log file. These can be start or end timestamps, or the type of action
14944: - log to look for Login or Logout events, check for Checkin or
14945: Checkout, role for role selection. The response is in the form
14946: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14947: escaped strings of the action recorded in the activity.log file.
14948: 
14949: =back
14950: 
14951: =head2 User Roles
14952: 
14953: =over 4
14954: 
14955: =item *
14956: 
14957: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14958: returns codes for allowed actions.
14959: 
14960: The first argument is required, all others are optional.
14961: 
14962: $priv is the privilege being checked.
14963: $uri contains additional information about what is being checked for access (e.g.,
14964: URL, course ID etc.). 
14965: $symb is the unique resource instance identifier in a course; if needed,
14966: but not provided, it will be retrieved via a call to &symbread(). 
14967: $role is the role for which a priv is being checked (only used if priv is evb). 
14968: $clientip is the user's IP address (only used when checking for access to portfolio 
14969: files).
14970: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14971: prevents recursive calls to &allowed.
14972: 
14973:  F: full access
14974:  U,I,K: authentication modes (cxx only)
14975:  '': forbidden
14976:  1: user needs to choose course
14977:  2: browse allowed
14978:  A: passphrase authentication needed
14979:  B: access temporarily blocked because of a blocking event in a course.
14980: 
14981: =item *
14982: 
14983: constructaccess($url,$setpriv) : check for access to construction space URL
14984: 
14985: See if the owner domain and name in the URL match those in the
14986: expected environment.  If so, return three element list
14987: ($ownername,$ownerdomain,$ownerhome).
14988: 
14989: Otherwise return the null string.
14990: 
14991: If second argument 'setpriv' is true, it assigns the privileges,
14992: and returns the same three element list, unless the owner has
14993: blocked "ad hoc" Domain Coordinator access to the Author Space,
14994: in which case the null string is returned.
14995: 
14996: =item *
14997: 
14998: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14999: define a custom role rolename set privileges in format of lonTabs/roles.tab
15000: for system, domain, and course level. $uname and $udom are optional (current
15001: user's username and domain will be used when either of $uname or $udom are absent.
15002: 
15003: =item *
15004: 
15005: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15006: (rolesplain.tab); plain text explanation of a user role term.
15007: $type is Course (default) or Community.
15008: If $forcedefault evaluates to true, text returned will be default 
15009: text for $type. Otherwise, if this is a course, the text returned 
15010: will be a custom name for the role (if defined in the course's 
15011: environment).  If no custom name is defined the default is returned.
15012:    
15013: =item *
15014: 
15015: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15016: All arguments are optional. Returns a hash of a roles, either for
15017: co-author/assistant author roles for a user's Construction Space
15018: (default), or if $context is 'userroles', roles for the user himself,
15019: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15020: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15021: For each key, value is set to colon-separated start and end times for
15022: the role.  If no username and domain are specified, will default to
15023: current user/domain. Types, roles, and roledoms are references to arrays
15024: of role statuses (active, future or previous), roles 
15025: (e.g., cc,in, st etc.) and domains of the roles which can be used
15026: to restrict the list of roles reported. If no array ref is 
15027: provided for types, will default to return only active roles.
15028: 
15029: =item *
15030: 
15031: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15032: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15033: 
15034: Additional optional arguments are: $type (if role checking is to be restricted 
15035: to certain user status types -- previous (expired roles), active (currently
15036: available roles) or future (roles available in the future), and
15037: $hideprivileged -- if true will not report course roles for users who
15038: have active Domain Coordinator role in course's domain or in additional
15039: domains (specified in 'Domains to check for privileged users' in course
15040: environment -- set via:  Course Settings -> Classlists and staff listing).
15041: 
15042: =item *
15043: 
15044: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15045: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15046: $possdomains and $possroles are optional array refs -- to domains to check and
15047: roles to check.  If $possdomains is not specified, a dump will be done of the
15048: users' roles.db to check for a dc or su role in any domain. This can be
15049: time consuming if &privileged is called repeatedly (e.g., when displaying a
15050: classlist), so in such cases, supplying a $possdomains array is preferred, as
15051: this then allows &privileged_by_domain() to be used, which caches the identity
15052: of privileged users, eliminating the need for repeated calls to &dump().
15053: 
15054: =item *
15055: 
15056: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15057: where the outer hash keys are domains specified in the $possdomains array ref,
15058: next inner hash keys are privileged roles specified in the $roles array ref,
15059: and the innermost hash contains key = value pairs for username:domain = end:start
15060: for active or future "privileged" users with that role in that domain. To avoid
15061: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15062: innerhash are cached using priv_$role and $dom as the identifiers.
15063: 
15064: =back
15065: 
15066: =head2 User Modification
15067: 
15068: =over 4
15069: 
15070: =item *
15071: 
15072: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15073: user for the level given by URL.  Optional start and end dates (leave empty
15074: string or zero for "no date")
15075: 
15076: =item *
15077: 
15078: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15079: change a users, password, possible return values are: ok,
15080: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15081: refused
15082: 
15083: =item *
15084: 
15085: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15086: 
15087: =item *
15088: 
15089: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15090:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15091: 
15092: will update user information (firstname,middlename,lastname,generation,
15093: permanentemail), and if forceid is true, student/employee ID also.
15094: A user's institutional affiliation(s) can also be updated.
15095: User information fields will not be overwritten with empty entries 
15096: unless the field is included in the $candelete array reference.
15097: This array is included when a single user is modified via "Manage Users",
15098: or when Autoupdate.pl is run by cron in a domain.
15099: 
15100: =item *
15101: 
15102: modifystudent
15103: 
15104: modify a student's enrollment and identification information.
15105: The course id is resolved based on the current user's environment.  
15106: This means the invoking user must be a course coordinator or otherwise
15107: associated with a course.
15108: 
15109: This call is essentially a wrapper for lonnet::modifyuser and
15110: lonnet::modify_student_enrollment
15111: 
15112: Inputs: 
15113: 
15114: =over 4
15115: 
15116: =item B<$udom> Student's loncapa domain
15117: 
15118: =item B<$uname> Student's loncapa login name
15119: 
15120: =item B<$uid> Student/Employee ID
15121: 
15122: =item B<$umode> Student's authentication mode
15123: 
15124: =item B<$upass> Student's password
15125: 
15126: =item B<$first> Student's first name
15127: 
15128: =item B<$middle> Student's middle name
15129: 
15130: =item B<$last> Student's last name
15131: 
15132: =item B<$gene> Student's generation
15133: 
15134: =item B<$usec> Student's section in course
15135: 
15136: =item B<$end> Unix time of the roles expiration
15137: 
15138: =item B<$start> Unix time of the roles start date
15139: 
15140: =item B<$forceid> If defined, allow $uid to be changed
15141: 
15142: =item B<$desiredhome> server to use as home server for student
15143: 
15144: =item B<$email> Student's permanent e-mail address
15145: 
15146: =item B<$type> Type of enrollment (auto or manual)
15147: 
15148: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15149: 
15150: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15151: 
15152: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15153: 
15154: =item B<$context> role change context (shown in User Management Logs display in a course)
15155: 
15156: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15157: 
15158: =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.
15159: 
15160: =back
15161: 
15162: =item *
15163: 
15164: modify_student_enrollment
15165: 
15166: Change a student's enrollment status in a class.  The environment variable
15167: 'role.request.course' must be defined for this function to proceed.
15168: 
15169: Inputs:
15170: 
15171: =over 4
15172: 
15173: =item $udom, student's domain
15174: 
15175: =item $uname, student's name
15176: 
15177: =item $uid, student's user id
15178: 
15179: =item $first, student's first name
15180: 
15181: =item $middle
15182: 
15183: =item $last
15184: 
15185: =item $gene
15186: 
15187: =item $usec
15188: 
15189: =item $end
15190: 
15191: =item $start
15192: 
15193: =item $type
15194: 
15195: =item $locktype
15196: 
15197: =item $cid
15198: 
15199: =item $selfenroll
15200: 
15201: =item $context
15202: 
15203: =item $credits, number of credits student will earn from this class
15204: 
15205: =item $instsec, institutional course section code for student
15206: 
15207: =back
15208: 
15209: 
15210: =item *
15211: 
15212: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15213: custom role; give a custom role to a user for the level given by URL.  Specify
15214: name and domain of role author, and role name
15215: 
15216: =item *
15217: 
15218: revokerole($udom,$uname,$url,$role) : revoke a role for url
15219: 
15220: =item *
15221: 
15222: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15223: 
15224: =back
15225: 
15226: =head2 Course Infomation
15227: 
15228: =over 4
15229: 
15230: =item *
15231: 
15232: coursedescription($courseid,$options) : returns a hash of information about the
15233: specified course id, including all environment settings for the
15234: course, the description of the course will be in the hash under the
15235: key 'description'
15236: 
15237: $options is an optional parameter that if supplied is a hash reference that controls
15238: what how this function works.  It has the following key/values:
15239: 
15240: =over 4
15241: 
15242: =item freshen_cache
15243: 
15244: If defined, and the environment cache for the course is valid, it is 
15245: returned in the returned hash.
15246: 
15247: =item one_time
15248: 
15249: If defined, the last cache time is set to _now_
15250: 
15251: =item user
15252: 
15253: If defined, the supplied username is used instead of the current user.
15254: 
15255: 
15256: =back
15257: 
15258: =item *
15259: 
15260: resdata($name,$domain,$type,@which) : request for current parameter
15261: setting for a specific $type, where $type is either 'course' or 'user',
15262: @what should be a list of parameters to ask about. This routine caches
15263: answers for 10 minutes.
15264: 
15265: =item *
15266: 
15267: get_courseresdata($courseid, $domain) : dump the entire course resource
15268: data base, returning a hash that is keyed by the resource name and has
15269: values that are the resource value.  I believe that the timestamps and
15270: versions are also returned.
15271: 
15272: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15273: supplemental content area. This routine caches the number of files for 
15274: 10 minutes.
15275: 
15276: =back
15277: 
15278: =head2 Course Modification
15279: 
15280: =over 4
15281: 
15282: =item *
15283: 
15284: writecoursepref($courseid,%prefs) : write preferences (environment
15285: database) for a course
15286: 
15287: =item *
15288: 
15289: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15290: 
15291: =item *
15292: 
15293: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15294: 
15295: =item *
15296: 
15297: is_course($courseid), is_course($cdom, $cnum)
15298: 
15299: Accepts either a combined $courseid (in the form of domain_courseid) or the
15300: two component version $cdom, $cnum. It checks if the specified course exists.
15301: 
15302: Returns:
15303:     undef if the course doesn't exist, otherwise
15304:     in scalar context the combined courseid.
15305:     in list context the two components of the course identifier, domain and 
15306:     courseid.    
15307: 
15308: =back
15309: 
15310: =head2 Bubblesheet Configuration
15311: 
15312: =over 4
15313: 
15314: =item *
15315: 
15316: get_scantron_config($which)
15317: 
15318: $which - the name of the configuration to parse from the file.
15319: 
15320: Parses and returns the bubblesheet configuration line selected as a
15321: hash of configuration file fields.
15322: 
15323: 
15324: Returns:
15325:     If the named configuration is not in the file, an empty
15326:     hash is returned.
15327: 
15328:     a hash with the fields
15329:       name         - internal name for the this configuration setup
15330:       description  - text to display to operator that describes this config
15331:       CODElocation - if 0 or the string 'none'
15332:                           - no CODE exists for this config
15333:                      if -1 || the string 'letter'
15334:                           - a CODE exists for this config and is
15335:                             a string of letters
15336:                      Unsupported value (but planned for future support)
15337:                           if a positive integer
15338:                                - The CODE exists as the first n items from
15339:                                  the question section of the form
15340:                           if the string 'number'
15341:                                - The CODE exists for this config and is
15342:                                  a string of numbers
15343:       CODEstart   - (only matter if a CODE exists) column in the line where
15344:                      the CODE starts
15345:       CODElength  - length of the CODE
15346:       IDstart     - column where the student/employee ID starts
15347:       IDlength    - length of the student/employee ID info
15348:       Qstart      - column where the information from the bubbled
15349:                     'questions' start
15350:       Qlength     - number of columns comprising a single bubble line from
15351:                     the sheet. (usually either 1 or 10)
15352:       Qon         - either a single character representing the character used
15353:                     to signal a bubble was chosen in the positional setup, or
15354:                     the string 'letter' if the letter of the chosen bubble is
15355:                     in the final, or 'number' if a number representing the
15356:                     chosen bubble is in the file (1->A 0->J)
15357:       Qoff        - the character used to represent that a bubble was
15358:                     left blank
15359:       PaperID     - if the scanning process generates a unique number for each
15360:                     sheet scanned the column that this ID number starts in
15361:       PaperIDlength - number of columns that comprise the unique ID number
15362:                       for the sheet of paper
15363:       FirstName   - column that the first name starts in
15364:       FirstNameLength - number of columns that the first name spans
15365: 
15366:       LastName    - column that the last name starts in
15367:       LastNameLength - number of columns that the last name spans
15368:       BubblesPerRow - number of bubbles available in each row used to
15369:                       bubble an answer. (If not specified, 10 assumed).
15370: 
15371: 
15372: =item *
15373: 
15374: get_scantronformat_file($cdom)
15375: 
15376: $cdom - the course's domain (optional); if not supplied, uses
15377: domain for current $env{'request.course.id'}.
15378: 
15379: Returns an array containing lines from the scantron format file for
15380: the domain of the course.
15381: 
15382: If a url for a custom.tab file is listed in domain's configuration.db,
15383: lines are from this file.
15384: 
15385: Otherwise, if a default.tab has been published in RES space by the
15386: domainconfig user, lines are from this file.
15387: 
15388: Otherwise, fall back to getting lines from the legacy file on the
15389: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15390: 
15391: =back
15392: 
15393: =head2 Resource Subroutines
15394: 
15395: =over 4
15396: 
15397: =item *
15398: 
15399: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15400: 
15401: =item *
15402: 
15403: repcopy($filename) : subscribes to the requested file, and attempts to
15404: replicate from the owning library server, Might return
15405: 'unavailable', 'not_found', 'forbidden', 'ok', or
15406: 'bad_request', also attempts to grab the metadata for the
15407: resource. Expects the local filesystem pathname
15408: (/home/httpd/html/res/....)
15409: 
15410: =back
15411: 
15412: =head2 Resource Information
15413: 
15414: =over 4
15415: 
15416: =item *
15417: 
15418: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15419: and returns the value of a variety of different possible values,
15420: $varname should be a request string, and the other parameters can be
15421: used to specify who and what one is asking about. Ordinarily, $cid 
15422: does not need to be specified, as it is retrived from 
15423: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15424: within lonuserstate::loadmap() when initializing a course, before
15425: $env{'request.course.id'} has been set, so it needs to be provided
15426: in that one case.
15427: 
15428: Possible values for $varname are environment.lastname (or other item
15429: from the envirnment hash), user.name (or someother aspect about the
15430: user), resource.0.maxtries (or some other part and parameter of a
15431: resource)
15432: 
15433: =item *
15434: 
15435: directcondval($number) : get current value of a condition; reads from a state
15436: string
15437: 
15438: =item *
15439: 
15440: condval($condidx) : value of condition index based on state
15441: 
15442: =item *
15443: 
15444: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15445: resource's metadata, $what should be either a specific key, or either
15446: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15447: packages that this resource currently uses, the last 3 arguments are 
15448: only used internally for recursive metadata.
15449: 
15450: the toolsymb is only used where the uri is for an external tool (for which
15451: the uri as well as the symb are guaranteed to be unique).
15452: 
15453: this function automatically caches all requests except any made recursively
15454: to retrieve a list of metadata keys for an imported library file ($liburi is 
15455: defined).
15456: 
15457: =item *
15458: 
15459: metadata_query($query,$custom,$customshow) : make a metadata query against the
15460: network of library servers; returns file handle of where SQL and regex results
15461: will be stored for query
15462: 
15463: =item *
15464: 
15465: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15466: return symbolic list entry (all arguments optional). 
15467: 
15468: Args: filename is the filename (including path) for the file for which a symb 
15469: is required; donotrecurse, if true will prevent calls to allowed() being made 
15470: to check access status if more than one resource was found in the bighash 
15471: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15472: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15473: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15474: cause possible symbs to be checked to determine if they are subject to content
15475: blocking, if so they will not be included as possible symbs; possibles is a
15476: ref to a hash, which, as a side effect, will be populated with all possible 
15477: symbs (content blocking not tested).
15478:  
15479: returns the data handle
15480: 
15481: =item *
15482: 
15483: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15484: and is a possible symb for the URL in $thisfn, and if is an encrypted
15485: resource that the user accessed using /enc/ returns a 1 on success, 0
15486: on failure, user must be in a course, as it assumes the existence of
15487: the course initial hash, and uses $env('request.course.id'}.  The third
15488: arg is an optional reference to a scalar.  If this arg is passed in the 
15489: call to symbverify, it will be set to 1 if the symb has been set to be 
15490: encrypted; otherwise it will be null.  
15491: 
15492: =item *
15493: 
15494: symbclean($symb) : removes versions numbers from a symb, returns the
15495: cleaned symb
15496: 
15497: =item *
15498: 
15499: is_on_map($uri) : checks if the $uri is somewhere on the current
15500: course map, user must be in a course for it to work.
15501: 
15502: =item *
15503: 
15504: numval($salt) : return random seed value (addend for rndseed)
15505: 
15506: =item *
15507: 
15508: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15509: a random seed, all arguments are optional, if they aren't sent it uses the
15510: environment to derive them. Note: if symb isn't sent and it can't get one
15511: from &symbread it will use the current time as its return value
15512: 
15513: =item *
15514: 
15515: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15516: unfakeable, receipt
15517: 
15518: =item *
15519: 
15520: receipt() : API to ireceipt working off of env values; given out to users
15521: 
15522: =item *
15523: 
15524: countacc($url) : count the number of accesses to a given URL
15525: 
15526: =item *
15527: 
15528: 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
15529: 
15530: =item *
15531: 
15532: 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)
15533: 
15534: =item *
15535: 
15536: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15537: 
15538: =item *
15539: 
15540: devalidate($symb) : devalidate temporary spreadsheet calculations,
15541: forcing spreadsheet to reevaluate the resource scores next time.
15542: 
15543: =item * 
15544: 
15545: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15546: when viewing in course context.
15547: 
15548:  input: six args -- filename (decluttered), course number, course domain,
15549:                     url, symb (if registered) and group (if this is a 
15550:                     group item -- e.g., bulletin board, group page etc.).
15551: 
15552:  output: array of five scalars --
15553:          $cfile -- url for file editing if editable on current server
15554:          $home -- homeserver of resource (i.e., for author if published,
15555:                                           or course if uploaded.).
15556:          $switchserver --  1 if server switch will be needed.
15557:          $forceedit -- 1 if icon/link should be to go to edit mode 
15558:          $forceview -- 1 if icon/link should be to go to view mode
15559: 
15560: =item *
15561: 
15562: is_course_upload($file,$cnum,$cdom)
15563: 
15564: Used in course context to determine if current file was uploaded to 
15565: the course (i.e., would be found in /userfiles/docs on the course's 
15566: homeserver.
15567: 
15568:   input: 3 args -- filename (decluttered), course number and course domain.
15569:   output: boolean -- 1 if file was uploaded.
15570: 
15571: =back
15572: 
15573: =head2 Storing/Retreiving Data
15574: 
15575: =over 4
15576: 
15577: =item *
15578: 
15579: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15580: permanently for this url; hashref needs to be given and should be a \%hashname;
15581: the remaining args aren't required and if they aren't passed or are '' they will
15582: be derived from the env (with the exception of $laststore, which is an 
15583: optional arg used when a user's submission is stored in grading).
15584: $laststore is $version=$timestamp, where $version is the most recent version
15585: number retrieved for the corresponding $symb in the $namespace db file, and
15586: $timestamp is the timestamp for that transaction (UNIX time).
15587: $laststore is currently only passed when cstore() is called by 
15588: structuretags::finalize_storage().
15589: 
15590: =item *
15591: 
15592: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15593: but uses critical subroutine
15594: 
15595: =item *
15596: 
15597: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15598: all args are optional
15599: 
15600: =item *
15601: 
15602: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15603: dumps the complete (or key matching regexp) namespace into a hash
15604: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15605: normally &store()ed into
15606: 
15607: $range should be either an integer '100' (give me the first 100
15608:                                            matching records)
15609:               or be  two integers sperated by a - with no spaces
15610:                  '30-50' (give me the 30th through the 50th matching
15611:                           records)
15612: 
15613: 
15614: =item *
15615: 
15616: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15617: replaces a &store() version of data with a replacement set of data
15618: for a particular resource in a namespace passed in the $storehash hash 
15619: reference. If $tolog is true, the transaction is logged in the courselog
15620: with an action=PUTSTORE.
15621: 
15622: =item *
15623: 
15624: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15625: works very similar to store/cstore, but all data is stored in a
15626: temporary location and can be reset using tmpreset, $storehash should
15627: be a hash reference, returns nothing on success
15628: 
15629: =item *
15630: 
15631: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15632: similar to restore, but all data is stored in a temporary location and
15633: can be reset using tmpreset. Returns a hash of values on success,
15634: error string otherwise.
15635: 
15636: =item *
15637: 
15638: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15639: deltes all keys for $symb form the temporary storage hash.
15640: 
15641: =item *
15642: 
15643: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15644: reference filled in from namesp ($udom and $uname are optional)
15645: 
15646: =item *
15647: 
15648: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15649: namesp ($udom and $uname are optional)
15650: 
15651: =item *
15652: 
15653: dump($namespace,$udom,$uname,$regexp,$range) : 
15654: dumps the complete (or key matching regexp) namespace into a hash
15655: ($udom, $uname, $regexp, $range are optional)
15656: 
15657: $range should be either an integer '100' (give me the first 100
15658:                                            matching records)
15659:               or be  two integers sperated by a - with no spaces
15660:                  '30-50' (give me the 30th through the 50th matching
15661:                           records)
15662: =item *
15663: 
15664: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15665: $store can be a scalar, an array reference, or if the amount to be 
15666: incremented is > 1, a hash reference.
15667: 
15668: ($udom and $uname are optional)
15669: 
15670: =item *
15671: 
15672: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15673: ($udom and $uname are optional)
15674: 
15675: =item *
15676: 
15677: cput($namespace,$storehash,$udom,$uname) : critical put
15678: ($udom and $uname are optional)
15679: 
15680: =item *
15681: 
15682: newput($namespace,$storehash,$udom,$uname) :
15683: 
15684: Attempts to store the items in the $storehash, but only if they don't
15685: currently exist, if this succeeds you can be certain that you have 
15686: successfully created a new key value pair in the $namespace db.
15687: 
15688: 
15689: Args:
15690:  $namespace: name of database to store values to
15691:  $storehash: hashref to store to the db
15692:  $udom: (optional) domain of user containing the db
15693:  $uname: (optional) name of user caontaining the db
15694: 
15695: Returns:
15696:  'ok' -> succeeded in storing all keys of $storehash
15697:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15698:                         least <key> already existed in the db (other
15699:                         requested keys may also already exist)
15700:  'error: <msg>' -> unable to tie the DB or other error occurred
15701:  'con_lost' -> unable to contact request server
15702:  'refused' -> action was not allowed by remote machine
15703: 
15704: 
15705: =item *
15706: 
15707: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15708: reference filled in from namesp (encrypts the return communication)
15709: ($udom and $uname are optional)
15710: 
15711: =item *
15712: 
15713: log($udom,$name,$home,$message) : write to permanent log for user; use
15714: critical subroutine
15715: 
15716: =item *
15717: 
15718: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15719: array reference filled in from namespace found in domain level on either
15720: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15721: 
15722: =item *
15723: 
15724: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15725: domain level either on specified domain server ($uhome) or primary domain 
15726: server ($udom and $uhome are optional)
15727: 
15728: =item * 
15729: 
15730: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15731: for: authentication, language, quotas, timezone, date locale, and portal URL in
15732: the target domain.
15733: 
15734: May also include additional key => value pairs for the following groups:
15735: 
15736: =over
15737: 
15738: =item
15739: disk quotas (MB allocated by default to portfolios and authoring spaces).
15740: 
15741: =over
15742: 
15743: =item defaultquota, authorquota
15744: 
15745: =back
15746: 
15747: =item
15748: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15749: portfolio for users).
15750: 
15751: =over
15752: 
15753: =item
15754: aboutme, blog, webdav, portfolio
15755: 
15756: =back
15757: 
15758: =item
15759: requestcourses: ability to request courses, and how requests are processed.
15760: 
15761: =over
15762: 
15763: =item
15764: official, unofficial, community, textbook, placement
15765: 
15766: =back
15767: 
15768: =item
15769: inststatus: types of institutional affiliation, and order in which they are displayed.
15770: 
15771: =over
15772: 
15773: =item
15774: inststatustypes, inststatusorder, inststatusguest
15775: 
15776: =back
15777: 
15778: =item
15779: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15780: for course's uploaded content.
15781: 
15782: =over
15783: 
15784: =item
15785: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15786: communityquota, textbookquota, placementquota
15787: 
15788: =back
15789: 
15790: =item
15791: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15792: on your servers.
15793: 
15794: =over
15795: 
15796: =item 
15797: remotesessions, hostedsessions
15798: 
15799: =back
15800: 
15801: =back
15802: 
15803: In cases where a domain coordinator has never used the "Set Domain Configuration"
15804: utility to create a configuration.db file on a domain's primary library server 
15805: only the following domain defaults: auth_def, auth_arg_def, lang_def
15806: -- corresponding values are authentication type (internal, krb4, krb5,
15807: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15808: will be available. Values are retrieved from cache (if current), unless the
15809: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15810: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15811: 
15812: Typical usage:
15813: 
15814: %domdefaults = &get_domain_defaults($target_domain);
15815: 
15816: =back
15817: 
15818: =head2 Network Status Functions
15819: 
15820: =over 4
15821: 
15822: =item *
15823: 
15824: dirlist() : return directory list based on URI (first arg).
15825: 
15826: Inputs: 1 required, 5 optional.
15827: 
15828: =over
15829: 
15830: =item 
15831: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15832: 
15833: =item
15834: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15835: 
15836: =item
15837: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15838: 
15839: =item
15840: $getpropath - boolean: 1 if prepend path using &propath(). 
15841: 
15842: =item
15843: $getuserdir - boolean: 1 if prepend path for "userfiles".
15844: 
15845: =item 
15846: $alternateRoot - path to prepend in place of path from $uri.
15847: 
15848: =back
15849: 
15850: Returns: Array of up to two items.
15851: 
15852: =over
15853: 
15854: a reference to an array of files/subdirectories
15855: 
15856: =over
15857: 
15858: Each element in the array of files/subdirectories is a & separated list of
15859: item name and the result of running stat on the item.  If dirlist was requested
15860: for a file instead of a directory, the item name will be ''. For a directory 
15861: listing, if the item is a metadata file, the element will end &N&M 
15862: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15863: default copyright set (1).  
15864: 
15865: =back
15866: 
15867: a scalar containing error condition (if encountered).
15868: 
15869: =over
15870: 
15871: =item 
15872: no_host (no homeserver identified for $username:$domain).
15873: 
15874: =item 
15875: no_such_host (server contacted for listing not identified as valid host).
15876: 
15877: =item 
15878: con_lost (connection to remote server failed).
15879: 
15880: =item 
15881: refused (invalid $username:$domain received on lond side).
15882: 
15883: =item 
15884: no_such_dir (directory at specified path on lond side does not exist). 
15885: 
15886: =item 
15887: empty (directory at specified path on lond side is empty).
15888: 
15889: =over
15890: 
15891: This is currently not encountered because the &ls3, &ls2, 
15892: &ls (_handler) routines on the lond side do not filter out
15893: . and .. from a directory listing. 
15894: 
15895: =back
15896: 
15897: =back
15898: 
15899: =back
15900: 
15901: =item *
15902: 
15903: spareserver() : find server with least workload from spare.tab
15904: 
15905: 
15906: =item *
15907: 
15908: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15909: if there is no corresponding loncapa host.
15910: 
15911: =back
15912: 
15913: 
15914: =head2 Apache Request
15915: 
15916: =over 4
15917: 
15918: =item *
15919: 
15920: ssi($url,%hash) : server side include, does a complete request cycle on url to
15921: localhost, posts hash
15922: 
15923: =back
15924: 
15925: =head2 Data to String to Data
15926: 
15927: =over 4
15928: 
15929: =item *
15930: 
15931: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15932: and '&' separators, supports elements that are arrayrefs and hashrefs
15933: 
15934: =item *
15935: 
15936: hashref2str($hashref) : convert a hashref into a string complete with
15937: escaping and '=' and '&' separators, supports elements that are
15938: arrayrefs and hashrefs
15939: 
15940: =item *
15941: 
15942: arrayref2str($arrayref) : convert an arrayref into a string complete
15943: with escaping and '&' separators, supports elements that are arrayrefs
15944: and hashrefs
15945: 
15946: =item *
15947: 
15948: str2hash($string) : convert string to hash using unescaping and
15949: splitting on '=' and '&', supports elements that are arrayrefs and
15950: hashrefs
15951: 
15952: =item *
15953: 
15954: str2array($string) : convert string to hash using unescaping and
15955: splitting on '&', supports elements that are arrayrefs and hashrefs
15956: 
15957: =back
15958: 
15959: =head2 Logging Routines
15960: 
15961: 
15962: These routines allow one to make log messages in the lonnet.log and
15963: lonnet.perm logfiles.
15964: 
15965: =over 4
15966: 
15967: =item *
15968: 
15969: logtouch() : make sure the logfile, lonnet.log, exists
15970: 
15971: =item *
15972: 
15973: logthis() : append message to the normal lonnet.log file, it gets
15974: preiodically rolled over and deleted.
15975: 
15976: =item *
15977: 
15978: logperm() : append a permanent message to lonnet.perm.log, this log
15979: file never gets deleted by any automated portion of the system, only
15980: messages of critical importance should go in here.
15981: 
15982: 
15983: =back
15984: 
15985: =head2 General File Helper Routines
15986: 
15987: =over 4
15988: 
15989: =item *
15990: 
15991: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15992: (a) files in /uploaded
15993:   (i) If a local copy of the file exists - 
15994:       compares modification date of local copy with last-modified date for 
15995:       definitive version stored on home server for course. If local copy is 
15996:       stale, requests a new version from the home server and stores it. 
15997:       If the original has been removed from the home server, then local copy 
15998:       is unlinked.
15999:   (ii) If local copy does not exist -
16000:       requests the file from the home server and stores it. 
16001:   
16002:   If $caller is 'uploadrep':  
16003:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16004:     for request for files originally uploaded via DOCS. 
16005:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16006:   
16007:   Otherwise:
16008:      This indicates a call from the content generation phase of the request.
16009:      -  returns the entire contents of the file or -1.
16010:      
16011: (b) files in /res
16012:    - returns the entire contents of a file or -1; 
16013:    it properly subscribes to and replicates the file if neccessary.
16014: 
16015: 
16016: =item *
16017: 
16018: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16019:                   reference
16020: 
16021: returns either a stat() list of data about the file or an empty list
16022: if the file doesn't exist or couldn't find out about it (connection
16023: problems or user unknown)
16024: 
16025: =item *
16026: 
16027: filelocation($dir,$file) : returns file system location of a file
16028: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16029: directory that relative $file lookups are to looked in ($dir of /a/dir
16030: and a file of ../bob will become /a/bob)
16031: 
16032: =item *
16033: 
16034: hreflocation($dir,$file) : returns file system location or a URL; same as
16035: filelocation except for hrefs
16036: 
16037: =item *
16038: 
16039: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16040: also removes beginning /home/httpd/html unless /priv/ follows it.
16041: 
16042: =back
16043: 
16044: =head2 Usererfile file routines (/uploaded*)
16045: 
16046: =over 4
16047: 
16048: =item *
16049: 
16050: userfileupload(): main rotine for putting a file in a user or course's
16051:                   filespace, arguments are,
16052: 
16053:  formname - required - this is the name of the element in $env where the
16054:            filename, and the contents of the file to create/modifed exist
16055:            the filename is in $env{'form.'.$formname.'.filename'} and the
16056:            contents of the file is located in $env{'form.'.$formname}
16057:  context - if coursedoc, store the file in the course of the active role
16058:              of the current user; 
16059:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16060:            if 'canceloverwrite': delete file in tmp/overwrites directory
16061:  subdir - required - subdirectory to put the file in under ../userfiles/
16062:          if undefined, it will be placed in "unknown"
16063: 
16064:  (This routine calls clean_filename() to remove any dangerous
16065:  characters from the filename, and then calls finuserfileupload() to
16066:  complete the transaction)
16067: 
16068:  returns either the url of the uploaded file (/uploaded/....) if successful
16069:  and /adm/notfound.html if unsuccessful
16070: 
16071: =item *
16072: 
16073: clean_filename(): routine for cleaing a filename up for storage in
16074:                  userfile space, argument is:
16075: 
16076:  filename - proposed filename
16077: 
16078: returns: the new clean filename
16079: 
16080: =item *
16081: 
16082: finishuserfileupload(): routine that creates and sends the file to
16083: userspace, probably shouldn't be called directly
16084: 
16085:   docuname: username or courseid of destination for the file
16086:   docudom: domain of user/course of destination for the file
16087:   formname: same as for userfileupload()
16088:   fname: filename (including subdirectories) for the file
16089:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16090:           if hashref, and context is scantron, will convert csv format to standard format
16091:   allfiles: reference to hash used to store objects found by parser
16092:   codebase: reference to hash used for codebases of java objects found by parser
16093:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16094:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16095:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16096:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16097:   context: if 'overwrite', will move the uploaded file from its temporary location to
16098:             userfiles to facilitate overwriting a previously uploaded file with same name.
16099:   mimetype: reference to scalar to accommodate mime type determined
16100:             from File::MMagic if $parser = parse.
16101: 
16102:  returns either the url of the uploaded file (/uploaded/....) if successful
16103:  and /adm/notfound.html if unsuccessful (or an error message if context 
16104:  was 'overwrite').
16105:  
16106: 
16107: =item *
16108: 
16109: renameuserfile(): renames an existing userfile to a new name
16110: 
16111:   Args:
16112:    docuname: username or courseid of destination for the file
16113:    docudom: domain of user/course of destination for the file
16114:    old: current file name (including any subdirs under userfiles)
16115:    new: desired file name (including any subdirs under userfiles)
16116: 
16117: =item *
16118: 
16119: mkdiruserfile(): creates a directory is a userfiles dir
16120: 
16121:   Args:
16122:    docuname: username or courseid of destination for the file
16123:    docudom: domain of user/course of destination for the file
16124:    dir: dir to create (including any subdirs under userfiles)
16125: 
16126: =item *
16127: 
16128: removeuserfile(): removes a file that exists in userfiles
16129: 
16130:   Args:
16131:    docuname: username or courseid of destination for the file
16132:    docudom: domain of user/course of destination for the file
16133:    fname: filname to delete (including any subdirs under userfiles)
16134: 
16135: =item *
16136: 
16137: removeuploadedurl(): convience function for removeuserfile()
16138: 
16139:   Args:
16140:    url:  a full /uploaded/... url to delete
16141: 
16142: =item * 
16143: 
16144: get_portfile_permissions():
16145:   Args:
16146:     domain: domain of user or course contain the portfolio files
16147:     user: name of user or num of course contain the portfolio files
16148:   Returns:
16149:     hashref of a dump of the proper file_permissions.db
16150:    
16151: 
16152: =item * 
16153: 
16154: get_access_controls():
16155: 
16156: Args:
16157:   current_permissions: the hash ref returned from get_portfile_permissions()
16158:   group: (optional) the group you want the files associated with
16159:   file: (optional) the file you want access info on
16160: 
16161: Returns:
16162:     a hash (keys are file names) of hashes containing
16163:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16164:         values are XML containing access control settings (see below) 
16165: 
16166: Internal notes:
16167: 
16168:  access controls are stored in file_permissions.db as key=value pairs.
16169:     key -> path to file/file_name\0uniqueID:scope_end_start
16170:         where scope -> public,guest,course,group,domains or users.
16171:               end -> UNIX time for end of access (0 -> no end date)
16172:               start -> UNIX time for start of access
16173: 
16174:     value -> XML description of access control
16175:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16176:             <start></start>
16177:             <end></end>
16178: 
16179:             <password></password>  for scope type = guest
16180: 
16181:             <domain></domain>     for scope type = course or group
16182:             <number></number>
16183:             <roles id="">
16184:              <role></role>
16185:              <access></access>
16186:              <section></section>
16187:              <group></group>
16188:             </roles>
16189: 
16190:             <dom></dom>         for scope type = domains
16191: 
16192:             <users>             for scope type = users
16193:              <user>
16194:               <uname></uname>
16195:               <udom></udom>
16196:              </user>
16197:             </users>
16198:            </scope> 
16199:               
16200:  Access data is also aggregated for each file in an additional key=value pair:
16201:  key -> path to file/file_name\0accesscontrol 
16202:  value -> reference to hash
16203:           hash contains key = value pairs
16204:           where key = uniqueID:scope_end_start
16205:                 value = UNIX time record was last updated
16206: 
16207:           Used to improve speed of look-ups of access controls for each file.  
16208:  
16209:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16210: 
16211: =item *
16212: 
16213: modify_access_controls():
16214: 
16215: Modifies access controls for a portfolio file
16216: Args
16217: 1. file name
16218: 2. reference to hash of required changes,
16219: 3. domain
16220: 4. username
16221:   where domain,username are the domain of the portfolio owner 
16222:   (either a user or a course) 
16223: 
16224: Returns:
16225: 1. result of additions or updates ('ok' or 'error', with error message). 
16226: 2. result of deletions ('ok' or 'error', with error message).
16227: 3. reference to hash of any new or updated access controls.
16228: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16229:    key = integer (inbound ID)
16230:    value = uniqueID
16231: 
16232: =item *
16233: 
16234: get_timebased_id():
16235: 
16236: Attempts to get a unique timestamp-based suffix for use with items added to a 
16237: course via the Course Editor (e.g., folders, composite pages, 
16238: group bulletin boards).
16239: 
16240: Args: (first three required; six others optional)
16241: 
16242: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16243:    docssequence, or name of group
16244: 
16245: 2. keyid (alphanumeric): name of temporary locking key in hash,
16246:    e.g., num, boardids
16247: 
16248: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16249:    file will be named nohist_namespace.db
16250: 
16251: 4. cdom: domain of course; default is current course domain from %env
16252: 
16253: 5. cnum: course number; default is current course number from %env
16254: 
16255: 6. idtype: set to concat if an additional digit is to be appended to the 
16256:    unix timestamp to form the suffix, if the plain timestamp is already
16257:    in use.  Default is to not do this, but simply increment the unix 
16258:    timestamp by 1 until a unique key is obtained.
16259: 
16260: 7. who: holder of locking key; defaults to user:domain for user.
16261: 
16262: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16263:    retrying); default is 3.
16264: 
16265: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16266: 
16267: Returns:
16268: 
16269: 1. suffix obtained (numeric)
16270: 
16271: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16272: 
16273: 3. error: contains (localized) error message if an error occurred.
16274: 
16275: 
16276: =back
16277: 
16278: =head2 HTTP Helper Routines
16279: 
16280: =over 4
16281: 
16282: =item *
16283: 
16284: escape() : unpack non-word characters into CGI-compatible hex codes
16285: 
16286: =item *
16287: 
16288: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16289: 
16290: =back
16291: 
16292: =head1 PRIVATE SUBROUTINES
16293: 
16294: =head2 Underlying communication routines (Shouldn't call)
16295: 
16296: =over 4
16297: 
16298: =item *
16299: 
16300: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16301: 
16302: =item *
16303: 
16304: reply() : uses subreply to send a message to remote machine, logs all failures
16305: 
16306: =item *
16307: 
16308: critical() : passes a critical message to another server; if cannot
16309: get through then place message in connection buffer directory and
16310: returns con_delayed, if incapable of saving message, returns
16311: con_failed
16312: 
16313: =item *
16314: 
16315: reconlonc() : tries to reconnect lonc client processes.
16316: 
16317: =back
16318: 
16319: =head2 Resource Access Logging
16320: 
16321: =over 4
16322: 
16323: =item *
16324: 
16325: flushcourselogs() : flush (save) buffer logs and access logs
16326: 
16327: =item *
16328: 
16329: courselog($what) : save message for course in hash
16330: 
16331: =item *
16332: 
16333: courseacclog($what) : save message for course using &courselog().  Perform
16334: special processing for specific resource types (problems, exams, quizzes, etc).
16335: 
16336: =item *
16337: 
16338: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16339: as a PerlChildExitHandler
16340: 
16341: =back
16342: 
16343: =head2 Other
16344: 
16345: =over 4
16346: 
16347: =item *
16348: 
16349: symblist($mapname,%newhash) : update symbolic storage links
16350: 
16351: =back
16352: 
16353: =cut
16354: 

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