File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1422: download - view: text, annotated - select for diffs
Wed May 13 17:44:10 2020 UTC (4 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Add &unsubscribe() subroutine, and use in place of lonnet::reply() in
  unsubresources.pl and in &remove_stale_resfile() in lonnet.pm

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1422 2020/05/13 17:44:10 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: use LONCAPA::transliterate;
  105: 
  106: use File::Copy;
  107: 
  108: my $readit;
  109: my $max_connection_retries = 20;     # Or some such value.
  110: 
  111: require Exporter;
  112: 
  113: our @ISA = qw (Exporter);
  114: our @EXPORT = qw(%env);
  115: 
  116: 
  117: # ------------------------------------ Logging (parameters, docs, slots, roles)
  118: {
  119:     my $logid;
  120:     sub write_log {
  121: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  122:         if ($context eq 'course') {
  123:             if (($cnum eq '') || ($cdom eq '')) {
  124:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  125:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  126:             }
  127:         }
  128: 	$logid ++;
  129:         my $now = time();
  130: 	my $id=$now.'00000'.$$.'00000'.$logid;
  131:         my $logentry = { 
  132:                           $id => {
  133:                                    'exe_uname' => $env{'user.name'},
  134:                                    'exe_udom'  => $env{'user.domain'},
  135:                                    'exe_time'  => $now,
  136:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  137:                                    'delflag'   => $delflag,
  138:                                    'logentry'  => $storehash,
  139:                                    'uname'     => $uname,
  140:                                    'udom'      => $udom,
  141:                                   }
  142:                        };
  143: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  144:     }
  145: }
  146: 
  147: sub logtouch {
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     unless (-e "$execdir/logs/lonnet.log") {	
  150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  151: 	close $fh;
  152:     }
  153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  155: }
  156: 
  157: sub logthis {
  158:     my $message=shift;
  159:     my $execdir=$perlvar{'lonDaemons'};
  160:     my $now=time;
  161:     my $local=localtime($now);
  162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  164: 	print $fh $logstring;
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub logperm {
  171:     my $message=shift;
  172:     my $execdir=$perlvar{'lonDaemons'};
  173:     my $now=time;
  174:     my $local=localtime($now);
  175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  176: 	print $fh "$now:$message:$local\n";
  177: 	close($fh);
  178:     }
  179:     return 1;
  180: }
  181: 
  182: sub create_connection {
  183:     my ($hostname,$lonid) = @_;
  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  185: 				     Type    => SOCK_STREAM,
  186: 				     Timeout => 10);
  187:     return 0 if (!$client);
  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  189:     my $result = <$client>;
  190:     chomp($result);
  191:     return 1 if ($result eq 'done');
  192:     return 0;
  193: }
  194: 
  195: sub get_server_timezone {
  196:     my ($cnum,$cdom) = @_;
  197:     my $home=&homeserver($cnum,$cdom);
  198:     if ($home ne 'no_host') {
  199:         my $cachetime = 24*3600;
  200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  201:         if (defined($cached)) {
  202:             return $timezone;
  203:         } else {
  204:             my $timezone = &reply('servertimezone',$home);
  205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  206:         }
  207:     }
  208: }
  209: 
  210: sub get_server_distarch {
  211:     my ($lonhost,$ignore_cache) = @_;
  212:     if (defined($lonhost)) {
  213:         if (!defined(&hostname($lonhost))) {
  214:             return;
  215:         }
  216:         my $cachetime = 12*3600;
  217:         if (!$ignore_cache) {
  218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  219:             if (defined($cached)) {
  220:                 return $distarch;
  221:             }
  222:         }
  223:         my $rep = &reply('serverdistarch',$lonhost);
  224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  226:                 $rep eq '') {
  227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  228:         }
  229:     }
  230:     return;
  231: }
  232: 
  233: sub get_servercerts_info {
  234:     my ($lonhost,$hostname,$context) = @_;
  235:     return if ($lonhost eq '');
  236:     if ($hostname eq '') {
  237:         $hostname = &hostname($lonhost);
  238:     }
  239:     return if ($hostname eq '');
  240:     my ($rep,$uselocal);
  241:     if ($context eq 'install') {
  242:         $uselocal = 1;
  243:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  244:         $uselocal = 1;
  245:     }
  246:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  247:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  248:         if ($distro eq '') {
  249:             $uselocal = 0;
  250:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  251:             if ($1 < 6) {
  252:                 $uselocal = 0;
  253:             }
  254:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  255:             if ($1 < 12) {
  256:                 $uselocal = 0;
  257:             }
  258:         }
  259:     }
  260:     if ($uselocal) {
  261:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  262:     } else {
  263:         $rep=&reply('servercerts',$lonhost);
  264:     }
  265:     my ($result,%returnhash);
  266:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  267:         ($rep eq 'unknown_cmd')) {
  268:         $result = $rep;
  269:     } else {
  270:         $result = 'ok';
  271:         my @pairs=split(/\&/,$rep);
  272:         foreach my $item (@pairs) {
  273:             my ($key,$value)=split(/=/,$item,2);
  274:             my $what = &unescape($key);
  275:             $returnhash{$what}=&thaw_unescape($value);
  276:         }
  277:     }
  278:     return ($result,\%returnhash);
  279: }
  280: 
  281: sub get_server_loncaparev {
  282:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  283:     if (defined($lonhost)) {
  284:         if (!defined(&hostname($lonhost))) {
  285:             undef($lonhost);
  286:         }
  287:     }
  288:     if (!defined($lonhost)) {
  289:         if (defined(&domain($dom,'primary'))) {
  290:             $lonhost=&domain($dom,'primary');
  291:             if ($lonhost eq 'no_host') {
  292:                 undef($lonhost);
  293:             }
  294:         }
  295:     }
  296:     if (defined($lonhost)) {
  297:         my $cachetime = 12*3600;
  298:         if (!$ignore_cache) {
  299:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  300:             if (defined($cached)) {
  301:                 return $loncaparev;
  302:             }
  303:         }
  304:         my ($answer,$loncaparev);
  305:         my @ids=&current_machine_ids();
  306:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  307:             $answer = $perlvar{'lonVersion'};
  308:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  309:                 $loncaparev = $1;
  310:             }
  311:         } else {
  312:             $answer = &reply('serverloncaparev',$lonhost);
  313:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  314:                 if ($caller eq 'loncron') {
  315:                     my $hostname = &hostname($lonhost);
  316:                     my $protocol = $protocol{$lonhost};
  317:                     $protocol = 'http' if ($protocol ne 'https');
  318:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  319:                     my $request=new HTTP::Request('GET',$url);
  320:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  321:                     unless ($response->is_error()) {
  322:                         my $content = $response->content;
  323:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  324:                             $loncaparev = $1;
  325:                         }
  326:                     }
  327:                 } else {
  328:                     $loncaparev = $loncaparevs{$lonhost};
  329:                 }
  330:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  331:                 $loncaparev = $1;
  332:             }
  333:         }
  334:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  335:     }
  336: }
  337: 
  338: sub get_server_homeID {
  339:     my ($hostname,$ignore_cache,$caller) = @_;
  340:     unless ($ignore_cache) {
  341:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  342:         if (defined($cached)) {
  343:             return $serverhomeID;
  344:         }
  345:     }
  346:     my $cachetime = 12*3600;
  347:     my $serverhomeID;
  348:     if ($caller eq 'loncron') { 
  349:         my @machine_ids = &machine_ids($hostname);
  350:         foreach my $id (@machine_ids) {
  351:             my $response = &reply('serverhomeID',$id);
  352:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  353:                 $serverhomeID = $response;
  354:                 last;
  355:             }
  356:         }
  357:         if ($serverhomeID eq '') {
  358:             $serverhomeID = $machine_ids[-1];
  359:         }
  360:     } else {
  361:         $serverhomeID = $serverhomeIDs{$hostname};
  362:     }
  363:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  364: }
  365: 
  366: sub get_remote_globals {
  367:     my ($lonhost,$whathash,$ignore_cache) = @_;
  368:     my ($result,%returnhash,%whatneeded);
  369:     if (ref($whathash) eq 'HASH') {
  370:         foreach my $what (sort(keys(%{$whathash}))) {
  371:             my $hashid = $lonhost.'-'.$what;
  372:             my ($response,$cached);
  373:             unless ($ignore_cache) {
  374:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  375:             }
  376:             if (defined($cached)) {
  377:                 $returnhash{$what} = $response;
  378:             } else {
  379:                 $whatneeded{$what} = 1;
  380:             }
  381:         }
  382:         if (keys(%whatneeded) == 0) {
  383:             $result = 'ok';
  384:         } else {
  385:             my $requested = &freeze_escape(\%whatneeded);
  386:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  387:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  388:                 ($rep eq 'unknown_cmd')) {
  389:                 $result = $rep;
  390:             } else {
  391:                 $result = 'ok';
  392:                 my @pairs=split(/\&/,$rep);
  393:                 foreach my $item (@pairs) {
  394:                     my ($key,$value)=split(/=/,$item,2);
  395:                     my $what = &unescape($key);
  396:                     my $hashid = $lonhost.'-'.$what;
  397:                     $returnhash{$what}=&thaw_unescape($value);
  398:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  399:                 }
  400:             }
  401:         }
  402:     }
  403:     return ($result,\%returnhash);
  404: }
  405: 
  406: sub remote_devalidate_cache {
  407:     my ($lonhost,$cachekeys) = @_;
  408:     my $items;
  409:     return unless (ref($cachekeys) eq 'ARRAY');
  410:     my $cachestr = join('&',@{$cachekeys});
  411:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  412:     return $response;
  413: }
  414: 
  415: # -------------------------------------------------- Non-critical communication
  416: sub subreply {
  417:     my ($cmd,$server)=@_;
  418:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  419:     #
  420:     #  With loncnew process trimming, there's a timing hole between lonc server
  421:     #  process exit and the master server picking up the listen on the AF_UNIX
  422:     #  socket.  In that time interval, a lock file will exist:
  423: 
  424:     my $lockfile=$peerfile.".lock";
  425:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  426: 	sleep(0.1);
  427:     }
  428:     # At this point, either a loncnew parent is listening or an old lonc
  429:     # or loncnew child is listening so we can connect or everything's dead.
  430:     #
  431:     #   We'll give the connection a few tries before abandoning it.  If
  432:     #   connection is not possible, we'll con_lost back to the client.
  433:     #   
  434:     my $client;
  435:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  436: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  437: 				      Type    => SOCK_STREAM,
  438: 				      Timeout => 10);
  439: 	if ($client) {
  440: 	    last;		# Connected!
  441: 	} else {
  442: 	    &create_connection(&hostname($server),$server);
  443: 	}
  444:         sleep(0.1);	# Try again later if failed connection.
  445:     }
  446:     my $answer;
  447:     if ($client) {
  448: 	print $client "sethost:$server:$cmd\n";
  449: 	$answer=<$client>;
  450: 	if (!$answer) { $answer="con_lost"; }
  451: 	chomp($answer);
  452:     } else {
  453: 	$answer = 'con_lost';	# Failed connection.
  454:     }
  455:     return $answer;
  456: }
  457: 
  458: sub reply {
  459:     my ($cmd,$server)=@_;
  460:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  461:     my $answer=subreply($cmd,$server);
  462:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  463:         my $logged = $cmd;
  464:         if ($cmd =~ /^encrypt:([^:]+):/) {
  465:             my $subcmd = $1;
  466:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  467:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  468:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  469:                 (undef,undef,my @rest) = split(/:/,$cmd);
  470:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  471:                     splice(@rest,2,1,'Hidden');
  472:                 } elsif ($subcmd eq 'passwd') {
  473:                     splice(@rest,2,2,('Hidden','Hidden'));
  474:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  475:                          ($subcmd eq 'autoexportgrades')) {
  476:                     splice(@rest,3,1,'Hidden');
  477:                 }
  478:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  479:             }
  480:         }
  481:         &logthis("<font color=\"blue\">WARNING:".
  482:                  " $logged to $server returned $answer</font>");
  483:     }
  484:     return $answer;
  485: }
  486: 
  487: # ----------------------------------------------------------- Send USR1 to lonc
  488: 
  489: sub reconlonc {
  490:     my ($lonid) = @_;
  491:     if ($lonid) {
  492:         my $hostname = &hostname($lonid);
  493: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  494: 	if ($hostname && -e $peerfile) {
  495: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  496: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  497: 					     Type    => SOCK_STREAM,
  498: 					     Timeout => 10);
  499: 	    if ($client) {
  500: 		print $client ("reset_retries\n");
  501: 		my $answer=<$client>;
  502: 		#reset just this one.
  503: 	    }
  504: 	}
  505: 	return;
  506:     }
  507: 
  508:     &logthis("Trying to reconnect lonc");
  509:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  510:     if (open(my $fh,"<",$loncfile)) {
  511: 	my $loncpid=<$fh>;
  512:         chomp($loncpid);
  513:         if (kill 0 => $loncpid) {
  514: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  515:             kill USR1 => $loncpid;
  516:             sleep 1;
  517:         } else {
  518: 	    &logthis(
  519:                "<font color=\"blue\">WARNING:".
  520:                " lonc at pid $loncpid not responding, giving up</font>");
  521:         }
  522:     } else {
  523: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  524:     }
  525: }
  526: 
  527: # ------------------------------------------------------ Critical communication
  528: 
  529: sub critical {
  530:     my ($cmd,$server)=@_;
  531:     unless (&hostname($server)) {
  532:         &logthis("<font color=\"blue\">WARNING:".
  533:                " Critical message to unknown server ($server)</font>");
  534:         return 'no_such_host';
  535:     }
  536:     my $answer=reply($cmd,$server);
  537:     if ($answer eq 'con_lost') {
  538: 	&reconlonc($server);
  539: 	my $answer=reply($cmd,$server);
  540:         if ($answer eq 'con_lost') {
  541:             my $now=time;
  542:             my $middlename=$cmd;
  543:             $middlename=substr($middlename,0,16);
  544:             $middlename=~s/\W//g;
  545:             my $dfilename=
  546:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  547:             $dumpcount++;
  548:             {
  549: 		my $dfh;
  550: 		if (open($dfh,">",$dfilename)) {
  551: 		    print $dfh "$cmd\n"; 
  552: 		    close($dfh);
  553: 		}
  554:             }
  555:             sleep 1;
  556:             my $wcmd='';
  557:             {
  558: 		my $dfh;
  559: 		if (open($dfh,"<",$dfilename)) {
  560: 		    $wcmd=<$dfh>; 
  561: 		    close($dfh);
  562: 		}
  563:             }
  564:             chomp($wcmd);
  565:             if ($wcmd eq $cmd) {
  566: 		&logthis("<font color=\"blue\">WARNING: ".
  567:                          "Connection buffer $dfilename: $cmd</font>");
  568:                 &logperm("D:$server:$cmd");
  569: 	        return 'con_delayed';
  570:             } else {
  571:                 &logthis("<font color=\"red\">CRITICAL:"
  572:                         ." Critical connection failed: $server $cmd</font>");
  573:                 &logperm("F:$server:$cmd");
  574:                 return 'con_failed';
  575:             }
  576:         }
  577:     }
  578:     return $answer;
  579: }
  580: 
  581: # ------------------------------------------- check if return value is an error
  582: 
  583: sub error {
  584:     my ($result) = @_;
  585:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  586: 	if ($2 == 2) { return undef; }
  587: 	return $1;
  588:     }
  589:     return undef;
  590: }
  591: 
  592: sub convert_and_load_session_env {
  593:     my ($lonidsdir,$handle)=@_;
  594:     my @profile;
  595:     {
  596: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  597: 	if (!$opened) {
  598: 	    return 0;
  599: 	}
  600: 	flock($idf,LOCK_SH);
  601: 	@profile=<$idf>;
  602: 	close($idf);
  603:     }
  604:     my %temp_env;
  605:     foreach my $line (@profile) {
  606: 	if ($line !~ m/=/) {
  607: 	    return 0;
  608: 	}
  609: 	chomp($line);
  610: 	my ($envname,$envvalue)=split(/=/,$line,2);
  611: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  612:     }
  613:     unlink("$lonidsdir/$handle.id");
  614:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  615: 	    0640)) {
  616: 	%disk_env = %temp_env;
  617: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  618: 	untie(%disk_env);
  619:     }
  620:     return 1;
  621: }
  622: 
  623: # ------------------------------------------- Transfer profile into environment
  624: my $env_loaded;
  625: sub transfer_profile_to_env {
  626:     my ($lonidsdir,$handle,$force_transfer) = @_;
  627:     if (!$force_transfer && $env_loaded) { return; } 
  628: 
  629:     if (!defined($lonidsdir)) {
  630: 	$lonidsdir = $perlvar{'lonIDsDir'};
  631:     }
  632:     if (!defined($handle)) {
  633:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  634:     }
  635: 
  636:     my $convert;
  637:     {
  638:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  639: 	if (!$opened) {
  640: 	    return;
  641: 	}
  642: 	flock($idf,LOCK_SH);
  643: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  644: 		&GDBM_READER(),0640)) {
  645: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  646: 	    untie(%disk_env);
  647: 	} else {
  648: 	    $convert = 1;
  649: 	}
  650:     }
  651:     if ($convert) {
  652: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  653: 	    &logthis("Failed to load session, or convert session.");
  654: 	}
  655:     }
  656: 
  657:     my %remove;
  658:     while ( my $envname = each(%env) ) {
  659:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  660:             if ($time < time-300) {
  661:                 $remove{$key}++;
  662:             }
  663:         }
  664:     }
  665: 
  666:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  667:     $env_loaded=1;
  668:     foreach my $expired_key (keys(%remove)) {
  669:         &delenv($expired_key);
  670:     }
  671: }
  672: 
  673: # ---------------------------------------------------- Check for valid session 
  674: sub check_for_valid_session {
  675:     my ($r,$name,$userhashref,$domref) = @_;
  676:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  677:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  678:     if ($name eq 'lonDAV') {
  679:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  680:     } else {
  681:         $lonidsdir=$r->dir_config('lonIDsDir');
  682:         if ($name eq '') {
  683:             $name = 'lonID';
  684:         }
  685:     }
  686:     if ($name eq 'lonID') {
  687:         $secure = 'lonSID';
  688:         $linkname = 'lonLinkID';
  689:         $pubname = 'lonPubID';
  690:         if (exists($cookies{$secure})) {
  691:             $lonid=$cookies{$secure};
  692:         } elsif (exists($cookies{$name})) {
  693:             $lonid=$cookies{$name};
  694:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  695:             $lonid=$cookies{$linkname};
  696:         } elsif (exists($cookies{$pubname})) {
  697:             $lonid=$cookies{$pubname};
  698:         }
  699:     } else {
  700:         $lonid=$cookies{$name};
  701:     }
  702:     return undef if (!$lonid);
  703: 
  704:     my $handle=&LONCAPA::clean_handle($lonid->value);
  705:     if (-l "$lonidsdir/$handle.id") {
  706:         my $link = readlink("$lonidsdir/$handle.id");
  707:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  708:             $handle = $1;
  709:         }
  710:     }
  711:     if (!-e "$lonidsdir/$handle.id") {
  712:         if ((ref($domref)) && ($name eq 'lonID') && 
  713:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  714:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  715:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  716:                 $$domref = $possudom;
  717:             }
  718:         }
  719:         return undef;
  720:     }
  721: 
  722:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  723:     return undef if (!$opened);
  724: 
  725:     flock($idf,LOCK_SH);
  726:     my %disk_env;
  727:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  728: 	    &GDBM_READER(),0640)) {
  729: 	return undef;	
  730:     }
  731: 
  732:     if (!defined($disk_env{'user.name'})
  733: 	|| !defined($disk_env{'user.domain'})) {
  734:         untie(%disk_env);
  735: 	return undef;
  736:     }
  737: 
  738:     if (ref($userhashref) eq 'HASH') {
  739:         $userhashref->{'name'} = $disk_env{'user.name'};
  740:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  741:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  742:         if ($userhashref->{'lti'}) {
  743:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  744:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  745:         }
  746:     }
  747:     untie(%disk_env);
  748: 
  749:     return $handle;
  750: }
  751: 
  752: sub timed_flock {
  753:     my ($file,$lock_type) = @_;
  754:     my $failed=0;
  755:     eval {
  756: 	local $SIG{__DIE__}='DEFAULT';
  757: 	local $SIG{ALRM}=sub {
  758: 	    $failed=1;
  759: 	    die("failed lock");
  760: 	};
  761: 	alarm(13);
  762: 	flock($file,$lock_type);
  763: 	alarm(0);
  764:     };
  765:     if ($failed) {
  766: 	return undef;
  767:     } else {
  768: 	return 1;
  769:     }
  770: }
  771: 
  772: sub get_sessionfile_vars {
  773:     my ($handle,$lonidsdir,$storearr) = @_;
  774:     my %returnhash;
  775:     unless (ref($storearr) eq 'ARRAY') {
  776:         return %returnhash;
  777:     }
  778:     if (-l "$lonidsdir/$handle.id") {
  779:         my $link = readlink("$lonidsdir/$handle.id");
  780:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  781:             $handle = $1;
  782:         }
  783:     }
  784:     if ((-e "$lonidsdir/$handle.id") &&
  785:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  786:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  787:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  788:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  789:                 flock($idf,LOCK_SH);
  790:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  791:                         &GDBM_READER(),0640)) {
  792:                     foreach my $item (@{$storearr}) {
  793:                         $returnhash{$item} = $disk_env{$item};
  794:                     }
  795:                     untie(%disk_env);
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return %returnhash;
  801: }
  802: 
  803: # ---------------------------------------------------------- Append Environment
  804: 
  805: sub appenv {
  806:     my ($newenv,$roles) = @_;
  807:     if (ref($newenv) eq 'HASH') {
  808:         foreach my $key (keys(%{$newenv})) {
  809:             my $refused = 0;
  810: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  811:                 $refused = 1;
  812:                 if (ref($roles) eq 'ARRAY') {
  813:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  814:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  815:                         $refused = 0;
  816:                     }
  817:                 }
  818:             }
  819:             if ($refused) {
  820:                 &logthis("<font color=\"blue\">WARNING: ".
  821:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  822:                          .'</font>');
  823: 	        delete($newenv->{$key});
  824:             } else {
  825:                 $env{$key}=$newenv->{$key};
  826:             }
  827:         }
  828:         my $lonids = $perlvar{'lonIDsDir'};
  829:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  830:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  831:             if ($opened
  832: 	        && &timed_flock($env_file,LOCK_EX)
  833: 	        &&
  834: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  835: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  836: 	        while (my ($key,$value) = each(%{$newenv})) {
  837: 	            $disk_env{$key} = $value;
  838: 	        }
  839: 	        untie(%disk_env);
  840:             }
  841:         }
  842:     }
  843:     return 'ok';
  844: }
  845: # ----------------------------------------------------- Delete from Environment
  846: 
  847: sub delenv {
  848:     my ($delthis,$regexp,$roles) = @_;
  849:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  850:         my $refused = 1;
  851:         if (ref($roles) eq 'ARRAY') {
  852:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  853:             if (grep(/^\Q$role\E$/,@{$roles})) {
  854:                 $refused = 0;
  855:             }
  856:         }
  857:         if ($refused) {
  858:             &logthis("<font color=\"blue\">WARNING: ".
  859:                      "Attempt to delete from environment ".$delthis);
  860:             return 'error';
  861:         }
  862:     }
  863:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  864:     if ($opened
  865: 	&& &timed_flock($env_file,LOCK_EX)
  866: 	&&
  867: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  868: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  869: 	foreach my $key (keys(%disk_env)) {
  870: 	    if ($regexp) {
  871:                 if ($key=~/^$delthis/) {
  872:                     delete($env{$key});
  873:                     delete($disk_env{$key});
  874:                 } 
  875:             } else {
  876:                 if ($key=~/^\Q$delthis\E/) {
  877: 		    delete($env{$key});
  878: 		    delete($disk_env{$key});
  879: 	        }
  880:             }
  881: 	}
  882: 	untie(%disk_env);
  883:     }
  884:     return 'ok';
  885: }
  886: 
  887: sub get_env_multiple {
  888:     my ($name) = @_;
  889:     my @values;
  890:     if (defined($env{$name})) {
  891:         # exists is it an array
  892:         if (ref($env{$name})) {
  893:             @values=@{ $env{$name} };
  894:         } else {
  895:             $values[0]=$env{$name};
  896:         }
  897:     }
  898:     return(@values);
  899: }
  900: 
  901: # ------------------------------------------------------------------- Locking
  902: 
  903: sub set_lock {
  904:     my ($text)=@_;
  905:     $locknum++;
  906:     my $id=$$.'-'.$locknum;
  907:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  908:              'session.lock.'.$id => $text});
  909:     return $id;
  910: }
  911: 
  912: sub get_locks {
  913:     my $num=0;
  914:     my %texts=();
  915:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  916:        if ($lock=~/\w/) {
  917:           $num++;
  918:           $texts{$lock}=$env{'session.lock.'.$lock};
  919:        }
  920:    }
  921:    return ($num,%texts);
  922: }
  923: 
  924: sub remove_lock {
  925:     my ($id)=@_;
  926:     my $newlocks='';
  927:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  928:        if (($lock=~/\w/) && ($lock ne $id)) {
  929:           $newlocks.=','.$lock;
  930:        }
  931:     }
  932:     &appenv({'session.locks' => $newlocks});
  933:     &delenv('session.lock.'.$id);
  934: }
  935: 
  936: sub remove_all_locks {
  937:     my $activelocks=$env{'session.locks'};
  938:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  939:        if ($lock=~/\w/) {
  940:           &remove_lock($lock);
  941:        }
  942:     }
  943: }
  944: 
  945: 
  946: # ------------------------------------------ Find out current server userload
  947: sub userload {
  948:     my $numusers=0;
  949:     {
  950: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  951: 	my $filename;
  952: 	my $curtime=time;
  953: 	while ($filename=readdir(LONIDS)) {
  954: 	    next if ($filename eq '.' || $filename eq '..');
  955: 	    next if ($filename =~ /publicuser_\d+\.id/);
  956:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  957: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  958: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  959: 	}
  960: 	closedir(LONIDS);
  961:     }
  962:     my $userloadpercent=0;
  963:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  964:     if ($maxuserload) {
  965: 	$userloadpercent=100*$numusers/$maxuserload;
  966:     }
  967:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  968:     return $userloadpercent;
  969: }
  970: 
  971: # ------------------------------ Find server with least workload from spare.tab
  972: 
  973: sub spareserver {
  974:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  975:     my $spare_server;
  976:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  977:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  978:                                                      :  $userloadpercent;
  979:     my ($uint_dom,$remotesessions);
  980:     if (($udom ne '') && (&domain($udom) ne '')) {
  981:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  982:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  983:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  984:         $remotesessions = $udomdefaults{'remotesessions'};
  985:     }
  986:     my $spareshash = &this_host_spares($udom);
  987:     if (ref($spareshash) eq 'HASH') {
  988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  990:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  991:                                              $try_server));
  992: 	        ($spare_server, $lowest_load) =
  993: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  994:             }
  995:         }
  996: 
  997:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  998: 
  999:         if (!$found_server) {
 1000:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1001: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1002:                     next unless (&spare_can_host($udom,$uint_dom,
 1003:                                                  $remotesessions,$try_server));
 1004: 	            ($spare_server, $lowest_load) =
 1005: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1006:                 }
 1007: 	    }
 1008:         }
 1009:     }
 1010: 
 1011:     if (!$want_server_name) {
 1012:         if (defined($spare_server)) {
 1013:             my $hostname = &hostname($spare_server);
 1014:             if (defined($hostname)) {
 1015:                 my $protocol = 'http';
 1016:                 if ($protocol{$spare_server} eq 'https') {
 1017:                     $protocol = $protocol{$spare_server};
 1018:                 }
 1019: 	        $spare_server = $protocol.'://'.$hostname;
 1020:             }
 1021:         }
 1022:     }
 1023:     return $spare_server;
 1024: }
 1025: 
 1026: sub compare_server_load {
 1027:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1028: 
 1029:     if ($required) {
 1030:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1031:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1032:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1033:         if (($major eq '' && $minor eq '') ||
 1034:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1035:             return ($spare_server,$lowest_load);
 1036:         }
 1037:     }
 1038: 
 1039:     my $loadans     = &reply('load',    $try_server);
 1040:     my $userloadans = &reply('userload',$try_server);
 1041: 
 1042:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1043: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1044:     }
 1045: 
 1046:     my $load;
 1047:     if ($loadans =~ /\d/) {
 1048: 	if ($userloadans =~ /\d/) {
 1049: 	    #both are numbers, pick the bigger one
 1050: 	    $load = ($loadans > $userloadans) ? $loadans 
 1051: 		                              : $userloadans;
 1052: 	} else {
 1053: 	    $load = $loadans;
 1054: 	}
 1055:     } else {
 1056: 	$load = $userloadans;
 1057:     }
 1058: 
 1059:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1060: 	$spare_server = $try_server;
 1061: 	$lowest_load  = $load;
 1062:     }
 1063:     return ($spare_server,$lowest_load);
 1064: }
 1065: 
 1066: # --------------------------- ask offload servers if user already has a session
 1067: sub find_existing_session {
 1068:     my ($udom,$uname) = @_;
 1069:     my $spareshash = &this_host_spares($udom);
 1070:     if (ref($spareshash) eq 'HASH') {
 1071:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1072:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1073:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1074:             }
 1075:         }
 1076:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1077:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1078:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1079:             }
 1080:         }
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: sub delusersession {
 1086:     my ($lonid,$udom,$uname) = @_;
 1087:     my $uprimary_id = &domain($udom,'primary');
 1088:     my $uintdom = &internet_dom($uprimary_id);
 1089:     my $intdom = &internet_dom($lonid);
 1090:     my $serverhomedom = &host_domain($lonid);
 1091:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1092:         return &reply(join(':','delusersession',
 1093:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1094:     }
 1095:     return;
 1096: }
 1097: 
 1098: # check if user's browser sent load balancer cookie and server still has session
 1099: # and is not overloaded.
 1100: sub check_for_balancer_cookie {
 1101:     my ($r,$update_mtime) = @_;
 1102:     my ($otherserver,$cookie);
 1103:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1104:     if (exists($cookies{'balanceID'})) {
 1105:         my $balid = $cookies{'balanceID'};
 1106:         $cookie=&LONCAPA::clean_handle($balid->value);
 1107:         my $balancedir=$r->dir_config('lonBalanceDir');
 1108:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1109:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1110:                 my ($possudom,$possuname) = ($1,$2);
 1111:                 my $has_session = 0;
 1112:                 if ((&domain($possudom) ne '') &&
 1113:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1114:                     my $try_server;
 1115:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1116:                     if ($opened) {
 1117:                         flock($idf,LOCK_SH);
 1118:                         while (my $line = <$idf>) {
 1119:                             chomp($line);
 1120:                             if (&hostname($line) ne '') {
 1121:                                 $try_server = $line;
 1122:                                 last;
 1123:                             }
 1124:                         }
 1125:                         close($idf);
 1126:                         if (($try_server) &&
 1127:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1128:                             my $lowest_load = 30000;
 1129:                             ($otherserver,$lowest_load) =
 1130:                                 &compare_server_load($try_server,undef,$lowest_load);
 1131:                             if ($otherserver ne '' && $lowest_load < 100) {
 1132:                                 $has_session = 1;
 1133:                             } else {
 1134:                                 undef($otherserver);
 1135:                             }
 1136:                         }
 1137:                     }
 1138:                 }
 1139:                 if ($has_session) {
 1140:                     if ($update_mtime) {
 1141:                         my $atime = my $mtime = time;
 1142:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1143:                     }
 1144:                 } else {
 1145:                     unlink("$balancedir/$cookie.id");
 1146:                 }
 1147:             }
 1148:         }
 1149:     }
 1150:     return ($otherserver,$cookie);
 1151: }
 1152: 
 1153: sub delbalcookie {
 1154:     my ($cookie,$balancer) =@_;
 1155:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1156:         my ($udom,$uname) = ($1,$2);
 1157:         my $uprimary_id = &domain($udom,'primary');
 1158:         my $uintdom = &internet_dom($uprimary_id);
 1159:         my $intdom = &internet_dom($balancer);
 1160:         my $serverhomedom = &host_domain($balancer);
 1161:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1162:             return &reply("delbalcookie:$cookie",$balancer);
 1163:         }
 1164:     }
 1165: }
 1166: 
 1167: # -------------------------------- ask if server already has a session for user
 1168: sub has_user_session {
 1169:     my ($lonid,$udom,$uname) = @_;
 1170:     my $result = &reply(join(':','userhassession',
 1171: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1172:     return 1 if ($result eq 'ok');
 1173: 
 1174:     return 0;
 1175: }
 1176: 
 1177: # --------- determine least loaded server in a user's domain which allows login
 1178: 
 1179: sub choose_server {
 1180:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1181:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1182:     my %servers = &get_servers($udom);
 1183:     my $lowest_load = 30000;
 1184:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1185:     if ($skiploadbal) {
 1186:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1187:         unless (defined($cached)) {
 1188:             my $cachetime = 60*60*24;
 1189:             my %domconfig =
 1190:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1191:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1192:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1193:                                            $cachetime);
 1194:             }
 1195:         }
 1196:     }
 1197:     foreach my $lonhost (keys(%servers)) {
 1198:         if ($skiploadbal) {
 1199:             if (ref($balancers) eq 'HASH') {
 1200:                 next if (exists($balancers->{$lonhost}));
 1201:             }
 1202:         }
 1203:         my $loginvia;
 1204:         if ($checkloginvia) {
 1205:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1206:             if ($loginvia) {
 1207:                 my ($server,$path) = split(/:/,$loginvia);
 1208:                 ($login_host, $lowest_load) =
 1209:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1210:                 if ($login_host eq $server) {
 1211:                     $portal_path = $path;
 1212:                     $isredirect = 1;
 1213:                 }
 1214:             } else {
 1215:                 ($login_host, $lowest_load) =
 1216:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1217:                 if ($login_host eq $lonhost) {
 1218:                     $portal_path = '';
 1219:                     $isredirect = ''; 
 1220:                 }
 1221:             }
 1222:         } else {
 1223:             ($login_host, $lowest_load) =
 1224:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1225:         }
 1226:     }
 1227:     if ($login_host ne '') {
 1228:         $hostname = &hostname($login_host);
 1229:     }
 1230:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1231: }
 1232: 
 1233: sub get_course_sessions {
 1234:     my ($cnum,$cdom,$lastactivity) = @_;
 1235:     my %servers = &internet_dom_servers($cdom);
 1236:     my %returnhash;
 1237:     foreach my $server (sort(keys(%servers))) {
 1238:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1239:         my @pairs=split(/\&/,$rep);
 1240:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1241:             foreach my $item (@pairs) {
 1242:                 my ($key,$value)=split(/=/,$item,2);
 1243:                 $key = &unescape($key);
 1244:                 next if ($key =~ /^error: 2 /);
 1245:                 if (exists($returnhash{$key})) {
 1246:                     next if ($value < $returnhash{$key});
 1247:                 }
 1248:                 $returnhash{$key}=$value;
 1249:             }
 1250:         }
 1251:     }
 1252:     return %returnhash;
 1253: }
 1254: 
 1255: # --------------------------------------------- Try to change a user's password
 1256: 
 1257: sub changepass {
 1258:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1259:     $currentpass = &escape($currentpass);
 1260:     $newpass     = &escape($newpass);
 1261:     my $lonhost = $perlvar{'lonHostID'};
 1262:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1263: 		       $server);
 1264:     if (! $answer) {
 1265: 	&logthis("No reply on password change request to $server ".
 1266: 		 "by $uname in domain $udom.");
 1267:     } elsif ($answer =~ "^ok") {
 1268:         &logthis("$uname in $udom successfully changed their password ".
 1269: 		 "on $server.");
 1270:     } elsif ($answer =~ "^pwchange_failure") {
 1271: 	&logthis("$uname in $udom was unable to change their password ".
 1272: 		 "on $server.  The action was blocked by either lcpasswd ".
 1273: 		 "or pwchange");
 1274:     } elsif ($answer =~ "^non_authorized") {
 1275:         &logthis("$uname in $udom did not get their password correct when ".
 1276: 		 "attempting to change it on $server.");
 1277:     } elsif ($answer =~ "^auth_mode_error") {
 1278:         &logthis("$uname in $udom attempted to change their password despite ".
 1279: 		 "not being locally or internally authenticated on $server.");
 1280:     } elsif ($answer =~ "^unknown_user") {
 1281:         &logthis("$uname in $udom attempted to change their password ".
 1282: 		 "on $server but were unable to because $server is not ".
 1283: 		 "their home server.");
 1284:     } elsif ($answer =~ "^refused") {
 1285: 	&logthis("$server refused to change $uname in $udom password because ".
 1286: 		 "it was sent an unencrypted request to change the password.");
 1287:     } elsif ($answer =~ "invalid_client") {
 1288:         &logthis("$server refused to change $uname in $udom password because ".
 1289:                  "it was a reset by e-mail originating from an invalid server.");
 1290:     } elsif ($answer =~ "^prioruse") {
 1291:        &logthis("$server refused to change $uname in $udom password because ".
 1292:                 "the password had been used before");
 1293:     }
 1294:     return $answer;
 1295: }
 1296: 
 1297: # ----------------------- Try to determine user's current authentication scheme
 1298: 
 1299: sub queryauthenticate {
 1300:     my ($uname,$udom)=@_;
 1301:     my $uhome=&homeserver($uname,$udom);
 1302:     if (!$uhome) {
 1303: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1304: 	return 'no_host';
 1305:     }
 1306:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1307:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1308: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1309:     }
 1310:     return $answer;
 1311: }
 1312: 
 1313: # --------- Try to authenticate user from domain's lib servers (first this one)
 1314: 
 1315: sub authenticate {
 1316:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1317:     $upass=&escape($upass);
 1318:     $uname= &LONCAPA::clean_username($uname);
 1319:     my $uhome=&homeserver($uname,$udom,1);
 1320:     my $newhome;
 1321:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1322: # Maybe the machine was offline and only re-appeared again recently?
 1323:         &reconlonc();
 1324: # One more
 1325: 	$uhome=&homeserver($uname,$udom,1);
 1326:         if (($uhome eq 'no_host') && $checkdefauth) {
 1327:             if (defined(&domain($udom,'primary'))) {
 1328:                 $newhome=&domain($udom,'primary');
 1329:             }
 1330:             if ($newhome ne '') {
 1331:                 $uhome = $newhome;
 1332:             }
 1333:         }
 1334: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1335: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1336: 	    return 'no_host';
 1337:         }
 1338:     }
 1339:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1340:     if ($answer eq 'authorized') {
 1341:         if ($newhome) {
 1342:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1343:             return 'no_account_on_host'; 
 1344:         } else {
 1345:             &logthis("User $uname at $udom authorized by $uhome");
 1346:             return $uhome;
 1347:         }
 1348:     }
 1349:     if ($answer eq 'non_authorized') {
 1350: 	&logthis("User $uname at $udom rejected by $uhome");
 1351: 	return 'no_host'; 
 1352:     }
 1353:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1354:     return 'no_host';
 1355: }
 1356: 
 1357: sub can_host_session {
 1358:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1359:     my $canhost = 1;
 1360:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1361:     if (ref($remotesessions) eq 'HASH') {
 1362:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1363:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1364:                 $canhost = 0;
 1365:             } else {
 1366:                 $canhost = 1;
 1367:             }
 1368:         }
 1369:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1370:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1371:                 $canhost = 1;
 1372:             } else {
 1373:                 $canhost = 0;
 1374:             }
 1375:         }
 1376:         if ($canhost) {
 1377:             if ($remotesessions->{'version'} ne '') {
 1378:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1379:                 if ($reqmajor ne '' && $reqminor ne '') {
 1380:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1381:                         my $major = $1;
 1382:                         my $minor = $2;
 1383:                         if (($major < $reqmajor ) ||
 1384:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1385:                             $canhost = 0;
 1386:                         }
 1387:                     } else {
 1388:                         $canhost = 0;
 1389:                     }
 1390:                 }
 1391:             }
 1392:         }
 1393:     }
 1394:     if ($canhost) {
 1395:         if (ref($hostedsessions) eq 'HASH') {
 1396:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1397:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1398:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1399:                 if (($uint_dom ne '') && 
 1400:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1401:                     $canhost = 0;
 1402:                 } else {
 1403:                     $canhost = 1;
 1404:                 }
 1405:             }
 1406:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1407:                 if (($uint_dom ne '') && 
 1408:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1409:                     $canhost = 1;
 1410:                 } else {
 1411:                     $canhost = 0;
 1412:                 }
 1413:             }
 1414:         }
 1415:     }
 1416:     return $canhost;
 1417: }
 1418: 
 1419: sub spare_can_host {
 1420:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1421:     my $canhost=1;
 1422:     my $try_server_hostname = &hostname($try_server);
 1423:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1424:     my $serverhomedom = &host_domain($serverhomeID);
 1425:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1426:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1427:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1428:             $canhost = 0;
 1429:         }
 1430:     }
 1431:     if (($canhost) && ($uint_dom)) {
 1432:         my @intdoms;
 1433:         my $internet_names = &get_internet_names($try_server);
 1434:         if (ref($internet_names) eq 'ARRAY') {
 1435:             @intdoms = @{$internet_names};
 1436:         }
 1437:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1438:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1439:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1440:                                          $remotesessions,
 1441:                                          $defdomdefaults{'hostedsessions'});
 1442:         }
 1443:     }
 1444:     return $canhost;
 1445: }
 1446: 
 1447: sub this_host_spares {
 1448:     my ($dom) = @_;
 1449:     my ($dom_in_use,$lonhost_in_use,$result);
 1450:     my @hosts = &current_machine_ids();
 1451:     foreach my $lonhost (@hosts) {
 1452:         if (&host_domain($lonhost) eq $dom) {
 1453:             $dom_in_use = $dom;
 1454:             $lonhost_in_use = $lonhost;
 1455:             last;
 1456:         }
 1457:     }
 1458:     if ($dom_in_use ne '') {
 1459:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1460:     }
 1461:     if (ref($result) ne 'HASH') {
 1462:         $lonhost_in_use = $perlvar{'lonHostID'};
 1463:         $dom_in_use = &host_domain($lonhost_in_use);
 1464:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1465:         if (ref($result) ne 'HASH') {
 1466:             $result = \%spareid;
 1467:         }
 1468:     }
 1469:     return $result;
 1470: }
 1471: 
 1472: sub spares_for_offload  {
 1473:     my ($dom_in_use,$lonhost_in_use) = @_;
 1474:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1475:     if (defined($cached)) {
 1476:         return $result;
 1477:     } else {
 1478:         my $cachetime = 60*60*24;
 1479:         my %domconfig =
 1480:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1481:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1482:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1483:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1484:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1485:                 }
 1486:             }
 1487:         }
 1488:     }
 1489:     return;
 1490: }
 1491: 
 1492: sub get_lonbalancer_config {
 1493:     my ($servers) = @_;
 1494:     my ($currbalancer,$currtargets);
 1495:     if (ref($servers) eq 'HASH') {
 1496:         foreach my $server (keys(%{$servers})) {
 1497:             my %what = (
 1498:                          spareid => 1,
 1499:                          perlvar => 1,
 1500:                        );
 1501:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1502:             if ($result eq 'ok') {
 1503:                 if (ref($returnhash) eq 'HASH') {
 1504:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1505:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1506:                             $currbalancer = $server;
 1507:                             $currtargets = {};
 1508:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1509:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1510:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1511:                                 }
 1512:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1513:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1514:                                 }
 1515:                             }
 1516:                             last;
 1517:                         }
 1518:                     }
 1519:                 }
 1520:             }
 1521:         }
 1522:     }
 1523:     return ($currbalancer,$currtargets);
 1524: }
 1525: 
 1526: sub check_loadbalancing {
 1527:     my ($uname,$udom,$caller) = @_;
 1528:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1529:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1530:     my $lonhost = $perlvar{'lonHostID'};
 1531:     my @hosts = &current_machine_ids();
 1532:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1533:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1534:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1535:     my $serverhomedom = &host_domain($lonhost);
 1536:     my $domneedscache;
 1537:     my $cachetime = 60*60*24;
 1538: 
 1539:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1540:         $dom_in_use = $udom;
 1541:         $homeintdom = 1;
 1542:     } else {
 1543:         $dom_in_use = $serverhomedom;
 1544:     }
 1545:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1546:     unless (defined($cached)) {
 1547:         my %domconfig =
 1548:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1549:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1550:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1551:         } else {
 1552:             $domneedscache = $dom_in_use;
 1553:         }
 1554:     }
 1555:     if (ref($result) eq 'HASH') {
 1556:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1557:             &check_balancer_result($result,@hosts);
 1558:         if ($is_balancer) {
 1559:             if (ref($currrules) eq 'HASH') {
 1560:                 if ($homeintdom) {
 1561:                     if ($uname ne '') {
 1562:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1563:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1564:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1565:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1566:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1567:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1568:                             }
 1569:                         }
 1570:                         if ($rule_in_effect eq '') {
 1571:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1572:                             if ($userenv{'inststatus'} ne '') {
 1573:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1574:                                 my ($othertitle,$usertypes,$types) =
 1575:                                     &Apache::loncommon::sorted_inst_types($udom);
 1576:                                 if (ref($types) eq 'ARRAY') {
 1577:                                     foreach my $type (@{$types}) {
 1578:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1579:                                             if (exists($currrules->{$type})) {
 1580:                                                 $rule_in_effect = $currrules->{$type};
 1581:                                             }
 1582:                                         }
 1583:                                     }
 1584:                                 }
 1585:                             } else {
 1586:                                 if (exists($currrules->{'default'})) {
 1587:                                     $rule_in_effect = $currrules->{'default'};
 1588:                                 }
 1589:                             }
 1590:                         }
 1591:                     } else {
 1592:                         if (exists($currrules->{'default'})) {
 1593:                             $rule_in_effect = $currrules->{'default'};
 1594:                         }
 1595:                     }
 1596:                 } else {
 1597:                     if ($currrules->{'_LC_external'} ne '') {
 1598:                         $rule_in_effect = $currrules->{'_LC_external'};
 1599:                     }
 1600:                 }
 1601:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1602:                                                        $uname,$udom);
 1603:             }
 1604:         }
 1605:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1606:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1607:         unless (defined($cached)) {
 1608:             my %domconfig =
 1609:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1610:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1611:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1612:             } else {
 1613:                 $domneedscache = $serverhomedom;
 1614:             }
 1615:         }
 1616:         if (ref($result) eq 'HASH') {
 1617:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1618:                 &check_balancer_result($result,@hosts);
 1619:             if ($is_balancer) {
 1620:                 if (ref($currrules) eq 'HASH') {
 1621:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1622:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1623:                     }
 1624:                 }
 1625:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1626:                                                        $uname,$udom);
 1627:             }
 1628:         } else {
 1629:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1630:                 $is_balancer = 1;
 1631:                 $offloadto = &this_host_spares($dom_in_use);
 1632:             }
 1633:             unless (defined($cached)) {
 1634:                 $domneedscache = $serverhomedom;
 1635:             }
 1636:         }
 1637:     } else {
 1638:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1639:             $is_balancer = 1;
 1640:             $offloadto = &this_host_spares($dom_in_use);
 1641:         }
 1642:         unless (defined($cached)) {
 1643:             $domneedscache = $serverhomedom;
 1644:         }
 1645:     }
 1646:     if ($domneedscache) {
 1647:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1648:     }
 1649:     if ($is_balancer) {
 1650:         my $lowest_load = 30000;
 1651:         if (ref($offloadto) eq 'HASH') {
 1652:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1653:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1654:                     ($otherserver,$lowest_load) =
 1655:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1656:                 }
 1657:             }
 1658:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1659: 
 1660:             if (!$found_server) {
 1661:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1662:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1663:                         ($otherserver,$lowest_load) =
 1664:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1665:                     }
 1666:                 }
 1667:             }
 1668:         } elsif (ref($offloadto) eq 'ARRAY') {
 1669:             if (@{$offloadto} == 1) {
 1670:                 $otherserver = $offloadto->[0];
 1671:             } elsif (@{$offloadto} > 1) {
 1672:                 foreach my $try_server (@{$offloadto}) {
 1673:                     ($otherserver,$lowest_load) =
 1674:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1675:                 }
 1676:             }
 1677:         }
 1678:         unless ($caller eq 'login') {
 1679:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1680:                 $is_balancer = 0;
 1681:                 if ($uname ne '' && $udom ne '') {
 1682:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1683:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1684:                                  'user.loadbalcheck.time' => time});
 1685:                     }
 1686:                 }
 1687:             }
 1688:         }
 1689:         unless ($homeintdom) {
 1690:             undef($setcookie);
 1691:         }
 1692:     }
 1693:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1694: }
 1695: 
 1696: sub check_balancer_result {
 1697:     my ($result,@hosts) = @_;
 1698:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1699:     if (ref($result) eq 'HASH') {
 1700:         if ($result->{'lonhost'} ne '') {
 1701:             my $currbalancer = $result->{'lonhost'};
 1702:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1703:                 $is_balancer = 1;
 1704:                 $currtargets = $result->{'targets'};
 1705:                 $currrules = $result->{'rules'};
 1706:             }
 1707:             $dom_balancers = $currbalancer;
 1708:         } else {
 1709:             if (keys(%{$result})) {
 1710:                 foreach my $key (keys(%{$result})) {
 1711:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1712:                         (ref($result->{$key}) eq 'HASH')) {
 1713:                         $is_balancer = 1;
 1714:                         $currrules = $result->{$key}{'rules'};
 1715:                         $currtargets = $result->{$key}{'targets'};
 1716:                         $setcookie = $result->{$key}{'cookie'};
 1717:                         last;
 1718:                     }
 1719:                 }
 1720:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1721:             }
 1722:         }
 1723:     }
 1724:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1725: }
 1726: 
 1727: sub get_loadbalancer_targets {
 1728:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1729:     my $offloadto;
 1730:     if ($rule_in_effect eq 'none') {
 1731:         return [$perlvar{'lonHostID'}];
 1732:     } elsif ($rule_in_effect eq '') {
 1733:         $offloadto = $currtargets;
 1734:     } else {
 1735:         if ($rule_in_effect eq 'homeserver') {
 1736:             my $homeserver = &homeserver($uname,$udom);
 1737:             if ($homeserver ne 'no_host') {
 1738:                 $offloadto = [$homeserver];
 1739:             }
 1740:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1741:             my %domconfig =
 1742:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1743:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1744:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1745:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1746:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1747:                     }
 1748:                 }
 1749:             } else {
 1750:                 my %servers = &internet_dom_servers($udom);
 1751:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1752:                 if (&hostname($remotebalancer) ne '') {
 1753:                     $offloadto = [$remotebalancer];
 1754:                 }
 1755:             }
 1756:         } elsif (&hostname($rule_in_effect) ne '') {
 1757:             $offloadto = [$rule_in_effect];
 1758:         }
 1759:     }
 1760:     return $offloadto;
 1761: }
 1762: 
 1763: sub internet_dom_servers {
 1764:     my ($dom) = @_;
 1765:     my (%uniqservers,%servers);
 1766:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1767:     my @machinedoms = &machine_domains($primaryserver);
 1768:     foreach my $mdom (@machinedoms) {
 1769:         my %currservers = %servers;
 1770:         my %server = &get_servers($mdom);
 1771:         %servers = (%currservers,%server);
 1772:     }
 1773:     my %by_hostname;
 1774:     foreach my $id (keys(%servers)) {
 1775:         push(@{$by_hostname{$servers{$id}}},$id);
 1776:     }
 1777:     foreach my $hostname (sort(keys(%by_hostname))) {
 1778:         if (@{$by_hostname{$hostname}} > 1) {
 1779:             my $match = 0;
 1780:             foreach my $id (@{$by_hostname{$hostname}}) {
 1781:                 if (&host_domain($id) eq $dom) {
 1782:                     $uniqservers{$id} = $hostname;
 1783:                     $match = 1;
 1784:                 }
 1785:             }
 1786:             unless ($match) {
 1787:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1788:             }
 1789:         } else {
 1790:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1791:         }
 1792:     }
 1793:     return %uniqservers;
 1794: }
 1795: 
 1796: sub trusted_domains {
 1797:     my ($cmdtype,$calldom) = @_;
 1798:     my ($trusted,$untrusted);
 1799:     if (&domain($calldom) eq '') {
 1800:         return ($trusted,$untrusted);
 1801:     }
 1802:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1803:         return ($trusted,$untrusted);
 1804:     }
 1805:     my $callprimary = &domain($calldom,'primary');
 1806:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1807:     if ($intcalldom eq '') {
 1808:         return ($trusted,$untrusted);
 1809:     }
 1810: 
 1811:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1812:     unless (defined($cached)) {
 1813:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1814:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1815:         $trustconfig = $domconfig{'trust'};
 1816:     }
 1817:     if (ref($trustconfig)) {
 1818:         my (%possexc,%possinc,@allexc,@allinc); 
 1819:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1820:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1821:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1822:             }
 1823:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1824:                 $possinc{$intcalldom} = 1;
 1825:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1826:             }
 1827:         }
 1828:         if (keys(%possexc)) {
 1829:             if (keys(%possinc)) {
 1830:                 foreach my $key (sort(keys(%possexc))) {
 1831:                     next if ($key eq $intcalldom);
 1832:                     unless ($possinc{$key}) {
 1833:                         push(@allexc,$key);
 1834:                     }
 1835:                 }
 1836:             } else {
 1837:                 @allexc = sort(keys(%possexc));
 1838:             }
 1839:         }
 1840:         if (keys(%possinc)) {
 1841:             $possinc{$intcalldom} = 1;
 1842:             @allinc = sort(keys(%possinc));
 1843:         }
 1844:         if ((@allexc > 0) || (@allinc > 0)) {
 1845:             my %doms_by_intdom;
 1846:             my %allintdoms = &all_host_intdom();
 1847:             my %alldoms = &all_host_domain();
 1848:             foreach my $key (%allintdoms) {
 1849:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1850:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1851:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1852:                     }
 1853:                 } else {
 1854:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1855:                 }
 1856:             }
 1857:             foreach my $exc (@allexc) {
 1858:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1859:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1860:                 }
 1861:             }
 1862:             foreach my $inc (@allinc) {
 1863:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1864:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1865:                 }
 1866:             }
 1867:         }
 1868:     }
 1869:     return ($trusted,$untrusted);
 1870: }
 1871: 
 1872: sub will_trust {
 1873:     my ($cmdtype,$domain,$possdom) = @_;
 1874:     return 1 if ($domain eq $possdom);
 1875:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1876:     my $willtrust; 
 1877:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1878:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1879:             $willtrust = 1;
 1880:         }
 1881:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1882:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1883:             $willtrust = 1;
 1884:         }
 1885:     } else {
 1886:         $willtrust = 1;
 1887:     }
 1888:     return $willtrust;
 1889: }
 1890: 
 1891: # ---------------------- Find the homebase for a user from domain's lib servers
 1892: 
 1893: my %homecache;
 1894: sub homeserver {
 1895:     my ($uname,$udom,$ignoreBadCache)=@_;
 1896:     my $index="$uname:$udom";
 1897: 
 1898:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1899: 
 1900:     my %servers = &get_servers($udom,'library');
 1901:     foreach my $tryserver (keys(%servers)) {
 1902:         next if ($ignoreBadCache ne 'true' && 
 1903: 		 exists($badServerCache{$tryserver}));
 1904: 
 1905: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1906: 	if ($answer eq 'found') {
 1907: 	    delete($badServerCache{$tryserver}); 
 1908: 	    return $homecache{$index}=$tryserver;
 1909: 	} elsif ($answer eq 'no_host') {
 1910: 	    $badServerCache{$tryserver}=1;
 1911: 	}
 1912:     }    
 1913:     return 'no_host';
 1914: }
 1915: 
 1916: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1917: 
 1918: sub idget {
 1919:     my ($udom,$idsref,$namespace)=@_;
 1920:     my %returnhash=();
 1921:     my @ids=(); 
 1922:     if (ref($idsref) eq 'ARRAY') {
 1923:         @ids = @{$idsref};
 1924:     } else {
 1925:         return %returnhash; 
 1926:     }
 1927:     if ($namespace eq '') {
 1928:         $namespace = 'ids';
 1929:     }
 1930:     
 1931:     my %servers = &get_servers($udom,'library');
 1932:     foreach my $tryserver (keys(%servers)) {
 1933: 	my $idlist=join('&', map { &escape($_); } @ids);
 1934: 	if ($namespace eq 'ids') {
 1935: 	    $idlist=~tr/A-Z/a-z/;
 1936: 	}
 1937: 	my $reply;
 1938: 	if ($namespace eq 'ids') {
 1939: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1940: 	} else {
 1941: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1942: 	}
 1943: 	my @answer=();
 1944: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1945: 	    @answer=split(/\&/,$reply);
 1946: 	}                    ;
 1947: 	my $i;
 1948: 	for ($i=0;$i<=$#ids;$i++) {
 1949: 	    if ($answer[$i]) {
 1950: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1951: 	    }
 1952: 	}
 1953:     }
 1954:     return %returnhash;
 1955: }
 1956: 
 1957: # ------------------------------------- Find the IDs behind a list of usernames
 1958: 
 1959: sub idrget {
 1960:     my ($udom,@unames)=@_;
 1961:     my %returnhash=();
 1962:     foreach my $uname (@unames) {
 1963:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1964:     }
 1965:     return %returnhash;
 1966: }
 1967: 
 1968: # Store away a list of names and associated student/employee IDs or clicker IDs
 1969: 
 1970: sub idput {
 1971:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1972:     my %servers=();
 1973:     my %ids=();
 1974:     my %byid = ();
 1975:     if (ref($idsref) eq 'HASH') {
 1976:         %ids=%{$idsref};
 1977:     }
 1978:     if ($namespace eq '') {
 1979:         $namespace = 'ids'; 
 1980:     }
 1981:     foreach my $uname (keys(%ids)) {
 1982: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1983:         if ($uhom eq '') {
 1984:             $uhom=&homeserver($uname,$udom);
 1985:         }
 1986:         if ($uhom ne 'no_host') {
 1987:             my $esc_unam=&escape($uname);
 1988:             if ($namespace eq 'ids') {
 1989:                 my $id=&escape($ids{$uname});
 1990:                 $id=~tr/A-Z/a-z/;
 1991:                 my $esc_unam=&escape($uname);
 1992:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1993:             } else {
 1994:                 my @currids = split(/,/,$ids{$uname});
 1995:                 foreach my $id (@currids) {
 1996:                     $byid{$uhom}{$id} .= $uname.',';
 1997:                 }
 1998:             }
 1999:         }
 2000:     }
 2001:     if ($namespace eq 'clickers') {
 2002:         foreach my $server (keys(%byid)) {
 2003:             if (ref($byid{$server}) eq 'HASH') {
 2004:                 foreach my $id (keys(%{$byid{$server}})) {
 2005:                     $byid{$server} =~ s/,$//;
 2006:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2007:                 }
 2008:             }
 2009:         }
 2010:     }
 2011:     foreach my $server (keys(%servers)) {
 2012:         $servers{$server} =~ s/\&$//;
 2013:         if ($namespace eq 'ids') {     
 2014:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2015:         } else {
 2016:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2017:         }
 2018:     }
 2019: }
 2020: 
 2021: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2022: 
 2023: sub iddel {
 2024:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2025:     my %result=();
 2026:     my %ids=();
 2027:     my %byid = ();
 2028:     if (ref($idshashref) eq 'HASH') {
 2029:         %ids=%{$idshashref};
 2030:     } else {
 2031:         return %result;
 2032:     }
 2033:     if ($namespace eq '') {
 2034:         $namespace = 'ids';
 2035:     }
 2036:     my %servers=();
 2037:     while (my ($id,$unamestr) = each(%ids)) {
 2038:         if ($namespace eq 'ids') {
 2039:             my $uhom = $uhome;
 2040:             if ($uhom eq '') { 
 2041:                 $uhom=&homeserver($unamestr,$udom);
 2042:             }
 2043:             if ($uhom ne 'no_host') {
 2044:                 $servers{$uhom}.='&'.&escape($id);
 2045:             }
 2046:          } else {
 2047:             my @curritems = split(/,/,$ids{$id});
 2048:             foreach my $uname (@curritems) {
 2049:                 my $uhom = $uhome;
 2050:                 if ($uhom eq '') {
 2051:                     $uhom=&homeserver($uname,$udom);
 2052:                 }
 2053:                 if ($uhom ne 'no_host') { 
 2054:                     $byid{$uhom}{$id} .= $uname.',';
 2055:                 }
 2056:             }
 2057:         }
 2058:     }
 2059:     if ($namespace eq 'clickers') {
 2060:         foreach my $server (keys(%byid)) {
 2061:             if (ref($byid{$server}) eq 'HASH') {
 2062:                 foreach my $id (keys(%{$byid{$server}})) {
 2063:                     $byid{$server}{$id} =~ s/,$//;
 2064:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2065:                 }
 2066:             }
 2067:         }
 2068:     }
 2069:     foreach my $server (keys(%servers)) {
 2070:         $servers{$server} =~ s/\&$//;
 2071:         if ($namespace eq 'ids') {
 2072:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2073:         } elsif ($namespace eq 'clickers') {
 2074:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2075:         }
 2076:     }
 2077:     return %result;
 2078: }
 2079: 
 2080: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2081: 
 2082: sub updateclickers {
 2083:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2084:     my %clickers;
 2085:     if (ref($idshashref) eq 'HASH') {
 2086:         %clickers=%{$idshashref};
 2087:     } else {
 2088:         return;
 2089:     }
 2090:     my $items='';
 2091:     foreach my $item (keys(%clickers)) {
 2092:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2093:     }
 2094:     $items=~s/\&$//;
 2095:     my $request = "updateclickers:$udom:$action:$items";
 2096:     if ($critical) {
 2097:         return &critical($request,$uhome);
 2098:     } else {
 2099:         return &reply($request,$uhome);
 2100:     }
 2101: }
 2102: 
 2103: # ------------------------------dump from db file owned by domainconfig user
 2104: sub dump_dom {
 2105:     my ($namespace, $udom, $regexp) = @_;
 2106: 
 2107:     $udom ||= $env{'user.domain'};
 2108: 
 2109:     return () unless $udom;
 2110: 
 2111:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2112: }
 2113: 
 2114: # ------------------------------------------ get items from domain db files   
 2115: 
 2116: sub get_dom {
 2117:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2118:     return if ($udom eq 'public');
 2119:     my $items='';
 2120:     foreach my $item (@$storearr) {
 2121:         $items.=&escape($item).'&';
 2122:     }
 2123:     $items=~s/\&$//;
 2124:     if (!$udom) {
 2125:         $udom=$env{'user.domain'};
 2126:         return if ($udom eq 'public');
 2127:         if (defined(&domain($udom,'primary'))) {
 2128:             $uhome=&domain($udom,'primary');
 2129:         } else {
 2130:             undef($uhome);
 2131:         }
 2132:     } else {
 2133:         if (!$uhome) {
 2134:             if (defined(&domain($udom,'primary'))) {
 2135:                 $uhome=&domain($udom,'primary');
 2136:             }
 2137:         }
 2138:     }
 2139:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2140:         my $rep;
 2141:         if ($namespace =~ /^enc/) {
 2142:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2143:         } else {
 2144:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2145:         }
 2146:         my %returnhash;
 2147:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2148:             return %returnhash;
 2149:         }
 2150:         my @pairs=split(/\&/,$rep);
 2151:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2152:             return @pairs;
 2153:         }
 2154:         my $i=0;
 2155:         foreach my $item (@$storearr) {
 2156:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2157:             $i++;
 2158:         }
 2159:         return %returnhash;
 2160:     } else {
 2161:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2162:     }
 2163: }
 2164: 
 2165: # -------------------------------------------- put items in domain db files 
 2166: 
 2167: sub put_dom {
 2168:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2169:     if (!$udom) {
 2170:         $udom=$env{'user.domain'};
 2171:         if (defined(&domain($udom,'primary'))) {
 2172:             $uhome=&domain($udom,'primary');
 2173:         } else {
 2174:             undef($uhome);
 2175:         }
 2176:     } else {
 2177:         if (!$uhome) {
 2178:             if (defined(&domain($udom,'primary'))) {
 2179:                 $uhome=&domain($udom,'primary');
 2180:             }
 2181:         }
 2182:     } 
 2183:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2184:         my $items='';
 2185:         foreach my $item (keys(%$storehash)) {
 2186:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2187:         }
 2188:         $items=~s/\&$//;
 2189:         if ($namespace =~ /^enc/) {
 2190:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2191:         } else {
 2192:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2193:         }
 2194:     } else {
 2195:         &logthis("put_dom failed - no homeserver and/or domain");
 2196:     }
 2197: }
 2198: 
 2199: # --------------------- newput for items in db file owned by domainconfig user
 2200: sub newput_dom {
 2201:     my ($namespace,$storehash,$udom) = @_;
 2202:     my $result;
 2203:     if (!$udom) {
 2204:         $udom=$env{'user.domain'};
 2205:     }
 2206:     if ($udom) {
 2207:         my $uname = &get_domainconfiguser($udom);
 2208:         $result = &newput($namespace,$storehash,$udom,$uname);
 2209:     }
 2210:     return $result;
 2211: }
 2212: 
 2213: # --------------------- delete for items in db file owned by domainconfig user
 2214: sub del_dom {
 2215:     my ($namespace,$storearr,$udom)=@_;
 2216:     if (ref($storearr) eq 'ARRAY') {
 2217:         if (!$udom) {
 2218:             $udom=$env{'user.domain'};
 2219:         }
 2220:         if ($udom) {
 2221:             my $uname = &get_domainconfiguser($udom); 
 2222:             return &del($namespace,$storearr,$udom,$uname);
 2223:         }
 2224:     }
 2225: }
 2226: 
 2227: # ----------------------------------construct domainconfig user for a domain 
 2228: sub get_domainconfiguser {
 2229:     my ($udom) = @_;
 2230:     return $udom.'-domainconfig';
 2231: }
 2232: 
 2233: sub retrieve_inst_usertypes {
 2234:     my ($udom) = @_;
 2235:     my (%returnhash,@order);
 2236:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2237:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2238:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2239:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2240:     } else {
 2241:         if (defined(&domain($udom,'primary'))) {
 2242:             my $uhome=&domain($udom,'primary');
 2243:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2244:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2245:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2246:                 return (\%returnhash,\@order);
 2247:             }
 2248:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2249:             my @pairs=split(/\&/,$hashitems);
 2250:             foreach my $item (@pairs) {
 2251:                 my ($key,$value)=split(/=/,$item,2);
 2252:                 $key = &unescape($key);
 2253:                 next if ($key =~ /^error: 2 /);
 2254:                 $returnhash{$key}=&thaw_unescape($value);
 2255:             }
 2256:             my @esc_order = split(/\&/,$orderitems);
 2257:             foreach my $item (@esc_order) {
 2258:                 push(@order,&unescape($item));
 2259:             }
 2260:         } else {
 2261:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2262:         }
 2263:         return (\%returnhash,\@order);
 2264:     }
 2265: }
 2266: 
 2267: sub is_domainimage {
 2268:     my ($url) = @_;
 2269:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2270:         if (&domain($1) ne '') {
 2271:             return '1';
 2272:         }
 2273:     }
 2274:     return;
 2275: }
 2276: 
 2277: sub inst_directory_query {
 2278:     my ($srch) = @_;
 2279:     my $udom = $srch->{'srchdomain'};
 2280:     my %results;
 2281:     my $homeserver = &domain($udom,'primary');
 2282:     my $outcome;
 2283:     if ($homeserver ne '') {
 2284:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2285:             if ($srch->{'srchby'} eq 'email') {
 2286:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2287:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2288:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2289:                     (($major == 2) && ($minor < 12))) {
 2290:                     return;
 2291:                 }
 2292:             }
 2293:         }
 2294: 	my $queryid=&reply("querysend:instdirsearch:".
 2295: 			   &escape($srch->{'srchby'}).':'.
 2296: 			   &escape($srch->{'srchterm'}).':'.
 2297: 			   &escape($srch->{'srchtype'}),$homeserver);
 2298: 	my $host=&hostname($homeserver);
 2299: 	if ($queryid !~/^\Q$host\E\_/) {
 2300: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2301: 	    return;
 2302: 	}
 2303: 	my $response = &get_query_reply($queryid);
 2304: 	my $maxtries = 5;
 2305: 	my $tries = 1;
 2306: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2307: 	    $response = &get_query_reply($queryid);
 2308: 	    $tries ++;
 2309: 	}
 2310: 
 2311:         if (!&error($response) && $response ne 'refused') {
 2312:             if ($response eq 'unavailable') {
 2313:                 $outcome = $response;
 2314:             } else {
 2315:                 $outcome = 'ok';
 2316:                 my @matches = split(/\n/,$response);
 2317:                 foreach my $match (@matches) {
 2318:                     my ($key,$value) = split(/=/,$match);
 2319:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2320:                 }
 2321:             }
 2322:         }
 2323:     }
 2324:     return ($outcome,%results);
 2325: }
 2326: 
 2327: sub usersearch {
 2328:     my ($srch) = @_;
 2329:     my $dom = $srch->{'srchdomain'};
 2330:     my %results;
 2331:     my %libserv = &all_library();
 2332:     my $query = 'usersearch';
 2333:     foreach my $tryserver (keys(%libserv)) {
 2334:         if (&host_domain($tryserver) eq $dom) {
 2335:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2336:                 if ($srch->{'srchby'} eq 'email') {
 2337:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2338:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2339:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2340:                              (($major == 2) && ($minor < 12)));
 2341:                 }
 2342:             }
 2343:             my $host=&hostname($tryserver);
 2344:             my $queryid=
 2345:                 &reply("querysend:".&escape($query).':'.
 2346:                        &escape($srch->{'srchby'}).':'.
 2347:                        &escape($srch->{'srchtype'}).':'.
 2348:                        &escape($srch->{'srchterm'}),$tryserver);
 2349:             if ($queryid !~/^\Q$host\E\_/) {
 2350:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2351:                 next;
 2352:             }
 2353:             my $reply = &get_query_reply($queryid);
 2354:             my $maxtries = 1;
 2355:             my $tries = 1;
 2356:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2357:                 $reply = &get_query_reply($queryid);
 2358:                 $tries ++;
 2359:             }
 2360:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2361:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2362:             } else {
 2363:                 my @matches;
 2364:                 if ($reply =~ /\n/) {
 2365:                     @matches = split(/\n/,$reply);
 2366:                 } else {
 2367:                     @matches = split(/\&/,$reply);
 2368:                 }
 2369:                 foreach my $match (@matches) {
 2370:                     my ($uname,$udom,%userhash);
 2371:                     foreach my $entry (split(/:/,$match)) {
 2372:                         my ($key,$value) =
 2373:                             map {&unescape($_);} split(/=/,$entry);
 2374:                         $userhash{$key} = $value;
 2375:                         if ($key eq 'username') {
 2376:                             $uname = $value;
 2377:                         } elsif ($key eq 'domain') {
 2378:                             $udom = $value;
 2379:                         }
 2380:                     }
 2381:                     $results{$uname.':'.$udom} = \%userhash;
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     return %results;
 2387: }
 2388: 
 2389: sub get_instuser {
 2390:     my ($udom,$uname,$id) = @_;
 2391:     my $homeserver = &domain($udom,'primary');
 2392:     my ($outcome,%results);
 2393:     if ($homeserver ne '') {
 2394:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2395:                            &escape($id).':'.&escape($udom),$homeserver);
 2396:         my $host=&hostname($homeserver);
 2397:         if ($queryid !~/^\Q$host\E\_/) {
 2398:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2399:             return;
 2400:         }
 2401:         my $response = &get_query_reply($queryid);
 2402:         my $maxtries = 5;
 2403:         my $tries = 1;
 2404:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2405:             $response = &get_query_reply($queryid);
 2406:             $tries ++;
 2407:         }
 2408:         if (!&error($response) && $response ne 'refused') {
 2409:             if ($response eq 'unavailable') {
 2410:                 $outcome = $response;
 2411:             } else {
 2412:                 $outcome = 'ok';
 2413:                 my @matches = split(/\n/,$response);
 2414:                 foreach my $match (@matches) {
 2415:                     my ($key,$value) = split(/=/,$match);
 2416:                     $results{&unescape($key)} = &thaw_unescape($value);
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     my %userinfo;
 2422:     if (ref($results{$uname}) eq 'HASH') {
 2423:         %userinfo = %{$results{$uname}};
 2424:     } 
 2425:     return ($outcome,%userinfo);
 2426: }
 2427: 
 2428: sub get_multiple_instusers {
 2429:     my ($udom,$users,$caller) = @_;
 2430:     my ($outcome,$results);
 2431:     if (ref($users) eq 'HASH') {
 2432:         my $count = keys(%{$users}); 
 2433:         my $requested = &freeze_escape($users);
 2434:         my $homeserver = &domain($udom,'primary');
 2435:         if ($homeserver ne '') {
 2436:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2437:             my $host=&hostname($homeserver);
 2438:             if ($queryid !~/^\Q$host\E\_/) {
 2439:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2440:                          ' for host: '.$homeserver.'in domain '.$udom);
 2441:                 return ($outcome,$results);
 2442:             }
 2443:             my $response = &get_query_reply($queryid);
 2444:             my $maxtries = 5;
 2445:             if ($count > 100) {
 2446:                 $maxtries = 1+int($count/20);
 2447:             }
 2448:             my $tries = 1;
 2449:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2450:                 $response = &get_query_reply($queryid);
 2451:                 $tries ++;
 2452:             }
 2453:             if ($response eq '') {
 2454:                 $results = {};
 2455:                 foreach my $key (keys(%{$users})) {
 2456:                     my ($uname,$id);
 2457:                     if ($caller eq 'id') {
 2458:                         $id = $key;
 2459:                     } else {
 2460:                         $uname = $key;
 2461:                     }
 2462:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2463:                     $outcome = $resp;
 2464:                     if ($resp eq 'ok') {
 2465:                         %{$results} = (%{$results}, %info);
 2466:                     } else {
 2467:                         last;
 2468:                     }
 2469:                 }
 2470:             } elsif(!&error($response) && ($response ne 'refused')) {
 2471:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2472:                     $outcome = $response;
 2473:                 } else {
 2474:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2475:                     if ($outcome eq 'ok') {
 2476:                         $results = &thaw_unescape($userdata); 
 2477:                     }
 2478:                 }
 2479:             }
 2480:         }
 2481:     }
 2482:     return ($outcome,$results);
 2483: }
 2484: 
 2485: sub inst_rulecheck {
 2486:     my ($udom,$uname,$id,$item,$rules) = @_;
 2487:     my %returnhash;
 2488:     if ($udom ne '') {
 2489:         if (ref($rules) eq 'ARRAY') {
 2490:             @{$rules} = map {&escape($_);} (@{$rules});
 2491:             my $rulestr = join(':',@{$rules});
 2492:             my $homeserver=&domain($udom,'primary');
 2493:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2494:                 my $response;
 2495:                 if ($item eq 'username') {                
 2496:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2497:                                               ':'.&escape($uname).':'.$rulestr,
 2498:                                               $homeserver));
 2499:                 } elsif ($item eq 'id') {
 2500:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2501:                                               ':'.&escape($id).':'.$rulestr,
 2502:                                               $homeserver));
 2503:                 } elsif ($item eq 'selfcreate') {
 2504:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2505:                                                &escape($udom).':'.&escape($uname).
 2506:                                               ':'.$rulestr,$homeserver));
 2507:                 }
 2508:                 if ($response ne 'refused') {
 2509:                     my @pairs=split(/\&/,$response);
 2510:                     foreach my $item (@pairs) {
 2511:                         my ($key,$value)=split(/=/,$item,2);
 2512:                         $key = &unescape($key);
 2513:                         next if ($key =~ /^error: 2 /);
 2514:                         $returnhash{$key}=&thaw_unescape($value);
 2515:                     }
 2516:                 }
 2517:             }
 2518:         }
 2519:     }
 2520:     return %returnhash;
 2521: }
 2522: 
 2523: sub inst_userrules {
 2524:     my ($udom,$check) = @_;
 2525:     my (%ruleshash,@ruleorder);
 2526:     if ($udom ne '') {
 2527:         my $homeserver=&domain($udom,'primary');
 2528:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2529:             my $response;
 2530:             if ($check eq 'id') {
 2531:                 $response=&reply('instidrules:'.&escape($udom),
 2532:                                  $homeserver);
 2533:             } elsif ($check eq 'email') {
 2534:                 $response=&reply('instemailrules:'.&escape($udom),
 2535:                                  $homeserver);
 2536:             } else {
 2537:                 $response=&reply('instuserrules:'.&escape($udom),
 2538:                                  $homeserver);
 2539:             }
 2540:             if (($response ne 'refused') && ($response ne 'error') && 
 2541:                 ($response ne 'unknown_cmd') && 
 2542:                 ($response ne 'no_such_host')) {
 2543:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2544:                 my @pairs=split(/\&/,$hashitems);
 2545:                 foreach my $item (@pairs) {
 2546:                     my ($key,$value)=split(/=/,$item,2);
 2547:                     $key = &unescape($key);
 2548:                     next if ($key =~ /^error: 2 /);
 2549:                     $ruleshash{$key}=&thaw_unescape($value);
 2550:                 }
 2551:                 my @esc_order = split(/\&/,$orderitems);
 2552:                 foreach my $item (@esc_order) {
 2553:                     push(@ruleorder,&unescape($item));
 2554:                 }
 2555:             }
 2556:         }
 2557:     }
 2558:     return (\%ruleshash,\@ruleorder);
 2559: }
 2560: 
 2561: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2562: 
 2563: sub get_domain_defaults {
 2564:     my ($domain,$ignore_cache) = @_;
 2565:     return if (($domain eq '') || ($domain eq 'public'));
 2566:     my $cachetime = 60*60*24;
 2567:     unless ($ignore_cache) {
 2568:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2569:         if (defined($cached)) {
 2570:             if (ref($result) eq 'HASH') {
 2571:                 return %{$result};
 2572:             }
 2573:         }
 2574:     }
 2575:     my %domdefaults;
 2576:     my %domconfig =
 2577:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2578:                                   'requestcourses','inststatus',
 2579:                                   'coursedefaults','usersessions',
 2580:                                   'requestauthor','selfenrollment',
 2581:                                   'coursecategories','ssl','autoenroll',
 2582:                                   'trust','helpsettings'],$domain);
 2583:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2584:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2585:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2586:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2587:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2588:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2589:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2590:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2591:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2592:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2593:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2594:     } else {
 2595:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2596:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2597:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2598:     }
 2599:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2600:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2601:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2602:         } else {
 2603:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2604:         }
 2605:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2606:         foreach my $item (@usertools) {
 2607:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2608:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2609:             }
 2610:         }
 2611:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2612:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2613:         }
 2614:     }
 2615:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2616:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2617:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2618:         }
 2619:     }
 2620:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2621:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2622:     }
 2623:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2624:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2625:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2626:         }
 2627:     }
 2628:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2629:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2630:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2631:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2632:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2633:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2634:         }
 2635:         foreach my $type (@coursetypes) {
 2636:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2637:                 unless ($type eq 'community') {
 2638:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2639:                 }
 2640:             }
 2641:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2642:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2643:             }
 2644:             if ($domdefaults{'postsubmit'} eq 'on') {
 2645:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2646:                     $domdefaults{$type.'postsubtimeout'} = 
 2647:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2648:                 }
 2649:             }
 2650:         }
 2651:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2652:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2653:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2654:                 if (@clonecodes) {
 2655:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2656:                 }
 2657:             }
 2658:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2659:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2660:         }
 2661:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2662:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2663:         } 
 2664:     }
 2665:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2666:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2667:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2668:         }
 2669:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2670:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2671:         }
 2672:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2673:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2674:         }
 2675:     }
 2676:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2677:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2678:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2679:                             'approval','limit');
 2680:             foreach my $type (@coursetypes) {
 2681:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2682:                     my @mgrdc = ();
 2683:                     foreach my $item (@settings) {
 2684:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2685:                             push(@mgrdc,$item);
 2686:                         }
 2687:                     }
 2688:                     if (@mgrdc) {
 2689:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2690:                     }
 2691:                 }
 2692:             }
 2693:         }
 2694:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2695:             foreach my $type (@coursetypes) {
 2696:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2697:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2698:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2699:                     }
 2700:                 }
 2701:             }
 2702:         }
 2703:     }
 2704:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2705:         $domdefaults{'catauth'} = 'std';
 2706:         $domdefaults{'catunauth'} = 'std';
 2707:         if ($domconfig{'coursecategories'}{'auth'}) {
 2708:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2709:         }
 2710:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2711:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2712:         }
 2713:     }
 2714:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2715:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2716:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2717:         }
 2718:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2719:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2720:         }
 2721:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2722:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2723:         }
 2724:     }
 2725:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2726:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2727:         foreach my $prefix (@prefixes) {
 2728:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2729:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2730:             }
 2731:         }
 2732:     }
 2733:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2734:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2735:     }
 2736:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2737:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2738:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2739:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2740:         }
 2741:     }
 2742:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2743:     return %domdefaults;
 2744: }
 2745: 
 2746: sub get_dom_cats {
 2747:     my ($dom) = @_;
 2748:     return unless (&domain($dom));
 2749:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2750:     unless (defined($cached)) {
 2751:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2752:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2753:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2754:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2755:             } else {
 2756:                 $cats = {};
 2757:             }
 2758:         } else {
 2759:             $cats = {};
 2760:         }
 2761:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2762:     }
 2763:     return $cats;
 2764: }
 2765: 
 2766: sub get_dom_instcats {
 2767:     my ($dom) = @_;
 2768:     return unless (&domain($dom));
 2769:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2770:     unless (defined($cached)) {
 2771:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2772:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2773:         if ($totcodes > 0) {
 2774:             my $caller = 'global';
 2775:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2776:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2777:                 $instcats = {
 2778:                                 codes => \%codes,
 2779:                                 codetitles => \@codetitles,
 2780:                                 cat_titles => \%cat_titles,
 2781:                                 cat_order => \%cat_order,
 2782:                             };
 2783:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2784:             }
 2785:         }
 2786:     }
 2787:     return $instcats;
 2788: }
 2789: 
 2790: sub retrieve_instcodes {
 2791:     my ($coursecodes,$dom) = @_;
 2792:     my $totcodes;
 2793:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2794:     foreach my $course (keys(%courses)) {
 2795:         if (ref($courses{$course}) eq 'HASH') {
 2796:             if ($courses{$course}{'inst_code'} ne '') {
 2797:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2798:                 $totcodes ++;
 2799:             }
 2800:         }
 2801:     }
 2802:     return $totcodes;
 2803: }
 2804: 
 2805: sub course_portal_url {
 2806:     my ($cnum,$cdom) = @_;
 2807:     my $chome = &homeserver($cnum,$cdom);
 2808:     my $hostname = &hostname($chome);
 2809:     my $protocol = $protocol{$chome};
 2810:     $protocol = 'http' if ($protocol ne 'https');
 2811:     my %domdefaults = &get_domain_defaults($cdom);
 2812:     my $firsturl;
 2813:     if ($domdefaults{'portal_def'}) {
 2814:         $firsturl = $domdefaults{'portal_def'};
 2815:     } else {
 2816:         $firsturl = $protocol.'://'.$hostname;
 2817:     }
 2818:     return $firsturl;
 2819: }
 2820: 
 2821: # --------------------------------------------- Get domain config for passwords
 2822: 
 2823: sub get_passwdconf {
 2824:     my ($dom) = @_;
 2825:     my (%passwdconf,$gotconf,$lookup);
 2826:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2827:     if (defined($cached)) {
 2828:         if (ref($result) eq 'HASH') {
 2829:             %passwdconf = %{$result};
 2830:             $gotconf = 1;
 2831:         }
 2832:     }
 2833:     unless ($gotconf) {
 2834:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2835:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2836:             %passwdconf = %{$domconfig{'passwords'}};
 2837:         }
 2838:         my $cachetime = 24*60*60;
 2839:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2840:     }
 2841:     return %passwdconf;
 2842: }
 2843: 
 2844: # --------------------------------------------------- Assign a key to a student
 2845: 
 2846: sub assign_access_key {
 2847: #
 2848: # a valid key looks like uname:udom#comments
 2849: # comments are being appended
 2850: #
 2851:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2852:     $kdom=
 2853:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2854:     $knum=
 2855:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2856:     $cdom=
 2857:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2858:     $cnum=
 2859:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2860:     $udom=$env{'user.name'} unless (defined($udom));
 2861:     $uname=$env{'user.domain'} unless (defined($uname));
 2862:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2863:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2864:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2865:                                                   # assigned to this person
 2866:                                                   # - this should not happen,
 2867:                                                   # unless something went wrong
 2868:                                                   # the first time around
 2869: # ready to assign
 2870:         $logentry=$1.'; '.$logentry;
 2871:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2872:                                                  $kdom,$knum) eq 'ok') {
 2873: # key now belongs to user
 2874: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2875:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2876:                 &appenv({'environment.'.$envkey => $ckey});
 2877:                 return 'ok';
 2878:             } else {
 2879:                 return 
 2880:   'error: Count not permanently assign key, will need to be re-entered later.';
 2881: 	    }
 2882:         } else {
 2883:             return 'error: Could not assign key, try again later.';
 2884:         }
 2885:     } elsif (!$existing{$ckey}) {
 2886: # the key does not exist
 2887: 	return 'error: The key does not exist';
 2888:     } else {
 2889: # the key is somebody else's
 2890: 	return 'error: The key is already in use';
 2891:     }
 2892: }
 2893: 
 2894: # ------------------------------------------ put an additional comment on a key
 2895: 
 2896: sub comment_access_key {
 2897: #
 2898: # a valid key looks like uname:udom#comments
 2899: # comments are being appended
 2900: #
 2901:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2902:     $cdom=
 2903:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2904:     $cnum=
 2905:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2906:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2907:     if ($existing{$ckey}) {
 2908:         $existing{$ckey}.='; '.$logentry;
 2909: # ready to assign
 2910:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2911:                                                  $cdom,$cnum) eq 'ok') {
 2912: 	    return 'ok';
 2913:         } else {
 2914: 	    return 'error: Count not store comment.';
 2915:         }
 2916:     } else {
 2917: # the key does not exist
 2918: 	return 'error: The key does not exist';
 2919:     }
 2920: }
 2921: 
 2922: # ------------------------------------------------------ Generate a set of keys
 2923: 
 2924: sub generate_access_keys {
 2925:     my ($number,$cdom,$cnum,$logentry)=@_;
 2926:     $cdom=
 2927:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2928:     $cnum=
 2929:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2930:     unless (&allowed('mky',$cdom)) { return 0; }
 2931:     unless (($cdom) && ($cnum)) { return 0; }
 2932:     if ($number>10000) { return 0; }
 2933:     sleep(2); # make sure don't get same seed twice
 2934:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2935:     my $total=0;
 2936:     for (my $i=1;$i<=$number;$i++) {
 2937:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2938:                   sprintf("%lx",int(100000*rand)).'-'.
 2939:                   sprintf("%lx",int(100000*rand));
 2940:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2941:        $newkey=~s/0/h/g; # and also 0 and O
 2942:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2943:        if ($existing{$newkey}) {
 2944:            $i--;
 2945:        } else {
 2946: 	  if (&put('accesskeys',
 2947:               { $newkey => '# generated '.localtime().
 2948:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2949:                            '; '.$logentry },
 2950: 		   $cdom,$cnum) eq 'ok') {
 2951:               $total++;
 2952: 	  }
 2953:        }
 2954:     }
 2955:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2956:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2957:     return $total;
 2958: }
 2959: 
 2960: # ------------------------------------------------------- Validate an accesskey
 2961: 
 2962: sub validate_access_key {
 2963:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2964:     $cdom=
 2965:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2966:     $cnum=
 2967:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2968:     $udom=$env{'user.domain'} unless (defined($udom));
 2969:     $uname=$env{'user.name'} unless (defined($uname));
 2970:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2971:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2972: }
 2973: 
 2974: # ------------------------------------- Find the section of student in a course
 2975: sub devalidate_getsection_cache {
 2976:     my ($udom,$unam,$courseid)=@_;
 2977:     my $hashid="$udom:$unam:$courseid";
 2978:     &devalidate_cache_new('getsection',$hashid);
 2979: }
 2980: 
 2981: sub courseid_to_courseurl {
 2982:     my ($courseid) = @_;
 2983:     #already url style courseid
 2984:     return $courseid if ($courseid =~ m{^/});
 2985: 
 2986:     if (exists($env{'course.'.$courseid.'.num'})) {
 2987: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2988: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2989: 	return "/$cdom/$cnum";
 2990:     }
 2991: 
 2992:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2993:     if (exists($courseinfo{'num'})) {
 2994: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2995:     }
 2996: 
 2997:     return undef;
 2998: }
 2999: 
 3000: sub getsection {
 3001:     my ($udom,$unam,$courseid)=@_;
 3002:     my $cachetime=1800;
 3003: 
 3004:     my $hashid="$udom:$unam:$courseid";
 3005:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3006:     if (defined($cached)) { return $result; }
 3007: 
 3008:     my %Pending; 
 3009:     my %Expired;
 3010:     #
 3011:     # Each role can either have not started yet (pending), be active, 
 3012:     #    or have expired.
 3013:     #
 3014:     # If there is an active role, we are done.
 3015:     #
 3016:     # If there is more than one role which has not started yet, 
 3017:     #     choose the one which will start sooner
 3018:     # If there is one role which has not started yet, return it.
 3019:     #
 3020:     # If there is more than one expired role, choose the one which ended last.
 3021:     # If there is a role which has expired, return it.
 3022:     #
 3023:     $courseid = &courseid_to_courseurl($courseid);
 3024:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3025:     foreach my $key (keys(%roleshash)) {
 3026:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3027:         my $section=$1;
 3028:         if ($key eq $courseid.'_st') { $section=''; }
 3029:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3030:         my $now=time;
 3031:         if (defined($end) && $end && ($now > $end)) {
 3032:             $Expired{$end}=$section;
 3033:             next;
 3034:         }
 3035:         if (defined($start) && $start && ($now < $start)) {
 3036:             $Pending{$start}=$section;
 3037:             next;
 3038:         }
 3039:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3040:     }
 3041:     #
 3042:     # Presumedly there will be few matching roles from the above
 3043:     # loop and the sorting time will be negligible.
 3044:     if (scalar(keys(%Pending))) {
 3045:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3046:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3047:     } 
 3048:     if (scalar(keys(%Expired))) {
 3049:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3050:         my $time = pop(@sorted);
 3051:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3052:     }
 3053:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3054: }
 3055: 
 3056: sub save_cache {
 3057:     &purge_remembered();
 3058:     #&Apache::loncommon::validate_page();
 3059:     undef(%env);
 3060:     undef($env_loaded);
 3061: }
 3062: 
 3063: my $to_remember=-1;
 3064: my %remembered;
 3065: my %accessed;
 3066: my $kicks=0;
 3067: my $hits=0;
 3068: sub make_key {
 3069:     my ($name,$id) = @_;
 3070:     if (length($id) > 65 
 3071: 	&& length(&escape($id)) > 200) {
 3072: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3073:     }
 3074:     return &escape($name.':'.$id);
 3075: }
 3076: 
 3077: sub devalidate_cache_new {
 3078:     my ($name,$id,$debug) = @_;
 3079:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3080:     my $remembered_id=$name.':'.$id;
 3081:     $id=&make_key($name,$id);
 3082:     $memcache->delete($id);
 3083:     delete($remembered{$remembered_id});
 3084:     delete($accessed{$remembered_id});
 3085: }
 3086: 
 3087: sub is_cached_new {
 3088:     my ($name,$id,$debug) = @_;
 3089:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3090:     if (exists($remembered{$remembered_id})) {
 3091: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3092: 	$accessed{$remembered_id}=[&gettimeofday()];
 3093: 	$hits++;
 3094: 	return ($remembered{$remembered_id},1);
 3095:     }
 3096:     $id=&make_key($name,$id);
 3097:     my $value = $memcache->get($id);
 3098:     if (!(defined($value))) {
 3099: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3100: 	return (undef,undef);
 3101:     }
 3102:     if ($value eq '__undef__') {
 3103: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3104: 	$value=undef;
 3105:     }
 3106:     &make_room($remembered_id,$value,$debug);
 3107:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3108:     return ($value,1);
 3109: }
 3110: 
 3111: sub do_cache_new {
 3112:     my ($name,$id,$value,$time,$debug) = @_;
 3113:     my $remembered_id=$name.':'.$id;
 3114:     $id=&make_key($name,$id);
 3115:     my $setvalue=$value;
 3116:     if (!defined($setvalue)) {
 3117: 	$setvalue='__undef__';
 3118:     }
 3119:     if (!defined($time) ) {
 3120: 	$time=600;
 3121:     }
 3122:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3123:     my $result = $memcache->set($id,$setvalue,$time);
 3124:     if (! $result) {
 3125: 	&logthis("caching of id -> $id  failed");
 3126: 	$memcache->disconnect_all();
 3127:     }
 3128:     # need to make a copy of $value
 3129:     &make_room($remembered_id,$value,$debug);
 3130:     return $value;
 3131: }
 3132: 
 3133: sub make_room {
 3134:     my ($remembered_id,$value,$debug)=@_;
 3135: 
 3136:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3137:                                     : $value;
 3138:     if ($to_remember<0) { return; }
 3139:     $accessed{$remembered_id}=[&gettimeofday()];
 3140:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3141:     my $to_kick;
 3142:     my $max_time=0;
 3143:     foreach my $other (keys(%accessed)) {
 3144: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3145: 	    $to_kick=$other;
 3146: 	    $max_time=&tv_interval($accessed{$other});
 3147: 	}
 3148:     }
 3149:     delete($remembered{$to_kick});
 3150:     delete($accessed{$to_kick});
 3151:     $kicks++;
 3152:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3153:     return;
 3154: }
 3155: 
 3156: sub purge_remembered {
 3157:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3158:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3159:     undef(%remembered);
 3160:     undef(%accessed);
 3161: }
 3162: # ------------------------------------- Read an entry from a user's environment
 3163: 
 3164: sub userenvironment {
 3165:     my ($udom,$unam,@what)=@_;
 3166:     my $items;
 3167:     foreach my $item (@what) {
 3168:         $items.=&escape($item).'&';
 3169:     }
 3170:     $items=~s/\&$//;
 3171:     my %returnhash=();
 3172:     my $uhome = &homeserver($unam,$udom);
 3173:     unless ($uhome eq 'no_host') {
 3174:         my @answer=split(/\&/, 
 3175:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3176:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3177:             return %returnhash;
 3178:         }
 3179:         my $i;
 3180:         for ($i=0;$i<=$#what;$i++) {
 3181: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3182:         }
 3183:     }
 3184:     return %returnhash;
 3185: }
 3186: 
 3187: # ---------------------------------------------------------- Get a studentphoto
 3188: sub studentphoto {
 3189:     my ($udom,$unam,$ext) = @_;
 3190:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3191:     if (defined($env{'request.course.id'})) {
 3192:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3193:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3194:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3195:             } else {
 3196:                 my ($result,$perm_reqd)=
 3197: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3198:                 if ($result eq 'ok') {
 3199:                     if (!($perm_reqd eq 'yes')) {
 3200:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3201:                     }
 3202:                 }
 3203:             }
 3204:         }
 3205:     } else {
 3206:         my ($result,$perm_reqd) = 
 3207: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3208:         if ($result eq 'ok') {
 3209:             if (!($perm_reqd eq 'yes')) {
 3210:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3211:             }
 3212:         }
 3213:     }
 3214:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3215: }
 3216: 
 3217: sub retrievestudentphoto {
 3218:     my ($udom,$unam,$ext,$type) = @_;
 3219:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3220:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3221:     if ($ret eq 'ok') {
 3222:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3223:         if ($type eq 'thumbnail') {
 3224:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3225:         }
 3226:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3227:         return $tokenurl;
 3228:     } else {
 3229:         if ($type eq 'thumbnail') {
 3230:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3231:         } else { 
 3232:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3233:         }
 3234:     }
 3235: }
 3236: 
 3237: # -------------------------------------------------------------------- New chat
 3238: 
 3239: sub chatsend {
 3240:     my ($newentry,$anon,$group)=@_;
 3241:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3242:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3243:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3244:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3245: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3246: 		   &escape($newentry)).':'.$group,$chome);
 3247: }
 3248: 
 3249: # ------------------------------------------ Find current version of a resource
 3250: 
 3251: sub getversion {
 3252:     my $fname=&clutter(shift);
 3253:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3254:     return &currentversion(&filelocation('',$fname));
 3255: }
 3256: 
 3257: sub currentversion {
 3258:     my $fname=shift;
 3259:     my $author=$fname;
 3260:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3261:     my ($udom,$uname)=split(/\//,$author);
 3262:     my $home=&homeserver($uname,$udom);
 3263:     if ($home eq 'no_host') { 
 3264:         return -1; 
 3265:     }
 3266:     my $answer=&reply("currentversion:$fname",$home);
 3267:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3268: 	return -1;
 3269:     }
 3270:     return $answer;
 3271: }
 3272: 
 3273: #
 3274: # Return special version number of resource if set by override, empty otherwise
 3275: #
 3276: sub usedversion {
 3277:     my $fname=shift;
 3278:     unless ($fname) { $fname=$env{'request.uri'}; }
 3279:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3280:     if ($urlversion) { return $urlversion; }
 3281:     return '';
 3282: }
 3283: 
 3284: # ----------------------------- Subscribe to a resource, return URL if possible
 3285: 
 3286: sub subscribe {
 3287:     my $fname=shift;
 3288:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3289:     $fname=~s/[\n\r]//g;
 3290:     my $author=$fname;
 3291:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3292:     my ($udom,$uname)=split(/\//,$author);
 3293:     my $home=homeserver($uname,$udom);
 3294:     if ($home eq 'no_host') {
 3295:         return 'not_found';
 3296:     }
 3297:     my $answer=reply("sub:$fname",$home);
 3298:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3299: 	$answer.=' by '.$home;
 3300:     }
 3301:     return $answer;
 3302: }
 3303:     
 3304: # -------------------------------------------------------------- Replicate file
 3305: 
 3306: sub repcopy {
 3307:     my $filename=shift;
 3308:     $filename=~s/\/+/\//g;
 3309:     my $londocroot = $perlvar{'lonDocRoot'};
 3310:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3311:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3312:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3313: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3314: 	return &repcopy_userfile($filename);
 3315:     }
 3316:     $filename=~s/[\n\r]//g;
 3317:     my $transname="$filename.in.transfer";
 3318: # FIXME: this should flock
 3319:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3320:     my $remoteurl=subscribe($filename);
 3321:     if ($remoteurl =~ /^con_lost by/) {
 3322: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3323:            return 'unavailable';
 3324:     } elsif ($remoteurl eq 'not_found') {
 3325: 	   #&logthis("Subscribe returned not_found: $filename");
 3326: 	   return 'not_found';
 3327:     } elsif ($remoteurl =~ /^rejected by/) {
 3328: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3329:            return 'forbidden';
 3330:     } elsif ($remoteurl eq 'directory') {
 3331:            return 'ok';
 3332:     } else {
 3333:         my $author=$filename;
 3334:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3335:         my ($udom,$uname)=split(/\//,$author);
 3336:         my $home=homeserver($uname,$udom);
 3337:         unless ($home eq $perlvar{'lonHostID'}) {
 3338:            my @parts=split(/\//,$filename);
 3339:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3340:            if ($path ne "$londocroot/res") {
 3341:                &logthis("Malconfiguration for replication: $filename");
 3342: 	       return 'bad_request';
 3343:            }
 3344:            my $count;
 3345:            for ($count=5;$count<$#parts;$count++) {
 3346:                $path.="/$parts[$count]";
 3347:                if ((-e $path)!=1) {
 3348: 		   mkdir($path,0777);
 3349:                }
 3350:            }
 3351:            my $request=new HTTP::Request('GET',"$remoteurl");
 3352:            my $response;
 3353:            if ($remoteurl =~ m{/raw/}) {
 3354:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3355:            } else {
 3356:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3357:            }
 3358:            if ($response->is_error()) {
 3359: 	       unlink($transname);
 3360:                my $message=$response->status_line;
 3361:                &logthis("<font color=\"blue\">WARNING:"
 3362:                        ." LWP get: $message: $filename</font>");
 3363:                return 'unavailable';
 3364:            } else {
 3365: 	       if ($remoteurl!~/\.meta$/) {
 3366:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3367:                   my $mresponse;
 3368:                   if ($remoteurl =~ m{/raw/}) {
 3369:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3370:                   } else {
 3371:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3372:                   }
 3373:                   if ($mresponse->is_error()) {
 3374: 		      unlink($filename.'.meta');
 3375:                       &logthis(
 3376:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3377:                   }
 3378: 	       }
 3379:                rename($transname,$filename);
 3380:                return 'ok';
 3381:            }
 3382:        }
 3383:     }
 3384: }
 3385: 
 3386: # ------------------------------------------------- Unsubscribe from a resource
 3387: 
 3388: sub unsubscribe {
 3389:     my ($fname) = @_;
 3390:     my $answer;
 3391:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3392:     $fname=~s/[\n\r]//g;
 3393:     my $author=$fname;
 3394:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3395:     my ($udom,$uname)=split(/\//,$author);
 3396:     my $home=homeserver($uname,$udom);
 3397:     if ($home eq 'no_host') {
 3398:         $answer = 'no_host';
 3399:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3400:         $answer = 'home';
 3401:     } else {
 3402:         my $defdom = $perlvar{'lonDefDomain'};
 3403:         if (&will_trust('content',$defdom,$udom)) {
 3404:             $answer = reply("unsub:$fname",$home);
 3405:         } else {
 3406:             $answer = 'untrusted';
 3407:         }
 3408:     }
 3409:     return $answer;
 3410: }
 3411: 
 3412: # ------------------------------------------------ Get server side include body
 3413: sub ssi_body {
 3414:     my ($filelink,%form)=@_;
 3415:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3416:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3417:     }
 3418:     my $output='';
 3419:     my $response;
 3420:     if ($filelink=~/^https?\:/) {
 3421:        ($output,$response)=&externalssi($filelink);
 3422:     } else {
 3423:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3424:        $filelink .= 'inhibitmenu=yes';
 3425:        ($output,$response)=&ssi($filelink,%form);
 3426:     }
 3427:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3428:     $output=~s/^.*?\<body[^\>]*\>//si;
 3429:     $output=~s/\<\/body\s*\>.*?$//si;
 3430:     if (wantarray) {
 3431:         return ($output, $response);
 3432:     } else {
 3433:         return $output;
 3434:     }
 3435: }
 3436: 
 3437: # --------------------------------------------------------- Server Side Include
 3438: 
 3439: sub absolute_url {
 3440:     my ($host_name) = @_;
 3441:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3442:     if ($host_name eq '') {
 3443: 	$host_name = $ENV{'SERVER_NAME'};
 3444:     }
 3445:     return $protocol.$host_name;
 3446: }
 3447: 
 3448: #
 3449: #   Server side include.
 3450: # Parameters:
 3451: #  fn     Possibly encrypted resource name/id.
 3452: #  form   Hash that describes how the rendering should be done
 3453: #         and other things.
 3454: # Returns:
 3455: #   Scalar context: The content of the response.
 3456: #   Array context:  2 element list of the content and the full response object.
 3457: #     
 3458: sub ssi {
 3459: 
 3460:     my ($fn,%form)=@_;
 3461:     my $request;
 3462: 
 3463:     $form{'no_update_last_known'}=1;
 3464:     &Apache::lonenc::check_encrypt(\$fn);
 3465:     if (%form) {
 3466:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3467:       $request->content(join('&',map { 
 3468:             my $name = escape($_);
 3469:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3470:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3471:             : &escape($form{$_}) );    
 3472:         } keys(%form)));
 3473:     } else {
 3474:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3475:     }
 3476: 
 3477:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3478:     my $lonhost = $perlvar{'lonHostID'};
 3479:     my $islocal;
 3480:     if (($env{'request.course.id'}) &&
 3481:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3482:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3483:         ($form{'grade_symb'} ne '') &&
 3484:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3485:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3486:         $islocal = 1;
 3487:     }
 3488:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3489:                                                 '','','',$islocal);
 3490: 
 3491:     if (wantarray) {
 3492: 	return ($response->content, $response);
 3493:     } else {
 3494: 	return $response->content;
 3495:     }
 3496: }
 3497: 
 3498: sub externalssi {
 3499:     my ($url)=@_;
 3500:     my $request=new HTTP::Request('GET',$url);
 3501:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3502:     if (wantarray) {
 3503:         return ($response->content, $response);
 3504:     } else {
 3505:         return $response->content;
 3506:     }
 3507: }
 3508: 
 3509: 
 3510: # If the local copy of a replicated resource is outdated, trigger a  
 3511: # connection from the homeserver to flush the delayed queue. If no update 
 3512: # happens, remove local copies of outdated resource (and corresponding
 3513: # metadata file).
 3514: 
 3515: sub remove_stale_resfile {
 3516:     my ($url) = @_;
 3517:     my $removed;
 3518:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3519:         my $audom = $1;
 3520:         my $auname = $2;
 3521:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3522:             my $homeserver = &homeserver($auname,$audom);
 3523:             unless (($homeserver eq 'no_host') ||
 3524:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3525:                 my $fname = &filelocation('',$url);
 3526:                 if (-e $fname) {
 3527:                     my $hostname = &hostname($homeserver);
 3528:                     if ($hostname) {
 3529:                         my $protocol = $protocol{$homeserver};
 3530:                         $protocol = 'http' if ($protocol ne 'https');
 3531:                         my $uri = &declutter($url);
 3532:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3533:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3534:                         if ($response->is_success()) {
 3535:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3536:                             my $locmodtime = (stat($fname))[9];
 3537:                             if ($locmodtime < $remmodtime) {
 3538:                                 my $stale;
 3539:                                 my $answer = &reply('pong',$homeserver);
 3540:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3541:                                     sleep(0.2);
 3542:                                     $locmodtime = (stat($fname))[9];
 3543:                                     if ($locmodtime < $remmodtime) {
 3544:                                         my $posstransfer = $fname.'.in.transfer';
 3545:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3546:                                             $removed = 1;
 3547:                                         } else {
 3548:                                             $stale = 1;
 3549:                                         }
 3550:                                     } else {
 3551:                                         $removed = 1;
 3552:                                     }
 3553:                                 } else {
 3554:                                     $stale = 1;
 3555:                                 }
 3556:                                 if ($stale) {
 3557:                                     if (unlink($fname)) {
 3558:                                         if ($uri!~/\.meta$/) {
 3559:                                             if (-e $fname.'.meta') {
 3560:                                                 unlink($fname.'.meta');
 3561:                                             }
 3562:                                         }
 3563:                                         my $unsubresult = &unsubscribe($fname);
 3564:                                         unless ($unsubresult eq 'ok') {
 3565:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3566:                                         }
 3567:                                         $removed = 1;
 3568:                                     }
 3569:                                 }
 3570:                             }
 3571:                         }
 3572:                     }
 3573:                 }
 3574:             }
 3575:         }
 3576:     }
 3577:     return $removed;
 3578: }
 3579: 
 3580: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3581: 
 3582: sub allowuploaded {
 3583:     my ($srcurl,$url)=@_;
 3584:     $url=&clutter(&declutter($url));
 3585:     my $dir=$url;
 3586:     $dir=~s/\/[^\/]+$//;
 3587:     my %httpref=();
 3588:     my $httpurl=&hreflocation('',$url);
 3589:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3590:     &Apache::lonnet::appenv(\%httpref);
 3591: }
 3592: 
 3593: #
 3594: # Determine if the current user should be able to edit a particular resource,
 3595: # when viewing in course context.
 3596: # (a) When viewing resource used to determine if "Edit" item is included in 
 3597: #     Functions.
 3598: # (b) When displaying folder contents in course editor, used to determine if
 3599: #     "Edit" link will be displayed alongside resource.
 3600: #
 3601: #  input: six args -- filename (decluttered), course number, course domain,
 3602: #                   url, symb (if registered) and group (if this is a group
 3603: #                   item -- e.g., bulletin board, group page etc.).
 3604: #  output: array of five scalars -- 
 3605: #          $cfile -- url for file editing if editable on current server
 3606: #          $home -- homeserver of resource (i.e., for author if published,
 3607: #                                           or course if uploaded.).
 3608: #          $switchserver --  1 if server switch will be needed.
 3609: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3610: #          $forceview -- 1 if icon/link should be to go to view mode
 3611: #
 3612: 
 3613: sub can_edit_resource {
 3614:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3615:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3616: #
 3617: # For aboutme pages user can only edit his/her own.
 3618: #
 3619:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3620:         my ($sdom,$sname) = ($1,$2);
 3621:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3622:             $home = $env{'user.home'};
 3623:             $cfile = $resurl;
 3624:             if ($env{'form.forceedit'}) {
 3625:                 $forceview = 1;
 3626:             } else {
 3627:                 $forceedit = 1;
 3628:             }
 3629:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3630:         } else {
 3631:             return;
 3632:         }
 3633:     }
 3634: 
 3635:     if ($env{'request.course.id'}) {
 3636:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3637:         if ($group ne '') {
 3638: # if this is a group homepage or group bulletin board, check group privs
 3639:             my $allowed = 0;
 3640:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3641:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3642:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3643:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3644:                     $allowed = 1;
 3645:                 }
 3646:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3647:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3648:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3649:                     $allowed = 1;
 3650:                 }
 3651:             }
 3652:             if ($allowed) {
 3653:                 $home=&homeserver($cnum,$cdom);
 3654:                 if ($env{'form.forceedit'}) {
 3655:                     $forceview = 1;
 3656:                 } else {
 3657:                     $forceedit = 1;
 3658:                 }
 3659:                 $cfile = $resurl;
 3660:             } else {
 3661:                 return;
 3662:             }
 3663:         } else {
 3664:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3665:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3666:                     return;
 3667:                 }
 3668:             } elsif (!$crsedit) {
 3669: #
 3670: # No edit allowed where CC has switched to student role.
 3671: #
 3672:                 return;
 3673:             }
 3674:         }
 3675:     }
 3676: 
 3677:     if ($file ne '') {
 3678:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3679:             if (&is_course_upload($file,$cnum,$cdom)) {
 3680:                 $uploaded = 1;
 3681:                 $incourse = 1;
 3682:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3683:                     $cfile = &hreflocation('',$file);
 3684:                     if ($env{'form.forceedit'}) {
 3685:                         $forceview = 1;
 3686:                     } else {
 3687:                         $forceedit = 1;
 3688:                     }
 3689:                 }
 3690:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3691:                 $incourse = 1;
 3692:                 if ($env{'form.forceedit'}) {
 3693:                     $forceview = 1;
 3694:                 } else {
 3695:                     $forceedit = 1;
 3696:                 }
 3697:                 $cfile = $resurl;
 3698:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3699:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3700:                     $incourse = 1;
 3701:                     if ($env{'form.forceedit'}) {
 3702:                         $forceview = 1;
 3703:                     } else {
 3704:                         $forceedit = 1;
 3705:                     }
 3706:                     $cfile = $resurl;
 3707:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3708:                     $incourse = 1;
 3709:                     $cfile = $resurl.'/smpedit';
 3710:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3711:                     $incourse = 1;
 3712:                     if ($env{'form.forceedit'}) {
 3713:                         $forceview = 1;
 3714:                     } else {
 3715:                         $forceedit = 1;
 3716:                     }
 3717:                     $cfile = $resurl;
 3718:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3719:                     my ($map,$id,$res) = &decode_symb($symb);
 3720:                     if ($map =~ /\.page$/) {
 3721:                         $incourse = 1;
 3722:                         if ($env{'form.forceedit'}) {
 3723:                             $forceview = 1;
 3724:                             $cfile = $map;
 3725:                         } else {
 3726:                             $forceedit = 1;
 3727:                             $cfile =  '/adm/wrapper'.$resurl;
 3728:                         }
 3729:                     }
 3730:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3731:                     $incourse = 1;
 3732:                     if ($env{'form.forceedit'}) {
 3733:                         $forceview = 1;
 3734:                     } else {
 3735:                         $forceedit = 1;
 3736:                     }
 3737:                     $cfile = $resurl;
 3738:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3739:                     $incourse = 1;
 3740:                     if ($env{'form.forceedit'}) {
 3741:                         $forceview = 1;
 3742:                     } else {
 3743:                         $forceedit = 1;
 3744:                     }
 3745:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3746:                 }
 3747:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3748:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3749:                 if (&is_on_map($template)) { 
 3750:                     $incourse = 1;
 3751:                     $forceview = 1;
 3752:                     $cfile = $template;
 3753:                 }
 3754:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3755:                 $incourse = 1;
 3756:                 if ($env{'form.forceedit'}) {
 3757:                     $forceview = 1;
 3758:                 } else {
 3759:                     $forceedit = 1;
 3760:                 }
 3761:                 $cfile = $resurl;
 3762:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3763:                 $incourse = 1;
 3764:                 if ($env{'form.forceedit'}) {
 3765:                     $forceview = 1;
 3766:                 } else {
 3767:                     $forceedit = 1;
 3768:                 }
 3769:                 $cfile = $resurl;
 3770:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3771:                 $incourse = 1;
 3772:                 $forceview = 1;
 3773:                 if ($symb) {
 3774:                     my ($map,$id,$res)=&decode_symb($symb);
 3775:                     $env{'request.symb'} = $symb;
 3776:                     $cfile = &clutter($res);
 3777:                 } else {
 3778:                     $cfile = $env{'form.suppurl'};
 3779:                     my $escfile = &unescape($cfile);
 3780:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3781:                         $cfile = '/adm/wrapper'.$escfile;
 3782:                     } else {
 3783:                         $escfile =~ s{^http://}{};
 3784:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3785:                     }
 3786:                 }
 3787:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3788:                 if ($env{'form.forceedit'}) {
 3789:                     $forceview = 1;
 3790:                 } else {
 3791:                     $forceedit = 1;
 3792:                 }
 3793:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3794:             }
 3795:         }
 3796:         if ($uploaded || $incourse) {
 3797:             $home=&homeserver($cnum,$cdom);
 3798:         } elsif ($file !~ m{/$}) {
 3799:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3800:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3801:             # Check that the user has permission to edit this resource
 3802:             my $setpriv = 1;
 3803:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3804:             if (defined($cfudom)) {
 3805:                 $home=&homeserver($cfuname,$cfudom);
 3806:                 $cfile=$file;
 3807:             }
 3808:         }
 3809:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3810:             (($home ne '') && ($home ne 'no_host'))) {
 3811:             my @ids=&current_machine_ids();
 3812:             unless (grep(/^\Q$home\E$/,@ids)) {
 3813:                 $switchserver=1;
 3814:             }
 3815:         }
 3816:     }
 3817:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3818: }
 3819: 
 3820: sub is_course_upload {
 3821:     my ($file,$cnum,$cdom) = @_;
 3822:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3823:     $uploadpath =~ s{^\/}{};
 3824:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3825:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3826:         return 1;
 3827:     }
 3828:     return;
 3829: }
 3830: 
 3831: sub in_course {
 3832:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3833:     if ($hideprivileged) {
 3834:         my $skipuser;
 3835:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3836:         my @possdoms = ($cdom);  
 3837:         if ($coursehash{'checkforpriv'}) { 
 3838:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3839:         }
 3840:         if (&privileged($uname,$udom,\@possdoms)) {
 3841:             $skipuser = 1;
 3842:             if ($coursehash{'nothideprivileged'}) {
 3843:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3844:                     my $user;
 3845:                     if ($item =~ /:/) {
 3846:                         $user = $item;
 3847:                     } else {
 3848:                         $user = join(':',split(/[\@]/,$item));
 3849:                     }
 3850:                     if ($user eq $uname.':'.$udom) {
 3851:                         undef($skipuser);
 3852:                         last;
 3853:                     }
 3854:                 }
 3855:             }
 3856:             if ($skipuser) {
 3857:                 return 0;
 3858:             }
 3859:         }
 3860:     }
 3861:     $type ||= 'any';
 3862:     if (!defined($cdom) || !defined($cnum)) {
 3863:         my $cid  = $env{'request.course.id'};
 3864:         $cdom = $env{'course.'.$cid.'.domain'};
 3865:         $cnum = $env{'course.'.$cid.'.num'};
 3866:     }
 3867:     my $typesref;
 3868:     if (($type eq 'any') || ($type eq 'all')) {
 3869:         $typesref = ['active','previous','future'];
 3870:     } elsif ($type eq 'previous' || $type eq 'future') {
 3871:         $typesref = [$type];
 3872:     }
 3873:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3874:                               $typesref,undef,[$cdom]);
 3875:     my ($tmp) = keys(%roles);
 3876:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3877:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3878:     if (@course_roles > 0) {
 3879:         return 1;
 3880:     }
 3881:     return 0;
 3882: }
 3883: 
 3884: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3885: # input: action, courseID, current domain, intended
 3886: #        path to file, source of file, instruction to parse file for objects,
 3887: #        ref to hash for embedded objects,
 3888: #        ref to hash for codebase of java objects.
 3889: #        reference to scalar to accommodate mime type determined
 3890: #          from File::MMagic if $parser = parse.
 3891: #
 3892: # output: url to file (if action was uploaddoc), 
 3893: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3894: #
 3895: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3896: # course.
 3897: #
 3898: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3899: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3900: #          course's home server.
 3901: #
 3902: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3903: #          be copied from $source (current location) to 
 3904: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3905: #         and will then be copied to
 3906: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3907: #         course's home server.
 3908: #
 3909: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3910: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3911: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3912: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3913: #         in course's home server.
 3914: #
 3915: 
 3916: sub process_coursefile {
 3917:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3918:         $mimetype)=@_;
 3919:     my $fetchresult;
 3920:     my $home=&homeserver($docuname,$docudom);
 3921:     if ($action eq 'propagate') {
 3922:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3923: 			     $home);
 3924:     } else {
 3925:         my $fpath = '';
 3926:         my $fname = $file;
 3927:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3928:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3929:         my $filepath = &build_filepath($fpath);
 3930:         if ($action eq 'copy') {
 3931:             if ($source eq '') {
 3932:                 $fetchresult = 'no source file';
 3933:                 return $fetchresult;
 3934:             } else {
 3935:                 my $destination = $filepath.'/'.$fname;
 3936:                 rename($source,$destination);
 3937:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3938:                                  $home);
 3939:             }
 3940:         } elsif ($action eq 'uploaddoc') {
 3941:             open(my $fh,'>',$filepath.'/'.$fname);
 3942:             print $fh $env{'form.'.$source};
 3943:             close($fh);
 3944:             if ($parser eq 'parse') {
 3945:                 my $mm = new File::MMagic;
 3946:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3947:                 if ($type eq 'text/html') {
 3948:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3949:                     unless ($parse_result eq 'ok') {
 3950:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3951:                     }
 3952:                 }
 3953:                 if (ref($mimetype)) {
 3954:                     $$mimetype = $type;
 3955:                 } 
 3956:             }
 3957:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3958:                                  $home);
 3959:             if ($fetchresult eq 'ok') {
 3960:                 return '/uploaded/'.$fpath.'/'.$fname;
 3961:             } else {
 3962:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3963:                         ' to host '.$home.': '.$fetchresult);
 3964:                 return '/adm/notfound.html';
 3965:             }
 3966:         }
 3967:     }
 3968:     unless ( $fetchresult eq 'ok') {
 3969:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3970:              ' to host '.$home.': '.$fetchresult);
 3971:     }
 3972:     return $fetchresult;
 3973: }
 3974: 
 3975: sub build_filepath {
 3976:     my ($fpath) = @_;
 3977:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3978:     unless ($fpath eq '') {
 3979:         my @parts=split('/',$fpath);
 3980:         foreach my $part (@parts) {
 3981:             $filepath.= '/'.$part;
 3982:             if ((-e $filepath)!=1) {
 3983:                 mkdir($filepath,0777);
 3984:             }
 3985:         }
 3986:     }
 3987:     return $filepath;
 3988: }
 3989: 
 3990: sub store_edited_file {
 3991:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3992:     my $file = $primary_url;
 3993:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3994:     my $fpath = '';
 3995:     my $fname = $file;
 3996:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3997:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3998:     my $filepath = &build_filepath($fpath);
 3999:     open(my $fh,'>',$filepath.'/'.$fname);
 4000:     print $fh $content;
 4001:     close($fh);
 4002:     my $home=&homeserver($docuname,$docudom);
 4003:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4004: 			  $home);
 4005:     if ($$fetchresult eq 'ok') {
 4006:         return '/uploaded/'.$fpath.'/'.$fname;
 4007:     } else {
 4008:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4009: 		 ' to host '.$home.': '.$$fetchresult);
 4010:         return '/adm/notfound.html';
 4011:     }
 4012: }
 4013: 
 4014: sub clean_filename {
 4015:     my ($fname,$args)=@_;
 4016: # Replace Windows backslashes by forward slashes
 4017:     $fname=~s/\\/\//g;
 4018:     if (!$args->{'keep_path'}) {
 4019:         # Get rid of everything but the actual filename
 4020: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4021:     }
 4022: # Replace spaces by underscores
 4023:     $fname=~s/\s+/\_/g;
 4024: # Transliterate non-ascii text to ascii
 4025:     my $lang = &Apache::lonlocal::current_language();
 4026:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4027: # Replace all other weird characters by nothing
 4028:     $fname=~s{[^/\w\.\-]}{}g;
 4029: # Replace all .\d. sequences with _\d. so they no longer look like version
 4030: # numbers
 4031:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4032:     return $fname;
 4033: }
 4034: 
 4035: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4036: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4037: # image with the same aspect ratio as the original, but with dimensions which do 
 4038: # not exceed $resizewidth and $resizeheight.
 4039:  
 4040: sub resizeImage {
 4041:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4042:     my $ima = Image::Magick->new;
 4043:     my $resized;
 4044:     if (-e $img_path) {
 4045:         $ima->Read($img_path);
 4046:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4047:             my $width = $ima->Get('width');
 4048:             my $height = $ima->Get('height');
 4049:             if ($width > $resizewidth) {
 4050: 	        my $factor = $width/$resizewidth;
 4051:                 my $newheight = $height/$factor;
 4052:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4053:                 $resized = 1;
 4054:             }
 4055:         }
 4056:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4057:             my $width = $ima->Get('width');
 4058:             my $height = $ima->Get('height');
 4059:             if ($height > $resizeheight) {
 4060:                 my $factor = $height/$resizeheight;
 4061:                 my $newwidth = $width/$factor;
 4062:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4063:                 $resized = 1;
 4064:             }
 4065:         }
 4066:         if ($resized) {
 4067:             $ima->Write($img_path);
 4068:         }
 4069:     }
 4070:     return;
 4071: }
 4072: 
 4073: # --------------- Take an uploaded file and put it into the userfiles directory
 4074: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4075: #                    the desired filename is in $env{"form.$formname.filename"}
 4076: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4077: #                                    canceloverwrite, scantron or ''.
 4078: #                   if 'coursedoc': upload to the current course
 4079: #                   if 'existingfile': write file to tmp/overwrites directory 
 4080: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4081: #                   $context is passed as argument to &finishuserfileupload
 4082: #        $subdir - directory in userfile to store the file into
 4083: #        $parser - instruction to parse file for objects ($parser = parse) or
 4084: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4085: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4086: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4087: #        $allfiles - reference to hash for embedded objects
 4088: #        $codebase - reference to hash for codebase of java objects
 4089: #        $desuname - username for permanent storage of uploaded file
 4090: #        $dsetudom - domain for permanaent storage of uploaded file
 4091: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4092: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4093: #        $resizewidth - width (pixels) to which to resize uploaded image
 4094: #        $resizeheight - height (pixels) to which to resize uploaded image
 4095: #        $mimetype - reference to scalar to accommodate mime type determined
 4096: #                    from File::MMagic.
 4097: # 
 4098: # output: url of file in userspace, or error: <message> 
 4099: #             or /adm/notfound.html if failure to upload occurse
 4100: 
 4101: sub userfileupload {
 4102:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4103:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4104:     if (!defined($subdir)) { $subdir='unknown'; }
 4105:     my $fname=$env{'form.'.$formname.'.filename'};
 4106:     $fname=&clean_filename($fname);
 4107:     # See if there is anything left
 4108:     unless ($fname) { return 'error: no uploaded file'; }
 4109:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4110:     if ($fname =~ /^\./) {
 4111:         my ($s,$usec) = &gettimeofday();
 4112:         while (length($usec) < 6) {
 4113:             $usec = '0'.$usec;
 4114:         }
 4115:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4116:     }
 4117:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4118:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4119:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4120:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4121:         my $now = time;
 4122:         my $filepath;
 4123:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4124:              $filepath = 'tmp/helprequests/'.$now;
 4125:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4126:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4127:                          '_'.$env{'user.domain'}.'/pending';
 4128:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4129:             my ($docuname,$docudom);
 4130:             if ($destudom =~ /^$match_domain$/) {
 4131:                 $docudom = $destudom;
 4132:             } else {
 4133:                 $docudom = $env{'user.domain'};
 4134:             }
 4135:             if ($destuname =~ /^$match_username$/) {
 4136:                 $docuname = $destuname;
 4137:             } else {
 4138:                 $docuname = $env{'user.name'};
 4139:             }
 4140:             if (exists($env{'form.group'})) {
 4141:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4142:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4143:             }
 4144:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4145:             if ($context eq 'canceloverwrite') {
 4146:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4147:                 if (-e  $tempfile) {
 4148:                     my @info = stat($tempfile);
 4149:                     if ($info[9] eq $env{'form.timestamp'}) {
 4150:                         unlink($tempfile);
 4151:                     }
 4152:                 }
 4153:                 return;
 4154:             }
 4155:         }
 4156:         # Create the directory if not present
 4157:         my @parts=split(/\//,$filepath);
 4158:         my $fullpath = $perlvar{'lonDaemons'};
 4159:         for (my $i=0;$i<@parts;$i++) {
 4160:             $fullpath .= '/'.$parts[$i];
 4161:             if ((-e $fullpath)!=1) {
 4162:                 mkdir($fullpath,0777);
 4163:             }
 4164:         }
 4165:         open(my $fh,'>',$fullpath.'/'.$fname);
 4166:         print $fh $env{'form.'.$formname};
 4167:         close($fh);
 4168:         if ($context eq 'existingfile') {
 4169:             my @info = stat($fullpath.'/'.$fname);
 4170:             return ($fullpath.'/'.$fname,$info[9]);
 4171:         } else {
 4172:             return $fullpath.'/'.$fname;
 4173:         }
 4174:     }
 4175:     if ($subdir eq 'scantron') {
 4176:         $fname = 'scantron_orig_'.$fname;
 4177:     } else {
 4178:         $fname="$subdir/$fname";
 4179:     }
 4180:     if ($context eq 'coursedoc') {
 4181: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4182: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4183:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4184:             return &finishuserfileupload($docuname,$docudom,
 4185: 					 $formname,$fname,$parser,$allfiles,
 4186: 					 $codebase,$thumbwidth,$thumbheight,
 4187:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4188:         } else {
 4189:             if ($env{'form.folder'}) {
 4190:                 $fname=$env{'form.folder'}.'/'.$fname;
 4191:             }
 4192:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4193: 				       $fname,$formname,$parser,
 4194: 				       $allfiles,$codebase,$mimetype);
 4195:         }
 4196:     } elsif (defined($destuname)) {
 4197:         my $docuname=$destuname;
 4198:         my $docudom=$destudom;
 4199: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4200: 				     $parser,$allfiles,$codebase,
 4201:                                      $thumbwidth,$thumbheight,
 4202:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4203:     } else {
 4204:         my $docuname=$env{'user.name'};
 4205:         my $docudom=$env{'user.domain'};
 4206:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4207:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4208:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4209:         }
 4210: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4211: 				     $parser,$allfiles,$codebase,
 4212:                                      $thumbwidth,$thumbheight,
 4213:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4214:     }
 4215: }
 4216: 
 4217: sub finishuserfileupload {
 4218:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4219:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4220:     my $path=$docudom.'/'.$docuname.'/';
 4221:     my $filepath=$perlvar{'lonDocRoot'};
 4222:   
 4223:     my ($fnamepath,$file,$fetchthumb);
 4224:     $file=$fname;
 4225:     if ($fname=~m|/|) {
 4226:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4227: 	$path.=$fnamepath.'/';
 4228:     }
 4229:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4230:     my $count;
 4231:     for ($count=4;$count<=$#parts;$count++) {
 4232:         $filepath.="/$parts[$count]";
 4233:         if ((-e $filepath)!=1) {
 4234: 	    mkdir($filepath,0777);
 4235:         }
 4236:     }
 4237: 
 4238: # Save the file
 4239:     {
 4240: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4241: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4242: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4243: 	    return '/adm/notfound.html';
 4244: 	}
 4245:         if ($context eq 'overwrite') {
 4246:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4247:             my $target = $filepath.'/'.$file;
 4248:             if (-e $source) {
 4249:                 my @info = stat($source);
 4250:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4251:                     unless (&File::Copy::move($source,$target)) {
 4252:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4253:                         return "Moving from $source failed";
 4254:                     }
 4255:                 } else {
 4256:                     return "Temporary file: $source had unexpected date/time for last modification";
 4257:                 }
 4258:             } else {
 4259:                 return "Temporary file: $source missing";
 4260:             }
 4261:         } elsif (!print FH ($env{'form.'.$formname})) {
 4262: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4263: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4264: 	    return '/adm/notfound.html';
 4265: 	}
 4266: 	close(FH);
 4267:         if ($resizewidth && $resizeheight) {
 4268:             my $mm = new File::MMagic;
 4269:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4270:             if ($mime_type =~ m{^image/}) {
 4271: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4272:             }  
 4273: 	}
 4274:     }
 4275:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4276:         if (ref($mimetype)) {
 4277:             if ($$mimetype eq '') {
 4278:                 my $mm = new File::MMagic;
 4279:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4280:                 $$mimetype = $type;
 4281:             }
 4282:         }
 4283:     }
 4284:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4285:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4286:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4287:                                                        $allfiles,$codebase);
 4288:             unless ($parse_result eq 'ok') {
 4289:                 &logthis('Failed to parse '.$filepath.$file.
 4290: 	   	         ' for embedded media: '.$parse_result); 
 4291:             }
 4292:         }
 4293:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4294:         my $format = $env{'form.scantron_format'};
 4295:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4296:     }
 4297:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4298:         my $input = $filepath.'/'.$file;
 4299:         my $output = $filepath.'/'.'tn-'.$file;
 4300:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4301:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4302:         system({$args[0]} @args);
 4303:         if (-e $filepath.'/'.'tn-'.$file) {
 4304:             $fetchthumb  = 1; 
 4305:         }
 4306:     }
 4307:  
 4308: # Notify homeserver to grep it
 4309: #
 4310:     my $docuhome=&homeserver($docuname,$docudom);	
 4311:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4312:     if ($fetchresult eq 'ok') {
 4313:         if ($fetchthumb) {
 4314:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4315:             if ($thumbresult ne 'ok') {
 4316:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4317:                          $docuhome.': '.$thumbresult);
 4318:             }
 4319:         }
 4320: #
 4321: # Return the URL to it
 4322:         return '/uploaded/'.$path.$file;
 4323:     } else {
 4324:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4325: 		 ': '.$fetchresult);
 4326:         return '/adm/notfound.html';
 4327:     }
 4328: }
 4329: 
 4330: sub extract_embedded_items {
 4331:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4332:     my @state = ();
 4333:     my (%lastids,%related,%shockwave,%flashvars);
 4334:     my %javafiles = (
 4335:                       codebase => '',
 4336:                       code => '',
 4337:                       archive => ''
 4338:                     );
 4339:     my %mediafiles = (
 4340:                       src => '',
 4341:                       movie => '',
 4342:                      );
 4343:     my $p;
 4344:     if ($content) {
 4345:         $p = HTML::LCParser->new($content);
 4346:     } else {
 4347:         $p = HTML::LCParser->new($fullpath);
 4348:     }
 4349:     while (my $t=$p->get_token()) {
 4350: 	if ($t->[0] eq 'S') {
 4351: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4352: 	    push(@state, $tagname);
 4353:             if (lc($tagname) eq 'allow') {
 4354:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4355:             }
 4356: 	    if (lc($tagname) eq 'img') {
 4357: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4358: 	    }
 4359: 	    if (lc($tagname) eq 'a') {
 4360:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4361:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4362:                 }
 4363: 	    }
 4364:             if (lc($tagname) eq 'script') {
 4365:                 my $src;
 4366:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4367:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4368:                 } else {
 4369:                     if ($attr->{'src'} ne '') {
 4370:                         $src = $attr->{'src'};
 4371:                         &add_filetype($allfiles,$src,'src');
 4372:                     }
 4373:                 }
 4374:                 my $text = $p->get_trimmed_text();
 4375:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4376:                     my @swfargs = split(/,/,$1);
 4377:                     foreach my $item (@swfargs) {
 4378:                         $item =~ s/["']//g;
 4379:                         $item =~ s/^\s+//;
 4380:                         $item =~ s/\s+$//;
 4381:                     }
 4382:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4383:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4384:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4385:                         } else {
 4386:                             $related{$swfargs[0]} = [$swfargs[2]];
 4387:                         }
 4388:                     }
 4389:                 }
 4390:             }
 4391:             if (lc($tagname) eq 'link') {
 4392:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4393:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4394:                 }
 4395:             }
 4396: 	    if (lc($tagname) eq 'object' ||
 4397: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4398: 		foreach my $item (keys(%javafiles)) {
 4399: 		    $javafiles{$item} = '';
 4400: 		}
 4401:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4402:                     $lastids{lc($tagname)} = $attr->{'id'};
 4403:                 }
 4404: 	    }
 4405: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4406: 		my $name = lc($attr->{'name'});
 4407: 		foreach my $item (keys(%javafiles)) {
 4408: 		    if ($name eq $item) {
 4409: 			$javafiles{$item} = $attr->{'value'};
 4410: 			last;
 4411: 		    }
 4412: 		}
 4413:                 my $pathfrom;
 4414: 		foreach my $item (keys(%mediafiles)) {
 4415: 		    if ($name eq $item) {
 4416:                         $pathfrom = $attr->{'value'};
 4417:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4418: 			&add_filetype($allfiles,$pathfrom,$name);
 4419: 			last;
 4420: 		    }
 4421: 		}
 4422:                 if ($name eq 'flashvars') {
 4423:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4424:                 }
 4425:                 if ($pathfrom ne '') {
 4426:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4427:                                          $pathfrom);
 4428:                 }
 4429: 	    }
 4430: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4431: 		foreach my $item (keys(%javafiles)) {
 4432: 		    if ($attr->{$item}) {
 4433: 			$javafiles{$item} = $attr->{$item};
 4434: 			last;
 4435: 		    }
 4436: 		}
 4437: 		foreach my $item (keys(%mediafiles)) {
 4438: 		    if ($attr->{$item}) {
 4439: 			&add_filetype($allfiles,$attr->{$item},$item);
 4440: 			last;
 4441: 		    }
 4442: 		}
 4443:                 if (lc($tagname) eq 'embed') {
 4444:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4445:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4446:                                              $attr->{'src'});
 4447:                     }
 4448:                 }
 4449: 	    }
 4450:             if (lc($tagname) eq 'iframe') {
 4451:                 my $src = $attr->{'src'} ;
 4452:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4453:                     &add_filetype($allfiles,$src,'src');
 4454:                 } elsif ($src =~ m{^/}) {
 4455:                     if ($env{'request.course.id'}) {
 4456:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4457:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4458:                         my $url = &hreflocation('',$fullpath);
 4459:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4460:                             my $relpath = $1;
 4461:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4462:                                 &add_filetype($allfiles,$1,'src');
 4463:                             }
 4464:                         }
 4465:                     }
 4466:                 }
 4467:             }
 4468:             if ($t->[4] =~ m{/>$}) {
 4469:                 pop(@state);
 4470:             }
 4471: 	} elsif ($t->[0] eq 'E') {
 4472: 	    my ($tagname) = ($t->[1]);
 4473: 	    if ($javafiles{'codebase'} ne '') {
 4474: 		$javafiles{'codebase'} .= '/';
 4475: 	    }  
 4476: 	    if (lc($tagname) eq 'applet' ||
 4477: 		lc($tagname) eq 'object' ||
 4478: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4479: 		) {
 4480: 		foreach my $item (keys(%javafiles)) {
 4481: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4482: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4483: 			&add_filetype($allfiles,$file,$item);
 4484: 		    }
 4485: 		}
 4486: 	    } 
 4487: 	    pop @state;
 4488: 	}
 4489:     }
 4490:     foreach my $id (sort(keys(%flashvars))) {
 4491:         if ($shockwave{$id} ne '') {
 4492:             my @pairs = split(/\&/,$flashvars{$id});
 4493:             foreach my $pair (@pairs) {
 4494:                 my ($key,$value) = split(/\=/,$pair);
 4495:                 if ($key eq 'thumb') {
 4496:                     &add_filetype($allfiles,$value,$key);
 4497:                 } elsif ($key eq 'content') {
 4498:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4499:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4500:                     if ($ext ne '') {
 4501:                         &add_filetype($allfiles,$path.$value,$ext);
 4502:                     }
 4503:                 }
 4504:             }
 4505:         }
 4506:     }
 4507:     return 'ok';
 4508: }
 4509: 
 4510: sub add_filetype {
 4511:     my ($allfiles,$file,$type)=@_;
 4512:     if (exists($allfiles->{$file})) {
 4513: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4514: 	    push(@{$allfiles->{$file}}, &escape($type));
 4515: 	}
 4516:     } else {
 4517: 	@{$allfiles->{$file}} = (&escape($type));
 4518:     }
 4519: }
 4520: 
 4521: sub embedded_dependency {
 4522:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4523:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4524:         if (($identifier ne '') &&
 4525:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4526:             ($pathfrom ne '')) {
 4527:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4528:             foreach my $dep (@{$related->{$identifier}}) {
 4529:                 &add_filetype($allfiles,$path.$dep,'object');
 4530:             }
 4531:         }
 4532:     }
 4533:     return;
 4534: }
 4535: 
 4536: sub bubblesheet_converter {
 4537:     my ($cdom,$fullpath,$config,$format) = @_;
 4538:     if ((&domain($cdom) ne '') &&
 4539:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4540:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4541:         my (%csvcols,%csvoptions);
 4542:         if (ref($config->{'fields'}) eq 'HASH') {  
 4543:             %csvcols = %{$config->{'fields'}};
 4544:         }
 4545:         if (ref($config->{'options'}) eq 'HASH') {
 4546:             %csvoptions = %{$config->{'options'}};
 4547:         }
 4548:         my %csvbynum = reverse(%csvcols);
 4549:         my %scantronconf = &get_scantron_config($format,$cdom);
 4550:         if (keys(%scantronconf)) {
 4551:             my %bynum = (
 4552:                           $scantronconf{CODEstart} => 'CODEstart',
 4553:                           $scantronconf{IDstart}   => 'IDstart',
 4554:                           $scantronconf{PaperID}   => 'PaperID',
 4555:                           $scantronconf{FirstName} => 'FirstName',
 4556:                           $scantronconf{LastName}  => 'LastName',
 4557:                           $scantronconf{Qstart}    => 'Qstart',
 4558:                         );
 4559:             my @ordered;
 4560:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4561:                 push(@ordered,$bynum{$item});
 4562:             }
 4563:             my %mapstart = (
 4564:                               CODEstart => 'CODE',
 4565:                               IDstart   => 'ID',
 4566:                               PaperID   => 'PaperID',
 4567:                               FirstName => 'FirstName',
 4568:                               LastName  => 'LastName',
 4569:                               Qstart    => 'FirstQuestion',
 4570:                            );
 4571:             my %maplength = (
 4572:                               CODEstart => 'CODElength',
 4573:                               IDstart   => 'IDlength',
 4574:                               PaperID   => 'PaperIDlength',
 4575:                               FirstName => 'FirstNamelength',
 4576:                               LastName  => 'LastNamelength',
 4577:             );
 4578:             if (open(my $fh,'<',$fullpath)) {
 4579:                 my $output;
 4580:                 my %lettdig = &letter_to_digits();
 4581:                 my %diglett = reverse(%lettdig);
 4582:                 my $numletts = scalar(keys(%lettdig));
 4583:                 my $num = 0;
 4584:                 while (my $line=<$fh>) {
 4585:                     $num ++;
 4586:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4587:                     $line =~ s{[\r\n]+$}{};
 4588:                     my %found;
 4589:                     my @values = split(/,/,$line);
 4590:                     my ($qstart,$record);
 4591:                     for (my $i=0; $i<@values; $i++) {
 4592:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4593:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4594:                             if ($values[$i] eq '') {
 4595:                                 $values[$i] = $scantronconf{'Qoff'};
 4596:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4597:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4598:                                     $values[$i] = $lettdig{uc($values[$i])};
 4599:                                 }
 4600:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4601:                                 if ($values[$i] =~ /^[0-9]$/) {
 4602:                                     $values[$i] = $diglett{$values[$i]};
 4603:                                 }
 4604:                             } else {
 4605:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4606:                                     my $digit;
 4607:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4608:                                         $digit = $lettdig{uc($values[$i])}-1;
 4609:                                         if ($values[$i] eq 'J') {
 4610:                                             $digit += $numletts;
 4611:                                         }
 4612:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4613:                                         $digit = $values[$i]-1;
 4614:                                         if ($values[$i] eq '0') {
 4615:                                             $digit += $numletts;
 4616:                                         }
 4617:                                     }
 4618:                                     my $qval='';
 4619:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4620:                                         if ($j == $digit) {
 4621:                                             $qval .= $scantronconf{'Qon'};
 4622:                                         } else {
 4623:                                             $qval .= $scantronconf{'Qoff'};
 4624:                                         }
 4625:                                     }
 4626:                                     $values[$i] = $qval;
 4627:                                 }
 4628:                             }
 4629:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4630:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4631:                             }
 4632:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4633:                             if ($numblank > 0) {
 4634:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4635:                             }
 4636:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4637:                                 $qstart = $i;
 4638:                                 $found{$csvbynum{$i}} = $values[$i];
 4639:                             } else {
 4640:                                 $found{'FirstQuestion'} .= $values[$i];
 4641:                             }
 4642:                         } elsif (exists($csvbynum{$i})) {
 4643:                             if ($csvoptions{'rem'}) {
 4644:                                 $values[$i] =~ s/^\s+//;
 4645:                             }
 4646:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4647:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4648:                                     $values[$i] = '0'.$values[$i];
 4649:                                 }
 4650:                             }
 4651:                             $found{$csvbynum{$i}} = $values[$i];
 4652:                         }
 4653:                     }
 4654:                     foreach my $item (@ordered) {
 4655:                         my $currlength = 1+length($record);
 4656:                         my $numspaces = $scantronconf{$item} - $currlength;
 4657:                         if ($numspaces > 0) {
 4658:                             $record .= (' ' x $numspaces);
 4659:                         }
 4660:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4661:                             unless ($item eq 'Qstart') {
 4662:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4663:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4664:                                 }
 4665:                             }
 4666:                             $record .= $found{$mapstart{$item}};
 4667:                         }
 4668:                     }
 4669:                     $output .= "$record\n";
 4670:                 }
 4671:                 close($fh);
 4672:                 if ($output) {
 4673:                     if (open(my $fh,'>',$fullpath)) {
 4674:                         print $fh $output;
 4675:                         close($fh);
 4676:                     }
 4677:                 }
 4678:             }
 4679:         }
 4680:         return;
 4681:     }
 4682: }
 4683: 
 4684: sub letter_to_digits {
 4685:     my %lettdig = (
 4686:                     A => 1,
 4687:                     B => 2,
 4688:                     C => 3,
 4689:                     D => 4,
 4690:                     E => 5,
 4691:                     F => 6,
 4692:                     G => 7,
 4693:                     H => 8,
 4694:                     I => 9,
 4695:                     J => 0,
 4696:                   );
 4697:     return %lettdig;
 4698: }
 4699: 
 4700: sub get_scantron_config {
 4701:     my ($which,$cdom) = @_;
 4702:     my @lines = &get_scantronformat_file($cdom);
 4703:     my %config;
 4704:     #FIXME probably should move to XML it has already gotten a bit much now
 4705:     foreach my $line (@lines) {
 4706:         my ($name,$descrip)=split(/:/,$line);
 4707:         if ($name ne $which ) { next; }
 4708:         chomp($line);
 4709:         my @config=split(/:/,$line);
 4710:         $config{'name'}=$config[0];
 4711:         $config{'description'}=$config[1];
 4712:         $config{'CODElocation'}=$config[2];
 4713:         $config{'CODEstart'}=$config[3];
 4714:         $config{'CODElength'}=$config[4];
 4715:         $config{'IDstart'}=$config[5];
 4716:         $config{'IDlength'}=$config[6];
 4717:         $config{'Qstart'}=$config[7];
 4718:         $config{'Qlength'}=$config[8];
 4719:         $config{'Qoff'}=$config[9];
 4720:         $config{'Qon'}=$config[10];
 4721:         $config{'PaperID'}=$config[11];
 4722:         $config{'PaperIDlength'}=$config[12];
 4723:         $config{'FirstName'}=$config[13];
 4724:         $config{'FirstNamelength'}=$config[14];
 4725:         $config{'LastName'}=$config[15];
 4726:         $config{'LastNamelength'}=$config[16];
 4727:         $config{'BubblesPerRow'}=$config[17];
 4728:         last;
 4729:     }
 4730:     return %config;
 4731: }
 4732: 
 4733: sub get_scantronformat_file {
 4734:     my ($cdom) = @_;
 4735:     if ($cdom eq '') {
 4736:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4737:     }
 4738:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4739:     my $gottab = 0;
 4740:     my @lines;
 4741:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4742:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4743:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4744:             if ($formatfile ne '-1') {
 4745:                 @lines = split("\n",$formatfile,-1);
 4746:                 $gottab = 1;
 4747:             }
 4748:         }
 4749:     }
 4750:     if (!$gottab) {
 4751:         my $confname = $cdom.'-domainconfig';
 4752:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4753:         my $formatfile = &getfile($default);
 4754:         if ($formatfile ne '-1') {
 4755:             @lines = split("\n",$formatfile,-1);
 4756:             $gottab = 1;
 4757:         }
 4758:     }
 4759:     if (!$gottab) {
 4760:         my @domains = &current_machine_domains();
 4761:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4762:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4763:                 @lines = <$fh>;
 4764:                 close($fh);
 4765:             }
 4766:         } else {
 4767:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4768:                 @lines = <$fh>;
 4769:                 close($fh);
 4770:             }
 4771:         }
 4772:     }
 4773:     return @lines;
 4774: }
 4775: 
 4776: sub removeuploadedurl {
 4777:     my ($url)=@_;	
 4778:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4779:     return &removeuserfile($uname,$udom,$fname);
 4780: }
 4781: 
 4782: sub removeuserfile {
 4783:     my ($docuname,$docudom,$fname)=@_;
 4784:     my $home=&homeserver($docuname,$docudom);    
 4785:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4786:     if ($result eq 'ok') {	
 4787:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4788:             my $metafile = $fname.'.meta';
 4789:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4790: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4791:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4792:             my $sqlresult = 
 4793:                 &update_portfolio_table($docuname,$docudom,$file,
 4794:                                         'portfolio_metadata',$group,
 4795:                                         'delete');
 4796:         }
 4797:     }
 4798:     return $result;
 4799: }
 4800: 
 4801: sub mkdiruserfile {
 4802:     my ($docuname,$docudom,$dir)=@_;
 4803:     my $home=&homeserver($docuname,$docudom);
 4804:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4805: }
 4806: 
 4807: sub renameuserfile {
 4808:     my ($docuname,$docudom,$old,$new)=@_;
 4809:     my $home=&homeserver($docuname,$docudom);
 4810:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4811:                         &escape("$old").':'.&escape("$new"),$home);
 4812:     if ($result eq 'ok') {
 4813:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4814:             my $oldmeta = $old.'.meta';
 4815:             my $newmeta = $new.'.meta';
 4816:             my $metaresult = 
 4817:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4818: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4819:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4820:             my $sqlresult = 
 4821:                 &update_portfolio_table($docuname,$docudom,$file,
 4822:                                         'portfolio_metadata',$group,
 4823:                                         'delete');
 4824:         }
 4825:     }
 4826:     return $result;
 4827: }
 4828: 
 4829: # ------------------------------------------------------------------------- Log
 4830: 
 4831: sub log {
 4832:     my ($dom,$nam,$hom,$what)=@_;
 4833:     return critical("log:$dom:$nam:$what",$hom);
 4834: }
 4835: 
 4836: # ------------------------------------------------------------------ Course Log
 4837: #
 4838: # This routine flushes several buffers of non-mission-critical nature
 4839: #
 4840: 
 4841: sub flushcourselogs {
 4842:     &logthis('Flushing log buffers');
 4843: #
 4844: # course logs
 4845: # This is a log of all transactions in a course, which can be used
 4846: # for data mining purposes
 4847: #
 4848: # It also collects the courseid database, which lists last transaction
 4849: # times and course titles for all courseids
 4850: #
 4851:     my %courseidbuffer=();
 4852:     foreach my $crsid (keys(%courselogs)) {
 4853:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4854: 		          &escape($courselogs{$crsid}),
 4855: 		          $coursehombuf{$crsid}) eq 'ok') {
 4856: 	    delete $courselogs{$crsid};
 4857:         } else {
 4858:             &logthis('Failed to flush log buffer for '.$crsid);
 4859:             if (length($courselogs{$crsid})>40000) {
 4860:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4861:                         " exceeded maximum size, deleting.</font>");
 4862:                delete $courselogs{$crsid};
 4863:             }
 4864:         }
 4865:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4866:             'description' => $coursedescrbuf{$crsid},
 4867:             'inst_code'    => $courseinstcodebuf{$crsid},
 4868:             'type'        => $coursetypebuf{$crsid},
 4869:             'owner'       => $courseownerbuf{$crsid},
 4870:         };
 4871:     }
 4872: #
 4873: # Write course id database (reverse lookup) to homeserver of courses 
 4874: # Is used in pickcourse
 4875: #
 4876:     foreach my $crs_home (keys(%courseidbuffer)) {
 4877:         my $response = &courseidput(&host_domain($crs_home),
 4878:                                     $courseidbuffer{$crs_home},
 4879:                                     $crs_home,'timeonly');
 4880:     }
 4881: #
 4882: # File accesses
 4883: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4884: #
 4885:     foreach my $entry (keys(%accesshash)) {
 4886:         if ($entry =~ /___count$/) {
 4887:             my ($dom,$name);
 4888:             ($dom,$name,undef)=
 4889: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4890:             if (! defined($dom) || $dom eq '' || 
 4891:                 ! defined($name) || $name eq '') {
 4892:                 my $cid = $env{'request.course.id'};
 4893:                 $dom  = $env{'request.'.$cid.'.domain'};
 4894:                 $name = $env{'request.'.$cid.'.num'};
 4895:             }
 4896:             my $value = $accesshash{$entry};
 4897:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4898:             my %temphash=($url => $value);
 4899:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4900:             if ($result eq 'ok') {
 4901:                 delete $accesshash{$entry};
 4902:             }
 4903:         } else {
 4904:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4905:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4906:             my %temphash=($entry => $accesshash{$entry});
 4907:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4908:                 delete $accesshash{$entry};
 4909:             }
 4910:         }
 4911:     }
 4912: #
 4913: # Roles
 4914: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4915: #
 4916:     foreach my $entry (keys(%userrolehash)) {
 4917:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4918: 	    split(/\:/,$entry);
 4919:         if (&Apache::lonnet::put('nohist_userroles',
 4920:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4921:                 $rudom,$runame) eq 'ok') {
 4922: 	    delete $userrolehash{$entry};
 4923:         }
 4924:     }
 4925: #
 4926: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4927: #
 4928:     my %domrolebuffer = ();
 4929:     foreach my $entry (keys(%domainrolehash)) {
 4930:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4931:         if ($domrolebuffer{$rudom}) {
 4932:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4933:                       '='.&escape($domainrolehash{$entry});
 4934:         } else {
 4935:             $domrolebuffer{$rudom}.=&escape($entry).
 4936:                       '='.&escape($domainrolehash{$entry});
 4937:         }
 4938:         delete $domainrolehash{$entry};
 4939:     }
 4940:     foreach my $dom (keys(%domrolebuffer)) {
 4941: 	my %servers;
 4942: 	if (defined(&domain($dom,'primary'))) {
 4943: 	    my $primary=&domain($dom,'primary');
 4944: 	    my $hostname=&hostname($primary);
 4945: 	    $servers{$primary} = $hostname;
 4946: 	} else { 
 4947: 	    %servers = &get_servers($dom,'library');
 4948: 	}
 4949: 	foreach my $tryserver (keys(%servers)) {
 4950: 	    if (&reply('domroleput:'.$dom.':'.
 4951: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4952: 		last;
 4953: 	    } else {  
 4954: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4955: 	    }
 4956:         }
 4957:     }
 4958:     $dumpcount++;
 4959: }
 4960: 
 4961: sub courselog {
 4962:     my $what=shift;
 4963:     $what=time.':'.$what;
 4964:     unless ($env{'request.course.id'}) { return ''; }
 4965:     $coursedombuf{$env{'request.course.id'}}=
 4966:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4967:     $coursenumbuf{$env{'request.course.id'}}=
 4968:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4969:     $coursehombuf{$env{'request.course.id'}}=
 4970:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4971:     $coursedescrbuf{$env{'request.course.id'}}=
 4972:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4973:     $courseinstcodebuf{$env{'request.course.id'}}=
 4974:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4975:     $courseownerbuf{$env{'request.course.id'}}=
 4976:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4977:     $coursetypebuf{$env{'request.course.id'}}=
 4978:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4979:     if (defined $courselogs{$env{'request.course.id'}}) {
 4980: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4981:     } else {
 4982: 	$courselogs{$env{'request.course.id'}}.=$what;
 4983:     }
 4984:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4985: 	&flushcourselogs();
 4986:     }
 4987: }
 4988: 
 4989: sub courseacclog {
 4990:     my $fnsymb=shift;
 4991:     unless ($env{'request.course.id'}) { return ''; }
 4992:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4993:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4994:         $what.=':POST';
 4995:         # FIXME: Probably ought to escape things....
 4996: 	foreach my $key (keys(%env)) {
 4997:             if ($key=~/^form\.(.*)/) {
 4998:                 my $formitem = $1;
 4999:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5000:                     $what.=':'.$formitem.'='.$env{$key};
 5001:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5002:                     $what.=':'.$formitem.'='.$env{$key};
 5003:                 }
 5004:             }
 5005:         }
 5006:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5007:         # FIXME: We should not be depending on a form parameter that someone
 5008:         # editing lonsearchcat.pm might change in the future.
 5009:         if ($env{'form.phase'} eq 'course_search') {
 5010:             $what.= ':POST';
 5011:             # FIXME: Probably ought to escape things....
 5012:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5013:                                  'crsdiscuss') {
 5014:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5015:             }
 5016:         }
 5017:     }
 5018:     &courselog($what);
 5019: }
 5020: 
 5021: sub countacc {
 5022:     my $url=&declutter(shift);
 5023:     return if (! defined($url) || $url eq '');
 5024:     unless ($env{'request.course.id'}) { return ''; }
 5025: #
 5026: # Mark that this url was used in this course
 5027: #
 5028:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5029: #
 5030: # Increase the access count for this resource in this child process
 5031: #
 5032:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5033:     $accesshash{$key}++;
 5034: }
 5035: 
 5036: sub linklog {
 5037:     my ($from,$to)=@_;
 5038:     $from=&declutter($from);
 5039:     $to=&declutter($to);
 5040:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5041:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5042: }
 5043: 
 5044: sub statslog {
 5045:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5046:     if ($users<2) { return; }
 5047:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5048:             'course'       => $env{'request.course.id'},
 5049:             'sections'     => '"all"',
 5050:             'num_students' => $users,
 5051:             'part'         => $part,
 5052:             'symb'         => $symb,
 5053:             'mean_tries'   => $av_attempts,
 5054:             'deg_of_diff'  => $degdiff});
 5055:     foreach my $key (keys(%dynstore)) {
 5056:         $accesshash{$key}=$dynstore{$key};
 5057:     }
 5058: }
 5059:   
 5060: sub userrolelog {
 5061:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5062:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5063:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5064:        $userrolehash
 5065:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5066:                     =$tend.':'.$tstart;
 5067:     }
 5068:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5069:        $userrolehash
 5070:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5071:                     =$tend.':'.$tstart;
 5072:     }
 5073:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5074:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5075:        $domainrolehash
 5076:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5077:                     = $tend.':'.$tstart;
 5078:     }
 5079: }
 5080: 
 5081: sub courserolelog {
 5082:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5083:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5084:         my $cdom = $1;
 5085:         my $cnum = $2;
 5086:         my $sec = $3;
 5087:         my $namespace = 'rolelog';
 5088:         my %storehash = (
 5089:                            role    => $trole,
 5090:                            start   => $tstart,
 5091:                            end     => $tend,
 5092:                            selfenroll => $selfenroll,
 5093:                            context    => $context,
 5094:                         );
 5095:         if ($trole eq 'gr') {
 5096:             $namespace = 'groupslog';
 5097:             $storehash{'group'} = $sec;
 5098:         } else {
 5099:             $storehash{'section'} = $sec;
 5100:         }
 5101:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5102:                    $domain,$cnum,$cdom);
 5103:         if (($trole ne 'st') || ($sec ne '')) {
 5104:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5105:         }
 5106:     }
 5107:     return;
 5108: }
 5109: 
 5110: sub domainrolelog {
 5111:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5112:     if ($area =~ m{^/($match_domain)/$}) {
 5113:         my $cdom = $1;
 5114:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5115:         my $namespace = 'rolelog';
 5116:         my %storehash = (
 5117:                            role    => $trole,
 5118:                            start   => $tstart,
 5119:                            end     => $tend,
 5120:                            context => $context,
 5121:                         );
 5122:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5123:                    $domain,$domconfiguser,$cdom);
 5124:     }
 5125:     return;
 5126: 
 5127: }
 5128: 
 5129: sub coauthorrolelog {
 5130:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5131:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5132:         my $audom = $1;
 5133:         my $auname = $2;
 5134:         my $namespace = 'rolelog';
 5135:         my %storehash = (
 5136:                            role    => $trole,
 5137:                            start   => $tstart,
 5138:                            end     => $tend,
 5139:                            context => $context,
 5140:                         );
 5141:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5142:                    $domain,$auname,$audom);
 5143:     }
 5144:     return;
 5145: }
 5146: 
 5147: sub get_course_adv_roles {
 5148:     my ($cid,$codes) = @_;
 5149:     $cid=$env{'request.course.id'} unless (defined($cid));
 5150:     my %coursehash=&coursedescription($cid);
 5151:     my $crstype = &Apache::loncommon::course_type($cid);
 5152:     my %nothide=();
 5153:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5154:         if ($user !~ /:/) {
 5155: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5156:         } else {
 5157:             $nothide{$user}=1;
 5158:         }
 5159:     }
 5160:     my @possdoms = ($coursehash{'domain'});
 5161:     if ($coursehash{'checkforpriv'}) {
 5162:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5163:     }
 5164:     my %returnhash=();
 5165:     my %dumphash=
 5166:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5167:     my $now=time;
 5168:     my %privileged;
 5169:     foreach my $entry (keys(%dumphash)) {
 5170: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5171:         if (($tstart) && ($tstart<0)) { next; }
 5172:         if (($tend) && ($tend<$now)) { next; }
 5173:         if (($tstart) && ($now<$tstart)) { next; }
 5174:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5175: 	if ($username eq '' || $domain eq '') { next; }
 5176:         if ((&privileged($username,$domain,\@possdoms)) &&
 5177:             (!$nothide{$username.':'.$domain})) { next; }
 5178: 	if ($role eq 'cr') { next; }
 5179:         if ($codes) {
 5180:             if ($section) { $role .= ':'.$section; }
 5181:             if ($returnhash{$role}) {
 5182:                 $returnhash{$role}.=','.$username.':'.$domain;
 5183:             } else {
 5184:                 $returnhash{$role}=$username.':'.$domain;
 5185:             }
 5186:         } else {
 5187:             my $key=&plaintext($role,$crstype);
 5188:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5189:             if ($returnhash{$key}) {
 5190: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5191:             } else {
 5192:                 $returnhash{$key}=$username.':'.$domain;
 5193:             }
 5194:         }
 5195:     }
 5196:     return %returnhash;
 5197: }
 5198: 
 5199: sub get_my_roles {
 5200:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5201:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5202:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5203:     my (%dumphash,%nothide);
 5204:     if ($context eq 'userroles') {
 5205:         %dumphash = &dump('roles',$udom,$uname);
 5206:     } else {
 5207:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5208:         if ($hidepriv) {
 5209:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5210:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5211:                 if ($user !~ /:/) {
 5212:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5213:                 } else {
 5214:                     $nothide{$user} = 1;
 5215:                 }
 5216:             }
 5217:         }
 5218:     }
 5219:     my %returnhash=();
 5220:     my $now=time;
 5221:     my %privileged;
 5222:     foreach my $entry (keys(%dumphash)) {
 5223:         my ($role,$tend,$tstart);
 5224:         if ($context eq 'userroles') {
 5225:             next if ($entry =~ /^rolesdef/);
 5226: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5227:         } else {
 5228:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5229:         }
 5230:         if (($tstart) && ($tstart<0)) { next; }
 5231:         my $status = 'active';
 5232:         if (($tend) && ($tend<=$now)) {
 5233:             $status = 'previous';
 5234:         } 
 5235:         if (($tstart) && ($now<$tstart)) {
 5236:             $status = 'future';
 5237:         }
 5238:         if (ref($types) eq 'ARRAY') {
 5239:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5240:                 next;
 5241:             } 
 5242:         } else {
 5243:             if ($status ne 'active') {
 5244:                 next;
 5245:             }
 5246:         }
 5247:         my ($rolecode,$username,$domain,$section,$area);
 5248:         if ($context eq 'userroles') {
 5249:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5250:             (undef,$domain,$username,$section) = split(/\//,$area);
 5251:         } else {
 5252:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5253:         }
 5254:         if (ref($roledoms) eq 'ARRAY') {
 5255:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5256:                 next;
 5257:             }
 5258:         }
 5259:         if (ref($roles) eq 'ARRAY') {
 5260:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5261:                 if ($role =~ /^cr\//) {
 5262:                     if (!grep(/^cr$/,@{$roles})) {
 5263:                         next;
 5264:                     }
 5265:                 } elsif ($role =~ /^gr\//) {
 5266:                     if (!grep(/^gr$/,@{$roles})) {
 5267:                         next;
 5268:                     }
 5269:                 } else {
 5270:                     next;
 5271:                 }
 5272:             }
 5273:         }
 5274:         if ($hidepriv) {
 5275:             my @privroles = ('dc','su');
 5276:             if ($context eq 'userroles') {
 5277:                 next if (grep(/^\Q$role\E$/,@privroles));
 5278:             } else {
 5279:                 my $possdoms = [$domain];
 5280:                 if (ref($roledoms) eq 'ARRAY') {
 5281:                    push(@{$possdoms},@{$roledoms}); 
 5282:                 }
 5283:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5284:                     if (!$nothide{$username.':'.$domain}) {
 5285:                         next;
 5286:                     }
 5287:                 }
 5288:             }
 5289:         }
 5290:         if ($withsec) {
 5291:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5292:                 $tstart.':'.$tend;
 5293:         } else {
 5294:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5295:         }
 5296:     }
 5297:     return %returnhash;
 5298: }
 5299: 
 5300: sub get_all_adhocroles {
 5301:     my ($dom) = @_;
 5302:     my @roles_by_num = ();
 5303:     my %domdefaults = &get_domain_defaults($dom);
 5304:     my (%description,%access_in_dom,%access_info);
 5305:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5306:         my $count = 0;
 5307:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5308:         my %ordered;
 5309:         foreach my $role (sort(keys(%domcurrent))) {
 5310:             my ($order,$desc,$access_in_dom);
 5311:             if (ref($domcurrent{$role}) eq 'HASH') {
 5312:                 $order = $domcurrent{$role}{'order'};
 5313:                 $desc = $domcurrent{$role}{'desc'};
 5314:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5315:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5316:             }
 5317:             if ($order eq '') {
 5318:                 $order = $count;
 5319:             }
 5320:             $ordered{$order} = $role;
 5321:             if ($desc ne '') {
 5322:                 $description{$role} = $desc;
 5323:             } else {
 5324:                 $description{$role}= $role;
 5325:             }
 5326:             $count++;
 5327:         }
 5328:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5329:             push(@roles_by_num,$ordered{$item});
 5330:         }
 5331:     }
 5332:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5333: }
 5334: 
 5335: sub get_my_adhocroles {
 5336:     my ($cid,$checkreg) = @_;
 5337:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5338:     if ($env{'request.course.id'} eq $cid) {
 5339:         $cdom = $env{'course.'.$cid.'.domain'};
 5340:         $cnum = $env{'course.'.$cid.'.num'};
 5341:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5342:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5343:         $cdom = $1;
 5344:         $cnum = $2;
 5345:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5346:                                      $cdom,$cnum);
 5347:     }
 5348:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5349:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5350:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5351:         if ($rosterhash{$user} ne '') {
 5352:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5353:             return ([],{}) if ($type eq 'auto');
 5354:         }
 5355:     }
 5356:     if (($cdom ne '') && ($cnum ne ''))  {
 5357:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5358:             my $then=$env{'user.login.time'};
 5359:             my $update=$env{'user.update.time'};
 5360:             if (!$update) {
 5361:                 $update = $then;
 5362:             }
 5363:             my @liveroles;
 5364:             foreach my $role ('dh','da') {
 5365:                 if ($env{"user.role.$role./$cdom/"}) {
 5366:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5367:                     my $limit = $update;
 5368:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5369:                         $limit = $then;
 5370:                     }
 5371:                     my $activerole = 1;
 5372:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5373:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5374:                     if ($activerole) {
 5375:                         push(@liveroles,$role);
 5376:                     }
 5377:                 }
 5378:             }
 5379:             if (@liveroles) {
 5380:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5381:                     my ($accessref,$accessinfo,%access_in_dom);
 5382:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5383:                     if (ref($roles_by_num) eq 'ARRAY') {
 5384:                         if (@{$roles_by_num}) {
 5385:                             my %settings;
 5386:                             if ($env{'request.course.id'} eq $cid) {
 5387:                                 foreach my $envkey (keys(%env)) {
 5388:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5389:                                         $settings{$1} = $env{$envkey};
 5390:                                     }
 5391:                                 }
 5392:                             } else {
 5393:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5394:                             }
 5395:                             my %setincrs;
 5396:                             if ($settings{'internal.adhocaccess'}) {
 5397:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5398:                             }
 5399:                             my @statuses;
 5400:                             if ($env{'environment.inststatus'}) {
 5401:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5402:                             }
 5403:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5404:                             if (ref($accessref) eq 'HASH') {
 5405:                                 %access_in_dom = %{$accessref};
 5406:                             }
 5407:                             foreach my $role (@{$roles_by_num}) {
 5408:                                 my ($curraccess,@okstatus,@personnel);
 5409:                                 if ($setincrs{$role}) {
 5410:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5411:                                     if ($curraccess eq 'status') {
 5412:                                         @okstatus = split(/\&/,$rest);
 5413:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5414:                                         @personnel = split(/\&/,$rest);
 5415:                                     }
 5416:                                 } else {
 5417:                                     $curraccess = $access_in_dom{$role};
 5418:                                     if (ref($accessinfo) eq 'HASH') {
 5419:                                         if ($curraccess eq 'status') {
 5420:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5421:                                                 @okstatus = @{$accessinfo->{$role}};
 5422:                                             }
 5423:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5424:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5425:                                                 @personnel = @{$accessinfo->{$role}};
 5426:                                             }
 5427:                                         }
 5428:                                     }
 5429:                                 }
 5430:                                 if ($curraccess eq 'none') {
 5431:                                     next;
 5432:                                 } elsif ($curraccess eq 'all') {
 5433:                                     push(@possroles,$role);
 5434:                                 } elsif ($curraccess eq 'dh') {
 5435:                                     if (grep(/^dh$/,@liveroles)) {
 5436:                                         push(@possroles,$role);
 5437:                                     } else {
 5438:                                         next;
 5439:                                     }
 5440:                                 } elsif ($curraccess eq 'da') {
 5441:                                     if (grep(/^da$/,@liveroles)) {
 5442:                                         push(@possroles,$role);
 5443:                                     } else {
 5444:                                         next;
 5445:                                     }
 5446:                                 } elsif ($curraccess eq 'status') {
 5447:                                     if (@okstatus) {
 5448:                                         if (!@statuses) {
 5449:                                             if (grep(/^default$/,@okstatus)) {
 5450:                                                 push(@possroles,$role);
 5451:                                             }
 5452:                                         } else {
 5453:                                             foreach my $status (@okstatus) {
 5454:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5455:                                                     push(@possroles,$role);
 5456:                                                     last;
 5457:                                                 }
 5458:                                             }
 5459:                                         }
 5460:                                     }
 5461:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5462:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5463:                                         if ($curraccess eq 'exc') {
 5464:                                             push(@possroles,$role);
 5465:                                         }
 5466:                                     } elsif ($curraccess eq 'inc') {
 5467:                                         push(@possroles,$role);
 5468:                                     }
 5469:                                 }
 5470:                             }
 5471:                         }
 5472:                     }
 5473:                 }
 5474:             }
 5475:         }
 5476:     }
 5477:     unless (ref($description) eq 'HASH') {
 5478:         if (ref($roles_by_num) eq 'ARRAY') {
 5479:             my %desc;
 5480:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5481:             $description = \%desc;
 5482:         } else {
 5483:             $description = {};
 5484:         }
 5485:     }
 5486:     return (\@possroles,$description);
 5487: }
 5488: 
 5489: # ----------------------------------------------------- Frontpage Announcements
 5490: #
 5491: #
 5492: 
 5493: sub postannounce {
 5494:     my ($server,$text)=@_;
 5495:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5496:     unless ($text=~/\w/) { $text=''; }
 5497:     return &reply('setannounce:'.&escape($text),$server);
 5498: }
 5499: 
 5500: sub getannounce {
 5501: 
 5502:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5503: 	my $announcement='';
 5504: 	while (my $line = <$fh>) { $announcement .= $line; }
 5505: 	close($fh);
 5506: 	if ($announcement=~/\w/) { 
 5507: 	    return 
 5508:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5509:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5510: 	} else {
 5511: 	    return '';
 5512: 	}
 5513:     } else {
 5514: 	return '';
 5515:     }
 5516: }
 5517: 
 5518: # ---------------------------------------------------------- Course ID routines
 5519: # Deal with domain's nohist_courseid.db files
 5520: #
 5521: 
 5522: sub courseidput {
 5523:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5524:     return unless (ref($storehash) eq 'HASH');
 5525:     my $outcome;
 5526:     if ($caller eq 'timeonly') {
 5527:         my $cids = '';
 5528:         foreach my $item (keys(%$storehash)) {
 5529:             $cids.=&escape($item).'&';
 5530:         }
 5531:         $cids=~s/\&$//;
 5532:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5533:                           $coursehome);       
 5534:     } else {
 5535:         my $items = '';
 5536:         foreach my $item (keys(%$storehash)) {
 5537:             $items.= &escape($item).'='.
 5538:                      &freeze_escape($$storehash{$item}).'&';
 5539:         }
 5540:         $items=~s/\&$//;
 5541:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5542:                           $coursehome);
 5543:     }
 5544:     if ($outcome eq 'unknown_cmd') {
 5545:         my $what;
 5546:         foreach my $cid (keys(%$storehash)) {
 5547:             $what .= &escape($cid).'=';
 5548:             foreach my $item ('description','inst_code','owner','type') {
 5549:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5550:             }
 5551:             $what =~ s/\:$/&/;
 5552:         }
 5553:         $what =~ s/\&$//;  
 5554:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5555:     } else {
 5556:         return $outcome;
 5557:     }
 5558: }
 5559: 
 5560: sub courseiddump {
 5561:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5562:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5563:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5564:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5565:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5566:     my $as_hash = 1;
 5567:     my %returnhash;
 5568:     if (!$domfilter) { $domfilter=''; }
 5569:     my %libserv = &all_library();
 5570:     foreach my $tryserver (keys(%libserv)) {
 5571:         if ( (  $hostidflag == 1 
 5572: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5573: 	     || (!defined($hostidflag)) ) {
 5574: 
 5575: 	    if (($domfilter eq '') ||
 5576: 		(&host_domain($tryserver) eq $domfilter)) {
 5577:                 my $rep;
 5578:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5579:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5580:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5581:                                 &escape($descfilter), &escape($instcodefilter), 
 5582:                                 &escape($ownerfilter), &escape($coursefilter),
 5583:                                 &escape($typefilter), &escape($regexp_ok), 
 5584:                                 $as_hash, &escape($selfenrollonly), 
 5585:                                 &escape($catfilter), $showhidden, $caller, 
 5586:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5587:                                 &escape($createdbefore), &escape($createdafter), 
 5588:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5589:                                 $reqcrsdom,&escape($reqinstcode))));
 5590:                 } else {
 5591:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5592:                              $sincefilter.':'.&escape($descfilter).':'.
 5593:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5594:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5595:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5596:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5597:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5598:                              &escape($cc_clone).':'.$cloneonly.':'.
 5599:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5600:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5601:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5602:                 }
 5603:                      
 5604:                 my @pairs=split(/\&/,$rep);
 5605:                 foreach my $item (@pairs) {
 5606:                     my ($key,$value)=split(/\=/,$item,2);
 5607:                     $key = &unescape($key);
 5608:                     next if ($key =~ /^error: 2 /);
 5609:                     my $result = &thaw_unescape($value);
 5610:                     if (ref($result) eq 'HASH') {
 5611:                         $returnhash{$key}=$result;
 5612:                     } else {
 5613:                         my @responses = split(/:/,$value);
 5614:                         my @items = ('description','inst_code','owner','type');
 5615:                         for (my $i=0; $i<@responses; $i++) {
 5616:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5617:                         }
 5618:                     }
 5619:                 }
 5620:             }
 5621:         }
 5622:     }
 5623:     return %returnhash;
 5624: }
 5625: 
 5626: sub courselastaccess {
 5627:     my ($cdom,$cnum,$hostidref) = @_;
 5628:     my %returnhash;
 5629:     if ($cdom && $cnum) {
 5630:         my $chome = &homeserver($cnum,$cdom);
 5631:         if ($chome ne 'no_host') {
 5632:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5633:             &extract_lastaccess(\%returnhash,$rep);
 5634:         }
 5635:     } else {
 5636:         if (!$cdom) { $cdom=''; }
 5637:         my %libserv = &all_library();
 5638:         foreach my $tryserver (keys(%libserv)) {
 5639:             if (ref($hostidref) eq 'ARRAY') {
 5640:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5641:             } 
 5642:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5643:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5644:                 &extract_lastaccess(\%returnhash,$rep);
 5645:             }
 5646:         }
 5647:     }
 5648:     return %returnhash;
 5649: }
 5650: 
 5651: sub extract_lastaccess {
 5652:     my ($returnhash,$rep) = @_;
 5653:     if (ref($returnhash) eq 'HASH') {
 5654:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5655:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5656:                  $rep eq '') {
 5657:             my @pairs=split(/\&/,$rep);
 5658:             foreach my $item (@pairs) {
 5659:                 my ($key,$value)=split(/\=/,$item,2);
 5660:                 $key = &unescape($key);
 5661:                 next if ($key =~ /^error: 2 /);
 5662:                 $returnhash->{$key} = &thaw_unescape($value);
 5663:             }
 5664:         }
 5665:     }
 5666:     return;
 5667: }
 5668: 
 5669: # ---------------------------------------------------------- DC e-mail
 5670: 
 5671: sub dcmailput {
 5672:     my ($domain,$msgid,$message,$server)=@_;
 5673:     my $status = &Apache::lonnet::critical(
 5674:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5675:        &escape($message),$server);
 5676:     return $status;
 5677: }
 5678: 
 5679: sub dcmaildump {
 5680:     my ($dom,$startdate,$enddate,$senders) = @_;
 5681:     my %returnhash=();
 5682: 
 5683:     if (defined(&domain($dom,'primary'))) {
 5684:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5685:                                                          &escape($enddate).':';
 5686: 	my @esc_senders=map { &escape($_)} @$senders;
 5687: 	$cmd.=&escape(join('&',@esc_senders));
 5688: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5689:             my ($key,$value) = split(/\=/,$line,2);
 5690:             if (($key) && ($value)) {
 5691:                 $returnhash{&unescape($key)} = &unescape($value);
 5692:             }
 5693:         }
 5694:     }
 5695:     return %returnhash;
 5696: }
 5697: # ---------------------------------------------------------- Domain roles
 5698: 
 5699: sub get_domain_roles {
 5700:     my ($dom,$roles,$startdate,$enddate)=@_;
 5701:     if ((!defined($startdate)) || ($startdate eq '')) {
 5702:         $startdate = '.';
 5703:     }
 5704:     if ((!defined($enddate)) || ($enddate eq '')) {
 5705:         $enddate = '.';
 5706:     }
 5707:     my $rolelist;
 5708:     if (ref($roles) eq 'ARRAY') {
 5709:         $rolelist = join('&',@{$roles});
 5710:     }
 5711:     my %personnel = ();
 5712: 
 5713:     my %servers = &get_servers($dom,'library');
 5714:     foreach my $tryserver (keys(%servers)) {
 5715: 	%{$personnel{$tryserver}}=();
 5716: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5717: 					    &escape($startdate).':'.
 5718: 					    &escape($enddate).':'.
 5719: 					    &escape($rolelist), $tryserver))) {
 5720: 	    my ($key,$value) = split(/\=/,$line,2);
 5721: 	    if (($key) && ($value)) {
 5722: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5723: 	    }
 5724: 	}
 5725:     }
 5726:     return %personnel;
 5727: }
 5728: 
 5729: sub get_active_domroles {
 5730:     my ($dom,$roles) = @_;
 5731:     return () unless (ref($roles) eq 'ARRAY');
 5732:     my $now = time;
 5733:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5734:     my %domroles;
 5735:     foreach my $server (keys(%dompersonnel)) {
 5736:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5737:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5738:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5739:         }
 5740:     }
 5741:     return %domroles;
 5742: }
 5743: 
 5744: # ----------------------------------------------------------- Interval timing 
 5745: 
 5746: {
 5747: # Caches needed for speedup of navmaps
 5748: # We don't want to cache this for very long at all (5 seconds at most)
 5749: # 
 5750: # The user for whom we cache
 5751: my $cachedkey='';
 5752: # The cached times for this user
 5753: my %cachedtimes=();
 5754: # When this was last done
 5755: my $cachedtime='';
 5756: 
 5757: sub load_all_first_access {
 5758:     my ($uname,$udom,$ignorecache)=@_;
 5759:     if (($cachedkey eq $uname.':'.$udom) &&
 5760:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5761:         (!$ignorecache)) {
 5762:         return;
 5763:     }
 5764:     $cachedtime=time;
 5765:     $cachedkey=$uname.':'.$udom;
 5766:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5767: }
 5768: 
 5769: sub get_first_access {
 5770:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5771:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5772:     if ($argsymb) { $symb=$argsymb; }
 5773:     my ($map,$id,$res)=&decode_symb($symb);
 5774:     if ($argmap) { $map = $argmap; }
 5775:     if ($type eq 'course') {
 5776: 	$res='course';
 5777:     } elsif ($type eq 'map') {
 5778: 	$res=&symbread($map);
 5779:     } else {
 5780: 	$res=$symb;
 5781:     }
 5782:     &load_all_first_access($uname,$udom,$ignorecache);
 5783:     return $cachedtimes{"$courseid\0$res"};
 5784: }
 5785: 
 5786: sub set_first_access {
 5787:     my ($type,$interval)=@_;
 5788:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5789:     my ($map,$id,$res)=&decode_symb($symb);
 5790:     if ($type eq 'course') {
 5791: 	$res='course';
 5792:     } elsif ($type eq 'map') {
 5793: 	$res=&symbread($map);
 5794:     } else {
 5795: 	$res=$symb;
 5796:     }
 5797:     $cachedkey='';
 5798:     my $firstaccess=&get_first_access($type,$symb,$map);
 5799:     if ($firstaccess) {
 5800:         &logthis("First access time already set ($firstaccess) when attempting ".
 5801:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5802:                  "in $courseid");
 5803:         return 'already_set';
 5804:     } else {
 5805:         my $start = time;
 5806: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5807:                           $udom,$uname);
 5808:         if ($putres eq 'ok') {
 5809:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5810:                  $udom,$uname); 
 5811:             &appenv(
 5812:                      {
 5813:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5814:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5815:                      }
 5816:                   );
 5817:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5818:                 $cachedtimes{"$courseid\0$res"} = $start;
 5819:             }
 5820:         } elsif ($putres ne 'refused') {
 5821:             &logthis("Result: $putres when attempting to set first access time ".
 5822:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5823:         }
 5824:         return $putres;
 5825:     }
 5826:     return 'already_set';
 5827: }
 5828: }
 5829: 
 5830: # --------------------------------------------- Set Expire Date for Spreadsheet
 5831: 
 5832: sub expirespread {
 5833:     my ($uname,$udom,$stype,$usymb)=@_;
 5834:     my $cid=$env{'request.course.id'}; 
 5835:     if ($cid) {
 5836:        my $now=time;
 5837:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5838:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5839:                             $env{'course.'.$cid.'.num'}.
 5840: 	        	    ':nohist_expirationdates:'.
 5841:                             &escape($key).'='.$now,
 5842:                             $env{'course.'.$cid.'.home'})
 5843:     }
 5844:     return 'ok';
 5845: }
 5846: 
 5847: # ----------------------------------------------------- Devalidate Spreadsheets
 5848: 
 5849: sub devalidate {
 5850:     my ($symb,$uname,$udom)=@_;
 5851:     my $cid=$env{'request.course.id'}; 
 5852:     if ($cid) {
 5853:         # delete the stored spreadsheets for
 5854:         # - the student level sheet of this user in course's homespace
 5855:         # - the assessment level sheet for this resource 
 5856:         #   for this user in user's homespace
 5857: 	# - current conditional state info
 5858: 	my $key=$uname.':'.$udom.':';
 5859:         my $status=
 5860: 	    &del('nohist_calculatedsheets',
 5861: 		 [$key.'studentcalc:'],
 5862: 		 $env{'course.'.$cid.'.domain'},
 5863: 		 $env{'course.'.$cid.'.num'})
 5864: 		.' '.
 5865: 	    &del('nohist_calculatedsheets_'.$cid,
 5866: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5867:         unless ($status eq 'ok ok') {
 5868:            &logthis('Could not devalidate spreadsheet '.
 5869:                     $uname.' at '.$udom.' for '.
 5870: 		    $symb.': '.$status);
 5871:         }
 5872: 	&delenv('user.state.'.$cid);
 5873:     }
 5874: }
 5875: 
 5876: sub get_scalar {
 5877:     my ($string,$end) = @_;
 5878:     my $value;
 5879:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5880: 	$value = $1;
 5881:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5882: 	$value = $1;
 5883:     }
 5884:     return &unescape($value);
 5885: }
 5886: 
 5887: sub array2str {
 5888:   my (@array) = @_;
 5889:   my $result=&arrayref2str(\@array);
 5890:   $result=~s/^__ARRAY_REF__//;
 5891:   $result=~s/__END_ARRAY_REF__$//;
 5892:   return $result;
 5893: }
 5894: 
 5895: sub arrayref2str {
 5896:   my ($arrayref) = @_;
 5897:   my $result='__ARRAY_REF__';
 5898:   foreach my $elem (@$arrayref) {
 5899:     if(ref($elem) eq 'ARRAY') {
 5900:       $result.=&arrayref2str($elem).'&';
 5901:     } elsif(ref($elem) eq 'HASH') {
 5902:       $result.=&hashref2str($elem).'&';
 5903:     } elsif(ref($elem)) {
 5904:       #print("Got a ref of ".(ref($elem))." skipping.");
 5905:     } else {
 5906:       $result.=&escape($elem).'&';
 5907:     }
 5908:   }
 5909:   $result=~s/\&$//;
 5910:   $result .= '__END_ARRAY_REF__';
 5911:   return $result;
 5912: }
 5913: 
 5914: sub hash2str {
 5915:   my (%hash) = @_;
 5916:   my $result=&hashref2str(\%hash);
 5917:   $result=~s/^__HASH_REF__//;
 5918:   $result=~s/__END_HASH_REF__$//;
 5919:   return $result;
 5920: }
 5921: 
 5922: sub hashref2str {
 5923:   my ($hashref)=@_;
 5924:   my $result='__HASH_REF__';
 5925:   foreach my $key (sort(keys(%$hashref))) {
 5926:     if (ref($key) eq 'ARRAY') {
 5927:       $result.=&arrayref2str($key).'=';
 5928:     } elsif (ref($key) eq 'HASH') {
 5929:       $result.=&hashref2str($key).'=';
 5930:     } elsif (ref($key)) {
 5931:       $result.='=';
 5932:       #print("Got a ref of ".(ref($key))." skipping.");
 5933:     } else {
 5934: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5935:     }
 5936: 
 5937:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5938:       $result.=&arrayref2str($hashref->{$key}).'&';
 5939:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5940:       $result.=&hashref2str($hashref->{$key}).'&';
 5941:     } elsif(ref($hashref->{$key})) {
 5942:        $result.='&';
 5943:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5944:     } else {
 5945:       $result.=&escape($hashref->{$key}).'&';
 5946:     }
 5947:   }
 5948:   $result=~s/\&$//;
 5949:   $result .= '__END_HASH_REF__';
 5950:   return $result;
 5951: }
 5952: 
 5953: sub str2hash {
 5954:     my ($string)=@_;
 5955:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5956:     return %$hash;
 5957: }
 5958: 
 5959: sub str2hashref {
 5960:   my ($string) = @_;
 5961: 
 5962:   my %hash;
 5963: 
 5964:   if($string !~ /^__HASH_REF__/) {
 5965:       if (! ($string eq '' || !defined($string))) {
 5966: 	  $hash{'error'}='Not hash reference';
 5967:       }
 5968:       return (\%hash, $string);
 5969:   }
 5970: 
 5971:   $string =~ s/^__HASH_REF__//;
 5972: 
 5973:   while($string !~ /^__END_HASH_REF__/) {
 5974:       #key
 5975:       my $key='';
 5976:       if($string =~ /^__HASH_REF__/) {
 5977:           ($key, $string)=&str2hashref($string);
 5978:           if(defined($key->{'error'})) {
 5979:               $hash{'error'}='Bad data';
 5980:               return (\%hash, $string);
 5981:           }
 5982:       } elsif($string =~ /^__ARRAY_REF__/) {
 5983:           ($key, $string)=&str2arrayref($string);
 5984:           if($key->[0] eq 'Array reference error') {
 5985:               $hash{'error'}='Bad data';
 5986:               return (\%hash, $string);
 5987:           }
 5988:       } else {
 5989:           $string =~ s/^(.*?)=//;
 5990: 	  $key=&unescape($1);
 5991:       }
 5992:       $string =~ s/^=//;
 5993: 
 5994:       #value
 5995:       my $value='';
 5996:       if($string =~ /^__HASH_REF__/) {
 5997:           ($value, $string)=&str2hashref($string);
 5998:           if(defined($value->{'error'})) {
 5999:               $hash{'error'}='Bad data';
 6000:               return (\%hash, $string);
 6001:           }
 6002:       } elsif($string =~ /^__ARRAY_REF__/) {
 6003:           ($value, $string)=&str2arrayref($string);
 6004:           if($value->[0] eq 'Array reference error') {
 6005:               $hash{'error'}='Bad data';
 6006:               return (\%hash, $string);
 6007:           }
 6008:       } else {
 6009: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6010:       }
 6011:       $string =~ s/^&//;
 6012: 
 6013:       $hash{$key}=$value;
 6014:   }
 6015: 
 6016:   $string =~ s/^__END_HASH_REF__//;
 6017: 
 6018:   return (\%hash, $string);
 6019: }
 6020: 
 6021: sub str2array {
 6022:     my ($string)=@_;
 6023:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6024:     return @$array;
 6025: }
 6026: 
 6027: sub str2arrayref {
 6028:   my ($string) = @_;
 6029:   my @array;
 6030: 
 6031:   if($string !~ /^__ARRAY_REF__/) {
 6032:       if (! ($string eq '' || !defined($string))) {
 6033: 	  $array[0]='Array reference error';
 6034:       }
 6035:       return (\@array, $string);
 6036:   }
 6037: 
 6038:   $string =~ s/^__ARRAY_REF__//;
 6039: 
 6040:   while($string !~ /^__END_ARRAY_REF__/) {
 6041:       my $value='';
 6042:       if($string =~ /^__HASH_REF__/) {
 6043:           ($value, $string)=&str2hashref($string);
 6044:           if(defined($value->{'error'})) {
 6045:               $array[0] ='Array reference error';
 6046:               return (\@array, $string);
 6047:           }
 6048:       } elsif($string =~ /^__ARRAY_REF__/) {
 6049:           ($value, $string)=&str2arrayref($string);
 6050:           if($value->[0] eq 'Array reference error') {
 6051:               $array[0] ='Array reference error';
 6052:               return (\@array, $string);
 6053:           }
 6054:       } else {
 6055: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6056:       }
 6057:       $string =~ s/^&//;
 6058: 
 6059:       push(@array, $value);
 6060:   }
 6061: 
 6062:   $string =~ s/^__END_ARRAY_REF__//;
 6063: 
 6064:   return (\@array, $string);
 6065: }
 6066: 
 6067: # -------------------------------------------------------------------Temp Store
 6068: 
 6069: sub tmpreset {
 6070:   my ($symb,$namespace,$domain,$stuname) = @_;
 6071:   if (!$symb) {
 6072:     $symb=&symbread();
 6073:     if (!$symb) { $symb= $env{'request.url'}; }
 6074:   }
 6075:   $symb=escape($symb);
 6076: 
 6077:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6078:   $namespace=~s/\//\_/g;
 6079:   $namespace=~s/\W//g;
 6080: 
 6081:   if (!$domain) { $domain=$env{'user.domain'}; }
 6082:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6083:   if ($domain eq 'public' && $stuname eq 'public') {
 6084:       $stuname=$ENV{'REMOTE_ADDR'};
 6085:   }
 6086:   my $path=LONCAPA::tempdir();
 6087:   my %hash;
 6088:   if (tie(%hash,'GDBM_File',
 6089: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6090: 	  &GDBM_WRCREAT(),0640)) {
 6091:     foreach my $key (keys(%hash)) {
 6092:       if ($key=~ /:$symb/) {
 6093: 	delete($hash{$key});
 6094:       }
 6095:     }
 6096:   }
 6097: }
 6098: 
 6099: sub tmpstore {
 6100:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6101: 
 6102:   if (!$symb) {
 6103:     $symb=&symbread();
 6104:     if (!$symb) { $symb= $env{'request.url'}; }
 6105:   }
 6106:   $symb=escape($symb);
 6107: 
 6108:   if (!$namespace) {
 6109:     # I don't think we would ever want to store this for a course.
 6110:     # it seems this will only be used if we don't have a course.
 6111:     #$namespace=$env{'request.course.id'};
 6112:     #if (!$namespace) {
 6113:       $namespace=$env{'request.state'};
 6114:     #}
 6115:   }
 6116:   $namespace=~s/\//\_/g;
 6117:   $namespace=~s/\W//g;
 6118:   if (!$domain) { $domain=$env{'user.domain'}; }
 6119:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6120:   if ($domain eq 'public' && $stuname eq 'public') {
 6121:       $stuname=$ENV{'REMOTE_ADDR'};
 6122:   }
 6123:   my $now=time;
 6124:   my %hash;
 6125:   my $path=LONCAPA::tempdir();
 6126:   if (tie(%hash,'GDBM_File',
 6127: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6128: 	  &GDBM_WRCREAT(),0640)) {
 6129:     $hash{"version:$symb"}++;
 6130:     my $version=$hash{"version:$symb"};
 6131:     my $allkeys=''; 
 6132:     foreach my $key (keys(%$storehash)) {
 6133:       $allkeys.=$key.':';
 6134:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6135:     }
 6136:     $hash{"$version:$symb:timestamp"}=$now;
 6137:     $allkeys.='timestamp';
 6138:     $hash{"$version:keys:$symb"}=$allkeys;
 6139:     if (untie(%hash)) {
 6140:       return 'ok';
 6141:     } else {
 6142:       return "error:$!";
 6143:     }
 6144:   } else {
 6145:     return "error:$!";
 6146:   }
 6147: }
 6148: 
 6149: # -----------------------------------------------------------------Temp Restore
 6150: 
 6151: sub tmprestore {
 6152:   my ($symb,$namespace,$domain,$stuname) = @_;
 6153: 
 6154:   if (!$symb) {
 6155:     $symb=&symbread();
 6156:     if (!$symb) { $symb= $env{'request.url'}; }
 6157:   }
 6158:   $symb=escape($symb);
 6159: 
 6160:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6161: 
 6162:   if (!$domain) { $domain=$env{'user.domain'}; }
 6163:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6164:   if ($domain eq 'public' && $stuname eq 'public') {
 6165:       $stuname=$ENV{'REMOTE_ADDR'};
 6166:   }
 6167:   my %returnhash;
 6168:   $namespace=~s/\//\_/g;
 6169:   $namespace=~s/\W//g;
 6170:   my %hash;
 6171:   my $path=LONCAPA::tempdir();
 6172:   if (tie(%hash,'GDBM_File',
 6173: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6174: 	  &GDBM_READER(),0640)) {
 6175:     my $version=$hash{"version:$symb"};
 6176:     $returnhash{'version'}=$version;
 6177:     my $scope;
 6178:     for ($scope=1;$scope<=$version;$scope++) {
 6179:       my $vkeys=$hash{"$scope:keys:$symb"};
 6180:       my @keys=split(/:/,$vkeys);
 6181:       my $key;
 6182:       $returnhash{"$scope:keys"}=$vkeys;
 6183:       foreach $key (@keys) {
 6184: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6185: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6186:       }
 6187:     }
 6188:     if (!(untie(%hash))) {
 6189:       return "error:$!";
 6190:     }
 6191:   } else {
 6192:     return "error:$!";
 6193:   }
 6194:   return %returnhash;
 6195: }
 6196: 
 6197: # ----------------------------------------------------------------------- Store
 6198: 
 6199: sub store {
 6200:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6201:     my $home='';
 6202: 
 6203:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6204: 
 6205:     $symb=&symbclean($symb);
 6206:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6207: 
 6208:     if (!$domain) { $domain=$env{'user.domain'}; }
 6209:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6210: 
 6211:     &devalidate($symb,$stuname,$domain);
 6212: 
 6213:     $symb=escape($symb);
 6214:     if (!$namespace) { 
 6215:        unless ($namespace=$env{'request.course.id'}) { 
 6216:           return ''; 
 6217:        } 
 6218:     }
 6219:     if (!$home) { $home=$env{'user.home'}; }
 6220: 
 6221:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6222:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6223: 
 6224:     my $namevalue='';
 6225:     foreach my $key (keys(%$storehash)) {
 6226:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6227:     }
 6228:     $namevalue=~s/\&$//;
 6229:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6230:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6231: }
 6232: 
 6233: # -------------------------------------------------------------- Critical Store
 6234: 
 6235: sub cstore {
 6236:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6237:     my $home='';
 6238: 
 6239:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6240: 
 6241:     $symb=&symbclean($symb);
 6242:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6243: 
 6244:     if (!$domain) { $domain=$env{'user.domain'}; }
 6245:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6246: 
 6247:     &devalidate($symb,$stuname,$domain);
 6248: 
 6249:     $symb=escape($symb);
 6250:     if (!$namespace) { 
 6251:        unless ($namespace=$env{'request.course.id'}) { 
 6252:           return ''; 
 6253:        } 
 6254:     }
 6255:     if (!$home) { $home=$env{'user.home'}; }
 6256: 
 6257:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6258:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6259: 
 6260:     my $namevalue='';
 6261:     foreach my $key (keys(%$storehash)) {
 6262:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6263:     }
 6264:     $namevalue=~s/\&$//;
 6265:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6266:     return critical
 6267:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6268: }
 6269: 
 6270: # --------------------------------------------------------------------- Restore
 6271: 
 6272: sub restore {
 6273:     my ($symb,$namespace,$domain,$stuname) = @_;
 6274:     my $home='';
 6275: 
 6276:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6277: 
 6278:     if (!$symb) {
 6279:         return if ($namespace eq 'courserequests');
 6280:         unless ($symb=escape(&symbread())) { return ''; }
 6281:     } else {
 6282:         unless ($namespace eq 'courserequests') {
 6283:             $symb=&escape(&symbclean($symb));
 6284:         }
 6285:     }
 6286:     if (!$namespace) { 
 6287:        unless ($namespace=$env{'request.course.id'}) { 
 6288:           return ''; 
 6289:        } 
 6290:     }
 6291:     if (!$domain) { $domain=$env{'user.domain'}; }
 6292:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6293:     if (!$home) { $home=$env{'user.home'}; }
 6294:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6295: 
 6296:     my %returnhash=();
 6297:     foreach my $line (split(/\&/,$answer)) {
 6298: 	my ($name,$value)=split(/\=/,$line);
 6299:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6300:     }
 6301:     my $version;
 6302:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6303:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6304:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6305:        }
 6306:     }
 6307:     return %returnhash;
 6308: }
 6309: 
 6310: # ---------------------------------------------------------- Course Description
 6311: #
 6312: #  
 6313: 
 6314: sub coursedescription {
 6315:     my ($courseid,$args)=@_;
 6316:     $courseid=~s/^\///;
 6317:     $courseid=~s/\_/\//g;
 6318:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6319:     my $chome=&homeserver($cnum,$cdomain);
 6320:     my $normalid=$cdomain.'_'.$cnum;
 6321:     # need to always cache even if we get errors otherwise we keep 
 6322:     # trying and trying and trying to get the course description.
 6323:     my %envhash=();
 6324:     my %returnhash=();
 6325:     
 6326:     my $expiretime=600;
 6327:     if ($env{'request.course.id'} eq $normalid) {
 6328: 	$expiretime=120;
 6329:     }
 6330: 
 6331:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6332:     if (!$args->{'freshen_cache'}
 6333: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6334: 	foreach my $key (keys(%env)) {
 6335: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6336: 	    my ($setting) = $1;
 6337: 	    $returnhash{$setting} = $env{$key};
 6338: 	}
 6339: 	return %returnhash;
 6340:     }
 6341: 
 6342:     # get the data again
 6343: 
 6344:     if (!$args->{'one_time'}) {
 6345: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6346:     }
 6347: 
 6348:     if ($chome ne 'no_host') {
 6349:        %returnhash=&dump('environment',$cdomain,$cnum);
 6350:        if (!exists($returnhash{'con_lost'})) {
 6351: 	   my $username = $env{'user.name'}; # Defult username
 6352: 	   if(defined $args->{'user'}) {
 6353: 	       $username = $args->{'user'};
 6354: 	   }
 6355:            $returnhash{'home'}= $chome;
 6356: 	   $returnhash{'domain'} = $cdomain;
 6357: 	   $returnhash{'num'} = $cnum;
 6358:            if (!defined($returnhash{'type'})) {
 6359:                $returnhash{'type'} = 'Course';
 6360:            }
 6361:            while (my ($name,$value) = each %returnhash) {
 6362:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6363:            }
 6364:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6365:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6366: 	       $username.'_'.$cdomain.'_'.$cnum;
 6367:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6368:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6369:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6370:        }
 6371:     }
 6372:     if (!$args->{'one_time'}) {
 6373: 	&appenv(\%envhash);
 6374:     }
 6375:     return %returnhash;
 6376: }
 6377: 
 6378: sub update_released_required {
 6379:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6380:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6381:         $cid = $env{'request.course.id'};
 6382:         $cdom = $env{'course.'.$cid.'.domain'};
 6383:         $cnum = $env{'course.'.$cid.'.num'};
 6384:         $chome = $env{'course.'.$cid.'.home'};
 6385:     }
 6386:     if ($needsrelease) {
 6387:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6388:         my $needsupdate;
 6389:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6390:             $needsupdate = 1;
 6391:         } else {
 6392:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6393:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6394:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6395:                 $needsupdate = 1;
 6396:             }
 6397:         }
 6398:         if ($needsupdate) {
 6399:             my %needshash = (
 6400:                              'internal.releaserequired' => $needsrelease,
 6401:                             );
 6402:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6403:             if ($putresult eq 'ok') {
 6404:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6405:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6406:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6407:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6408:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6409:                 }
 6410:             }
 6411:         }
 6412:     }
 6413:     return;
 6414: }
 6415: 
 6416: # -------------------------------------------------See if a user is privileged
 6417: 
 6418: sub privileged {
 6419:     my ($username,$domain,$possdomains,$possroles)=@_;
 6420:     my $now = time;
 6421:     my $roles;
 6422:     if (ref($possroles) eq 'ARRAY') {
 6423:         $roles = $possroles; 
 6424:     } else {
 6425:         $roles = ['dc','su'];
 6426:     }
 6427:     if (ref($possdomains) eq 'ARRAY') {
 6428:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6429:         foreach my $dom (@{$possdomains}) {
 6430:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6431:                 (ref($privileged{$dom}) eq 'HASH')) {
 6432:                 foreach my $role (@{$roles}) {
 6433:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6434:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6435:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6436:                             return 1 unless (($end && $end < $now) ||
 6437:                                              ($start && $start > $now));
 6438:                         }
 6439:                     }
 6440:                 }
 6441:             }
 6442:         }
 6443:     } else {
 6444:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6445:         my $now = time;
 6446: 
 6447:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6448:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6449:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6450:                 return 1 unless ($tend && $tend < $now) 
 6451:                         or ($tstart && $tstart > $now);
 6452:             }
 6453:         }
 6454:     }
 6455:     return 0;
 6456: }
 6457: 
 6458: sub privileged_by_domain {
 6459:     my ($domains,$roles) = @_;
 6460:     my %privileged = ();
 6461:     my $cachetime = 60*60*24;
 6462:     my $now = time;
 6463:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6464:         return %privileged;
 6465:     }
 6466:     foreach my $dom (@{$domains}) {
 6467:         next if (ref($privileged{$dom}) eq 'HASH');
 6468:         my $needroles;
 6469:         foreach my $role (@{$roles}) {
 6470:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6471:             if (defined($cached)) {
 6472:                 if (ref($result) eq 'HASH') {
 6473:                     $privileged{$dom}{$role} = $result;
 6474:                 }
 6475:             } else {
 6476:                 $needroles = 1;
 6477:             }
 6478:         }
 6479:         if ($needroles) {
 6480:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6481:             $privileged{$dom} = {};
 6482:             foreach my $server (keys(%dompersonnel)) {
 6483:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6484:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6485:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6486:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6487:                         next if ($end && $end < $now);
 6488:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6489:                             $dompersonnel{$server}{$item};
 6490:                     }
 6491:                 }
 6492:             }
 6493:             if (ref($privileged{$dom}) eq 'HASH') {
 6494:                 foreach my $role (@{$roles}) {
 6495:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6496:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6497:                     } else {
 6498:                         my %hash = ();
 6499:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6500:                     }
 6501:                 }
 6502:             }
 6503:         }
 6504:     }
 6505:     return %privileged;
 6506: }
 6507: 
 6508: # -------------------------------------------------------- Get user privileges
 6509: 
 6510: sub rolesinit {
 6511:     my ($domain, $username) = @_;
 6512:     my %userroles = ('user.login.time' => time);
 6513:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6514: 
 6515:     # firstaccess and timerinterval are related to timed maps/resources. 
 6516:     # also, blocking can be triggered by an activating timer
 6517:     # it's saved in the user's %env.
 6518:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6519:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6520:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6521:         %timerintchk, %timerintenv);
 6522: 
 6523:     foreach my $key (keys(%firstaccess)) {
 6524:         my ($cid, $rest) = split(/\0/, $key);
 6525:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6526:     }
 6527: 
 6528:     foreach my $key (keys(%timerinterval)) {
 6529:         my ($cid,$rest) = split(/\0/,$key);
 6530:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6531:     }
 6532: 
 6533:     my %allroles=();
 6534:     my %allgroups=();
 6535: 
 6536:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6537:         my $role = $rolesdump{$area};
 6538:         $area =~ s/\_\w\w$//;
 6539: 
 6540:         my ($trole, $tend, $tstart, $group_privs);
 6541: 
 6542:         if ($role =~ /^cr/) {
 6543:         # Custom role, defined by a user 
 6544:         # e.g., user.role.cr/msu/smith/mynewrole
 6545:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6546:                 $trole = $1;
 6547:                 ($tend, $tstart) = split('_', $2);
 6548:             } else {
 6549:                 $trole = $role;
 6550:             }
 6551:         } elsif ($role =~ m|^gr/|) {
 6552:         # Role of member in a group, defined within a course/community
 6553:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6554:             ($trole, $tend, $tstart) = split(/_/, $role);
 6555:             next if $tstart eq '-1';
 6556:             ($trole, $group_privs) = split(/\//, $trole);
 6557:             $group_privs = &unescape($group_privs);
 6558:         } else {
 6559:         # Just a normal role, defined in roles.tab
 6560:             ($trole, $tend, $tstart) = split(/_/,$role);
 6561:         }
 6562: 
 6563:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6564:                  $username);
 6565:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6566: 
 6567:         # role expired or not available yet?
 6568:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6569:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6570: 
 6571:         next if $area eq '' or $trole eq '';
 6572: 
 6573:         my $spec = "$trole.$area";
 6574:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6575: 
 6576:         if ($trole =~ /^cr\//) {
 6577:         # Custom role, defined by a user
 6578:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6579:         } elsif ($trole eq 'gr') {
 6580:         # Role of a member in a group, defined within a course/community
 6581:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6582:             next;
 6583:         } else {
 6584:         # Normal role, defined in roles.tab
 6585:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6586:         }
 6587: 
 6588:         my $cid = $tdomain.'_'.$trest;
 6589:         unless ($firstaccchk{$cid}) {
 6590:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6591:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6592:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6593:                         $coursetimerstarts{$cid}{$item}; 
 6594:                 }
 6595:             }
 6596:             $firstaccchk{$cid} = 1;
 6597:         }
 6598:         unless ($timerintchk{$cid}) {
 6599:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6600:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6601:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6602:                        $coursetimerintervals{$cid}{$item};
 6603:                 }
 6604:             }
 6605:             $timerintchk{$cid} = 1;
 6606:         }
 6607:     }
 6608: 
 6609:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6610:                                                           \%allroles, \%allgroups);
 6611:     $env{'user.adv'} = $userroles{'user.adv'};
 6612:     $env{'user.rar'} = $userroles{'user.rar'};
 6613: 
 6614:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6615: }
 6616: 
 6617: sub set_arearole {
 6618:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6619:     unless ($nolog) {
 6620: # log the associated role with the area
 6621:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6622:     }
 6623:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6624: }
 6625: 
 6626: sub custom_roleprivs {
 6627:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6628:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6629:     my $homsvr = &homeserver($rauthor,$rdomain);
 6630:     if (&hostname($homsvr) ne '') {
 6631:         my ($rdummy,$roledef)=
 6632:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6633:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6634:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6635:             if (defined($syspriv)) {
 6636:                 if ($trest =~ /^$match_community$/) {
 6637:                     $syspriv =~ s/bre\&S//; 
 6638:                 }
 6639:                 $$allroles{'cm./'}.=':'.$syspriv;
 6640:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6641:             }
 6642:             if ($tdomain ne '') {
 6643:                 if (defined($dompriv)) {
 6644:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6645:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6646:                 }
 6647:                 if (($trest ne '') && (defined($coursepriv))) {
 6648:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6649:                         my $rolename = $1;
 6650:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6651:                     }
 6652:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6653:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6654:                 }
 6655:             }
 6656:         }
 6657:     }
 6658: }
 6659: 
 6660: sub course_adhocrole_privs {
 6661:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6662:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6663:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6664:         my (%currprivs,%storeprivs);
 6665:         foreach my $item (split(/:/,$coursepriv)) {
 6666:             my ($priv,$restrict) = split(/\&/,$item);
 6667:             $currprivs{$priv} = $restrict;
 6668:         }
 6669:         my (%possadd,%possremove,%full);
 6670:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6671:             my ($priv,$restrict)=split(/\&/,$item);
 6672:             $full{$priv} = $restrict;
 6673:         }
 6674:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6675:              next if ($item eq '');
 6676:              my ($rule,$rest) = split(/=/,$item);
 6677:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6678:              foreach my $priv (split(/:/,$rest)) {
 6679:                  if ($priv ne '') {
 6680:                      if ($rule eq 'off') {
 6681:                          $possremove{$priv} = 1;
 6682:                      } else {
 6683:                          $possadd{$priv} = 1;
 6684:                      }
 6685:                  }
 6686:              }
 6687:          }
 6688:          foreach my $priv (sort(keys(%full))) {
 6689:              if (exists($currprivs{$priv})) {
 6690:                  unless (exists($possremove{$priv})) {
 6691:                      $storeprivs{$priv} = $currprivs{$priv};
 6692:                  }
 6693:              } elsif (exists($possadd{$priv})) {
 6694:                  $storeprivs{$priv} = $full{$priv};
 6695:              }
 6696:          }
 6697:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6698:      }
 6699:      return $coursepriv;
 6700: }
 6701: 
 6702: sub group_roleprivs {
 6703:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6704:     my $access = 1;
 6705:     my $now = time;
 6706:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6707:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6708:     if ($access) {
 6709:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6710:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6711:     }
 6712: }
 6713: 
 6714: sub standard_roleprivs {
 6715:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6716:     if (defined($pr{$trole.':s'})) {
 6717:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6718:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6719:     }
 6720:     if ($tdomain ne '') {
 6721:         if (defined($pr{$trole.':d'})) {
 6722:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6723:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6724:         }
 6725:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6726:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6727:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6728:         }
 6729:     }
 6730: }
 6731: 
 6732: sub set_userprivs {
 6733:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6734:     my $author=0;
 6735:     my $adv=0;
 6736:     my $rar=0;
 6737:     my %grouproles = ();
 6738:     if (keys(%{$allgroups}) > 0) {
 6739:         my @groupkeys; 
 6740:         foreach my $role (keys(%{$allroles})) {
 6741:             push(@groupkeys,$role);
 6742:         }
 6743:         if (ref($groups_roles) eq 'HASH') {
 6744:             foreach my $key (keys(%{$groups_roles})) {
 6745:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6746:                     push(@groupkeys,$key);
 6747:                 }
 6748:             }
 6749:         }
 6750:         if (@groupkeys > 0) {
 6751:             foreach my $role (@groupkeys) {
 6752:                 my ($trole,$area,$sec,$extendedarea);
 6753:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6754:                     $trole = $1;
 6755:                     $area = $2;
 6756:                     $sec = $3;
 6757:                     $extendedarea = $area.$sec;
 6758:                     if (exists($$allgroups{$area})) {
 6759:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6760:                             my $spec = $trole.'.'.$extendedarea;
 6761:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6762:                                                 $$allgroups{$area}{$group};
 6763:                         }
 6764:                     }
 6765:                 }
 6766:             }
 6767:         }
 6768:     }
 6769:     foreach my $group (keys(%grouproles)) {
 6770:         $$allroles{$group} = $grouproles{$group};
 6771:     }
 6772:     foreach my $role (keys(%{$allroles})) {
 6773:         my %thesepriv;
 6774:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6775:         foreach my $item (split(/:/,$$allroles{$role})) {
 6776:             if ($item ne '') {
 6777:                 my ($privilege,$restrictions)=split(/&/,$item);
 6778:                 if ($restrictions eq '') {
 6779:                     $thesepriv{$privilege}='F';
 6780:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6781:                     $thesepriv{$privilege}.=$restrictions;
 6782:                 }
 6783:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6784:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6785:             }
 6786:         }
 6787:         my $thesestr='';
 6788:         foreach my $priv (sort(keys(%thesepriv))) {
 6789: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6790: 	}
 6791:         $userroles->{'user.priv.'.$role} = $thesestr;
 6792:     }
 6793:     return ($author,$adv,$rar);
 6794: }
 6795: 
 6796: sub role_status {
 6797:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6798:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6799:         my ($one,$two) = split(m{\./},$rolekey,2);
 6800:         (undef,undef,$$role) = split(/\./,$one,3);
 6801:         unless (!defined($$role) || $$role eq '') {
 6802:             $$where = '/'.$two;
 6803:             $$trolecode=$$role.'.'.$$where;
 6804:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6805:             $$tstatus='is';
 6806:             if ($$tstart && $$tstart>$update) {
 6807:                 $$tstatus='future';
 6808:                 if ($$tstart<$now) {
 6809:                     if ($$tstart && $$tstart>$refresh) {
 6810:                         if (($$where ne '') && ($$role ne '')) {
 6811:                             my (%allroles,%allgroups,$group_privs,
 6812:                                 %groups_roles,@rolecodes);
 6813:                             my %userroles = (
 6814:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6815:                             );
 6816:                             @rolecodes = ('cm'); 
 6817:                             my $spec=$$role.'.'.$$where;
 6818:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6819:                             if ($$role =~ /^cr\//) {
 6820:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6821:                                 push(@rolecodes,'cr');
 6822:                             } elsif ($$role eq 'gr') {
 6823:                                 push(@rolecodes,$$role);
 6824:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6825:                                                     $env{'user.name'});
 6826:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6827:                                 (undef,my $group_privs) = split(/\//,$trole);
 6828:                                 $group_privs = &unescape($group_privs);
 6829:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6830:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6831:                                 &get_groups_roles($tdomain,$trest,
 6832:                                                   \%course_roles,\@rolecodes,
 6833:                                                   \%groups_roles);
 6834:                             } else {
 6835:                                 push(@rolecodes,$$role);
 6836:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6837:                             }
 6838:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6839:                                                                    \%groups_roles);
 6840:                             &appenv(\%userroles,\@rolecodes);
 6841:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6842:                         }
 6843:                     }
 6844:                     $$tstatus = 'is';
 6845:                 }
 6846:             }
 6847:             if ($$tend) {
 6848:                 if ($$tend<$update) {
 6849:                     $$tstatus='expired';
 6850:                 } elsif ($$tend<$now) {
 6851:                     $$tstatus='will_not';
 6852:                 }
 6853:             }
 6854:         }
 6855:     }
 6856: }
 6857: 
 6858: sub get_groups_roles {
 6859:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6860:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6861:                   (ref($rolecodes) eq 'ARRAY') && 
 6862:                   (ref($groups_roles) eq 'HASH')); 
 6863:     if (keys(%{$cdom_courseroles}) > 0) {
 6864:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6865:         if ($cdom ne '' && $cnum ne '') {
 6866:             foreach my $key (keys(%{$cdom_courseroles})) {
 6867:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6868:                     my $crsrole = $1;
 6869:                     my $crssec = $2;
 6870:                     if ($crsrole =~ /^cr/) {
 6871:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6872:                             push(@{$rolecodes},'cr');
 6873:                         }
 6874:                     } else {
 6875:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6876:                             push(@{$rolecodes},$crsrole);
 6877:                         }
 6878:                     }
 6879:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6880:                     if ($crssec ne '') {
 6881:                         $rolekey .= "/$crssec";
 6882:                     }
 6883:                     $rolekey .= './';
 6884:                     $groups_roles->{$rolekey} = $rolecodes;
 6885:                 }
 6886:             }
 6887:         }
 6888:     }
 6889:     return;
 6890: }
 6891: 
 6892: sub delete_env_groupprivs {
 6893:     my ($where,$courseroles,$possroles) = @_;
 6894:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6895:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6896:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6897:         %{$courseroles->{$udom}} =
 6898:             &get_my_roles('','','userroles',['active'],
 6899:                           $possroles,[$udom],1);
 6900:     }
 6901:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6902:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6903:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6904:             my $area = '/'.$cdom.'/'.$cnum;
 6905:             my $privkey = "user.priv.$crsrole.$area";
 6906:             if ($crssec ne '') {
 6907:                 $privkey .= '/'.$crssec;
 6908:             }
 6909:             $privkey .= ".$area/$group";
 6910:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6911:         }
 6912:     }
 6913:     return;
 6914: }
 6915: 
 6916: sub check_adhoc_privs {
 6917:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6918:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6919:     if ($sec) {
 6920:         $cckey .= '/'.$sec;
 6921:     } 
 6922:     my $setprivs;
 6923:     if ($env{$cckey}) {
 6924:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6925:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6926:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6927:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6928:             $setprivs = 1;
 6929:         }
 6930:     } else {
 6931:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6932:         $setprivs = 1;
 6933:     }
 6934:     return $setprivs;
 6935: }
 6936: 
 6937: sub set_adhoc_privileges {
 6938: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6939:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6940:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6941:     if ($sec ne '') {
 6942:         $area .= '/'.$sec;
 6943:     }
 6944:     my $spec = $role.'.'.$area;
 6945:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6946:                                   $env{'user.name'},1);
 6947:     my %rolehash = ();
 6948:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6949:         my $rolename = $1;
 6950:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6951:         my %domdef = &get_domain_defaults($dcdom);
 6952:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6953:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6954:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6955:             }
 6956:         }
 6957:     } else {
 6958:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6959:     }
 6960:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6961:     &appenv(\%userroles,[$role,'cm']);
 6962:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6963:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 6964:             ($caller eq 'tiny')) {
 6965:         &appenv( {'request.role'        => $spec,
 6966:                   'request.role.domain' => $dcdom,
 6967:                   'request.course.sec'  => $sec,
 6968:                  }
 6969:                );
 6970:         my $tadv=0;
 6971:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6972:         &appenv({'request.role.adv'    => $tadv});
 6973:     }
 6974: }
 6975: 
 6976: # --------------------------------------------------------------- get interface
 6977: 
 6978: sub get {
 6979:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6980:    my $items='';
 6981:    foreach my $item (@$storearr) {
 6982:        $items.=&escape($item).'&';
 6983:    }
 6984:    $items=~s/\&$//;
 6985:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6986:    if (!$uname) { $uname=$env{'user.name'}; }
 6987:    my $uhome=&homeserver($uname,$udomain);
 6988: 
 6989:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6990:    my @pairs=split(/\&/,$rep);
 6991:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6992:      return @pairs;
 6993:    }
 6994:    my %returnhash=();
 6995:    my $i=0;
 6996:    foreach my $item (@$storearr) {
 6997:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6998:       $i++;
 6999:    }
 7000:    return %returnhash;
 7001: }
 7002: 
 7003: # --------------------------------------------------------------- del interface
 7004: 
 7005: sub del {
 7006:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7007:    my $items='';
 7008:    foreach my $item (@$storearr) {
 7009:        $items.=&escape($item).'&';
 7010:    }
 7011: 
 7012:    $items=~s/\&$//;
 7013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7014:    if (!$uname) { $uname=$env{'user.name'}; }
 7015:    my $uhome=&homeserver($uname,$udomain);
 7016:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7017: }
 7018: 
 7019: # -------------------------------------------------------------- dump interface
 7020: 
 7021: sub unserialize {
 7022:     my ($rep, $escapedkeys) = @_;
 7023: 
 7024:     return {} if $rep =~ /^error/;
 7025: 
 7026:     my %returnhash=();
 7027: 	foreach my $item (split(/\&/,$rep)) {
 7028: 	    my ($key, $value) = split(/=/, $item, 2);
 7029: 	    $key = unescape($key) unless $escapedkeys;
 7030: 	    next if $key =~ /^error: 2 /;
 7031: 	    $returnhash{$key} = &thaw_unescape($value);
 7032: 	}
 7033:     #return %returnhash;
 7034:     return \%returnhash;
 7035: }        
 7036: 
 7037: # see Lond::dump_with_regexp
 7038: # if $escapedkeys hash keys won't get unescaped.
 7039: sub dump {
 7040:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7041:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7042:     if (!$uname) { $uname=$env{'user.name'}; }
 7043:     my $uhome=&homeserver($uname,$udomain);
 7044: 
 7045:     if ($regexp) {
 7046:         $regexp=&escape($regexp);
 7047:     } else {
 7048:         $regexp='.';
 7049:     }
 7050:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7051:         # user is hosted on this machine
 7052:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7053:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7054:         return %{unserialize($reply, $escapedkeys)};
 7055:     }
 7056:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7057:     my @pairs=split(/\&/,$rep);
 7058:     my %returnhash=();
 7059:     if (!($rep =~ /^error/ )) {
 7060: 	foreach my $item (@pairs) {
 7061: 	    my ($key,$value)=split(/=/,$item,2);
 7062:         $key = unescape($key) unless $escapedkeys;
 7063:         #$key = &unescape($key);
 7064: 	    next if ($key =~ /^error: 2 /);
 7065: 	    $returnhash{$key}=&thaw_unescape($value);
 7066: 	}
 7067:     }
 7068:     return %returnhash;
 7069: }
 7070: 
 7071: 
 7072: # --------------------------------------------------------- dumpstore interface
 7073: 
 7074: sub dumpstore {
 7075:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7076:    # same as dump but keys must be escaped. They may contain colon separated
 7077:    # lists of values that may themself contain colons (e.g. symbs).
 7078:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7079: }
 7080: 
 7081: # -------------------------------------------------------------- keys interface
 7082: 
 7083: sub getkeys {
 7084:    my ($namespace,$udomain,$uname)=@_;
 7085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7086:    if (!$uname) { $uname=$env{'user.name'}; }
 7087:    my $uhome=&homeserver($uname,$udomain);
 7088:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7089:    my @keyarray=();
 7090:    foreach my $key (split(/\&/,$rep)) {
 7091:       next if ($key =~ /^error: 2 /);
 7092:       push(@keyarray,&unescape($key));
 7093:    }
 7094:    return @keyarray;
 7095: }
 7096: 
 7097: # --------------------------------------------------------------- currentdump
 7098: sub currentdump {
 7099:    my ($courseid,$sdom,$sname)=@_;
 7100:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7101:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7102:    $sname    = $env{'user.name'}         if (! defined($sname));
 7103:    my $uhome = &homeserver($sname,$sdom);
 7104:    my $rep;
 7105: 
 7106:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7107:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7108:                    $courseid)));
 7109:    } else {
 7110:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7111:    }
 7112: 
 7113:    return if ($rep =~ /^(error:|no_such_host)/);
 7114:    #
 7115:    my %returnhash=();
 7116:    #
 7117:    if ($rep eq 'unknown_cmd') {
 7118:        # an old lond will not know currentdump
 7119:        # Do a dump and make it look like a currentdump
 7120:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7121:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7122:        my %hash = @tmp;
 7123:        @tmp=();
 7124:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7125:    } else {
 7126:        my @pairs=split(/\&/,$rep);
 7127:        foreach my $pair (@pairs) {
 7128:            my ($key,$value)=split(/=/,$pair,2);
 7129:            my ($symb,$param) = split(/:/,$key);
 7130:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7131:                                                         &thaw_unescape($value);
 7132:        }
 7133:    }
 7134:    return %returnhash;
 7135: }
 7136: 
 7137: sub convert_dump_to_currentdump{
 7138:     my %hash = %{shift()};
 7139:     my %returnhash;
 7140:     # Code ripped from lond, essentially.  The only difference
 7141:     # here is the unescaping done by lonnet::dump().  Conceivably
 7142:     # we might run in to problems with parameter names =~ /^v\./
 7143:     while (my ($key,$value) = each(%hash)) {
 7144:         my ($v,$symb,$param) = split(/:/,$key);
 7145: 	$symb  = &unescape($symb);
 7146: 	$param = &unescape($param);
 7147:         next if ($v eq 'version' || $symb eq 'keys');
 7148:         next if (exists($returnhash{$symb}) &&
 7149:                  exists($returnhash{$symb}->{$param}) &&
 7150:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7151:         $returnhash{$symb}->{$param}=$value;
 7152:         $returnhash{$symb}->{'v.'.$param}=$v;
 7153:     }
 7154:     #
 7155:     # Remove all of the keys in the hashes which keep track of
 7156:     # the version of the parameter.
 7157:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7158:         # use a foreach because we are going to delete from the hash.
 7159:         foreach my $key (keys(%$param_hash)) {
 7160:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7161:         }
 7162:     }
 7163:     return \%returnhash;
 7164: }
 7165: 
 7166: # ------------------------------------------------------ critical inc interface
 7167: 
 7168: sub cinc {
 7169:     return &inc(@_,'critical');
 7170: }
 7171: 
 7172: # --------------------------------------------------------------- inc interface
 7173: 
 7174: sub inc {
 7175:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7176:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7177:     if (!$uname) { $uname=$env{'user.name'}; }
 7178:     my $uhome=&homeserver($uname,$udomain);
 7179:     my $items='';
 7180:     if (! ref($store)) {
 7181:         # got a single value, so use that instead
 7182:         $items = &escape($store).'=&';
 7183:     } elsif (ref($store) eq 'SCALAR') {
 7184:         $items = &escape($$store).'=&';        
 7185:     } elsif (ref($store) eq 'ARRAY') {
 7186:         $items = join('=&',map {&escape($_);} @{$store});
 7187:     } elsif (ref($store) eq 'HASH') {
 7188:         while (my($key,$value) = each(%{$store})) {
 7189:             $items.= &escape($key).'='.&escape($value).'&';
 7190:         }
 7191:     }
 7192:     $items=~s/\&$//;
 7193:     if ($critical) {
 7194: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7195:     } else {
 7196: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7197:     }
 7198: }
 7199: 
 7200: # --------------------------------------------------------------- put interface
 7201: 
 7202: sub put {
 7203:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7204:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7205:    if (!$uname) { $uname=$env{'user.name'}; }
 7206:    my $uhome=&homeserver($uname,$udomain);
 7207:    my $items='';
 7208:    foreach my $item (keys(%$storehash)) {
 7209:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7210:    }
 7211:    $items=~s/\&$//;
 7212:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7213: }
 7214: 
 7215: # ------------------------------------------------------------ newput interface
 7216: 
 7217: sub newput {
 7218:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7219:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7220:    if (!$uname) { $uname=$env{'user.name'}; }
 7221:    my $uhome=&homeserver($uname,$udomain);
 7222:    my $items='';
 7223:    foreach my $key (keys(%$storehash)) {
 7224:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7225:    }
 7226:    $items=~s/\&$//;
 7227:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7228: }
 7229: 
 7230: # ---------------------------------------------------------  putstore interface
 7231: 
 7232: sub putstore {
 7233:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7235:    if (!$uname) { $uname=$env{'user.name'}; }
 7236:    my $uhome=&homeserver($uname,$udomain);
 7237:    my $items='';
 7238:    foreach my $key (keys(%$storehash)) {
 7239:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7240:    }
 7241:    $items=~s/\&$//;
 7242:    my $esc_symb=&escape($symb);
 7243:    my $esc_v=&escape($version);
 7244:    my $reply =
 7245:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7246: 	      $uhome);
 7247:    if (($tolog) && ($reply eq 'ok')) {
 7248:        my $namevalue='';
 7249:        foreach my $key (keys(%{$storehash})) {
 7250:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7251:        }
 7252:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7253:                      '&host='.&escape($perlvar{'lonHostID'}).
 7254:                      '&version='.$esc_v.
 7255:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7256:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7257:    }
 7258:    if ($reply eq 'unknown_cmd') {
 7259:        # gfall back to way things use to be done
 7260:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7261: 			    $uname);
 7262:    }
 7263:    return $reply;
 7264: }
 7265: 
 7266: sub old_putstore {
 7267:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7268:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7269:     if (!$uname) { $uname=$env{'user.name'}; }
 7270:     my $uhome=&homeserver($uname,$udomain);
 7271:     my %newstorehash;
 7272:     foreach my $item (keys(%$storehash)) {
 7273: 	my $key = $version.':'.&escape($symb).':'.$item;
 7274: 	$newstorehash{$key} = $storehash->{$item};
 7275:     }
 7276:     my $items='';
 7277:     my %allitems = ();
 7278:     foreach my $item (keys(%newstorehash)) {
 7279: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7280: 	    my $key = $1.':keys:'.$2;
 7281: 	    $allitems{$key} .= $3.':';
 7282: 	}
 7283: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7284:     }
 7285:     foreach my $item (keys(%allitems)) {
 7286: 	$allitems{$item} =~ s/\:$//;
 7287: 	$items.= $item.'='.$allitems{$item}.'&';
 7288:     }
 7289:     $items=~s/\&$//;
 7290:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7291: }
 7292: 
 7293: # ------------------------------------------------------ critical put interface
 7294: 
 7295: sub cput {
 7296:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7297:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7298:    if (!$uname) { $uname=$env{'user.name'}; }
 7299:    my $uhome=&homeserver($uname,$udomain);
 7300:    my $items='';
 7301:    foreach my $item (keys(%$storehash)) {
 7302:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7303:    }
 7304:    $items=~s/\&$//;
 7305:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7306: }
 7307: 
 7308: # -------------------------------------------------------------- eget interface
 7309: 
 7310: sub eget {
 7311:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7312:    my $items='';
 7313:    foreach my $item (@$storearr) {
 7314:        $items.=&escape($item).'&';
 7315:    }
 7316:    $items=~s/\&$//;
 7317:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7318:    if (!$uname) { $uname=$env{'user.name'}; }
 7319:    my $uhome=&homeserver($uname,$udomain);
 7320:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7321:    my @pairs=split(/\&/,$rep);
 7322:    my %returnhash=();
 7323:    my $i=0;
 7324:    foreach my $item (@$storearr) {
 7325:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7326:       $i++;
 7327:    }
 7328:    return %returnhash;
 7329: }
 7330: 
 7331: # ------------------------------------------------------------ tmpput interface
 7332: sub tmpput {
 7333:     my ($storehash,$server,$context)=@_;
 7334:     my $items='';
 7335:     foreach my $item (keys(%$storehash)) {
 7336: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7337:     }
 7338:     $items=~s/\&$//;
 7339:     if (defined($context)) {
 7340:         $items .= ':'.&escape($context);
 7341:     }
 7342:     return &reply("tmpput:$items",$server);
 7343: }
 7344: 
 7345: # ------------------------------------------------------------ tmpget interface
 7346: sub tmpget {
 7347:     my ($token,$server)=@_;
 7348:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7349:     my $rep=&reply("tmpget:$token",$server);
 7350:     my %returnhash;
 7351:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7352:         return %returnhash;
 7353:     }
 7354:     foreach my $item (split(/\&/,$rep)) {
 7355: 	my ($key,$value)=split(/=/,$item);
 7356: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7357:     }
 7358:     return %returnhash;
 7359: }
 7360: 
 7361: # ------------------------------------------------------------ tmpdel interface
 7362: sub tmpdel {
 7363:     my ($token,$server)=@_;
 7364:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7365:     return &reply("tmpdel:$token",$server);
 7366: }
 7367: 
 7368: # ------------------------------------------------------------ get_timebased_id 
 7369: 
 7370: sub get_timebased_id {
 7371:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7372:         $maxtries) = @_;
 7373:     my ($newid,$error,$dellock);
 7374:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7375:         return ('','ok','invalid call to get suffix');
 7376:     }
 7377: 
 7378: # set defaults for any optional args for which values were not supplied
 7379:     if ($who eq '') {
 7380:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7381:     }
 7382:     if (!$locktries) {
 7383:         $locktries = 3;
 7384:     }
 7385:     if (!$maxtries) {
 7386:         $maxtries = 10;
 7387:     }
 7388:     
 7389:     if (($cdom eq '') || ($cnum eq '')) {
 7390:         if ($env{'request.course.id'}) {
 7391:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7392:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7393:         }
 7394:         if (($cdom eq '') || ($cnum eq '')) {
 7395:             return ('','ok','call to get suffix not in course context');
 7396:         }
 7397:     }
 7398: 
 7399: # construct locking item
 7400:     my $lockhash = {
 7401:                       $prefix."\0".'locked_'.$keyid => $who,
 7402:                    };
 7403:     my $tries = 0;
 7404: 
 7405: # attempt to get lock on nohist_$namespace file
 7406:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7407:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7408:         $tries ++;
 7409:         sleep 1;
 7410:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7411:     }
 7412: 
 7413: # attempt to get unique identifier, based on current timestamp
 7414:     if ($gotlock eq 'ok') {
 7415:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7416:         my $id = time;
 7417:         $newid = $id;
 7418:         if ($idtype eq 'addcode') {
 7419:             $newid .= &sixnum_code();
 7420:         }
 7421:         my $idtries = 0;
 7422:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7423:             if ($idtype eq 'concat') {
 7424:                 $newid = $id.$idtries;
 7425:             } elsif ($idtype eq 'addcode') {
 7426:                 $newid = $newid.&sixnum_code();
 7427:             } else {
 7428:                 $newid ++;
 7429:             }
 7430:             $idtries ++;
 7431:         }
 7432:         if (!exists($inuse{$prefix."\0".$newid})) {
 7433:             my %new_item =  (
 7434:                               $prefix."\0".$newid => $who,
 7435:                             );
 7436:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7437:                                                  $cdom,$cnum);
 7438:             if ($putresult ne 'ok') {
 7439:                 undef($newid);
 7440:                 $error = 'error saving new item: '.$putresult;
 7441:             }
 7442:         } else {
 7443:              undef($newid);
 7444:              $error = ('error: no unique suffix available for the new item ');
 7445:         }
 7446: #  remove lock
 7447:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7448:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7449:     } else {
 7450:         $error = "error: could not obtain lockfile\n";
 7451:         $dellock = 'ok';
 7452:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7453:             $dellock = 'nolock';
 7454:         }
 7455:     }
 7456:     return ($newid,$dellock,$error);
 7457: }
 7458: 
 7459: sub sixnum_code {
 7460:     my $code;
 7461:     for (0..6) {
 7462:         $code .= int( rand(9) );
 7463:     }
 7464:     return $code;
 7465: }
 7466: 
 7467: # -------------------------------------------------- portfolio access checking
 7468: 
 7469: sub portfolio_access {
 7470:     my ($requrl,$clientip) = @_;
 7471:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7472:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7473:     if ($result) {
 7474:         my %setters;
 7475:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7476:             my ($startblock,$endblock) =
 7477:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7478:             if ($startblock && $endblock) {
 7479:                 return 'B';
 7480:             }
 7481:         } else {
 7482:             my ($startblock,$endblock) =
 7483:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7484:             if ($startblock && $endblock) {
 7485:                 return 'B';
 7486:             }
 7487:         }
 7488:     }
 7489:     if ($result eq 'ok') {
 7490:        return 'F';
 7491:     } elsif ($result =~ /^[^:]+:guest_/) {
 7492:        return 'A';
 7493:     }
 7494:     return '';
 7495: }
 7496: 
 7497: sub get_portfolio_access {
 7498:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7499: 
 7500:     if (!ref($access_hash)) {
 7501: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7502: 	my %access_controls = &get_access_controls($current_perms,$group,
 7503: 						   $file_name);
 7504: 	$access_hash = $access_controls{$file_name};
 7505:     }
 7506: 
 7507:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7508:     my $now = time;
 7509:     if (ref($access_hash) eq 'HASH') {
 7510:         foreach my $key (keys(%{$access_hash})) {
 7511:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7512:             if ($start > $now) {
 7513:                 next;
 7514:             }
 7515:             if ($end && $end<$now) {
 7516:                 next;
 7517:             }
 7518:             if ($scope eq 'public') {
 7519:                 $public = $key;
 7520:                 last;
 7521:             } elsif ($scope eq 'guest') {
 7522:                 $guest = $key;
 7523:             } elsif ($scope eq 'domains') {
 7524:                 push(@domains,$key);
 7525:             } elsif ($scope eq 'users') {
 7526:                 push(@users,$key);
 7527:             } elsif ($scope eq 'course') {
 7528:                 push(@courses,$key);
 7529:             } elsif ($scope eq 'group') {
 7530:                 push(@groups,$key);
 7531:             } elsif ($scope eq 'ip') {
 7532:                 push(@ips,$key);
 7533:             }
 7534:         }
 7535:         if ($public) {
 7536:             return 'ok';
 7537:         } elsif (@ips > 0) {
 7538:             my $allowed;
 7539:             foreach my $ipkey (@ips) {
 7540:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7541:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7542:                         $allowed = 1;
 7543:                         last; 
 7544:                     }
 7545:                 }
 7546:             }
 7547:             if ($allowed) {
 7548:                 return 'ok';
 7549:             }
 7550:         }
 7551:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7552:             if ($guest) {
 7553:                 return $guest;
 7554:             }
 7555:         } else {
 7556:             if (@domains > 0) {
 7557:                 foreach my $domkey (@domains) {
 7558:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7559:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7560:                             return 'ok';
 7561:                         }
 7562:                     }
 7563:                 }
 7564:             }
 7565:             if (@users > 0) {
 7566:                 foreach my $userkey (@users) {
 7567:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7568:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7569:                             if (ref($item) eq 'HASH') {
 7570:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7571:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7572:                                     return 'ok';
 7573:                                 }
 7574:                             }
 7575:                         }
 7576:                     } 
 7577:                 }
 7578:             }
 7579:             my %roleshash;
 7580:             my @courses_and_groups = @courses;
 7581:             push(@courses_and_groups,@groups); 
 7582:             if (@courses_and_groups > 0) {
 7583:                 my (%allgroups,%allroles); 
 7584:                 my ($start,$end,$role,$sec,$group);
 7585:                 foreach my $envkey (%env) {
 7586:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7587:                         my $cid = $2.'_'.$3; 
 7588:                         if ($1 eq 'gr') {
 7589:                             $group = $4;
 7590:                             $allgroups{$cid}{$group} = $env{$envkey};
 7591:                         } else {
 7592:                             if ($4 eq '') {
 7593:                                 $sec = 'none';
 7594:                             } else {
 7595:                                 $sec = $4;
 7596:                             }
 7597:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7598:                         }
 7599:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7600:                         my $cid = $2.'_'.$3;
 7601:                         if ($4 eq '') {
 7602:                             $sec = 'none';
 7603:                         } else {
 7604:                             $sec = $4;
 7605:                         }
 7606:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7607:                     }
 7608:                 }
 7609:                 if (keys(%allroles) == 0) {
 7610:                     return;
 7611:                 }
 7612:                 foreach my $key (@courses_and_groups) {
 7613:                     my %content = %{$$access_hash{$key}};
 7614:                     my $cnum = $content{'number'};
 7615:                     my $cdom = $content{'domain'};
 7616:                     my $cid = $cdom.'_'.$cnum;
 7617:                     if (!exists($allroles{$cid})) {
 7618:                         next;
 7619:                     }    
 7620:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7621:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7622:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7623:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7624:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7625:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7626:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7627:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7628:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7629:                                         if (grep/^all$/,@sections) {
 7630:                                             return 'ok';
 7631:                                         } else {
 7632:                                             if (grep/^$sec$/,@sections) {
 7633:                                                 return 'ok';
 7634:                                             }
 7635:                                         }
 7636:                                     }
 7637:                                 }
 7638:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7639:                                     if (grep/^none$/,@groups) {
 7640:                                         return 'ok';
 7641:                                     }
 7642:                                 } else {
 7643:                                     if (grep/^all$/,@groups) {
 7644:                                         return 'ok';
 7645:                                     } 
 7646:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7647:                                         if (grep/^$group$/,@groups) {
 7648:                                             return 'ok';
 7649:                                         }
 7650:                                     }
 7651:                                 } 
 7652:                             }
 7653:                         }
 7654:                     }
 7655:                 }
 7656:             }
 7657:             if ($guest) {
 7658:                 return $guest;
 7659:             }
 7660:         }
 7661:     }
 7662:     return;
 7663: }
 7664: 
 7665: sub course_group_datechecker {
 7666:     my ($dates,$now,$status) = @_;
 7667:     my ($start,$end) = split(/\./,$dates);
 7668:     if (!$start && !$end) {
 7669:         return 'ok';
 7670:     }
 7671:     if (grep/^active$/,@{$status}) {
 7672:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7673:             return 'ok';
 7674:         }
 7675:     }
 7676:     if (grep/^previous$/,@{$status}) {
 7677:         if ($end > $now ) {
 7678:             return 'ok';
 7679:         }
 7680:     }
 7681:     if (grep/^future$/,@{$status}) {
 7682:         if ($start > $now) {
 7683:             return 'ok';
 7684:         }
 7685:     }
 7686:     return; 
 7687: }
 7688: 
 7689: sub parse_portfolio_url {
 7690:     my ($url) = @_;
 7691: 
 7692:     my ($type,$udom,$unum,$group,$file_name);
 7693:     
 7694:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7695: 	$type = 1;
 7696:         $udom = $1;
 7697:         $unum = $2;
 7698:         $file_name = $3;
 7699:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7700: 	$type = 2;
 7701:         $udom = $1;
 7702:         $unum = $2;
 7703:         $group = $3;
 7704:         $file_name = $3.'/'.$4;
 7705:     }
 7706:     if (wantarray) {
 7707: 	return ($type,$udom,$unum,$file_name,$group);
 7708:     }
 7709:     return $type;
 7710: }
 7711: 
 7712: sub is_portfolio_url {
 7713:     my ($url) = @_;
 7714:     return scalar(&parse_portfolio_url($url));
 7715: }
 7716: 
 7717: sub is_portfolio_file {
 7718:     my ($file) = @_;
 7719:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7720:         return 1;
 7721:     }
 7722:     return;
 7723: }
 7724: 
 7725: sub usertools_access {
 7726:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7727:     my ($access,%tools);
 7728:     if ($context eq '') {
 7729:         $context = 'tools';
 7730:     }
 7731:     if ($context eq 'requestcourses') {
 7732:         %tools = (
 7733:                       official   => 1,
 7734:                       unofficial => 1,
 7735:                       community  => 1,
 7736:                       textbook   => 1,
 7737:                       placement  => 1,
 7738:                       lti        => 1,
 7739:                  );
 7740:     } elsif ($context eq 'requestauthor') {
 7741:         %tools = (
 7742:                       requestauthor => 1,
 7743:                  );
 7744:     } else {
 7745:         %tools = (
 7746:                       aboutme   => 1,
 7747:                       blog      => 1,
 7748:                       webdav    => 1,
 7749:                       portfolio => 1,
 7750:                  );
 7751:     }
 7752:     return if (!defined($tools{$tool}));
 7753: 
 7754:     if (($udom eq '') || ($uname eq '')) {
 7755:         $udom = $env{'user.domain'};
 7756:         $uname = $env{'user.name'};
 7757:     }
 7758: 
 7759:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7760:         if ($action ne 'reload') {
 7761:             if ($context eq 'requestcourses') {
 7762:                 return $env{'environment.canrequest.'.$tool};
 7763:             } elsif ($context eq 'requestauthor') {
 7764:                 return $env{'environment.canrequest.author'};
 7765:             } else {
 7766:                 return $env{'environment.availabletools.'.$tool};
 7767:             }
 7768:         }
 7769:     }
 7770: 
 7771:     my ($toolstatus,$inststatus,$envkey);
 7772:     if ($context eq 'requestauthor') {
 7773:         $envkey = $context; 
 7774:     } else {
 7775:         $envkey = $context.'.'.$tool;
 7776:     }
 7777: 
 7778:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7779:          ($action ne 'reload')) {
 7780:         $toolstatus = $env{'environment.'.$envkey};
 7781:         $inststatus = $env{'environment.inststatus'};
 7782:     } else {
 7783:         if (ref($userenvref) eq 'HASH') {
 7784:             $toolstatus = $userenvref->{$envkey};
 7785:             $inststatus = $userenvref->{'inststatus'};
 7786:         } else {
 7787:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7788:             $toolstatus = $userenv{$envkey};
 7789:             $inststatus = $userenv{'inststatus'};
 7790:         }
 7791:     }
 7792: 
 7793:     if ($toolstatus ne '') {
 7794:         if ($toolstatus) {
 7795:             $access = 1;
 7796:         } else {
 7797:             $access = 0;
 7798:         }
 7799:         return $access;
 7800:     }
 7801: 
 7802:     my ($is_adv,%domdef);
 7803:     if (ref($is_advref) eq 'HASH') {
 7804:         $is_adv = $is_advref->{'is_adv'};
 7805:     } else {
 7806:         $is_adv = &is_advanced_user($udom,$uname);
 7807:     }
 7808:     if (ref($domdefref) eq 'HASH') {
 7809:         %domdef = %{$domdefref};
 7810:     } else {
 7811:         %domdef = &get_domain_defaults($udom);
 7812:     }
 7813:     if (ref($domdef{$tool}) eq 'HASH') {
 7814:         if ($is_adv) {
 7815:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7816:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7817:                     $access = 1;
 7818:                 } else {
 7819:                     $access = 0;
 7820:                 }
 7821:                 return $access;
 7822:             }
 7823:         }
 7824:         if ($inststatus ne '') {
 7825:             my ($hasaccess,$hasnoaccess);
 7826:             foreach my $affiliation (split(/:/,$inststatus)) {
 7827:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7828:                     if ($domdef{$tool}{$affiliation}) {
 7829:                         $hasaccess = 1;
 7830:                     } else {
 7831:                         $hasnoaccess = 1;
 7832:                     }
 7833:                 }
 7834:             }
 7835:             if ($hasaccess || $hasnoaccess) {
 7836:                 if ($hasaccess) {
 7837:                     $access = 1;
 7838:                 } elsif ($hasnoaccess) {
 7839:                     $access = 0; 
 7840:                 }
 7841:                 return $access;
 7842:             }
 7843:         } else {
 7844:             if ($domdef{$tool}{'default'} ne '') {
 7845:                 if ($domdef{$tool}{'default'}) {
 7846:                     $access = 1;
 7847:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7848:                     $access = 0;
 7849:                 }
 7850:                 return $access;
 7851:             }
 7852:         }
 7853:     } else {
 7854:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7855:             $access = 1;
 7856:         } else {
 7857:             $access = 0;
 7858:         }
 7859:         return $access;
 7860:     }
 7861: }
 7862: 
 7863: sub is_course_owner {
 7864:     my ($cdom,$cnum,$udom,$uname) = @_;
 7865:     if (($udom eq '') || ($uname eq '')) {
 7866:         $udom = $env{'user.domain'};
 7867:         $uname = $env{'user.name'};
 7868:     }
 7869:     unless (($udom eq '') || ($uname eq '')) {
 7870:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7871:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7872:                 return 1;
 7873:             } else {
 7874:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7875:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7876:                     return 1;
 7877:                 }
 7878:             }
 7879:         }
 7880:     }
 7881:     return;
 7882: }
 7883: 
 7884: sub is_advanced_user {
 7885:     my ($udom,$uname) = @_;
 7886:     if ($udom ne '' && $uname ne '') {
 7887:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7888:             if (wantarray) {
 7889:                 return ($env{'user.adv'},$env{'user.author'});
 7890:             } else {
 7891:                 return $env{'user.adv'};
 7892:             }
 7893:         }
 7894:     }
 7895:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7896:     my %allroles;
 7897:     my ($is_adv,$is_author);
 7898:     foreach my $role (keys(%roleshash)) {
 7899:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7900:         my $area = '/'.$tdomain.'/'.$trest;
 7901:         if ($sec ne '') {
 7902:             $area .= '/'.$sec;
 7903:         }
 7904:         if (($area ne '') && ($trole ne '')) {
 7905:             my $spec=$trole.'.'.$area;
 7906:             if ($trole =~ /^cr\//) {
 7907:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7908:             } elsif ($trole ne 'gr') {
 7909:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7910:             }
 7911:             if ($trole eq 'au') {
 7912:                 $is_author = 1;
 7913:             }
 7914:         }
 7915:     }
 7916:     foreach my $role (keys(%allroles)) {
 7917:         last if ($is_adv);
 7918:         foreach my $item (split(/:/,$allroles{$role})) {
 7919:             if ($item ne '') {
 7920:                 my ($privilege,$restrictions)=split(/&/,$item);
 7921:                 if ($privilege eq 'adv') {
 7922:                     $is_adv = 1;
 7923:                     last;
 7924:                 }
 7925:             }
 7926:         }
 7927:     }
 7928:     if (wantarray) {
 7929:         return ($is_adv,$is_author);
 7930:     }
 7931:     return $is_adv;
 7932: }
 7933: 
 7934: sub check_can_request {
 7935:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7936:     my $canreq = 0;
 7937:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7938:         $uname = $env{'user.name'};
 7939:         $udom = $env{'user.domain'};
 7940:     }
 7941:     my ($types,$typename) = &Apache::loncommon::course_types();
 7942:     my @options = ('approval','validate','autolimit');
 7943:     my $optregex = join('|',@options);
 7944:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7945:         foreach my $type (@{$types}) {
 7946:             if (&usertools_access($uname,$udom,$type,undef,
 7947:                                   'requestcourses')) {
 7948:                 $canreq ++;
 7949:                 if (ref($request_domains) eq 'HASH') {
 7950:                     push(@{$request_domains->{$type}},$udom);
 7951:                 }
 7952:                 if ($dom eq $udom) {
 7953:                     $can_request->{$type} = 1;
 7954:                 }
 7955:             }
 7956:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7957:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7958:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7959:                 if (@curr > 0) {
 7960:                     foreach my $item (@curr) {
 7961:                         if (ref($request_domains) eq 'HASH') {
 7962:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7963:                             if ($otherdom ne '') {
 7964:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7965:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7966:                                         push(@{$request_domains->{$type}},$otherdom);
 7967:                                     }
 7968:                                 } else {
 7969:                                     push(@{$request_domains->{$type}},$otherdom);
 7970:                                 }
 7971:                             }
 7972:                         }
 7973:                     }
 7974:                     unless ($dom eq $env{'user.domain'}) {
 7975:                         $canreq ++;
 7976:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7977:                             $can_request->{$type} = 1;
 7978:                         }
 7979:                     }
 7980:                 }
 7981:             }
 7982:         }
 7983:     }
 7984:     return $canreq;
 7985: }
 7986: 
 7987: # ---------------------------------------------- Custom access rule evaluation
 7988: 
 7989: sub customaccess {
 7990:     my ($priv,$uri)=@_;
 7991:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7992:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7993:     $udom = &LONCAPA::clean_domain($udom);
 7994:     $ucrs = &LONCAPA::clean_username($ucrs);
 7995:     my $access=0;
 7996:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7997: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7998: 	if ($type eq 'user') {
 7999: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8000: 		my ($tdom,$tuname)=split(m{/},$scope);
 8001: 		if ($tdom) {
 8002: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8003: 		}
 8004: 		if ($tuname) {
 8005: 		    if ($tuname ne $env{'user.name'}) { next; }
 8006: 		}
 8007: 		$access=($effect eq 'allow');
 8008: 		last;
 8009: 	    }
 8010: 	} else {
 8011: 	    if ($role) {
 8012: 		if ($role ne $urole) { next; }
 8013: 	    }
 8014: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8015: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8016: 		if ($tdom) {
 8017: 		    if ($tdom ne $udom) { next; }
 8018: 		}
 8019: 		if ($tcrs) {
 8020: 		    if ($tcrs ne $ucrs) { next; }
 8021: 		}
 8022: 		if ($tsec) {
 8023: 		    if ($tsec ne $usec) { next; }
 8024: 		}
 8025: 		$access=($effect eq 'allow');
 8026: 		last;
 8027: 	    }
 8028: 	    if ($realm eq '' && $role eq '') {
 8029: 		$access=($effect eq 'allow');
 8030: 	    }
 8031: 	}
 8032:     }
 8033:     return $access;
 8034: }
 8035: 
 8036: # ------------------------------------------------- Check for a user privilege
 8037: 
 8038: sub allowed {
 8039:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 8040:     my $ver_orguri=$uri;
 8041:     $uri=&deversion($uri);
 8042:     my $orguri=$uri;
 8043:     $uri=&declutter($uri);
 8044: 
 8045:     if ($priv eq 'evb') {
 8046: # Evade communication block restrictions for specified role in a course
 8047:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8048:             return $1;
 8049:         } else {
 8050:             return;
 8051:         }
 8052:     }
 8053: 
 8054:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8055: # Free bre access to adm and meta resources
 8056:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 8057: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8058: 	&& ($priv eq 'bre')) {
 8059: 	return 'F';
 8060:     }
 8061: 
 8062: # Free bre access to user's own portfolio contents
 8063:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8064:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8065: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8066:         my %setters;
 8067:         my ($startblock,$endblock) = 
 8068:             &Apache::loncommon::blockcheck(\%setters,'port');
 8069:         if ($startblock && $endblock) {
 8070:             return 'B';
 8071:         } else {
 8072:             return 'F';
 8073:         }
 8074:     }
 8075: 
 8076: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8077:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8078:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8079:         if (exists($env{'request.course.id'})) {
 8080:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8081:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8082:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8083:                 my $courseprivid=$env{'request.course.id'};
 8084:                 $courseprivid=~s/\_/\//;
 8085:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8086:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8087:                     return $1; 
 8088:                 } else {
 8089:                     if ($env{'request.course.sec'}) {
 8090:                         $courseprivid.='/'.$env{'request.course.sec'};
 8091:                     }
 8092:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8093:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8094:                         return $2;
 8095:                     }
 8096:                 }
 8097:             }
 8098:         }
 8099:     }
 8100: 
 8101: # Free bre to public access
 8102: 
 8103:     if ($priv eq 'bre') {
 8104:         my $copyright;
 8105:         unless ($uri =~ /ext\.tool/) {
 8106:             $copyright=&metadata($uri,'copyright');
 8107:         }
 8108: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8109:            return 'F'; 
 8110:         }
 8111:         if ($copyright eq 'priv') {
 8112:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8113: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8114: 		return '';
 8115:             }
 8116:         }
 8117:         if ($copyright eq 'domain') {
 8118:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8119: 	    unless (($env{'user.domain'} eq $1) ||
 8120:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8121: 		return '';
 8122:             }
 8123:         }
 8124:         if ($env{'request.role'}=~ /li\.\//) {
 8125:             # Library role, so allow browsing of resources in this domain.
 8126:             return 'F';
 8127:         }
 8128:         if ($copyright eq 'custom') {
 8129: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8130:         }
 8131:     }
 8132:     # Domain coordinator is trying to create a course
 8133:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8134:         # uri is the requested domain in this case.
 8135:         # comparison to 'request.role.domain' shows if the user has selected
 8136:         # a role of dc for the domain in question.
 8137:         return 'F' if ($uri eq $env{'request.role.domain'});
 8138:     }
 8139: 
 8140:     my $thisallowed='';
 8141:     my $statecond=0;
 8142:     my $courseprivid='';
 8143: 
 8144:     my $ownaccess;
 8145:     # Community Coordinator or Assistant Co-author browsing resource space.
 8146:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8147:         if ($uri eq '') {
 8148:             $ownaccess = 1;
 8149:         } else {
 8150:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8151:                 my $udom = $env{'user.domain'};
 8152:                 my $uname = $env{'user.name'};
 8153:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8154:                     $ownaccess = 1;
 8155:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8156:                     unless ($uri =~ m{\.\./}) {
 8157:                         $ownaccess = 1;
 8158:                     }
 8159:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8160:                     my $now = time;
 8161:                     if ($uri =~ m{^([^/]+)/?$}) {
 8162:                         my $adom = $1;
 8163:                         foreach my $key (keys(%env)) {
 8164:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8165:                                 my ($start,$end) = split('.',$env{$key});
 8166:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8167:                                     $ownaccess = 1;
 8168:                                     last;
 8169:                                 }
 8170:                             }
 8171:                         }
 8172:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8173:                         my $adom = $1;
 8174:                         my $aname = $2;
 8175:                         foreach my $role ('ca','aa') { 
 8176:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8177:                                 my ($start,$end) =
 8178:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8179:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8180:                                     $ownaccess = 1;
 8181:                                     last;
 8182:                                 }
 8183:                             }
 8184:                         }
 8185:                     }
 8186:                 }
 8187:             }
 8188:         }
 8189:     }
 8190: 
 8191: # Course
 8192: 
 8193:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8194:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8195:             $thisallowed.=$1;
 8196:         }
 8197:     }
 8198: 
 8199: # Domain
 8200: 
 8201:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8202:        =~/\Q$priv\E\&([^\:]*)/) {
 8203:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8204:             $thisallowed.=$1;
 8205:         }
 8206:     }
 8207: 
 8208: # User who is not author or co-author might still be able to edit
 8209: # resource of an author in the domain (e.g., if Domain Coordinator).
 8210:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8211:         (&allowed('mdc',$env{'request.course.id'}))) {
 8212:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8213:             $thisallowed.=$1;
 8214:         }
 8215:     }
 8216: 
 8217: # Course: uri itself is a course
 8218:     my $courseuri=$uri;
 8219:     $courseuri=~s/\_(\d)/\/$1/;
 8220:     $courseuri=~s/^([^\/])/\/$1/;
 8221: 
 8222:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8223:        =~/\Q$priv\E\&([^\:]*)/) {
 8224:         if ($priv eq 'mip') {
 8225:             my $rem = $1;
 8226:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8227:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8228:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8229:                 if ($cdom ne '') {
 8230:                     my %passwdconf = &get_passwdconf($cdom);
 8231:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8232:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8233:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8234:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8235:                                 unless (@inststatuses) {
 8236:                                     @inststatuses = ('default');
 8237:                                 }
 8238:                                 foreach my $status (@inststatuses) {
 8239:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8240:                                         $thisallowed.=$rem;
 8241:                                     }
 8242:                                 }
 8243:                             }
 8244:                         }
 8245:                     }
 8246:                 }
 8247:             }
 8248:         } else {
 8249:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8250:                 $thisallowed.=$1;
 8251:             }
 8252:         }
 8253:     }
 8254: 
 8255: # URI is an uploaded document for this course, default permissions don't matter
 8256: # not allowing 'edit' access (editupload) to uploaded course docs
 8257:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8258: 	$thisallowed='';
 8259:         my ($match)=&is_on_map($uri);
 8260:         if ($match) {
 8261:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8262:                   =~/\Q$priv\E\&([^\:]*)/) {
 8263:                 my $value = $1;
 8264:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8265:                 if ($deeplinkblock) {
 8266:                     $thisallowed='D';
 8267:                 } elsif ($noblockcheck) {
 8268:                     $thisallowed.=$value;
 8269:                 } else {
 8270:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8271:                     if (@blockers > 0) {
 8272:                         $thisallowed = 'B';
 8273:                     } else {
 8274:                         $thisallowed.=$value;
 8275:                     }
 8276:                 }
 8277:             }
 8278:         } else {
 8279:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8280:             if ($refuri) {
 8281:                 if ($refuri =~ m|^/adm/|) {
 8282:                     $thisallowed='F';
 8283:                 } else {
 8284:                     $refuri=&declutter($refuri);
 8285:                     my ($match) = &is_on_map($refuri);
 8286:                     if ($match) {
 8287:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8288:                         if ($deeplinkblock) {
 8289:                             $thisallowed='D';
 8290:                         } elsif ($noblockcheck) {
 8291:                             $thisallowed='F';
 8292:                         } else {
 8293:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8294:                             if (@blockers > 0) {
 8295:                                 $thisallowed = 'B';
 8296:                             } else {
 8297:                                 $thisallowed='F';
 8298:                             }
 8299:                         }
 8300:                     }
 8301:                 }
 8302:             }
 8303:         }
 8304:     }
 8305: 
 8306:     if ($priv eq 'bre'
 8307: 	&& $thisallowed ne 'F' 
 8308: 	&& $thisallowed ne '2'
 8309: 	&& &is_portfolio_url($uri)) {
 8310: 	$thisallowed = &portfolio_access($uri,$clientip);
 8311:     }
 8312: 
 8313: # Full access at system, domain or course-wide level? Exit.
 8314:     if ($thisallowed=~/F/) {
 8315: 	return 'F';
 8316:     }
 8317: 
 8318: # If this is generating or modifying users, exit with special codes
 8319: 
 8320:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8321: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8322: 	    my ($audom,$auname)=split('/',$uri);
 8323: # no author name given, so this just checks on the general right to make a co-author in this domain
 8324: 	    unless ($auname) { return $thisallowed; }
 8325: # an author name is given, so we are about to actually make a co-author for a certain account
 8326: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8327: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8328: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8329: 	}
 8330: 	return $thisallowed;
 8331:     }
 8332: #
 8333: # Gathered so far: system, domain and course wide privileges
 8334: #
 8335: # Course: See if uri or referer is an individual resource that is part of 
 8336: # the course
 8337: 
 8338:     if ($env{'request.course.id'}) {
 8339: 
 8340: # If this is modifying password (internal auth) domains must match for user and user's role.
 8341: 
 8342:         if ($priv eq 'mip') {
 8343:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8344:                 return $thisallowed;
 8345:             } else {
 8346:                 return '';
 8347:             }
 8348:         }
 8349: 
 8350:        $courseprivid=$env{'request.course.id'};
 8351:        if ($env{'request.course.sec'}) {
 8352:           $courseprivid.='/'.$env{'request.course.sec'};
 8353:        }
 8354:        $courseprivid=~s/\_/\//;
 8355:        my $checkreferer=1;
 8356:        my ($match,$cond)=&is_on_map($uri);
 8357:        if ($match) {
 8358:            $statecond=$cond;
 8359:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8360:                =~/\Q$priv\E\&([^\:]*)/) {
 8361:                my $value = $1;
 8362:                if ($priv eq 'bre') {
 8363:                    if ($noblockcheck) {
 8364:                        $thisallowed.=$value;
 8365:                    } else {
 8366:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8367:                        if (@blockers > 0) {
 8368:                            $thisallowed = 'B';
 8369:                        } else {
 8370:                            $thisallowed.=$value;
 8371:                        }
 8372:                    }
 8373:                } else {
 8374:                    $thisallowed.=$value;
 8375:                }
 8376:                $checkreferer=0;
 8377:            }
 8378:        }
 8379:        
 8380:        if ($checkreferer) {
 8381: 	  my $refuri=$env{'httpref.'.$orguri};
 8382:             unless ($refuri) {
 8383:                 foreach my $key (keys(%env)) {
 8384: 		    if ($key=~/^httpref\..*\*/) {
 8385: 			my $pattern=$key;
 8386:                         $pattern=~s/^httpref\.\/res\///;
 8387:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8388:                         $pattern=~s/\//\\\//g;
 8389:                         if ($orguri=~/$pattern/) {
 8390: 			    $refuri=$env{$key};
 8391:                         }
 8392:                     }
 8393:                 }
 8394:             }
 8395: 
 8396:          if ($refuri) { 
 8397: 	  $refuri=&declutter($refuri);
 8398:           my ($match,$cond)=&is_on_map($refuri);
 8399:             if ($match) {
 8400:               my $refstatecond=$cond;
 8401:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8402:                   =~/\Q$priv\E\&([^\:]*)/) {
 8403:                   my $value = $1;
 8404:                   if ($priv eq 'bre') {
 8405:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8406:                       if ($deeplinkblock) {
 8407:                           $thisallowed = 'D';
 8408:                       } elsif ($noblockcheck) {
 8409:                           $thisallowed.=$value;
 8410:                       } else {
 8411:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8412:                           if (@blockers > 0) {
 8413:                               $thisallowed = 'B';
 8414:                           } else {
 8415:                               $thisallowed.=$value;
 8416:                           }
 8417:                       }
 8418:                   } else {
 8419:                       $thisallowed.=$value;
 8420:                   }
 8421:                   $uri=$refuri;
 8422:                   $statecond=$refstatecond;
 8423:               }
 8424:           }
 8425:         }
 8426:        }
 8427:    }
 8428: 
 8429: #
 8430: # Gathered now: all privileges that could apply, and condition number
 8431: # 
 8432: #
 8433: # Full or no access?
 8434: #
 8435: 
 8436:     if ($thisallowed=~/F/) {
 8437: 	return 'F';
 8438:     }
 8439: 
 8440:     unless ($thisallowed) {
 8441:         return '';
 8442:     }
 8443: 
 8444: # Restrictions exist, deal with them
 8445: #
 8446: #   C:according to course preferences
 8447: #   R:according to resource settings
 8448: #   L:unless locked
 8449: #   X:according to user session state
 8450: #
 8451: 
 8452: # Possibly locked functionality, check all courses
 8453: # Locks might take effect only after 10 minutes cache expiration for other
 8454: # courses, and 2 minutes for current course
 8455: 
 8456:     my $envkey;
 8457:     if ($thisallowed=~/L/) {
 8458:         foreach $envkey (keys(%env)) {
 8459:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8460:                my $courseid=$2;
 8461:                my $roleid=$1.'.'.$2;
 8462:                $courseid=~s/^\///;
 8463:                my $expiretime=600;
 8464:                if ($env{'request.role'} eq $roleid) {
 8465: 		  $expiretime=120;
 8466:                }
 8467: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8468:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8469:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8470: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8471:                }
 8472:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8473:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8474: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8475:                        &log($env{'user.domain'},$env{'user.name'},
 8476:                             $env{'user.home'},
 8477:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8478:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8479:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8480: 		       return '';
 8481:                    }
 8482:                }
 8483:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8484:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8485: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8486:                        &log($env{'user.domain'},$env{'user.name'},
 8487:                             $env{'user.home'},
 8488:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8489:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8490:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8491: 		       return '';
 8492:                    }
 8493:                }
 8494: 	   }
 8495:        }
 8496:     }
 8497:    
 8498: #
 8499: # Rest of the restrictions depend on selected course
 8500: #
 8501: 
 8502:     unless ($env{'request.course.id'}) {
 8503: 	if ($thisallowed eq 'A') {
 8504: 	    return 'A';
 8505:         } elsif ($thisallowed eq 'B') {
 8506:             return 'B';
 8507: 	} else {
 8508: 	    return '1';
 8509: 	}
 8510:     }
 8511: 
 8512: #
 8513: # Now user is definitely in a course
 8514: #
 8515: 
 8516: 
 8517: # Course preferences
 8518: 
 8519:    if ($thisallowed=~/C/) {
 8520:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8521:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8522:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8523: 	   =~/\Q$rolecode\E/) {
 8524: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8525: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8526: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8527: 			$env{'request.course.id'});
 8528: 	   }
 8529:            return '';
 8530:        }
 8531: 
 8532:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8533: 	   =~/\Q$unamedom\E/) {
 8534: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8535: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8536: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8537: 			$env{'request.course.id'});
 8538: 	   }
 8539:            return '';
 8540:        }
 8541:    }
 8542: 
 8543: # Resource preferences
 8544: 
 8545:    if ($thisallowed=~/R/) {
 8546:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8547:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8548: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8549: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8550: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8551: 	   }
 8552: 	   return '';
 8553:        }
 8554:    }
 8555: 
 8556: # Restricted by state or randomout?
 8557: 
 8558:    if ($thisallowed=~/X/) {
 8559:       if ($env{'acc.randomout'}) {
 8560: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8561:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8562:             return ''; 
 8563:          }
 8564:       }
 8565:       if (&condval($statecond)) {
 8566: 	 return '2';
 8567:       } else {
 8568:          return '';
 8569:       }
 8570:    }
 8571: 
 8572:     if ($thisallowed eq 'A') {
 8573: 	return 'A';
 8574:     } elsif ($thisallowed eq 'B') {
 8575:         return 'B';
 8576:     } elsif ($thisallowed eq 'D') {
 8577:         return 'D';
 8578:     }
 8579:    return 'F';
 8580: }
 8581: 
 8582: # ------------------------------------------- Check construction space access
 8583: 
 8584: sub constructaccess {
 8585:     my ($url,$setpriv)=@_;
 8586: 
 8587: # We do not allow editing of previous versions of files
 8588:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8589: 
 8590: # Get username and domain from URL
 8591:     my ($ownername,$ownerdomain,$ownerhome);
 8592: 
 8593:     ($ownerdomain,$ownername) =
 8594:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8595: 
 8596: # The URL does not really point to any authorspace, forget it
 8597:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8598: 
 8599: # Now we need to see if the user has access to the authorspace of
 8600: # $ownername at $ownerdomain
 8601: 
 8602:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8603: # Real author for this?
 8604:        $ownerhome = $env{'user.home'};
 8605:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8606:           return ($ownername,$ownerdomain,$ownerhome);
 8607:        }
 8608:     } else {
 8609: # Co-author for this?
 8610:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8611:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8612:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8613:             return ($ownername,$ownerdomain,$ownerhome);
 8614:         }
 8615:         if ($env{'request.course.id'}) {
 8616:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8617:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8618:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8619:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8620:                     return ($ownername,$ownerdomain,$ownerhome);
 8621:                 }
 8622:             }
 8623:         }
 8624:     }
 8625: 
 8626: # We don't have any access right now. If we are not possibly going to do anything about this,
 8627: # we might as well leave
 8628:    unless ($setpriv) { return ''; }
 8629: 
 8630: # Backdoor access?
 8631:     my $allowed=&allowed('eco',$ownerdomain);
 8632: # Nope
 8633:     unless ($allowed) { return ''; }
 8634: # Looks like we may have access, but could be locked by the owner of the construction space
 8635:     if ($allowed eq 'U') {
 8636:         my %blocked=&get('environment',['domcoord.author'],
 8637:                          $ownerdomain,$ownername);
 8638: # Is blocked by owner
 8639:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8640:     }
 8641:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8642: # Grant temporary access
 8643:         my $then=$env{'user.login.time'};
 8644:         my $update=$env{'user.update.time'};
 8645:         if (!$update) { $update = $then; }
 8646:         my $refresh=$env{'user.refresh.time'};
 8647:         if (!$refresh) { $refresh = $update; }
 8648:         my $now = time;
 8649:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8650:                            $now,'ca','constructaccess');
 8651:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8652:         return($ownername,$ownerdomain,$ownerhome);
 8653:     }
 8654: # No business here
 8655:     return '';
 8656: }
 8657: 
 8658: # ----------------------------------------------------------- Content Blocking
 8659: 
 8660: {
 8661: # Caches for faster Course Contents display where content blocking
 8662: # is in operation (i.e., interval param set) for timed quiz.
 8663: #
 8664: # User for whom data are being temporarily cached.
 8665: my $cacheduser='';
 8666: # Cached blockers for this user (a hash of blocking items). 
 8667: my %cachedblockers=();
 8668: # When the data were last cached.
 8669: my $cachedlast='';
 8670: 
 8671: sub load_all_blockers {
 8672:     my ($uname,$udom,$blocks)=@_;
 8673:     if (($uname ne '') && ($udom ne '')) { 
 8674:         if (($cacheduser eq $uname.':'.$udom) &&
 8675:             (abs($cachedlast-time)<5)) {
 8676:             return;
 8677:         }
 8678:     }
 8679:     $cachedlast=time;
 8680:     $cacheduser=$uname.':'.$udom;
 8681:     %cachedblockers = &get_commblock_resources($blocks);
 8682: }
 8683: 
 8684: sub get_comm_blocks {
 8685:     my ($cdom,$cnum) = @_;
 8686:     if ($cdom eq '' || $cnum eq '') {
 8687:         return unless ($env{'request.course.id'});
 8688:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8689:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8690:     }
 8691:     my %commblocks;
 8692:     my $hashid=$cdom.'_'.$cnum;
 8693:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8694:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8695:         %commblocks = %{$blocksref};
 8696:     } else {
 8697:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8698:         my $cachetime = 600;
 8699:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8700:     }
 8701:     return %commblocks;
 8702: }
 8703: 
 8704: sub get_commblock_resources {
 8705:     my ($blocks) = @_;
 8706:     my %blockers = ();
 8707:     return %blockers unless ($env{'request.course.id'});
 8708:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8709:     my %commblocks;
 8710:     if (ref($blocks) eq 'HASH') {
 8711:         %commblocks = %{$blocks};
 8712:     } else {
 8713:         %commblocks = &get_comm_blocks();
 8714:     }
 8715:     return %blockers unless (keys(%commblocks) > 0); 
 8716:     my $navmap = Apache::lonnavmaps::navmap->new();
 8717:     return %blockers unless (ref($navmap));
 8718:     my $now = time;
 8719:     foreach my $block (keys(%commblocks)) {
 8720:         if ($block =~ /^(\d+)____(\d+)$/) {
 8721:             my ($start,$end) = ($1,$2);
 8722:             if ($start <= $now && $end >= $now) {
 8723:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8724:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8725:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8726:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8727:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8728:                             }
 8729:                         }
 8730:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8731:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8732:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8733:                             }
 8734:                         }
 8735:                     }
 8736:                 }
 8737:             }
 8738:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8739:             my $item = $1;
 8740:             my @to_test;
 8741:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8742:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8743:                     my @interval;
 8744:                     my $type = 'map';
 8745:                     if ($item eq 'course') {
 8746:                         $type = 'course';
 8747:                         @interval=&EXT("resource.0.interval");
 8748:                     } else {
 8749:                         if ($item =~ /___\d+___/) {
 8750:                             $type = 'resource';
 8751:                             @interval=&EXT("resource.0.interval",$item);
 8752:                             if (ref($navmap)) {                        
 8753:                                 my $res = $navmap->getBySymb($item); 
 8754:                                 push(@to_test,$res);
 8755:                             }
 8756:                         } else {
 8757:                             my $mapsymb = &symbread($item,1);
 8758:                             if ($mapsymb) {
 8759:                                 if (ref($navmap)) {
 8760:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8761:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8762:                                     foreach my $res (@to_test) {
 8763:                                         my $symb = $res->symb();
 8764:                                         next if ($symb eq $mapsymb);
 8765:                                         if ($symb ne '') {
 8766:                                             @interval=&EXT("resource.0.interval",$symb);
 8767:                                             if ($interval[1] eq 'map') {
 8768:                                                 last;
 8769:                                             }
 8770:                                         }
 8771:                                     }
 8772:                                 }
 8773:                             }
 8774:                         }
 8775:                     }
 8776:                     if ($interval[0] =~ /^(\d+)/) {
 8777:                         my $timelimit = $1; 
 8778:                         my $first_access;
 8779:                         if ($type eq 'resource') {
 8780:                             $first_access=&get_first_access($interval[1],$item);
 8781:                         } elsif ($type eq 'map') {
 8782:                             $first_access=&get_first_access($interval[1],undef,$item);
 8783:                         } else {
 8784:                             $first_access=&get_first_access($interval[1]);
 8785:                         }
 8786:                         if ($first_access) {
 8787:                             my $timesup = $first_access+$timelimit;
 8788:                             if ($timesup > $now) {
 8789:                                 my $activeblock;
 8790:                                 foreach my $res (@to_test) {
 8791:                                     if ($res->answerable()) {
 8792:                                         $activeblock = 1;
 8793:                                         last;
 8794:                                     }
 8795:                                 }
 8796:                                 if ($activeblock) {
 8797:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8798:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8799:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8800:                                          }
 8801:                                     }
 8802:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8803:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8804:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8805:                                         }
 8806:                                     }
 8807:                                 }
 8808:                             }
 8809:                         }
 8810:                     }
 8811:                 }
 8812:             }
 8813:         }
 8814:     }
 8815:     return %blockers;
 8816: }
 8817: 
 8818: sub has_comm_blocking {
 8819:     my ($priv,$symb,$uri,$blocks) = @_;
 8820:     my @blockers;
 8821:     return unless ($env{'request.course.id'});
 8822:     return unless ($priv eq 'bre');
 8823:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8824:     return if ($env{'request.state'} eq 'construct');
 8825:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8826:     return unless (keys(%cachedblockers) > 0);
 8827:     my (%possibles,@symbs);
 8828:     if (!$symb) {
 8829:         $symb = &symbread($uri,1,1,1,\%possibles);
 8830:     }
 8831:     if ($symb) {
 8832:         @symbs = ($symb);
 8833:     } elsif (keys(%possibles)) { 
 8834:         @symbs = keys(%possibles);
 8835:     }
 8836:     my $noblock;
 8837:     foreach my $symb (@symbs) {
 8838:         last if ($noblock);
 8839:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8840:         foreach my $block (keys(%cachedblockers)) {
 8841:             if ($block =~ /^firstaccess____(.+)$/) {
 8842:                 my $item = $1;
 8843:                 if (($item eq $map) || ($item eq $symb)) {
 8844:                     $noblock = 1;
 8845:                     last;
 8846:                 }
 8847:             }
 8848:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8849:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8850:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8851:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8852:                             push(@blockers,$block);
 8853:                         }
 8854:                     }
 8855:                 }
 8856:             }
 8857:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8858:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8859:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8860:                         push(@blockers,$block);
 8861:                     }
 8862:                 }
 8863:             }
 8864:         }
 8865:     }
 8866:     return if ($noblock);
 8867:     return @blockers;
 8868: }
 8869: }
 8870: 
 8871: sub deeplink_check {
 8872:     my ($priv,$symb,$uri) = @_;
 8873:     return unless ($env{'request.course.id'});
 8874:     return unless ($priv eq 'bre');
 8875:     return if ($env{'request.state'} eq 'construct');
 8876:     return if ($env{'request.role.adv'});
 8877:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8878:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8879:     my (%possibles,@symbs);
 8880:     if (!$symb) {
 8881:         $symb = &symbread($uri,1,1,1,\%possibles);
 8882:     }
 8883:     if ($symb) {
 8884:         @symbs = ($symb);
 8885:     } elsif (keys(%possibles)) {
 8886:         @symbs = keys(%possibles);
 8887:     }
 8888: 
 8889:     my ($login,$switchrole,$allow);
 8890:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8891:         my $key = $1;
 8892:         my $tinyurl;
 8893:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8894:         if (defined($cached)) {
 8895:              $tinyurl = $result;
 8896:         } else {
 8897:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8898:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8899:              if ($currtiny{$key} ne '') {
 8900:                  $tinyurl = $currtiny{$key};
 8901:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8902:              }
 8903:         }
 8904:         if ($tinyurl ne '') {
 8905:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8906:             if ($cnumreq eq $cnum) {
 8907:                 $login = $posslogin;
 8908:             } else {
 8909:                 $switchrole = 1;
 8910:             }
 8911:         }
 8912:     }
 8913:     foreach my $symb (@symbs) {
 8914:         last if ($allow);
 8915:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8916:         if ($deeplink eq '') {
 8917:             $allow = 1;
 8918:         } else {
 8919:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8920:             if ($access eq 'any') {
 8921:                 $allow = 1;
 8922:             } elsif ($login) {
 8923:                 if ($access eq 'only') {
 8924:                     if ($scope eq 'res') {
 8925:                         if ($symb eq $login) {
 8926:                             $allow = 1;
 8927:                         }
 8928:                     } elsif ($scope eq 'map') {
 8929: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 8930:                     } elsif ($scope eq 'rec') {
 8931: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 8932:                     }
 8933:                 } else {
 8934:                     my ($acctype,$item) = split(/:/,$access);
 8935:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 8936:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 8937:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8938:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 8939:                                 $allow = 1;
 8940:                             }
 8941:                         }
 8942:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 8943:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 8944:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 8945:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 8946:                                 $allow = 1;
 8947:                             }
 8948:                         }
 8949:                     }
 8950:                 }
 8951:             }
 8952:         }
 8953:     }
 8954:     return if ($allow);
 8955:     return 1;
 8956: }
 8957: 
 8958: # -------------------------------- Deversion and split uri into path an filename   
 8959: 
 8960: #
 8961: #   Removes the version from a URI and
 8962: #   splits it in to its filename and path to the filename.
 8963: #   Seems like File::Basename could have done this more clearly.
 8964: #   Parameters:
 8965: #      $uri   - input URI
 8966: #   Returns:
 8967: #     Two element list consisting of 
 8968: #     $pathname  - the URI up to and excluding the trailing /
 8969: #     $filename  - The part of the URI following the last /
 8970: #  NOTE:
 8971: #    Another realization of this is simply:
 8972: #    use File::Basename;
 8973: #    ...
 8974: #    $uri = shift;
 8975: #    $filename = basename($uri);
 8976: #    $path     = dirname($uri);
 8977: #    return ($filename, $path);
 8978: #
 8979: #     The implementation below is probably faster however.
 8980: #
 8981: sub split_uri_for_cond {
 8982:     my $uri=&deversion(&declutter(shift));
 8983:     my @uriparts=split(/\//,$uri);
 8984:     my $filename=pop(@uriparts);
 8985:     my $pathname=join('/',@uriparts);
 8986:     return ($pathname,$filename);
 8987: }
 8988: # --------------------------------------------------- Is a resource on the map?
 8989: 
 8990: sub is_on_map {
 8991:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8992:     #Trying to find the conditional for the file
 8993:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8994: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8995:     if ($match) {
 8996: 	return (1,$1);
 8997:     } else {
 8998: 	return (0,0);
 8999:     }
 9000: }
 9001: 
 9002: # --------------------------------------------------------- Get symb from alias
 9003: 
 9004: sub get_symb_from_alias {
 9005:     my $symb=shift;
 9006:     my ($map,$resid,$url)=&decode_symb($symb);
 9007: # Already is a symb
 9008:     if ($url) { return $symb; }
 9009: # Must be an alias
 9010:     my $aliassymb='';
 9011:     my %bighash;
 9012:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9013:                             &GDBM_READER(),0640)) {
 9014:         my $rid=$bighash{'mapalias_'.$symb};
 9015: 	if ($rid) {
 9016: 	    my ($mapid,$resid)=split(/\./,$rid);
 9017: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9018: 				    $resid,$bighash{'src_'.$rid});
 9019: 	}
 9020:         untie %bighash;
 9021:     }
 9022:     return $aliassymb;
 9023: }
 9024: 
 9025: # ----------------------------------------------------------------- Define Role
 9026: 
 9027: sub definerole {
 9028:   if (allowed('mcr','/')) {
 9029:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9030:     foreach my $role (split(':',$sysrole)) {
 9031: 	my ($crole,$cqual)=split(/\&/,$role);
 9032:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9033:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9034: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9035:                return "refused:s:$crole&$cqual"; 
 9036:             }
 9037:         }
 9038:     }
 9039:     foreach my $role (split(':',$domrole)) {
 9040: 	my ($crole,$cqual)=split(/\&/,$role);
 9041:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9042:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9043: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9044:                return "refused:d:$crole&$cqual"; 
 9045:             }
 9046:         }
 9047:     }
 9048:     foreach my $role (split(':',$courole)) {
 9049: 	my ($crole,$cqual)=split(/\&/,$role);
 9050:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9051:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9052: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9053:                return "refused:c:$crole&$cqual"; 
 9054:             }
 9055:         }
 9056:     }
 9057:     my $uhome;
 9058:     if (($uname ne '') && ($udom ne '')) {
 9059:         $uhome = &homeserver($uname,$udom);
 9060:         return $uhome if ($uhome eq 'no_host');
 9061:     } else {
 9062:         $uname = $env{'user.name'};
 9063:         $udom = $env{'user.domain'};
 9064:         $uhome = $env{'user.home'};
 9065:     }
 9066:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9067:                 "$udom:$uname:rolesdef_$rolename=".
 9068:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9069:     return reply($command,$uhome);
 9070:   } else {
 9071:     return 'refused';
 9072:   }
 9073: }
 9074: 
 9075: # ---------------- Make a metadata query against the network of library servers
 9076: 
 9077: sub metadata_query {
 9078:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9079:     my %rhash;
 9080:     my %libserv = &all_library();
 9081:     my @server_list = (defined($server_array) ? @$server_array
 9082:                                               : keys(%libserv) );
 9083:     for my $server (@server_list) {
 9084:         my $domains = ''; 
 9085:         if (ref($domains_hash) eq 'HASH') {
 9086:             $domains = $domains_hash->{$server}; 
 9087:         }
 9088: 	unless ($custom or $customshow) {
 9089: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9090: 	    $rhash{$server}=$reply;
 9091: 	}
 9092: 	else {
 9093: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9094: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9095: 			     $server);
 9096: 	    $rhash{$server}=$reply;
 9097: 	}
 9098:     }
 9099:     return \%rhash;
 9100: }
 9101: 
 9102: # ----------------------------------------- Send log queries and wait for reply
 9103: 
 9104: sub log_query {
 9105:     my ($uname,$udom,$query,%filters)=@_;
 9106:     my $uhome=&homeserver($uname,$udom);
 9107:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9108:     my $uhost=&hostname($uhome);
 9109:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9110:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9111:                        $uhome);
 9112:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9113:     return get_query_reply($queryid);
 9114: }
 9115: 
 9116: # -------------------------- Update MySQL table for portfolio file
 9117: 
 9118: sub update_portfolio_table {
 9119:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9120:     if ($group ne '') {
 9121:         $file_name =~s /^\Q$group\E//;
 9122:     }
 9123:     my $homeserver = &homeserver($uname,$udom);
 9124:     my $queryid=
 9125:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9126:                ':'.&escape($file_name).':'.$action,$homeserver);
 9127:     my $reply = &get_query_reply($queryid);
 9128:     return $reply;
 9129: }
 9130: 
 9131: # -------------------------- Update MySQL allusers table
 9132: 
 9133: sub update_allusers_table {
 9134:     my ($uname,$udom,$names) = @_;
 9135:     my $homeserver = &homeserver($uname,$udom);
 9136:     my $queryid=
 9137:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9138:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9139:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9140:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9141:                'generation='.&escape($names->{'generation'}).'%%'.
 9142:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9143:                'id='.&escape($names->{'id'}),$homeserver);
 9144:     return;
 9145: }
 9146: 
 9147: # ------- Request retrieval of institutional classlists for course(s)
 9148: 
 9149: sub fetch_enrollment_query {
 9150:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9151:     my ($homeserver,$sleep,$loopmax);
 9152:     my $maxtries = 1;
 9153:     if ($context eq 'automated') {
 9154:         $homeserver = $perlvar{'lonHostID'};
 9155:         $sleep = 2;
 9156:         $loopmax = 100;
 9157:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9158:     } else {
 9159:         $homeserver = &homeserver($cnum,$dom);
 9160:     }
 9161:     my $host=&hostname($homeserver);
 9162:     my $cmd = '';
 9163:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9164:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9165:     }
 9166:     $cmd =~ s/%%$//;
 9167:     $cmd = &escape($cmd);
 9168:     my $query = 'fetchenrollment';
 9169:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9170:     unless ($queryid=~/^\Q$host\E\_/) { 
 9171:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9172:         return 'error: '.$queryid;
 9173:     }
 9174:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9175:     my $tries = 1;
 9176:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9177:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9178:         $tries ++;
 9179:     }
 9180:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9181:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9182:     } else {
 9183:         my @responses = split(/:/,$reply);
 9184:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9185:             foreach my $line (@responses) {
 9186:                 my ($key,$value) = split(/=/,$line,2);
 9187:                 $$replyref{$key} = $value;
 9188:             }
 9189:         } else {
 9190:             my $pathname = LONCAPA::tempdir();
 9191:             foreach my $line (@responses) {
 9192:                 my ($key,$value) = split(/=/,$line);
 9193:                 $$replyref{$key} = $value;
 9194:                 if ($value > 0) {
 9195:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9196:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9197:                         my $destname = $pathname.'/'.$filename;
 9198:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9199:                         if ($xml_classlist =~ /^error/) {
 9200:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9201:                         } else {
 9202:                             if ( open(FILE,">",$destname) ) {
 9203:                                 print FILE &unescape($xml_classlist);
 9204:                                 close(FILE);
 9205:                             } else {
 9206:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9207:                             }
 9208:                         }
 9209:                     }
 9210:                 }
 9211:             }
 9212:         }
 9213:         return 'ok';
 9214:     }
 9215:     return 'error';
 9216: }
 9217: 
 9218: sub get_query_reply {
 9219:     my ($queryid,$sleep,$loopmax) = @_;;
 9220:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9221:         $sleep = 0.2;
 9222:     }
 9223:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9224:         $loopmax = 100;
 9225:     }
 9226:     my $replyfile=LONCAPA::tempdir().$queryid;
 9227:     my $reply='';
 9228:     for (1..$loopmax) {
 9229: 	sleep($sleep);
 9230:         if (-e $replyfile.'.end') {
 9231: 	    if (open(my $fh,"<",$replyfile)) {
 9232: 		$reply = join('',<$fh>);
 9233: 		close($fh);
 9234: 	   } else { return 'error: reply_file_error'; }
 9235:            return &unescape($reply);
 9236: 	}
 9237:     }
 9238:     return 'timeout:'.$queryid;
 9239: }
 9240: 
 9241: sub courselog_query {
 9242: #
 9243: # possible filters:
 9244: # url: url or symb
 9245: # username
 9246: # domain
 9247: # action: view, submit, grade
 9248: # start: timestamp
 9249: # end: timestamp
 9250: #
 9251:     my (%filters)=@_;
 9252:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9253:     if ($filters{'url'}) {
 9254: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9255:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9256:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9257:     }
 9258:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9259:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9260:     return &log_query($cname,$cdom,'courselog',%filters);
 9261: }
 9262: 
 9263: sub userlog_query {
 9264: #
 9265: # possible filters:
 9266: # action: log check role
 9267: # start: timestamp
 9268: # end: timestamp
 9269: #
 9270:     my ($uname,$udom,%filters)=@_;
 9271:     return &log_query($uname,$udom,'userlog',%filters);
 9272: }
 9273: 
 9274: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9275: 
 9276: sub auto_run {
 9277:     my ($cnum,$cdom) = @_;
 9278:     my $response = 0;
 9279:     my $settings;
 9280:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9281:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9282:         $settings = $domconfig{'autoenroll'};
 9283:         if ($settings->{'run'} eq '1') {
 9284:             $response = 1;
 9285:         }
 9286:     } else {
 9287:         my $homeserver;
 9288:         if (&is_course($cdom,$cnum)) {
 9289:             $homeserver = &homeserver($cnum,$cdom);
 9290:         } else {
 9291:             $homeserver = &domain($cdom,'primary');
 9292:         }
 9293:         if ($homeserver ne 'no_host') {
 9294:             $response = &reply('autorun:'.$cdom,$homeserver);
 9295:         }
 9296:     }
 9297:     return $response;
 9298: }
 9299: 
 9300: sub auto_get_sections {
 9301:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9302:     my $homeserver;
 9303:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9304:         $homeserver = &homeserver($cnum,$cdom);
 9305:     }
 9306:     if (!defined($homeserver)) { 
 9307:         if ($cdom =~ /^$match_domain$/) {
 9308:             $homeserver = &domain($cdom,'primary');
 9309:         }
 9310:     }
 9311:     my @secs;
 9312:     if (defined($homeserver)) {
 9313:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9314:         unless ($response eq 'refused') {
 9315:             @secs = split(/:/,$response);
 9316:         }
 9317:     }
 9318:     return @secs;
 9319: }
 9320: 
 9321: sub auto_new_course {
 9322:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9323:     my $homeserver = &homeserver($cnum,$cdom);
 9324:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9325:     return $response;
 9326: }
 9327: 
 9328: sub auto_validate_courseID {
 9329:     my ($cnum,$cdom,$inst_course_id) = @_;
 9330:     my $homeserver = &homeserver($cnum,$cdom);
 9331:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9332:     return $response;
 9333: }
 9334: 
 9335: sub auto_validate_instcode {
 9336:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9337:     my ($homeserver,$response);
 9338:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9339:         $homeserver = &homeserver($cnum,$cdom);
 9340:     }
 9341:     if (!defined($homeserver)) {
 9342:         if ($cdom =~ /^$match_domain$/) {
 9343:             $homeserver = &domain($cdom,'primary');
 9344:         }
 9345:     }
 9346:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9347:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9348:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9349:     return ($outcome,$description,$defaultcredits);
 9350: }
 9351: 
 9352: sub auto_create_password {
 9353:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9354:     my ($homeserver,$response);
 9355:     my $create_passwd = 0;
 9356:     my $authchk = '';
 9357:     if ($udom =~ /^$match_domain$/) {
 9358:         $homeserver = &domain($udom,'primary');
 9359:     }
 9360:     if ($homeserver eq '') {
 9361:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9362:             $homeserver = &homeserver($cnum,$cdom);
 9363:         }
 9364:     }
 9365:     if ($homeserver eq '') {
 9366:         $authchk = 'nodomain';
 9367:     } else {
 9368:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9369:         if ($response eq 'refused') {
 9370:             $authchk = 'refused';
 9371:         } else {
 9372:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9373:         }
 9374:     }
 9375:     return ($authparam,$create_passwd,$authchk);
 9376: }
 9377: 
 9378: sub auto_photo_permission {
 9379:     my ($cnum,$cdom,$students) = @_;
 9380:     my $homeserver = &homeserver($cnum,$cdom);
 9381:     my ($outcome,$perm_reqd,$conditions) = 
 9382: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9383:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9384: 	return (undef,undef);
 9385:     }
 9386:     return ($outcome,$perm_reqd,$conditions);
 9387: }
 9388: 
 9389: sub auto_checkphotos {
 9390:     my ($uname,$udom,$pid) = @_;
 9391:     my $homeserver = &homeserver($uname,$udom);
 9392:     my ($result,$resulttype);
 9393:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9394: 				   &escape($uname).':'.&escape($pid),
 9395: 				   $homeserver));
 9396:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9397: 	return (undef,undef);
 9398:     }
 9399:     if ($outcome) {
 9400:         ($result,$resulttype) = split(/:/,$outcome);
 9401:     } 
 9402:     return ($result,$resulttype);
 9403: }
 9404: 
 9405: sub auto_photochoice {
 9406:     my ($cnum,$cdom) = @_;
 9407:     my $homeserver = &homeserver($cnum,$cdom);
 9408:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9409: 						       &escape($cdom),
 9410: 						       $homeserver)));
 9411:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9412: 	return (undef,undef);
 9413:     }
 9414:     return ($update,$comment);
 9415: }
 9416: 
 9417: sub auto_photoupdate {
 9418:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9419:     my $homeserver = &homeserver($cnum,$dom);
 9420:     my $host=&hostname($homeserver);
 9421:     my $cmd = '';
 9422:     my $maxtries = 1;
 9423:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9424:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9425:     }
 9426:     $cmd =~ s/%%$//;
 9427:     $cmd = &escape($cmd);
 9428:     my $query = 'institutionalphotos';
 9429:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9430:     unless ($queryid=~/^\Q$host\E\_/) {
 9431:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9432:         return 'error: '.$queryid;
 9433:     }
 9434:     my $reply = &get_query_reply($queryid);
 9435:     my $tries = 1;
 9436:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9437:         $reply = &get_query_reply($queryid);
 9438:         $tries ++;
 9439:     }
 9440:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9441:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9442:     } else {
 9443:         my @responses = split(/:/,$reply);
 9444:         my $outcome = shift(@responses); 
 9445:         foreach my $item (@responses) {
 9446:             my ($key,$value) = split(/=/,$item);
 9447:             $$photo{$key} = $value;
 9448:         }
 9449:         return $outcome;
 9450:     }
 9451:     return 'error';
 9452: }
 9453: 
 9454: sub auto_instcode_format {
 9455:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9456: 	$cat_order) = @_;
 9457:     my $courses = '';
 9458:     my @homeservers;
 9459:     if ($caller eq 'global') {
 9460: 	my %servers = &get_servers($codedom,'library');
 9461: 	foreach my $tryserver (keys(%servers)) {
 9462: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9463: 		push(@homeservers,$tryserver);
 9464: 	    }
 9465:         }
 9466:     } elsif ($caller eq 'requests') {
 9467:         if ($codedom =~ /^$match_domain$/) {
 9468:             my $chome = &domain($codedom,'primary');
 9469:             unless ($chome eq 'no_host') {
 9470:                 push(@homeservers,$chome);
 9471:             }
 9472:         }
 9473:     } else {
 9474:         push(@homeservers,&homeserver($caller,$codedom));
 9475:     }
 9476:     foreach my $code (keys(%{$instcodes})) {
 9477:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9478:     }
 9479:     chop($courses);
 9480:     my $ok_response = 0;
 9481:     my $response;
 9482:     while (@homeservers > 0 && $ok_response == 0) {
 9483:         my $server = shift(@homeservers); 
 9484:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9485:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9486:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9487: 		split(/:/,$response);
 9488:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9489:             push(@{$codetitles},&str2array($codetitles_str));
 9490:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9491:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9492:             $ok_response = 1;
 9493:         }
 9494:     }
 9495:     if ($ok_response) {
 9496:         return 'ok';
 9497:     } else {
 9498:         return $response;
 9499:     }
 9500: }
 9501: 
 9502: sub auto_instcode_defaults {
 9503:     my ($domain,$returnhash,$code_order) = @_;
 9504:     my @homeservers;
 9505: 
 9506:     my %servers = &get_servers($domain,'library');
 9507:     foreach my $tryserver (keys(%servers)) {
 9508: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9509: 	    push(@homeservers,$tryserver);
 9510: 	}
 9511:     }
 9512: 
 9513:     my $response;
 9514:     foreach my $server (@homeservers) {
 9515:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9516:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9517: 	
 9518: 	foreach my $pair (split(/\&/,$response)) {
 9519: 	    my ($name,$value)=split(/\=/,$pair);
 9520: 	    if ($name eq 'code_order') {
 9521: 		@{$code_order} = split(/\&/,&unescape($value));
 9522: 	    } else {
 9523: 		$returnhash->{&unescape($name)}=&unescape($value);
 9524: 	    }
 9525: 	}
 9526: 	return 'ok';
 9527:     }
 9528: 
 9529:     return $response;
 9530: }
 9531: 
 9532: sub auto_possible_instcodes {
 9533:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9534:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9535:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9536:         return;
 9537:     }
 9538:     my (@homeservers,$uhome);
 9539:     if (defined(&domain($domain,'primary'))) {
 9540:         $uhome=&domain($domain,'primary');
 9541:         push(@homeservers,&domain($domain,'primary'));
 9542:     } else {
 9543:         my %servers = &get_servers($domain,'library');
 9544:         foreach my $tryserver (keys(%servers)) {
 9545:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9546:                 push(@homeservers,$tryserver);
 9547:             }
 9548:         }
 9549:     }
 9550:     my $response;
 9551:     foreach my $server (@homeservers) {
 9552:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9553:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9554:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9555:             split(':',$response);
 9556:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9557:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9558:         foreach my $item (split('&',$cat_title)) {   
 9559:             my ($name,$value)=split('=',$item);
 9560:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9561:         }
 9562:         foreach my $item (split('&',$cat_order)) {
 9563:             my ($name,$value)=split('=',$item);
 9564:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9565:         }
 9566:         return 'ok';
 9567:     }
 9568:     return $response;
 9569: }
 9570: 
 9571: sub auto_courserequest_checks {
 9572:     my ($dom) = @_;
 9573:     my ($homeserver,%validations);
 9574:     if ($dom =~ /^$match_domain$/) {
 9575:         $homeserver = &domain($dom,'primary');
 9576:     }
 9577:     unless ($homeserver eq 'no_host') {
 9578:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9579:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9580:             my @items = split(/&/,$response);
 9581:             foreach my $item (@items) {
 9582:                 my ($key,$value) = split('=',$item);
 9583:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9584:             }
 9585:         }
 9586:     }
 9587:     return %validations; 
 9588: }
 9589: 
 9590: sub auto_courserequest_validation {
 9591:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9592:     my ($homeserver,$response);
 9593:     if ($dom =~ /^$match_domain$/) {
 9594:         $homeserver = &domain($dom,'primary');
 9595:     }
 9596:     unless ($homeserver eq 'no_host') {
 9597:         my $customdata;
 9598:         if (ref($custominfo) eq 'HASH') {
 9599:             $customdata = &freeze_escape($custominfo);
 9600:         }
 9601:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9602:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9603:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9604:                                     $customdata,$homeserver));
 9605:     }
 9606:     return $response;
 9607: }
 9608: 
 9609: sub auto_validate_class_sec {
 9610:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9611:     my $homeserver = &homeserver($cnum,$cdom);
 9612:     my $ownerlist;
 9613:     if (ref($owners) eq 'ARRAY') {
 9614:         $ownerlist = join(',',@{$owners});
 9615:     } else {
 9616:         $ownerlist = $owners;
 9617:     }
 9618:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9619:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9620:     return $response;
 9621: }
 9622: 
 9623: sub auto_validate_instclasses {
 9624:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9625:     my ($homeserver,%validations);
 9626:     $homeserver = &homeserver($cnum,$cdom);
 9627:     unless ($homeserver eq 'no_host') {
 9628:         my $ownerlist;
 9629:         if (ref($owners) eq 'ARRAY') {
 9630:             $ownerlist = join(',',@{$owners});
 9631:         } else {
 9632:             $ownerlist = $owners;
 9633:         }
 9634:         if (ref($classesref) eq 'HASH') {
 9635:             my $classes = &freeze_escape($classesref);
 9636:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9637:                                 ':'.$cdom.':'.$classes,$homeserver);
 9638:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9639:                 my @items = split(/&/,$response);
 9640:                 foreach my $item (@items) {
 9641:                     my ($key,$value) = split('=',$item);
 9642:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9643:                 }
 9644:             }
 9645:         }
 9646:     }
 9647:     return %validations;
 9648: }
 9649: 
 9650: sub auto_crsreq_update {
 9651:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9652:         $code,$accessstart,$accessend,$inbound) = @_;
 9653:     my ($homeserver,%crsreqresponse);
 9654:     if ($cdom =~ /^$match_domain$/) {
 9655:         $homeserver = &domain($cdom,'primary');
 9656:     }
 9657:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9658:         my $info;
 9659:         if (ref($inbound) eq 'HASH') {
 9660:             $info = &freeze_escape($inbound);
 9661:         }
 9662:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9663:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9664:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9665:                             &escape($title).':'.&escape($code).':'.
 9666:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9667:                             $homeserver);
 9668:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9669:             my @items = split(/&/,$response);
 9670:             foreach my $item (@items) {
 9671:                 my ($key,$value) = split('=',$item);
 9672:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9673:             }
 9674:         }
 9675:     }
 9676:     return \%crsreqresponse;
 9677: }
 9678: 
 9679: sub auto_export_grades {
 9680:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9681:     my ($homeserver,%exportresponse);
 9682:     if ($cdom =~ /^$match_domain$/) {
 9683:         $homeserver = &domain($cdom,'primary');
 9684:     }
 9685:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9686:         my $info;
 9687:         if (ref($inforef) eq 'HASH') {
 9688:             $info = &freeze_escape($inforef);
 9689:         }
 9690:         if (ref($gradesref) eq 'HASH') {
 9691:             my $grades = &freeze_escape($gradesref);
 9692:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9693:                                 $info.':'.$grades,$homeserver);
 9694:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9695:                 my @items = split(/&/,$response);
 9696:                 foreach my $item (@items) {
 9697:                     my ($key,$value) = split('=',$item);
 9698:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9699:                 }
 9700:             }
 9701:         }
 9702:     }
 9703:     return \%exportresponse;
 9704: }
 9705: 
 9706: sub check_instcode_cloning {
 9707:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9708:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9709:         return;
 9710:     }
 9711:     my $canclone;
 9712:     if (@{$code_order} > 0) {
 9713:         my $instcoderegexp ='^';
 9714:         my @clonecodes = split(/\&/,$cloner);
 9715:         foreach my $item (@{$code_order}) {
 9716:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9717:                 foreach my $pair (@clonecodes) {
 9718:                     my ($key,$val) = split(/\=/,$pair,2);
 9719:                     $val = &unescape($val);
 9720:                     if ($key eq $item) {
 9721:                         $instcoderegexp .= '('.$val.')';
 9722:                         last;
 9723:                     }
 9724:                 }
 9725:             } else {
 9726:                 $instcoderegexp .= $codedefaults->{$item};
 9727:             }
 9728:         }
 9729:         $instcoderegexp .= '$';
 9730:         my (@from,@to);
 9731:         eval {
 9732:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9733:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9734:         };
 9735:         if ((@from > 0) && (@to > 0)) {
 9736:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9737:             if (!@diffs) {
 9738:                 $canclone = 1;
 9739:             }
 9740:         }
 9741:     }
 9742:     return $canclone;
 9743: }
 9744: 
 9745: sub default_instcode_cloning {
 9746:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9747:     my (%codedefaults,@code_order,$canclone);
 9748:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9749:         %codedefaults = %{$codedefaultsref};
 9750:         @code_order = @{$codeorderref};
 9751:     } elsif ($clonedom) {
 9752:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9753:     }
 9754:     if (($domdefclone) && (@code_order)) {
 9755:         my @clonecodes = split(/\+/,$domdefclone);
 9756:         my $instcoderegexp ='^';
 9757:         foreach my $item (@code_order) {
 9758:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9759:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9760:             } else {
 9761:                 $instcoderegexp .= $codedefaults{$item};
 9762:             }
 9763:         }
 9764:         $instcoderegexp .= '$';
 9765:         my (@from,@to);
 9766:         eval {
 9767:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9768:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9769:         };
 9770:         if ((@from > 0) && (@to > 0)) {
 9771:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9772:             if (!@diffs) {
 9773:                 $canclone = 1;
 9774:             }
 9775:         }
 9776:     }
 9777:     return $canclone;
 9778: }
 9779: 
 9780: # ------------------------------------------------------- Course Group routines
 9781: 
 9782: sub get_coursegroups {
 9783:     my ($cdom,$cnum,$group,$namespace) = @_;
 9784:     return(&dump($namespace,$cdom,$cnum,$group));
 9785: }
 9786: 
 9787: sub modify_coursegroup {
 9788:     my ($cdom,$cnum,$groupsettings) = @_;
 9789:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9790: }
 9791: 
 9792: sub toggle_coursegroup_status {
 9793:     my ($cdom,$cnum,$group,$action) = @_;
 9794:     my ($from_namespace,$to_namespace);
 9795:     if ($action eq 'delete') {
 9796:         $from_namespace = 'coursegroups';
 9797:         $to_namespace = 'deleted_groups';
 9798:     } else {
 9799:         $from_namespace = 'deleted_groups';
 9800:         $to_namespace = 'coursegroups';
 9801:     }
 9802:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9803:     if (my $tmp = &error(%curr_group)) {
 9804:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9805:         return ('read error',$tmp);
 9806:     } else {
 9807:         my %savedsettings = %curr_group; 
 9808:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9809:         my $deloutcome;
 9810:         if ($result eq 'ok') {
 9811:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9812:         } else {
 9813:             return ('write error',$result);
 9814:         }
 9815:         if ($deloutcome eq 'ok') {
 9816:             return 'ok';
 9817:         } else {
 9818:             return ('delete error',$deloutcome);
 9819:         }
 9820:     }
 9821: }
 9822: 
 9823: sub modify_group_roles {
 9824:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9825:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9826:     my $role = 'gr/'.&escape($userprivs);
 9827:     my ($uname,$udom) = split(/:/,$user);
 9828:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9829:     if ($result eq 'ok') {
 9830:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9831:     }
 9832:     return $result;
 9833: }
 9834: 
 9835: sub modify_coursegroup_membership {
 9836:     my ($cdom,$cnum,$membership) = @_;
 9837:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9838:     return $result;
 9839: }
 9840: 
 9841: sub get_active_groups {
 9842:     my ($udom,$uname,$cdom,$cnum) = @_;
 9843:     my $now = time;
 9844:     my %groups = ();
 9845:     foreach my $key (keys(%env)) {
 9846:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9847:             my ($start,$end) = split(/\./,$env{$key});
 9848:             if (($end!=0) && ($end<$now)) { next; }
 9849:             if (($start!=0) && ($start>$now)) { next; }
 9850:             if ($1 eq $cdom && $2 eq $cnum) {
 9851:                 $groups{$3} = $env{$key} ;
 9852:             }
 9853:         }
 9854:     }
 9855:     return %groups;
 9856: }
 9857: 
 9858: sub get_group_membership {
 9859:     my ($cdom,$cnum,$group) = @_;
 9860:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9861: }
 9862: 
 9863: sub get_users_groups {
 9864:     my ($udom,$uname,$courseid) = @_;
 9865:     my @usersgroups;
 9866:     my $cachetime=1800;
 9867: 
 9868:     my $hashid="$udom:$uname:$courseid";
 9869:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9870:     if (defined($cached)) {
 9871:         @usersgroups = split(/:/,$grouplist);
 9872:     } else {  
 9873:         $grouplist = '';
 9874:         my $courseurl = &courseid_to_courseurl($courseid);
 9875:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9876:         my $access_end = $env{'course.'.$courseid.
 9877:                               '.default_enrollment_end_date'};
 9878:         my $now = time;
 9879:         foreach my $key (keys(%roleshash)) {
 9880:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9881:                 my $group = $1;
 9882:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9883:                     my $start = $2;
 9884:                     my $end = $1;
 9885:                     if ($start == -1) { next; } # deleted from group
 9886:                     if (($start!=0) && ($start>$now)) { next; }
 9887:                     if (($end!=0) && ($end<$now)) {
 9888:                         if ($access_end && $access_end < $now) {
 9889:                             if ($access_end - $end < 86400) {
 9890:                                 push(@usersgroups,$group);
 9891:                             }
 9892:                         }
 9893:                         next;
 9894:                     }
 9895:                     push(@usersgroups,$group);
 9896:                 }
 9897:             }
 9898:         }
 9899:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9900:         $grouplist = join(':',@usersgroups);
 9901:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9902:     }
 9903:     return @usersgroups;
 9904: }
 9905: 
 9906: sub devalidate_getgroups_cache {
 9907:     my ($udom,$uname,$cdom,$cnum)=@_;
 9908:     my $courseid = $cdom.'_'.$cnum;
 9909: 
 9910:     my $hashid="$udom:$uname:$courseid";
 9911:     &devalidate_cache_new('getgroups',$hashid);
 9912: }
 9913: 
 9914: # ------------------------------------------------------------------ Plain Text
 9915: 
 9916: sub plaintext {
 9917:     my ($short,$type,$cid,$forcedefault) = @_;
 9918:     if ($short =~ m{^cr/}) {
 9919: 	return (split('/',$short))[-1];
 9920:     }
 9921:     if (!defined($cid)) {
 9922:         $cid = $env{'request.course.id'};
 9923:     }
 9924:     my %rolenames = (
 9925:                       Course    => 'std',
 9926:                       Community => 'alt1',
 9927:                       Placement => 'std',
 9928:                     );
 9929:     if ($cid ne '') {
 9930:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9931:             unless ($forcedefault) {
 9932:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9933:                 &Apache::lonlocal::mt_escape(\$roletext);
 9934:                 return &Apache::lonlocal::mt($roletext);
 9935:             }
 9936:         }
 9937:     }
 9938:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9939:         (defined($rolenames{$type})) && 
 9940:         (defined($prp{$short}{$rolenames{$type}}))) {
 9941:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9942:     } elsif ($cid ne '') {
 9943:         my $crstype = $env{'course.'.$cid.'.type'};
 9944:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9945:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9946:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9947:         }
 9948:     }
 9949:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9950: }
 9951: 
 9952: # ----------------------------------------------------------------- Assign Role
 9953: 
 9954: sub assignrole {
 9955:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9956:         $context)=@_;
 9957:     my $mrole;
 9958:     if ($role =~ /^cr\//) {
 9959:         my $cwosec=$url;
 9960:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9961: 	unless (&allowed('ccr',$cwosec)) {
 9962:            my $refused = 1;
 9963:            if ($context eq 'requestcourses') {
 9964:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9965:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9966:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9967:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9968:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9969:                            if ($crsenv{'internal.courseowner'} eq
 9970:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9971:                                $refused = '';
 9972:                            }
 9973:                        }
 9974:                    }
 9975:                }
 9976:            }
 9977:            if ($refused) {
 9978:                &logthis('Refused custom assignrole: '.
 9979:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9980:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9981:                return 'refused';
 9982:            }
 9983:         }
 9984:         $mrole='cr';
 9985:     } elsif ($role =~ /^gr\//) {
 9986:         my $cwogrp=$url;
 9987:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9988:         unless (&allowed('mdg',$cwogrp)) {
 9989:             &logthis('Refused group assignrole: '.
 9990:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9991:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9992:             return 'refused';
 9993:         }
 9994:         $mrole='gr';
 9995:     } else {
 9996:         my $cwosec=$url;
 9997:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9998:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9999:             my $refused;
10000:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10001:                 if (!(&allowed('c'.$role,$url))) {
10002:                     $refused = 1;
10003:                 }
10004:             } else {
10005:                 $refused = 1;
10006:             }
10007:             if ($refused) {
10008:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10009:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10010:                     my %crsenv;
10011:                     if ($role eq 'cc' || $role eq 'co') {
10012:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10013:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10014:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10015:                                 if ($crsenv{'internal.courseowner'} eq 
10016:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10017:                                     $refused = '';
10018:                                 }
10019:                             }
10020:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10021:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10022:                                 if ($crsenv{'internal.courseowner'} eq 
10023:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10024:                                     $refused = '';
10025:                                 }
10026:                             }
10027:                         }
10028:                     }
10029:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10030:                     if ($role eq 'st') {
10031:                         $refused = '';
10032:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10033:                         $refused = '';
10034:                     }
10035:                 } elsif ($context eq 'requestcourses') {
10036:                     my @possroles = ('st','ta','ep','in','cc','co');
10037:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10038:                         my $wrongcc;
10039:                         if ($cnum =~ /^$match_community$/) {
10040:                             $wrongcc = 1 if ($role eq 'cc');
10041:                         } else {
10042:                             $wrongcc = 1 if ($role eq 'co');
10043:                         }
10044:                         unless ($wrongcc) {
10045:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10046:                             if ($crsenv{'internal.courseowner'} eq 
10047:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10048:                                 $refused = '';
10049:                             }
10050:                         }
10051:                     }
10052:                 } elsif ($context eq 'requestauthor') {
10053:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10054:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10055:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10056:                             $refused = '';
10057:                         } else {
10058:                             my %domdefaults = &get_domain_defaults($udom);
10059:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10060:                                 my $checkbystatus;
10061:                                 if ($env{'user.adv'}) { 
10062:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10063:                                     if ($disposition eq 'automatic') {
10064:                                         $refused = '';
10065:                                     } elsif ($disposition eq '') {
10066:                                         $checkbystatus = 1;
10067:                                     } 
10068:                                 } else {
10069:                                     $checkbystatus = 1;
10070:                                 }
10071:                                 if ($checkbystatus) {
10072:                                     if ($env{'environment.inststatus'}) {
10073:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10074:                                         foreach my $type (@inststatuses) {
10075:                                             if (($type ne '') &&
10076:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10077:                                                 $refused = '';
10078:                                             }
10079:                                         }
10080:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10081:                                         $refused = '';
10082:                                     }
10083:                                 }
10084:                             }
10085:                         }
10086:                     }
10087:                 }
10088:                 if ($refused) {
10089:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10090:                              ' '.$role.' '.$end.' '.$start.' by '.
10091: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10092:                     return 'refused';
10093:                 }
10094:             }
10095:         } elsif ($role eq 'au') {
10096:             if ($url ne '/'.$udom.'/') {
10097:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10098:                          ' to assign author role for '.$uname.':'.$udom.
10099:                          ' in domain: '.$url.' refused (wrong domain).');
10100:                 return 'refused';
10101:             }
10102:         }
10103:         $mrole=$role;
10104:     }
10105:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10106:                 "$udom:$uname:$url".'_'."$mrole=$role";
10107:     if ($end) { $command.='_'.$end; }
10108:     if ($start) {
10109: 	if ($end) { 
10110:            $command.='_'.$start; 
10111:         } else {
10112:            $command.='_0_'.$start;
10113:         }
10114:     }
10115:     my $origstart = $start;
10116:     my $origend = $end;
10117:     my $delflag;
10118: # actually delete
10119:     if ($deleteflag) {
10120: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10121: # modify command to delete the role
10122:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10123:                 "$udom:$uname:$url".'_'."$mrole";
10124: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10125: # set start and finish to negative values for userrolelog
10126:            $start=-1;
10127:            $end=-1;
10128:            $delflag = 1;
10129:         }
10130:     }
10131: # send command
10132:     my $answer=&reply($command,&homeserver($uname,$udom));
10133: # log new user role if status is ok
10134:     if ($answer eq 'ok') {
10135: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10136:         if (($role eq 'cc') || ($role eq 'in') ||
10137:             ($role eq 'ep') || ($role eq 'ad') ||
10138:             ($role eq 'ta') || ($role eq 'st') ||
10139:             ($role=~/^cr/) || ($role eq 'gr') ||
10140:             ($role eq 'co')) {
10141: # for course roles, perform group memberships changes triggered by role change.
10142:             unless ($role =~ /^gr/) {
10143:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10144:                                                  $origstart,$selfenroll,$context);
10145:             }
10146:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10147:                            $selfenroll,$context);
10148:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10149:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10150:                  ($role eq 'da')) {
10151:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10152:                            $context);
10153:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10154:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10155:                              $context); 
10156:         }
10157:         if ($role eq 'cc') {
10158:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10159:         }
10160:     }
10161:     return $answer;
10162: }
10163: 
10164: sub autoupdate_coowners {
10165:     my ($url,$end,$start,$uname,$udom) = @_;
10166:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10167:     if (($cdom ne '') && ($cnum ne '')) {
10168:         my $now = time;
10169:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10170:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10171:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10172:             my $instcode = $coursehash{'internal.coursecode'};
10173:             if ($instcode ne '') {
10174:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10175:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10176:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10177:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10178:                         if ($result eq 'valid') {
10179:                             if ($coursehash{'internal.co-owners'}) {
10180:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10181:                                     push(@newcoowners,$coowner);
10182:                                 }
10183:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10184:                                     push(@newcoowners,$uname.':'.$udom);
10185:                                 }
10186:                                 @newcoowners = sort(@newcoowners);
10187:                             } else {
10188:                                 push(@newcoowners,$uname.':'.$udom);
10189:                             }
10190:                         } else {
10191:                             if ($coursehash{'internal.co-owners'}) {
10192:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10193:                                     unless ($coowner eq $uname.':'.$udom) {
10194:                                         push(@newcoowners,$coowner);
10195:                                     }
10196:                                 }
10197:                                 unless (@newcoowners > 0) {
10198:                                     $delcoowners = 1;
10199:                                     $coowners = '';
10200:                                 }
10201:                             }
10202:                         }
10203:                         if (@newcoowners || $delcoowners) {
10204:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10205:                                             $delcoowners,@newcoowners);
10206:                         }
10207:                     }
10208:                 }
10209:             }
10210:         }
10211:     }
10212: }
10213: 
10214: sub store_coowners {
10215:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10216:     my $cid = $cdom.'_'.$cnum;
10217:     my ($coowners,$delresult,$putresult);
10218:     if (@newcoowners) {
10219:         $coowners = join(',',@newcoowners);
10220:         my %coownershash = (
10221:                             'internal.co-owners' => $coowners,
10222:                            );
10223:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10224:         if ($putresult eq 'ok') {
10225:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10226:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10227:             }
10228:         }
10229:     }
10230:     if ($delcoowners) {
10231:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10232:         if ($delresult eq 'ok') {
10233:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10234:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10235:             }
10236:         }
10237:     }
10238:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10239:         my %crsinfo =
10240:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10241:         if (ref($crsinfo{$cid}) eq 'HASH') {
10242:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10243:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10244:         }
10245:     }
10246: }
10247: 
10248: # -------------------------------------------------- Modify user authentication
10249: # Overrides without validation
10250: 
10251: sub modifyuserauth {
10252:     my ($udom,$uname,$umode,$upass)=@_;
10253:     my $uhome=&homeserver($uname,$udom);
10254:     my $allowed;
10255:     if (&allowed('mau',$udom)) {
10256:         $allowed = 1;
10257:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10258:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10259:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10260:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10261:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10262:         if (($cdom ne '') && ($cnum ne '')) {
10263:             my $is_owner = &is_course_owner($cdom,$cnum);
10264:             if ($is_owner) {
10265:                 $allowed = 1;
10266:             }
10267:         }
10268:     }
10269:     unless ($allowed) { return 'refused'; }
10270:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10271:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10272:              ' in domain '.$env{'request.role.domain'});  
10273:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10274: 		     &escape($upass),$uhome);
10275:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10276:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10277:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10278:     &log($udom,,$uname,$uhome,
10279:         'Authentication changed by '.$env{'user.domain'}.', '.
10280:                                      $env{'user.name'}.', '.$umode.
10281:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
10282:     unless ($reply eq 'ok') {
10283:         &logthis('Authentication mode error: '.$reply);
10284: 	return 'error: '.$reply;
10285:     }   
10286:     return 'ok';
10287: }
10288: 
10289: # --------------------------------------------------------------- Modify a user
10290: 
10291: sub modifyuser {
10292:     my ($udom,    $uname, $uid,
10293:         $umode,   $upass, $first,
10294:         $middle,  $last,  $gene,
10295:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10296:     $udom= &LONCAPA::clean_domain($udom);
10297:     $uname=&LONCAPA::clean_username($uname);
10298:     my $showcandelete = 'none';
10299:     if (ref($candelete) eq 'ARRAY') {
10300:         if (@{$candelete} > 0) {
10301:             $showcandelete = join(', ',@{$candelete});
10302:         }
10303:     }
10304:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10305:              $umode.', '.$first.', '.$middle.', '.
10306: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10307:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10308:                                      ' desiredhome not specified'). 
10309:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10310:              ' in domain '.$env{'request.role.domain'});
10311:     my $uhome=&homeserver($uname,$udom,'true');
10312:     my $newuser;
10313:     if ($uhome eq 'no_host') {
10314:         $newuser = 1;
10315:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10316:                 ($umode eq 'lti')) {
10317:             return 'error: more information needed to create new user';
10318:         }
10319:     }
10320: # ----------------------------------------------------------------- Create User
10321:     if (($uhome eq 'no_host') && 
10322: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10323:         my $unhome='';
10324:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10325:             $unhome = $desiredhome;
10326: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10327: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10328:         } else { # load balancing routine for determining $unhome
10329:             my $loadm=10000000;
10330: 	    my %servers = &get_servers($udom,'library');
10331: 	    foreach my $tryserver (keys(%servers)) {
10332: 		my $answer=reply('load',$tryserver);
10333: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10334: 		    $loadm=$answer;
10335: 		    $unhome=$tryserver;
10336: 		}
10337: 	    }
10338:         }
10339:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10340: 	    return 'error: unable to find a home server for '.$uname.
10341:                    ' in domain '.$udom;
10342:         }
10343:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10344:                          &escape($upass),$unhome);
10345: 	unless ($reply eq 'ok') {
10346:             return 'error: '.$reply;
10347:         }   
10348:         $uhome=&homeserver($uname,$udom,'true');
10349:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10350: 	    return 'error: unable verify users home machine.';
10351:         }
10352:     }   # End of creation of new user
10353: # ---------------------------------------------------------------------- Add ID
10354:     if ($uid) {
10355:        $uid=~tr/A-Z/a-z/;
10356:        my %uidhash=&idrget($udom,$uname);
10357:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10358:          && (!$forceid)) {
10359: 	  unless ($uid eq $uidhash{$uname}) {
10360: 	      return 'error: user id "'.$uid.'" does not match '.
10361:                   'current user id "'.$uidhash{$uname}.'".';
10362:           }
10363:        } else {
10364: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10365:        }
10366:     }
10367: # -------------------------------------------------------------- Add names, etc
10368:     my @tmp=&get('environment',
10369: 		   ['firstname','middlename','lastname','generation','id',
10370:                     'permanentemail','inststatus'],
10371: 		   $udom,$uname);
10372:     my (%names,%oldnames);
10373:     if ($tmp[0] =~ m/^error:.*/) { 
10374:         %names=(); 
10375:     } else {
10376:         %names = @tmp;
10377:         %oldnames = %names;
10378:     }
10379: #
10380: # If name, email and/or uid are blank (e.g., because an uploaded file
10381: # of users did not contain them), do not overwrite existing values
10382: # unless field is in $candelete array ref.  
10383: #
10384: 
10385:     my @fields = ('firstname','middlename','lastname','generation',
10386:                   'permanentemail','id');
10387:     my %newvalues;
10388:     if (ref($candelete) eq 'ARRAY') {
10389:         foreach my $field (@fields) {
10390:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10391:                 if ($field eq 'firstname') {
10392:                     $names{$field} = $first;
10393:                 } elsif ($field eq 'middlename') {
10394:                     $names{$field} = $middle;
10395:                 } elsif ($field eq 'lastname') {
10396:                     $names{$field} = $last;
10397:                 } elsif ($field eq 'generation') { 
10398:                     $names{$field} = $gene;
10399:                 } elsif ($field eq 'permanentemail') {
10400:                     $names{$field} = $email;
10401:                 } elsif ($field eq 'id') {
10402:                     $names{$field}  = $uid;
10403:                 }
10404:             }
10405:         }
10406:     }
10407:     if ($first)  { $names{'firstname'}  = $first; }
10408:     if (defined($middle)) { $names{'middlename'} = $middle; }
10409:     if ($last)   { $names{'lastname'}   = $last; }
10410:     if (defined($gene))   { $names{'generation'} = $gene; }
10411:     if ($email) {
10412:        $email=~s/[^\w\@\.\-\,]//gs;
10413:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10414:     }
10415:     if ($uid) { $names{'id'}  = $uid; }
10416:     if (defined($inststatus)) {
10417:         $names{'inststatus'} = '';
10418:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10419:         if (ref($usertypes) eq 'HASH') {
10420:             my @okstatuses; 
10421:             foreach my $item (split(/:/,$inststatus)) {
10422:                 if (defined($usertypes->{$item})) {
10423:                     push(@okstatuses,$item);  
10424:                 }
10425:             }
10426:             if (@okstatuses) {
10427:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10428:             }
10429:         }
10430:     }
10431:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10432:                  $umode.', '.$first.', '.$middle.', '.
10433:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10434:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10435:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10436:     } else {
10437:         $logmsg .= ' during self creation';
10438:     }
10439:     my $changed;
10440:     if ($newuser) {
10441:         $changed = 1;
10442:     } else {
10443:         foreach my $field (@fields) {
10444:             if ($names{$field} ne $oldnames{$field}) {
10445:                 $changed = 1;
10446:                 last;
10447:             }
10448:         }
10449:     }
10450:     unless ($changed) {
10451:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10452:         &logthis($logmsg);
10453:         return 'ok';
10454:     }
10455:     my $reply = &put('environment', \%names, $udom,$uname);
10456:     if ($reply ne 'ok') { 
10457:         return 'error: '.$reply;
10458:     }
10459:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10460:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10461:     }
10462:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10463:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10464:     $logmsg = 'Success modifying user '.$logmsg;
10465:     &logthis($logmsg);
10466:     return 'ok';
10467: }
10468: 
10469: # -------------------------------------------------------------- Modify student
10470: 
10471: sub modifystudent {
10472:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10473:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10474:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10475:     if (!$cid) {
10476: 	unless ($cid=$env{'request.course.id'}) {
10477: 	    return 'not_in_class';
10478: 	}
10479:     }
10480: # --------------------------------------------------------------- Make the user
10481:     my $reply=&modifyuser
10482: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10483:          $desiredhome,$email,$inststatus);
10484:     unless ($reply eq 'ok') { return $reply; }
10485:     # This will cause &modify_student_enrollment to get the uid from the
10486:     # student's environment
10487:     $uid = undef if (!$forceid);
10488:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10489:                                         $gene,$usec,$end,$start,$type,$locktype,
10490:                                         $cid,$selfenroll,$context,$credits,$instsec);
10491:     return $reply;
10492: }
10493: 
10494: sub modify_student_enrollment {
10495:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10496:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10497:     my ($cdom,$cnum,$chome);
10498:     if (!$cid) {
10499: 	unless ($cid=$env{'request.course.id'}) {
10500: 	    return 'not_in_class';
10501: 	}
10502: 	$cdom=$env{'course.'.$cid.'.domain'};
10503: 	$cnum=$env{'course.'.$cid.'.num'};
10504:     } else {
10505: 	($cdom,$cnum)=split(/_/,$cid);
10506:     }
10507:     $chome=$env{'course.'.$cid.'.home'};
10508:     if (!$chome) {
10509: 	$chome=&homeserver($cnum,$cdom);
10510:     }
10511:     if (!$chome) { return 'unknown_course'; }
10512:     # Make sure the user exists
10513:     my $uhome=&homeserver($uname,$udom);
10514:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10515: 	return 'error: no such user';
10516:     }
10517:     # Get student data if we were not given enough information
10518:     if (!defined($first)  || $first  eq '' || 
10519:         !defined($last)   || $last   eq '' || 
10520:         !defined($uid)    || $uid    eq '' || 
10521:         !defined($middle) || $middle eq '' || 
10522:         !defined($gene)   || $gene   eq '') {
10523:         # They did not supply us with enough data to enroll the student, so
10524:         # we need to pick up more information.
10525:         my %tmp = &get('environment',
10526:                        ['firstname','middlename','lastname', 'generation','id']
10527:                        ,$udom,$uname);
10528: 
10529:         #foreach my $key (keys(%tmp)) {
10530:         #    &logthis("key $key = ".$tmp{$key});
10531:         #}
10532:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10533:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10534:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10535:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10536:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10537:     }
10538:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10539:     my $user = "$uname:$udom";
10540:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10541:     my $reply=cput('classlist',
10542: 		   {$user => 
10543: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10544: 		   $cdom,$cnum);
10545:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10546:         &devalidate_getsection_cache($udom,$uname,$cid);
10547:     } else { 
10548: 	return 'error: '.$reply;
10549:     }
10550:     # Add student role to user
10551:     my $uurl='/'.$cid;
10552:     $uurl=~s/\_/\//g;
10553:     if ($usec) {
10554: 	$uurl.='/'.$usec;
10555:     }
10556:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10557:                              $selfenroll,$context);
10558:     if ($result ne 'ok') {
10559:         if ($old_entry{$user} ne '') {
10560:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10561:         } else {
10562:             $reply = &del('classlist',[$user],$cdom,$cnum);
10563:         }
10564:     }
10565:     return $result; 
10566: }
10567: 
10568: sub format_name {
10569:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10570:     my $name;
10571:     if ($first ne 'lastname') {
10572: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10573:     } else {
10574: 	if ($lastname=~/\S/) {
10575: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10576: 	    $name=~s/\s+,/,/;
10577: 	} else {
10578: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10579: 	}
10580:     }
10581:     $name=~s/^\s+//;
10582:     $name=~s/\s+$//;
10583:     $name=~s/\s+/ /g;
10584:     return $name;
10585: }
10586: 
10587: # ------------------------------------------------- Write to course preferences
10588: 
10589: sub writecoursepref {
10590:     my ($courseid,%prefs)=@_;
10591:     $courseid=~s/^\///;
10592:     $courseid=~s/\_/\//g;
10593:     my ($cdomain,$cnum)=split(/\//,$courseid);
10594:     my $chome=homeserver($cnum,$cdomain);
10595:     if (($chome eq '') || ($chome eq 'no_host')) { 
10596: 	return 'error: no such course';
10597:     }
10598:     my $cstring='';
10599:     foreach my $pref (keys(%prefs)) {
10600: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10601:     }
10602:     $cstring=~s/\&$//;
10603:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10604: }
10605: 
10606: # ---------------------------------------------------------- Make/modify course
10607: 
10608: sub createcourse {
10609:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10610:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10611:     $url=&declutter($url);
10612:     my $cid='';
10613:     if ($context eq 'requestcourses') {
10614:         my $can_create = 0;
10615:         my ($ownername,$ownerdom) = split(':',$course_owner);
10616:         if ($udom eq $ownerdom) {
10617:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10618:                                   $context)) {
10619:                 $can_create = 1;
10620:             }
10621:         } else {
10622:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10623:                                            $category);
10624:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10625:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10626:                 if (@curr > 0) {
10627:                     my @options = qw(approval validate autolimit);
10628:                     my $optregex = join('|',@options);
10629:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10630:                         $can_create = 1;
10631:                     }
10632:                 }
10633:             }
10634:         }
10635:         if ($can_create) {
10636:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10637:                 unless (&allowed('ccc',$udom)) {
10638:                     return 'refused'; 
10639:                 }
10640:             }
10641:         } else {
10642:             return 'refused';
10643:         }
10644:     } elsif (!&allowed('ccc',$udom)) {
10645:         return 'refused';
10646:     }
10647: # --------------------------------------------------------------- Get Unique ID
10648:     my $uname;
10649:     if ($cnum =~ /^$match_courseid$/) {
10650:         my $chome=&homeserver($cnum,$udom,'true');
10651:         if (($chome eq '') || ($chome eq 'no_host')) {
10652:             $uname = $cnum;
10653:         } else {
10654:             $uname = &generate_coursenum($udom,$crstype);
10655:         }
10656:     } else {
10657:         $uname = &generate_coursenum($udom,$crstype);
10658:     }
10659:     return $uname if ($uname =~ /^error/);
10660: # -------------------------------------------------- Check supplied server name
10661:     if (!defined($course_server)) {
10662:         if (defined(&domain($udom,'primary'))) {
10663:             $course_server = &domain($udom,'primary');
10664:         } else {
10665:             $course_server = $env{'user.home'}; 
10666:         }
10667:     }
10668:     my %host_servers =
10669:         &Apache::lonnet::get_servers($udom,'library');
10670:     unless ($host_servers{$course_server}) {
10671:         return 'error: invalid home server for course: '.$course_server;
10672:     }
10673: # ------------------------------------------------------------- Make the course
10674:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10675:                       $course_server);
10676:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10677:     my $uhome=&homeserver($uname,$udom,'true');
10678:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10679: 	return 'error: no such course';
10680:     }
10681: # ----------------------------------------------------------------- Course made
10682: # log existence
10683:     my $now = time;
10684:     my $newcourse = {
10685:                     $udom.'_'.$uname => {
10686:                                      description => $description,
10687:                                      inst_code   => $inst_code,
10688:                                      owner       => $course_owner,
10689:                                      type        => $crstype,
10690:                                      creator     => $env{'user.name'}.':'.
10691:                                                     $env{'user.domain'},
10692:                                      created     => $now,
10693:                                      context     => $context,
10694:                                                 },
10695:                     };
10696:     &courseidput($udom,$newcourse,$uhome,'notime');
10697: # set toplevel url
10698:     my $topurl=$url;
10699:     unless ($nonstandard) {
10700: # ------------------------------------------ For standard courses, make top url
10701:         my $mapurl=&clutter($url);
10702:         if ($mapurl eq '/res/') { $mapurl=''; }
10703:         $env{'form.initmap'}=(<<ENDINITMAP);
10704: <map>
10705: <resource id="1" type="start"></resource>
10706: <resource id="2" src="$mapurl"></resource>
10707: <resource id="3" type="finish"></resource>
10708: <link index="1" from="1" to="2"></link>
10709: <link index="2" from="2" to="3"></link>
10710: </map>
10711: ENDINITMAP
10712:         $topurl=&declutter(
10713:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10714:                           );
10715:     }
10716: # ----------------------------------------------------------- Write preferences
10717:     &writecoursepref($udom.'_'.$uname,
10718:                      ('description'              => $description,
10719:                       'url'                      => $topurl,
10720:                       'internal.creator'         => $env{'user.name'}.':'.
10721:                                                     $env{'user.domain'},
10722:                       'internal.created'         => $now,
10723:                       'internal.creationcontext' => $context)
10724:                     );
10725:     return '/'.$udom.'/'.$uname;
10726: }
10727: 
10728: # ------------------------------------------------------------------- Create ID
10729: sub generate_coursenum {
10730:     my ($udom,$crstype) = @_;
10731:     my $domdesc = &domain($udom);
10732:     return 'error: invalid domain' if ($domdesc eq '');
10733:     my $first;
10734:     if ($crstype eq 'Community') {
10735:         $first = '0';
10736:     } else {
10737:         $first = int(1+rand(9)); 
10738:     } 
10739:     my $uname=$first.
10740:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10741:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10742:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10743: # ----------------------------------------------- Make sure that does not exist
10744:     my $uhome=&homeserver($uname,$udom,'true');
10745:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10746:         if ($crstype eq 'Community') {
10747:             $first = '0';
10748:         } else {
10749:             $first = int(1+rand(9));
10750:         }
10751:         $uname=$first.
10752:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10753:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10754:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10755:         $uhome=&homeserver($uname,$udom,'true');
10756:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10757:             return 'error: unable to generate unique course-ID';
10758:         }
10759:     }
10760:     return $uname;
10761: }
10762: 
10763: sub is_course {
10764:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10765:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10766: 
10767:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10768:     my $uhome=&homeserver($cnum,$cdom);
10769:     my $iscourse;
10770:     if (grep { $_ eq $uhome } current_machine_ids()) {
10771:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10772:     } else {
10773:         my $hashid = $cdom.':'.$cnum;
10774:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10775:         unless (defined($cached)) {
10776:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10777:                                         $cnum,undef,undef,'.');
10778:             $iscourse = 0;
10779:             if (exists($courses{$cdom.'_'.$cnum})) {
10780:                 $iscourse = 1;
10781:             }
10782:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10783:         }
10784:     }
10785:     return unless ($iscourse);
10786:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10787: }
10788: 
10789: sub store_userdata {
10790:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10791:     my $result;
10792:     if ($datakey ne '') {
10793:         if (ref($storehash) eq 'HASH') {
10794:             if ($udom eq '' || $uname eq '') {
10795:                 $udom = $env{'user.domain'};
10796:                 $uname = $env{'user.name'};
10797:             }
10798:             my $uhome=&homeserver($uname,$udom);
10799:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10800:                 $result = 'error: no_host';
10801:             } else {
10802:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10803:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10804: 
10805:                 my $namevalue='';
10806:                 foreach my $key (keys(%{$storehash})) {
10807:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10808:                 }
10809:                 $namevalue=~s/\&$//;
10810:                 unless ($namespace eq 'courserequests') {
10811:                     $datakey = &escape($datakey);
10812:                 }
10813:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10814:                                   $namevalue,$uhome);
10815:             }
10816:         } else {
10817:             $result = 'error: data to store was not a hash reference'; 
10818:         }
10819:     } else {
10820:         $result= 'error: invalid requestkey'; 
10821:     }
10822:     return $result;
10823: }
10824: 
10825: # ---------------------------------------------------------- Assign Custom Role
10826: 
10827: sub assigncustomrole {
10828:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10829:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10830:                        $end,$start,$deleteflag,$selfenroll,$context);
10831: }
10832: 
10833: # ----------------------------------------------------------------- Revoke Role
10834: 
10835: sub revokerole {
10836:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10837:     my $now=time;
10838:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10839: }
10840: 
10841: # ---------------------------------------------------------- Revoke Custom Role
10842: 
10843: sub revokecustomrole {
10844:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10845:     my $now=time;
10846:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10847:            $deleteflag,$selfenroll,$context);
10848: }
10849: 
10850: # ------------------------------------------------------------ Disk usage
10851: sub diskusage {
10852:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10853:     $directorypath =~ s/\/$//;
10854:     my $listing=&reply('du2:'.&escape($directorypath).':'
10855:                        .&escape($getpropath).':'.&escape($uname).':'
10856:                        .&escape($udom),homeserver($uname,$udom));
10857:     if ($listing eq 'unknown_cmd') {
10858:         if ($getpropath) {
10859:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10860:         }
10861:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10862:     }
10863:     return $listing;
10864: }
10865: 
10866: sub is_locked {
10867:     my ($file_name, $domain, $user, $which) = @_;
10868:     my @check;
10869:     my $is_locked;
10870:     push (@check,$file_name);
10871:     my %locked = &get('file_permissions',\@check,
10872: 		      $env{'user.domain'},$env{'user.name'});
10873:     my ($tmp)=keys(%locked);
10874:     if ($tmp=~/^error:/) { undef(%locked); }
10875:     
10876:     if (ref($locked{$file_name}) eq 'ARRAY') {
10877:         $is_locked = 'false';
10878:         foreach my $entry (@{$locked{$file_name}}) {
10879:            if (ref($entry) eq 'ARRAY') {
10880:                $is_locked = 'true';
10881:                if (ref($which) eq 'ARRAY') {
10882:                    push(@{$which},$entry);
10883:                } else {
10884:                    last;
10885:                }
10886:            }
10887:        }
10888:     } else {
10889:         $is_locked = 'false';
10890:     }
10891:     return $is_locked;
10892: }
10893: 
10894: sub declutter_portfile {
10895:     my ($file) = @_;
10896:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10897:     return $file;
10898: }
10899: 
10900: # ------------------------------------------------------------- Mark as Read Only
10901: 
10902: sub mark_as_readonly {
10903:     my ($domain,$user,$files,$what) = @_;
10904:     my %current_permissions = &dump('file_permissions',$domain,$user);
10905:     my ($tmp)=keys(%current_permissions);
10906:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10907:     foreach my $file (@{$files}) {
10908: 	$file = &declutter_portfile($file);
10909:         push(@{$current_permissions{$file}},$what);
10910:     }
10911:     &put('file_permissions',\%current_permissions,$domain,$user);
10912:     return;
10913: }
10914: 
10915: # ------------------------------------------------------------Save Selected Files
10916: 
10917: sub save_selected_files {
10918:     my ($user, $path, @files) = @_;
10919:     my $filename = $user."savedfiles";
10920:     my @other_files = &files_not_in_path($user, $path);
10921:     open (OUT,'>',LONCAPA::tempdir().$filename);
10922:     foreach my $file (@files) {
10923:         print (OUT $env{'form.currentpath'}.$file."\n");
10924:     }
10925:     foreach my $file (@other_files) {
10926:         print (OUT $file."\n");
10927:     }
10928:     close (OUT);
10929:     return 'ok';
10930: }
10931: 
10932: sub clear_selected_files {
10933:     my ($user) = @_;
10934:     my $filename = $user."savedfiles";
10935:     open (OUT,'>',LONCAPA::tempdir().$filename);
10936:     print (OUT undef);
10937:     close (OUT);
10938:     return ("ok");    
10939: }
10940: 
10941: sub files_in_path {
10942:     my ($user, $path) = @_;
10943:     my $filename = $user."savedfiles";
10944:     my %return_files;
10945:     open (IN,'<',LONCAPA::tempdir().$filename);
10946:     while (my $line_in = <IN>) {
10947:         chomp ($line_in);
10948:         my @paths_and_file = split (m!/!, $line_in);
10949:         my $file_part = pop (@paths_and_file);
10950:         my $path_part = join ('/', @paths_and_file);
10951:         $path_part.='/';
10952:         my $path_and_file = $path_part.$file_part;
10953:         if ($path_part eq $path) {
10954:             $return_files{$file_part}= 'selected';
10955:         }
10956:     }
10957:     close (IN);
10958:     return (\%return_files);
10959: }
10960: 
10961: # called in portfolio select mode, to show files selected NOT in current directory
10962: sub files_not_in_path {
10963:     my ($user, $path) = @_;
10964:     my $filename = $user."savedfiles";
10965:     my @return_files;
10966:     my $path_part;
10967:     open(IN, '<',LONCAPA::tempdir().$filename);
10968:     while (my $line = <IN>) {
10969:         #ok, I know it's clunky, but I want it to work
10970:         my @paths_and_file = split(m|/|, $line);
10971:         my $file_part = pop(@paths_and_file);
10972:         chomp($file_part);
10973:         my $path_part = join('/', @paths_and_file);
10974:         $path_part .= '/';
10975:         my $path_and_file = $path_part.$file_part;
10976:         if ($path_part ne $path) {
10977:             push(@return_files, ($path_and_file));
10978:         }
10979:     }
10980:     close(OUT);
10981:     return (@return_files);
10982: }
10983: 
10984: #------------------------------Submitted/Handedback Portfolio Files Versioning
10985:  
10986: sub portfiles_versioning {
10987:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10988:     my $portfolio_root = '/userfiles/portfolio';
10989:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10990:     foreach my $file (@{$portfiles}) {
10991:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10992:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10993:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10994:         my $getpropath = 1;
10995:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10996:                                              $stu_name,$getpropath);
10997:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10998:         my $new_answer = 
10999:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11000:         if ($new_answer ne 'problem getting file') {
11001:             push(@{$versioned_portfiles}, $directory.$new_answer);
11002:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11003:                               [$symb,$env{'request.course.id'},'graded']);
11004:         }
11005:     }
11006: }
11007: 
11008: sub get_next_version {
11009:     my ($answer_name, $answer_ext, $dir_list) = @_;
11010:     my $version;
11011:     if (ref($dir_list) eq 'ARRAY') {
11012:         foreach my $row (@{$dir_list}) {
11013:             my ($file) = split(/\&/,$row,2);
11014:             my ($file_name,$file_version,$file_ext) =
11015:                 &file_name_version_ext($file);
11016:             if (($file_name eq $answer_name) &&
11017:                 ($file_ext eq $answer_ext)) {
11018:                      # gets here if filename and extension match,
11019:                      # regardless of version
11020:                 if ($file_version ne '') {
11021:                     # a versioned file is found  so save it for later
11022:                     if ($file_version > $version) {
11023:                         $version = $file_version;
11024:                     }
11025:                 }
11026:             }
11027:         }
11028:     }
11029:     $version ++;
11030:     return($version);
11031: }
11032: 
11033: sub version_selected_portfile {
11034:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11035:     my ($answer_name,$answer_ver,$answer_ext) =
11036:         &file_name_version_ext($file_name);
11037:     my $new_answer;
11038:     $env{'form.copy'} =
11039:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11040:     if($env{'form.copy'} eq '-1') {
11041:         $new_answer = 'problem getting file';
11042:     } else {
11043:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11044:         my $copy_result = 
11045:             &finishuserfileupload($stu_name,$domain,'copy',
11046:                                   '/portfolio'.$directory.$new_answer);
11047:     }
11048:     undef($env{'form.copy'});
11049:     return ($new_answer);
11050: }
11051: 
11052: sub file_name_version_ext {
11053:     my ($file)=@_;
11054:     my @file_parts = split(/\./, $file);
11055:     my ($name,$version,$ext);
11056:     if (@file_parts > 1) {
11057:         $ext=pop(@file_parts);
11058:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11059:             $version=pop(@file_parts);
11060:         }
11061:         $name=join('.',@file_parts);
11062:     } else {
11063:         $name=join('.',@file_parts);
11064:     }
11065:     return($name,$version,$ext);
11066: }
11067: 
11068: #----------------------------------------------Get portfolio file permissions
11069: 
11070: sub get_portfile_permissions {
11071:     my ($domain,$user) = @_;
11072:     my %current_permissions = &dump('file_permissions',$domain,$user);
11073:     my ($tmp)=keys(%current_permissions);
11074:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11075:     return \%current_permissions;
11076: }
11077: 
11078: #---------------------------------------------Get portfolio file access controls
11079: 
11080: sub get_access_controls {
11081:     my ($current_permissions,$group,$file) = @_;
11082:     my %access;
11083:     my $real_file = $file;
11084:     $file =~ s/\.meta$//;
11085:     if (defined($file)) {
11086:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11087:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11088:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11089:             }
11090:         }
11091:     } else {
11092:         foreach my $key (keys(%{$current_permissions})) {
11093:             if ($key =~ /\0accesscontrol$/) {
11094:                 if (defined($group)) {
11095:                     if ($key !~ m-^\Q$group\E/-) {
11096:                         next;
11097:                     }
11098:                 }
11099:                 my ($fullpath) = split(/\0/,$key);
11100:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11101:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11102:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11103:                     }
11104:                 }
11105:             }
11106:         }
11107:     }
11108:     return %access;
11109: }
11110: 
11111: sub modify_access_controls {
11112:     my ($file_name,$changes,$domain,$user)=@_;
11113:     my ($outcome,$deloutcome);
11114:     my %store_permissions;
11115:     my %new_values;
11116:     my %new_control;
11117:     my %translation;
11118:     my @deletions = ();
11119:     my $now = time;
11120:     if (exists($$changes{'activate'})) {
11121:         if (ref($$changes{'activate'}) eq 'HASH') {
11122:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11123:             my $numnew = scalar(@newitems);
11124:             for (my $i=0; $i<$numnew; $i++) {
11125:                 my $newkey = $newitems[$i];
11126:                 my $newid = &Apache::loncommon::get_cgi_id();
11127:                 if ($newkey =~ /^\d+:/) { 
11128:                     $newkey =~ s/^(\d+)/$newid/;
11129:                     $translation{$1} = $newid;
11130:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11131:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11132:                     $translation{$1} = $newid;
11133:                 }
11134:                 $new_values{$file_name."\0".$newkey} = 
11135:                                           $$changes{'activate'}{$newitems[$i]};
11136:                 $new_control{$newkey} = $now;
11137:             }
11138:         }
11139:     }
11140:     my %todelete;
11141:     my %changed_items;
11142:     foreach my $action ('delete','update') {
11143:         if (exists($$changes{$action})) {
11144:             if (ref($$changes{$action}) eq 'HASH') {
11145:                 foreach my $key (keys(%{$$changes{$action}})) {
11146:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11147:                     if ($action eq 'delete') { 
11148:                         $todelete{$itemnum} = 1;
11149:                     } else {
11150:                         $changed_items{$itemnum} = $key;
11151:                     }
11152:                 }
11153:             }
11154:         }
11155:     }
11156:     # get lock on access controls for file.
11157:     my $lockhash = {
11158:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11159:                                                        ':'.$env{'user.domain'},
11160:                    }; 
11161:     my $tries = 0;
11162:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11163:    
11164:     while (($gotlock ne 'ok') && $tries < 10) {
11165:         $tries ++;
11166:         sleep(0.1);
11167:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11168:     }
11169:     if ($gotlock eq 'ok') {
11170:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11171:         my ($tmp)=keys(%curr_permissions);
11172:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11173:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11174:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11175:             if (ref($curr_controls) eq 'HASH') {
11176:                 foreach my $control_item (keys(%{$curr_controls})) {
11177:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11178:                     if (defined($todelete{$itemnum})) {
11179:                         push(@deletions,$file_name."\0".$control_item);
11180:                     } else {
11181:                         if (defined($changed_items{$itemnum})) {
11182:                             $new_control{$changed_items{$itemnum}} = $now;
11183:                             push(@deletions,$file_name."\0".$control_item);
11184:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11185:                         } else {
11186:                             $new_control{$control_item} = $$curr_controls{$control_item};
11187:                         }
11188:                     }
11189:                 }
11190:             }
11191:         }
11192:         my ($group);
11193:         if (&is_course($domain,$user)) {
11194:             ($group,my $file) = split(/\//,$file_name,2);
11195:         }
11196:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11197:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11198:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11199:         #  remove lock
11200:         my @del_lock = ($file_name."\0".'locked_access_records');
11201:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11202:         my $sqlresult =
11203:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11204:                                     $group);
11205:     } else {
11206:         $outcome = "error: could not obtain lockfile\n";  
11207:     }
11208:     return ($outcome,$deloutcome,\%new_values,\%translation);
11209: }
11210: 
11211: sub make_public_indefinitely {
11212:     my (@requrl) = @_;
11213:     return &automated_portfile_access('public',\@requrl);
11214: }
11215: 
11216: sub automated_portfile_access {
11217:     my ($accesstype,$addsref,$delsref,$info) = @_;
11218:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11219:         return 'invalid';
11220:     }
11221:     my %urls;
11222:     if (ref($addsref) eq 'ARRAY') {
11223:         foreach my $requrl (@{$addsref}) {
11224:             if (&is_portfolio_url($requrl)) {
11225:                 unless (exists($urls{$requrl})) {
11226:                     $urls{$requrl} = 'add';
11227:                 }
11228:             }
11229:         }
11230:     }
11231:     if (ref($delsref) eq 'ARRAY') {
11232:         foreach my $requrl (@{$delsref}) { 
11233:             if (&is_portfolio_url($requrl)) {
11234:                 unless (exists($urls{$requrl})) {
11235:                     $urls{$requrl} = 'delete'; 
11236:                 }
11237:             }
11238:         }
11239:     }
11240:     unless (keys(%urls)) {
11241:         return 'invalid';
11242:     }
11243:     my $ip;
11244:     if ($accesstype eq 'ip') {
11245:         if (ref($info) eq 'HASH') {
11246:             if ($info->{'ip'} ne '') {
11247:                 $ip = $info->{'ip'};
11248:             }
11249:         }
11250:         if ($ip eq '') {
11251:             return 'invalid';
11252:         }
11253:     }
11254:     my $errors;
11255:     my $now = time;
11256:     my %current_perms;
11257:     foreach my $requrl (sort(keys(%urls))) {
11258:         my $action;
11259:         if ($urls{$requrl} eq 'add') {
11260:             $action = 'activate';
11261:         } else {
11262:             $action = 'none';
11263:         }
11264:         my $aclnum = 0;
11265:         my (undef,$udom,$unum,$file_name,$group) =
11266:             &parse_portfolio_url($requrl);
11267:         unless (exists($current_perms{$unum.':'.$udom})) {
11268:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11269:         }
11270:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11271:                                                    $group,$file_name);
11272:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11273:             my ($num,$scope,$end,$start) = 
11274:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11275:             if ($scope eq $accesstype) {
11276:                 if (($start <= $now) && ($end == 0)) {
11277:                     if ($accesstype eq 'ip') {
11278:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11279:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11280:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11281:                                     if ($urls{$requrl} eq 'add') {
11282:                                         $action = 'none';
11283:                                         last;
11284:                                     } else {
11285:                                         $action = 'delete';
11286:                                         $aclnum = $num;
11287:                                         last;
11288:                                     }
11289:                                 }
11290:                             }
11291:                         }
11292:                     } elsif ($accesstype eq 'public') {
11293:                         if ($urls{$requrl} eq 'add') {
11294:                             $action = 'none';
11295:                             last;
11296:                         } else {
11297:                             $action = 'delete';
11298:                             $aclnum = $num;
11299:                             last;
11300:                         }
11301:                     }
11302:                 } elsif ($accesstype eq 'public') {
11303:                     $action = 'update';
11304:                     $aclnum = $num;
11305:                     last;
11306:                 }
11307:             }
11308:         }
11309:         if ($action eq 'none') {
11310:             next;
11311:         } else {
11312:             my %changes;
11313:             my $newend = 0;
11314:             my $newstart = $now;
11315:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11316:             $changes{$action}{$newkey} = {
11317:                 type => $accesstype,
11318:                 time => {
11319:                     start => $newstart,
11320:                     end   => $newend,
11321:                 },
11322:             };
11323:             if ($accesstype eq 'ip') {
11324:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11325:             }
11326:             my ($outcome,$deloutcome,$new_values,$translation) =
11327:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11328:             unless ($outcome eq 'ok') {
11329:                 $errors .= $outcome.' ';
11330:             }
11331:         }
11332:     }
11333:     if ($errors) {
11334:         $errors =~ s/\s$//;
11335:         return $errors;
11336:     } else {
11337:         return 'ok';
11338:     }
11339: }
11340: 
11341: #------------------------------------------------------Get Marked as Read Only
11342: 
11343: sub get_marked_as_readonly {
11344:     my ($domain,$user,$what,$group) = @_;
11345:     my $current_permissions = &get_portfile_permissions($domain,$user);
11346:     my @readonly_files;
11347:     my $cmp1=$what;
11348:     if (ref($what)) { $cmp1=join('',@{$what}) };
11349:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11350:         if (defined($group)) {
11351:             if ($file_name !~ m-^\Q$group\E/-) {
11352:                 next;
11353:             }
11354:         }
11355:         if (ref($value) eq "ARRAY"){
11356:             foreach my $stored_what (@{$value}) {
11357:                 my $cmp2=$stored_what;
11358:                 if (ref($stored_what) eq 'ARRAY') {
11359:                     $cmp2=join('',@{$stored_what});
11360:                 }
11361:                 if ($cmp1 eq $cmp2) {
11362:                     push(@readonly_files, $file_name);
11363:                     last;
11364:                 } elsif (!defined($what)) {
11365:                     push(@readonly_files, $file_name);
11366:                     last;
11367:                 }
11368:             }
11369:         }
11370:     }
11371:     return @readonly_files;
11372: }
11373: #-----------------------------------------------------------Get Marked as Read Only Hash
11374: 
11375: sub get_marked_as_readonly_hash {
11376:     my ($current_permissions,$group,$what) = @_;
11377:     my %readonly_files;
11378:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11379:         if (defined($group)) {
11380:             if ($file_name !~ m-^\Q$group\E/-) {
11381:                 next;
11382:             }
11383:         }
11384:         if (ref($value) eq "ARRAY"){
11385:             foreach my $stored_what (@{$value}) {
11386:                 if (ref($stored_what) eq 'ARRAY') {
11387:                     foreach my $lock_descriptor(@{$stored_what}) {
11388:                         if ($lock_descriptor eq 'graded') {
11389:                             $readonly_files{$file_name} = 'graded';
11390:                         } elsif ($lock_descriptor eq 'handback') {
11391:                             $readonly_files{$file_name} = 'handback';
11392:                         } else {
11393:                             if (!exists($readonly_files{$file_name})) {
11394:                                 $readonly_files{$file_name} = 'locked';
11395:                             }
11396:                         }
11397:                     }
11398:                 } 
11399:             }
11400:         } 
11401:     }
11402:     return %readonly_files;
11403: }
11404: # ------------------------------------------------------------ Unmark as Read Only
11405: 
11406: sub unmark_as_readonly {
11407:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11408:     # for portfolio submissions, $what contains [$symb,$crsid] 
11409:     my ($domain,$user,$what,$file_name,$group) = @_;
11410:     $file_name = &declutter_portfile($file_name);
11411:     my $symb_crs = $what;
11412:     if (ref($what)) { $symb_crs=join('',@$what); }
11413:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11414:     my ($tmp)=keys(%current_permissions);
11415:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11416:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11417:     foreach my $file (@readonly_files) {
11418: 	my $clean_file = &declutter_portfile($file);
11419: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11420: 	my $current_locks = $current_permissions{$file};
11421:         my @new_locks;
11422:         my @del_keys;
11423:         if (ref($current_locks) eq "ARRAY"){
11424:             foreach my $locker (@{$current_locks}) {
11425:                 my $compare=$locker;
11426:                 if (ref($locker) eq 'ARRAY') {
11427:                     $compare=join('',@{$locker});
11428:                     if ($compare ne $symb_crs) {
11429:                         push(@new_locks, $locker);
11430:                     }
11431:                 }
11432:             }
11433:             if (scalar(@new_locks) > 0) {
11434:                 $current_permissions{$file} = \@new_locks;
11435:             } else {
11436:                 push(@del_keys, $file);
11437:                 &del('file_permissions',\@del_keys, $domain, $user);
11438:                 delete($current_permissions{$file});
11439:             }
11440:         }
11441:     }
11442:     &put('file_permissions',\%current_permissions,$domain,$user);
11443:     return;
11444: }
11445: 
11446: # ------------------------------------------------------------ Directory lister
11447: 
11448: sub dirlist {
11449:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11450:     $uri=~s/^\///;
11451:     $uri=~s/\/$//;
11452:     my ($udom, $uname);
11453:     if ($getuserdir) {
11454:         $udom = $userdomain;
11455:         $uname = $username;
11456:     } else {
11457:         (undef,$udom,$uname)=split(/\//,$uri);
11458:         if(defined($userdomain)) {
11459:             $udom = $userdomain;
11460:         }
11461:         if(defined($username)) {
11462:             $uname = $username;
11463:         }
11464:     }
11465:     my ($dirRoot,$listing,@listing_results);
11466: 
11467:     $dirRoot = $perlvar{'lonDocRoot'};
11468:     if (defined($getpropath)) {
11469:         $dirRoot = &propath($udom,$uname);
11470:         $dirRoot =~ s/\/$//;
11471:     } elsif (defined($getuserdir)) {
11472:         my $subdir=$uname.'__';
11473:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11474:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11475:                    ."/$udom/$subdir/$uname";
11476:     } elsif (defined($alternateRoot)) {
11477:         $dirRoot = $alternateRoot;
11478:     }
11479: 
11480:     if($udom) {
11481:         if($uname) {
11482:             my $uhome = &homeserver($uname,$udom);
11483:             if ($uhome eq 'no_host') {
11484:                 return ([],'no_host');
11485:             }
11486:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11487:                               .$getuserdir.':'.&escape($dirRoot)
11488:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11489:             if ($listing eq 'unknown_cmd') {
11490:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11491:             } else {
11492:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11493:             }
11494:             if ($listing eq 'unknown_cmd') {
11495:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11496:                 @listing_results = split(/:/,$listing);
11497:             } else {
11498:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11499:             }
11500:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11501:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11502:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11503:                 return ([],$listing);
11504:             } else {
11505:                 return (\@listing_results);
11506:             }
11507:         } elsif(!$alternateRoot) {
11508:             my (%allusers,%listerror);
11509: 	    my %servers = &get_servers($udom,'library');
11510:  	    foreach my $tryserver (keys(%servers)) {
11511:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11512:                                   &escape($udom),$tryserver);
11513:                 if ($listing eq 'unknown_cmd') {
11514: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11515: 				      $udom, $tryserver);
11516:                 } else {
11517:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11518:                 }
11519: 		if ($listing eq 'unknown_cmd') {
11520: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11521: 				      $udom, $tryserver);
11522: 		    @listing_results = split(/:/,$listing);
11523: 		} else {
11524: 		    @listing_results =
11525: 			map { &unescape($_); } split(/:/,$listing);
11526: 		}
11527:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11528:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11529:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11530:                     $listerror{$tryserver} = $listing;
11531:                 } else {
11532: 		    foreach my $line (@listing_results) {
11533: 			my ($entry) = split(/&/,$line,2);
11534: 			$allusers{$entry} = 1;
11535: 		    }
11536: 		}
11537:             }
11538:             my @alluserslist=();
11539:             foreach my $user (sort(keys(%allusers))) {
11540:                 push(@alluserslist,$user.'&user');
11541:             }
11542: 
11543:             if (!%listerror) {
11544:                 # no errors
11545:                 return (\@alluserslist);
11546:             } elsif (scalar(keys(%servers)) == 1) {
11547:                 # one library server, one error 
11548:                 my ($key) = keys(%listerror);
11549:                 return (\@alluserslist, $listerror{$key});
11550:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11551:                 # con_lost indicates that we might miss data from at least one
11552:                 # library server
11553:                 return (\@alluserslist, 'con_lost');
11554:             } else {
11555:                 # multiple library servers and no con_lost -> data should be
11556:                 # complete. 
11557:                 return (\@alluserslist);
11558:             }
11559: 
11560:         } else {
11561:             return ([],'missing username');
11562:         }
11563:     } elsif(!defined($getpropath)) {
11564:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11565:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11566:         return (\@all_domains);
11567:     } else {
11568:         return ([],'missing domain');
11569:     }
11570: }
11571: 
11572: # --------------------------------------------- GetFileTimestamp
11573: # This function utilizes dirlist and returns the date stamp for
11574: # when it was last modified.  It will also return an error of -1
11575: # if an error occurs
11576: 
11577: sub GetFileTimestamp {
11578:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11579:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11580:     $studentName   = &LONCAPA::clean_username($studentName);
11581:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11582:                                     undef,$getuserdir);
11583:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11584:         return -1;
11585:     }
11586:     if (ref($fileref) eq 'ARRAY') {
11587:         my @stats = split('&',$fileref->[0]);
11588:         # @stats contains first the filename, then the stat output
11589:         return $stats[10]; # so this is 10 instead of 9.
11590:     } else {
11591:         return -1;
11592:     }
11593: }
11594: 
11595: sub stat_file {
11596:     my ($uri) = @_;
11597:     $uri = &clutter_with_no_wrapper($uri);
11598: 
11599:     my ($udom,$uname,$file);
11600:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11601: 	($udom,$uname,$file) =
11602: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11603: 	$file = 'userfiles/'.$file;
11604:     }
11605:     if ($uri =~ m-^/res/-) {
11606: 	($udom,$uname) = 
11607: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11608: 	$file = $uri;
11609:     }
11610: 
11611:     if (!$udom || !$uname || !$file) {
11612: 	# unable to handle the uri
11613: 	return ();
11614:     }
11615:     my $getpropath;
11616:     if ($file =~ /^userfiles\//) {
11617:         $getpropath = 1;
11618:     }
11619:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11620:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11621:         return ();
11622:     } else {
11623:         if (ref($listref) eq 'ARRAY') {
11624:             my @stats = split('&',$listref->[0]);
11625: 	    shift(@stats); #filename is first
11626: 	    return @stats;
11627:         }
11628:     }
11629:     return ();
11630: }
11631: 
11632: # --------------------------------------------------------- recursedirs
11633: # Recursive function to traverse either a specific user's Authoring Space
11634: # or corresponding Published Resource Space, and populate the hash ref:
11635: # $dirhashref with URLs of all directories, and if $filehashref hash
11636: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11637: # or .rights files in resource space, and .meta, .save, .log, and .bak
11638: # files in Authoring Space.
11639: #
11640: # Inputs:
11641: #
11642: # $is_home - true if current server is home server for user's space
11643: # $context - either: priv, or res respectively for Authoring or Resource Space.
11644: # $docroot - Document root (i.e., /home/httpd/html
11645: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11646: # $relpath - Current path (relative to top level).
11647: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11648: # $filehashref - reference to hash to populate with URLs of files (Optional)
11649: #
11650: # Returns: nothing
11651: #
11652: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11653: #
11654: # Currently used by interface/londocs.pm to create linked select boxes for
11655: # directory and filename to import a Course "Author" resource into a course, and
11656: # also to create linked select boxes for Authoring Space and Directory to choose
11657: # save location for creation of a new "standard" problem from the Course Editor.
11658: #
11659: 
11660: sub recursedirs {
11661:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11662:     return unless (ref($dirhashref) eq 'HASH');
11663:     my $currpath = $docroot.$toppath;
11664:     if ($relpath) {
11665:         $currpath .= "/$relpath";
11666:     }
11667:     my $savefile;
11668:     if (ref($filehashref)) {
11669:         $savefile = 1;
11670:     }
11671:     if ($is_home) {
11672:         if (opendir(my $dirh,$currpath)) {
11673:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11674:                 next if ($item eq '');
11675:                 if (-d "$currpath/$item") {
11676:                     my $newpath;
11677:                     if ($relpath) {
11678:                         $newpath = "$relpath/$item";
11679:                     } else {
11680:                         $newpath = $item;
11681:                     }
11682:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11683:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11684:                 } elsif ($savefile) {
11685:                     if ($context eq 'priv') {
11686:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11687:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11688:                         }
11689:                     } else {
11690:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11691:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11692:                         }
11693:                     }
11694:                 }
11695:             }
11696:             closedir($dirh);
11697:         }
11698:     } else {
11699:         my ($dirlistref,$listerror) =
11700:             &dirlist($toppath.$relpath);
11701:         my @dir_lines;
11702:         my $dirptr=16384;
11703:         if (ref($dirlistref) eq 'ARRAY') {
11704:             foreach my $dir_line (sort
11705:                               {
11706:                                   my ($afile)=split('&',$a,2);
11707:                                   my ($bfile)=split('&',$b,2);
11708:                                   return (lc($afile) cmp lc($bfile));
11709:                               } (@{$dirlistref})) {
11710:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11711:                     split(/\&/,$dir_line,16);
11712:                 $item =~ s/\s+$//;
11713:                 next if (($item =~ /^\.\.?$/) || ($obs));
11714:                 if ($dirptr&$testdir) {
11715:                     my $newpath;
11716:                     if ($relpath) {
11717:                         $newpath = "$relpath/$item";
11718:                     } else {
11719:                         $relpath = '/';
11720:                         $newpath = $item;
11721:                     }
11722:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11723:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11724:                 } elsif ($savefile) {
11725:                     if ($context eq 'priv') {
11726:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11727:                             $filehashref->{$relpath}{$item} = 1;
11728:                         }
11729:                     } else {
11730:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11731:                             $filehashref->{$relpath}{$item} = 1;
11732:                         }
11733:                     }
11734:                 }
11735:             }
11736:         }
11737:     }
11738:     return;
11739: }
11740: 
11741: # -------------------------------------------------------- Value of a Condition
11742: 
11743: # gets the value of a specific preevaluated condition
11744: #    stored in the string  $env{user.state.<cid>}
11745: # or looks up a condition reference in the bighash and if if hasn't
11746: # already been evaluated recurses into docondval to get the value of
11747: # the condition, then memoizing it to 
11748: #   $env{user.state.<cid>.<condition>}
11749: sub directcondval {
11750:     my $number=shift;
11751:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11752: 	&Apache::lonuserstate::evalstate();
11753:     }
11754:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11755: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11756:     } elsif ($number =~ /^_/) {
11757: 	my $sub_condition;
11758: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11759: 		&GDBM_READER(),0640)) {
11760: 	    $sub_condition=$bighash{'conditions'.$number};
11761: 	    untie(%bighash);
11762: 	}
11763: 	my $value = &docondval($sub_condition);
11764: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11765: 	return $value;
11766:     }
11767:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11768:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11769:     } else {
11770:        return 2;
11771:     }
11772: }
11773: 
11774: # get the collection of conditions for this resource
11775: sub condval {
11776:     my $condidx=shift;
11777:     my $allpathcond='';
11778:     foreach my $cond (split(/\|/,$condidx)) {
11779: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11780: 	    $allpathcond.=
11781: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11782: 	}
11783:     }
11784:     $allpathcond=~s/\|$//;
11785:     return &docondval($allpathcond);
11786: }
11787: 
11788: #evaluates an expression of conditions
11789: sub docondval {
11790:     my ($allpathcond) = @_;
11791:     my $result=0;
11792:     if ($env{'request.course.id'}
11793: 	&& defined($allpathcond)) {
11794: 	my $operand='|';
11795: 	my @stack;
11796: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11797: 	    if ($chunk eq '(') {
11798: 		push @stack,($operand,$result);
11799: 	    } elsif ($chunk eq ')') {
11800: 		my $before=pop @stack;
11801: 		if (pop @stack eq '&') {
11802: 		    $result=$result>$before?$before:$result;
11803: 		} else {
11804: 		    $result=$result>$before?$result:$before;
11805: 		}
11806: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11807: 		$operand=$chunk;
11808: 	    } else {
11809: 		my $new=directcondval($chunk);
11810: 		if ($operand eq '&') {
11811: 		    $result=$result>$new?$new:$result;
11812: 		} else {
11813: 		    $result=$result>$new?$result:$new;
11814: 		}
11815: 	    }
11816: 	}
11817:     }
11818:     return $result;
11819: }
11820: 
11821: # ---------------------------------------------------- Devalidate courseresdata
11822: 
11823: sub devalidatecourseresdata {
11824:     my ($coursenum,$coursedomain)=@_;
11825:     my $hashid=$coursenum.':'.$coursedomain;
11826:     &devalidate_cache_new('courseres',$hashid);
11827: }
11828: 
11829: 
11830: # --------------------------------------------------- Course Resourcedata Query
11831: #
11832: #  Parameters:
11833: #      $coursenum    - Number of the course.
11834: #      $coursedomain - Domain at which the course was created.
11835: #  Returns:
11836: #     A hash of the course parameters along (I think) with timestamps
11837: #     and version info.
11838: 
11839: sub get_courseresdata {
11840:     my ($coursenum,$coursedomain)=@_;
11841:     my $coursehom=&homeserver($coursenum,$coursedomain);
11842:     my $hashid=$coursenum.':'.$coursedomain;
11843:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11844:     my %dumpreply;
11845:     unless (defined($cached)) {
11846: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11847: 	$result=\%dumpreply;
11848: 	my ($tmp) = keys(%dumpreply);
11849: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11850: 	    &do_cache_new('courseres',$hashid,$result,600);
11851: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11852: 	    return $tmp;
11853: 	} elsif ($tmp =~ /^(error)/) {
11854: 	    $result=undef;
11855: 	    &do_cache_new('courseres',$hashid,$result,600);
11856: 	}
11857:     }
11858:     return $result;
11859: }
11860: 
11861: sub devalidateuserresdata {
11862:     my ($uname,$udom)=@_;
11863:     my $hashid="$udom:$uname";
11864:     &devalidate_cache_new('userres',$hashid);
11865: }
11866: 
11867: sub get_userresdata {
11868:     my ($uname,$udom)=@_;
11869:     #most student don\'t have any data set, check if there is some data
11870:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11871: 
11872:     my $hashid="$udom:$uname";
11873:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11874:     if (!defined($cached)) {
11875: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11876: 	$result=\%resourcedata;
11877: 	&do_cache_new('userres',$hashid,$result,600);
11878:     }
11879:     my ($tmp)=keys(%$result);
11880:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11881: 	return $result;
11882:     }
11883:     #error 2 occurs when the .db doesn't exist
11884:     if ($tmp!~/error: 2 /) {
11885:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11886: 	    &logthis("<font color=\"blue\">WARNING:".
11887: 		     " Trying to get resource data for ".
11888: 		     $uname." at ".$udom.": ".
11889: 		     $tmp."</font>");
11890:         }
11891:     } elsif ($tmp=~/error: 2 /) {
11892: 	#&EXT_cache_set($udom,$uname);
11893: 	&do_cache_new('userres',$hashid,undef,600);
11894: 	undef($tmp); # not really an error so don't send it back
11895:     }
11896:     return $tmp;
11897: }
11898: #----------------------------------------------- resdata - return resource data
11899: #  Purpose:
11900: #    Return resource data for either users or for a course.
11901: #  Parameters:
11902: #     $name      - Course/user name.
11903: #     $domain    - Name of the domain the user/course is registered on.
11904: #     $type      - Type of thing $name is (must be 'course' or 'user')
11905: #     $mapp      - decluttered URL of enclosing map  
11906: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11907: #     $recurseup - Ref to array of map URLs, starting with map containing
11908: #                  $mapp up through hierarchy of nested maps to top level map.  
11909: #     $courseid  - CourseID (first part of param identifier).
11910: #     $modifier  - Middle part of param identifier.
11911: #     $what      - Last part of param identifier.
11912: #     @which     - Array of names of resources desired.
11913: #  Returns:
11914: #     The value of the first reasource in @which that is found in the
11915: #     resource hash.
11916: #  Exceptional Conditions:
11917: #     If the $type passed in is not valid (not the string 'course' or 
11918: #     'user', an undefined  reference is returned.
11919: #     If none of the resources are found, an undef is returned
11920: sub resdata {
11921:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11922:         $modifier,$what,@which)=@_;
11923:     my $result;
11924:     if ($type eq 'course') {
11925: 	$result=&get_courseresdata($name,$domain);
11926:     } elsif ($type eq 'user') {
11927: 	$result=&get_userresdata($name,$domain);
11928:     }
11929:     if (!ref($result)) { return $result; }    
11930:     foreach my $item (@which) {
11931:         if ($item->[1] eq 'course') {
11932:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11933:                 unless ($$recursed) {
11934:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11935:                     $$recursed = 1;
11936:                 }
11937:                 foreach my $item (@${recurseup}) {
11938:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11939:                     last if (defined($result->{$norecursechk}));
11940:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11941:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11942:                 }
11943:             }
11944:         }
11945:         if (defined($result->{$item->[0]})) {
11946: 	    return [$result->{$item->[0]},$item->[1]];
11947: 	}
11948:     }
11949:     return undef;
11950: }
11951: 
11952: sub get_domain_lti {
11953:     my ($cdom,$context) = @_;
11954:     my ($name,%lti);
11955:     if ($context eq 'consumer') {
11956:         $name = 'ltitools';
11957:     } elsif ($context eq 'provider') {
11958:         $name = 'lti';
11959:     } else {
11960:         return %lti;
11961:     }
11962:     my ($result,$cached)=&is_cached_new($name,$cdom);
11963:     if (defined($cached)) {
11964:         if (ref($result) eq 'HASH') {
11965:             %lti = %{$result};
11966:         }
11967:     } else {
11968:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11969:         if (ref($domconfig{$name}) eq 'HASH') {
11970:             %lti = %{$domconfig{$name}};
11971:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11972:             if (ref($encdomconfig{$name}) eq 'HASH') {
11973:                 foreach my $id (keys(%lti)) {
11974:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11975:                         foreach my $item ('key','secret') {
11976:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11977:                         }
11978:                     }
11979:                 }
11980:             }
11981:         }
11982:         my $cachetime = 24*60*60;
11983:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11984:     }
11985:     return %lti;
11986: }
11987: 
11988: sub get_numsuppfiles {
11989:     my ($cnum,$cdom,$ignorecache)=@_;
11990:     my $hashid=$cnum.':'.$cdom;
11991:     my ($suppcount,$cached);
11992:     unless ($ignorecache) {
11993:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11994:     }
11995:     unless (defined($cached)) {
11996:         my $chome=&homeserver($cnum,$cdom);
11997:         unless ($chome eq 'no_host') {
11998:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11999:             my $suppmap = 'supplemental.sequence';
12000:             ($suppcount,$supptools,$errors) =
12001:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12002:                                                          $supptools,$errors);
12003:         }
12004:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12005:     }
12006:     return $suppcount;
12007: }
12008: 
12009: #
12010: # EXT resource caching routines
12011: #
12012: 
12013: {
12014: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12015: #
12016: # The course for which we cache
12017: my $cachedmapkey='';
12018: # The cached recursive maps for this course
12019: my %cachedmaps=();
12020: # When this was last done
12021: my $cachedmaptime='';
12022: 
12023: sub clear_EXT_cache_status {
12024:     &delenv('cache.EXT.');
12025: }
12026: 
12027: sub EXT_cache_status {
12028:     my ($target_domain,$target_user) = @_;
12029:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12030:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12031:         # We know already the user has no data
12032:         return 1;
12033:     } else {
12034:         return 0;
12035:     }
12036: }
12037: 
12038: sub EXT_cache_set {
12039:     my ($target_domain,$target_user) = @_;
12040:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12041:     #&appenv({$cachename => time});
12042: }
12043: 
12044: # --------------------------------------------------------- Value of a Variable
12045: sub EXT {
12046: 
12047:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12048:     unless ($varname) { return ''; }
12049:     #get real user name/domain, courseid and symb
12050:     my $courseid;
12051:     my $publicuser;
12052:     if ($symbparm) {
12053: 	$symbparm=&get_symb_from_alias($symbparm);
12054:     }
12055:     if (!($uname && $udom)) {
12056:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12057:       if (!$symbparm) {	$symbparm=$cursymb; }
12058:     } else {
12059: 	$courseid=$env{'request.course.id'};
12060:     }
12061:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12062:     my $rest;
12063:     if (defined($therest[0])) {
12064:        $rest=join('.',@therest);
12065:     } else {
12066:        $rest='';
12067:     }
12068: 
12069:     my $qualifierrest=$qualifier;
12070:     if ($rest) { $qualifierrest.='.'.$rest; }
12071:     my $spacequalifierrest=$space;
12072:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12073:     if ($realm eq 'user') {
12074: # --------------------------------------------------------------- user.resource
12075: 	if ($space eq 'resource') {
12076: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12077: 		  || defined($Apache::lonhomework::parsing_a_task))
12078: 		 &&
12079: 		 ($symbparm eq &symbread()) ) {	
12080: 		# if we are in the middle of processing the resource the
12081: 		# get the value we are planning on committing
12082:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12083:                     return $Apache::lonhomework::results{$qualifierrest};
12084:                 } else {
12085:                     return $Apache::lonhomework::history{$qualifierrest};
12086:                 }
12087: 	    } else {
12088: 		my %restored;
12089: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12090: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12091: 		} else {
12092: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12093: 		}
12094: 		return $restored{$qualifierrest};
12095: 	    }
12096: # ----------------------------------------------------------------- user.access
12097:         } elsif ($space eq 'access') {
12098: 	    # FIXME - not supporting calls for a specific user
12099:             return &allowed($qualifier,$rest);
12100: # ------------------------------------------ user.preferences, user.environment
12101:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12102: 	    if (($uname eq $env{'user.name'}) &&
12103: 		($udom eq $env{'user.domain'})) {
12104: 		return $env{join('.',('environment',$qualifierrest))};
12105: 	    } else {
12106: 		my %returnhash;
12107: 		if (!$publicuser) {
12108: 		    %returnhash=&userenvironment($udom,$uname,
12109: 						 $qualifierrest);
12110: 		}
12111: 		return $returnhash{$qualifierrest};
12112: 	    }
12113: # ----------------------------------------------------------------- user.course
12114:         } elsif ($space eq 'course') {
12115: 	    # FIXME - not supporting calls for a specific user
12116:             return $env{join('.',('request.course',$qualifier))};
12117: # ------------------------------------------------------------------- user.role
12118:         } elsif ($space eq 'role') {
12119: 	    # FIXME - not supporting calls for a specific user
12120:             my ($role,$where)=split(/\./,$env{'request.role'});
12121:             if ($qualifier eq 'value') {
12122: 		return $role;
12123:             } elsif ($qualifier eq 'extent') {
12124:                 return $where;
12125:             }
12126: # ----------------------------------------------------------------- user.domain
12127:         } elsif ($space eq 'domain') {
12128:             return $udom;
12129: # ------------------------------------------------------------------- user.name
12130:         } elsif ($space eq 'name') {
12131:             return $uname;
12132: # ---------------------------------------------------- Any other user namespace
12133:         } else {
12134: 	    my %reply;
12135: 	    if (!$publicuser) {
12136: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12137: 	    }
12138: 	    return $reply{$qualifierrest};
12139:         }
12140:     } elsif ($realm eq 'query') {
12141: # ---------------------------------------------- pull stuff out of query string
12142:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12143: 						[$spacequalifierrest]);
12144: 	return $env{'form.'.$spacequalifierrest}; 
12145:    } elsif ($realm eq 'request') {
12146: # ------------------------------------------------------------- request.browser
12147:         if ($space eq 'browser') {
12148:             return $env{'browser.'.$qualifier};
12149: # ------------------------------------------------------------ request.filename
12150:         } else {
12151:             return $env{'request.'.$spacequalifierrest};
12152:         }
12153:     } elsif ($realm eq 'course') {
12154: # ---------------------------------------------------------- course.description
12155:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12156:     } elsif ($realm eq 'resource') {
12157: 
12158: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12159: 	    if (!$symbparm) { $symbparm=&symbread(); }
12160: 	}
12161: 
12162:         if ($qualifier eq '') {
12163: 	    if ($space eq 'title') {
12164: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12165: 	        return &gettitle($symbparm);
12166: 	    }
12167: 	
12168: 	    if ($space eq 'map') {
12169: 	        my ($map) = &decode_symb($symbparm);
12170: 	        return &symbread($map);
12171: 	    }
12172:             if ($space eq 'maptitle') {
12173:                 my ($map) = &decode_symb($symbparm);
12174:                 return &gettitle($map);
12175:             }
12176: 	    if ($space eq 'filename') {
12177: 	        if ($symbparm) {
12178: 		    return &clutter((&decode_symb($symbparm))[2]);
12179: 	        }
12180: 	        return &hreflocation('',$env{'request.filename'});
12181: 	    }
12182: 
12183:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12184:                 if ($space eq 'visibleparts') {
12185:                     my $navmap = Apache::lonnavmaps::navmap->new();
12186:                     my $item;
12187:                     if (ref($navmap)) {
12188:                         my $res = $navmap->getBySymb($symbparm);
12189:                         my $parts = $res->parts();
12190:                         if (ref($parts) eq 'ARRAY') {
12191:                             $item = join(',',@{$parts});
12192:                         }
12193:                         undef($navmap);
12194:                     }
12195:                     return $item;
12196:                 }
12197:             }
12198:         }
12199: 
12200: 	my ($section, $group, @groups, @recurseup, $recursed);
12201: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12202:         if (($courseid eq '') && ($cid)) {
12203:             $courseid = $cid;
12204:         }
12205: 	if (($symbparm && $courseid) && 
12206: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12207: 
12208: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12209: 
12210: # ----------------------------------------------------- Cascading lookup scheme
12211: 	    my $symbp=$symbparm;
12212: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12213: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12214:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12215: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12216: 	    if (($env{'user.name'} eq $uname) &&
12217: 		($env{'user.domain'} eq $udom)) {
12218: 		$section=$env{'request.course.sec'};
12219:                 @groups = split(/:/,$env{'request.course.groups'});  
12220:                 @groups=&sort_course_groups($courseid,@groups); 
12221: 	    } else {
12222: 		if (! defined($usection)) {
12223: 		    $section=&getsection($udom,$uname,$courseid);
12224: 		} else {
12225: 		    $section = $usection;
12226: 		}
12227:                 @groups = &get_users_groups($udom,$uname,$courseid);
12228: 	    }
12229: 
12230: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12231: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12232:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12233: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12234: 
12235: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12236: 	    my $courselevelr=$courseid.'.'.$symbparm;
12237:             $courseleveli=$courseid.'.'.$recurseparm;
12238: 	    $courselevelm=$courseid.'.'.$mapparm;
12239: 
12240: # ----------------------------------------------------------- first, check user
12241: 
12242: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12243:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12244: 				       ([$courselevelr,'resource'],
12245: 					[$courselevelm,'map'     ],
12246:                                         [$courseleveli,'map'     ],
12247: 					[$courselevel, 'course'  ]));
12248: 	    if (defined($userreply)) { return &get_reply($userreply); }
12249: 
12250: # ------------------------------------------------ second, check some of course
12251:             my $coursereply;
12252:             if (@groups > 0) {
12253:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12254:                                        $recurseparm,$mapparm,$spacequalifierrest,
12255:                                        $mapp,\$recursed,\@recurseup);
12256:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12257:             }
12258: 
12259: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12260: 				  $env{'course.'.$courseid.'.domain'},
12261: 				  'course',$mapp,\$recursed,\@recurseup,
12262:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12263: 				  ([$seclevelr,   'resource'],
12264: 				   [$seclevelm,   'map'     ],
12265:                                    [$secleveli,   'map'     ],
12266: 				   [$seclevel,    'course'  ],
12267: 				   [$courselevelr,'resource']));
12268: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12269: 
12270: # ------------------------------------------------------ third, check map parms
12271: 	    my %parmhash=();
12272: 	    my $thisparm='';
12273: 	    if (tie(%parmhash,'GDBM_File',
12274: 		    $env{'request.course.fn'}.'_parms.db',
12275: 		    &GDBM_READER(),0640)) {
12276: 		$thisparm=$parmhash{$symbparm};
12277: 		untie(%parmhash);
12278: 	    }
12279: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12280: 	}
12281: # ------------------------------------------ fourth, look in resource metadata
12282:  
12283:         my $what = $spacequalifierrest;
12284: 	$what=~s/\./\_/;
12285: 	my $filename;
12286: 	if (!$symbparm) { $symbparm=&symbread(); }
12287: 	if ($symbparm) {
12288: 	    $filename=(&decode_symb($symbparm))[2];
12289: 	} else {
12290: 	    $filename=$env{'request.filename'};
12291: 	}
12292:         my $toolsymb;
12293:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12294:             $toolsymb = $symbparm;
12295:         }
12296: 	my $metadata=&metadata($filename,$what,$toolsymb);
12297: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12298: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12299: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12300: 
12301: # ----------------------------------------------- fifth, look in rest of course
12302: 	if ($symbparm && defined($courseid) && 
12303: 	    $courseid eq $env{'request.course.id'}) {
12304: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12305: 				     $env{'course.'.$courseid.'.domain'},
12306: 				     'course',$mapp,\$recursed,\@recurseup,
12307:                                      $courseid,'.',$spacequalifierrest,
12308: 				     ([$courselevelm,'map'   ],
12309:                                       [$courseleveli,'map'   ],
12310: 				      [$courselevel, 'course']));
12311: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12312: 	}
12313: # ------------------------------------------------------------------ Cascade up
12314: 	unless ($space eq '0') {
12315: 	    my @parts=split(/_/,$space);
12316: 	    my $id=pop(@parts);
12317: 	    my $part=join('_',@parts);
12318: 	    if ($part eq '') { $part='0'; }
12319: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12320: 				 $symbparm,$udom,$uname,$section,1);
12321: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12322: 	}
12323: 	if ($recurse) { return undef; }
12324: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12325: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12326: # ---------------------------------------------------- Any other user namespace
12327:     } elsif ($realm eq 'environment') {
12328: # ----------------------------------------------------------------- environment
12329: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12330: 	    return $env{'environment.'.$spacequalifierrest};
12331: 	} else {
12332: 	    if ($uname eq 'anonymous' && $udom eq '') {
12333: 		return '';
12334: 	    }
12335: 	    my %returnhash=&userenvironment($udom,$uname,
12336: 					    $spacequalifierrest);
12337: 	    return $returnhash{$spacequalifierrest};
12338: 	}
12339:     } elsif ($realm eq 'system') {
12340: # ----------------------------------------------------------------- system.time
12341: 	if ($space eq 'time') {
12342: 	    return time;
12343:         }
12344:     } elsif ($realm eq 'server') {
12345: # ----------------------------------------------------------------- system.time
12346: 	if ($space eq 'name') {
12347: 	    return $ENV{'SERVER_NAME'};
12348:         }
12349:     } elsif ($realm eq 'client') {
12350:         if ($space eq 'remote_addr') {
12351:             return $ENV{'REMOTE_ADDR'};
12352:         }
12353:     }
12354:     return '';
12355: }
12356: 
12357: sub get_reply {
12358:     my ($reply_value) = @_;
12359:     if (ref($reply_value) eq 'ARRAY') {
12360:         if (wantarray) {
12361: 	    return @$reply_value;
12362:         }
12363:         return $reply_value->[0];
12364:     } else {
12365:         return $reply_value;
12366:     }
12367: }
12368: 
12369: sub check_group_parms {
12370:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12371:         $recursed,$recurseupref) = @_;
12372:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12373:                   [$what,'course']);
12374:     my $coursereply;
12375:     foreach my $group (@{$groups}) {
12376:         my @groupitems = ();
12377:         foreach my $level (@levels) {
12378:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12379:              push(@groupitems,[$item,$level->[1]]);
12380:         }
12381:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12382:                                    $env{'course.'.$courseid.'.domain'},
12383:                                    'course',$mapp,$recursed,$recurseupref,
12384:                                    $courseid,'.['.$group.'].',$what,
12385:                                    @groupitems);
12386:         last if (defined($coursereply));
12387:     }
12388:     return $coursereply;
12389: }
12390: 
12391: sub get_map_hierarchy {
12392:     my ($mapname,$courseid) = @_;
12393:     my @recurseup = ();
12394:     if ($mapname) {
12395:         if (($cachedmapkey eq $courseid) &&
12396:             (abs($cachedmaptime-time)<5)) {
12397:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12398:                 return @{$cachedmaps{$mapname}};
12399:             }
12400:         }
12401:         my $navmap = Apache::lonnavmaps::navmap->new();
12402:         if (ref($navmap)) {
12403:             @recurseup = $navmap->recurseup_maps($mapname);
12404:             undef($navmap);
12405:             $cachedmaps{$mapname} = \@recurseup;
12406:             $cachedmaptime=time;
12407:             $cachedmapkey=$courseid;
12408:         }
12409:     }
12410:     return @recurseup;
12411: }
12412: 
12413: }
12414: 
12415: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12416:     my ($courseid,@groups) = @_;
12417:     @groups = sort(@groups);
12418:     return @groups;
12419: }
12420: 
12421: sub packages_tab_default {
12422:     my ($uri,$varname,$toolsymb)=@_;
12423:     my (undef,$part,$name)=split(/\./,$varname);
12424: 
12425:     my (@extension,@specifics,$do_default);
12426:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12427: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12428: 	if ($pack_type eq 'default') {
12429: 	    $do_default=1;
12430: 	} elsif ($pack_type eq 'extension') {
12431: 	    push(@extension,[$package,$pack_type,$pack_part]);
12432: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12433: 	    # only look at packages defaults for packages that this id is
12434: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12435: 	}
12436:     }
12437:     # first look for a package that matches the requested part id
12438:     foreach my $package (@specifics) {
12439: 	my (undef,$pack_type,$pack_part)=@{$package};
12440: 	next if ($pack_part ne $part);
12441: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12442: 	    return $packagetab{"$pack_type&$name&default"};
12443: 	}
12444:     }
12445:     # look for any possible matching non extension_ package
12446:     foreach my $package (@specifics) {
12447: 	my (undef,$pack_type,$pack_part)=@{$package};
12448: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12449: 	    return $packagetab{"$pack_type&$name&default"};
12450: 	}
12451: 	if ($pack_type eq 'part') { $pack_part='0'; }
12452: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12453: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12454: 	}
12455:     }
12456:     # look for any posible extension_ match
12457:     foreach my $package (@extension) {
12458: 	my ($package,$pack_type)=@{$package};
12459: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12460: 	    return $packagetab{"$pack_type&$name&default"};
12461: 	}
12462: 	if (defined($packagetab{$package."&$name&default"})) {
12463: 	    return $packagetab{$package."&$name&default"};
12464: 	}
12465:     }
12466:     # look for a global default setting
12467:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12468: 	return $packagetab{"default&$name&default"};
12469:     }
12470:     return undef;
12471: }
12472: 
12473: sub add_prefix_and_part {
12474:     my ($prefix,$part)=@_;
12475:     my $keyroot;
12476:     if (defined($prefix) && $prefix !~ /^__/) {
12477: 	# prefix that has a part already
12478: 	$keyroot=$prefix;
12479:     } elsif (defined($prefix)) {
12480: 	# prefix that is missing a part
12481: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12482:     } else {
12483: 	# no prefix at all
12484: 	if (defined($part)) { $keyroot='_'.$part; }
12485:     }
12486:     return $keyroot;
12487: }
12488: 
12489: # ---------------------------------------------------------------- Get metadata
12490: 
12491: my %metaentry;
12492: my %importedpartids;
12493: my %importedrespids;
12494: sub metadata {
12495:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12496:     $uri=&declutter($uri);
12497:     # if it is a non metadata possible uri return quickly
12498:     if (($uri eq '') || 
12499: 	(($uri =~ m|^/*adm/|) && 
12500: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12501:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12502: 	return undef;
12503:     }
12504:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12505: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12506: 	return undef;
12507:     }
12508:     my $filename=$uri;
12509:     $uri=~s/\.meta$//;
12510: #
12511: # Is the metadata already cached?
12512: # Look at timestamp of caching
12513: # Everything is cached by the main uri, libraries are never directly cached
12514: #
12515:     if (!defined($liburi)) {
12516: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12517: 	if (defined($cached)) { return $result->{':'.$what}; }
12518:     }
12519: 
12520: #
12521: # If the uri is for an external tool the file from
12522: # which metadata should be retrieved depends on whether
12523: # the tool had been configured to be gradable (set in the Course
12524: # Editor or Resource Editor).
12525: #
12526: # If a valid symb has been included as the third arg in the call
12527: # to &metadata() that can be used to retrieve the value of
12528: # parameter_0_gradable set for the resource, and included in the
12529: # uploaded map containing the tool. The value is retrieved via
12530: # &EXT(), if a valid symb is available.  Otherwise the value of
12531: # gradable in the exttool_$marker.db file for the tool instance
12532: # is retrieved via &get().
12533: #
12534: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12535: # hiddenresource and encrypturl (during course initialization)
12536: # the map-level parameter for resource.0.gradable included in the 
12537: # uploaded map containing the tool will not yet have been stored
12538: # in the user_course_parms.db file for the user's session, so in 
12539: # this case fall back to retrieving gradable status from the
12540: # exttool_$marker.db file.
12541: #
12542: # In order to avoid an infinite loop, &metadata() will return
12543: # before a call to &EXT(), if the uri is for an external tool
12544: # and the $what for which metadata is being requested is
12545: # parameter_0_gradable or 0_gradable.
12546: #
12547: 
12548:     if ($uri =~ /ext\.tool$/) {
12549:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12550:             return;
12551:         } else {
12552:             my ($checked,$use_passback);
12553:             if ($toolsymb ne '') {
12554:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12555:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12556:                     $checked = 1;
12557:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12558:                         $use_passback = 1;
12559:                     }
12560:                 }
12561:             }
12562:             unless ($checked) {
12563:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12564:                 $marker=~s/\D//g;
12565:                 if ($marker) {
12566:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12567:                     $use_passback = $toolsettings{'gradable'};
12568:                 }
12569:             }
12570:             if ($use_passback) {
12571:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12572:             } else {
12573:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12574:             }
12575:         }
12576:     }
12577: 
12578:     {
12579: # Imported parts would go here
12580:         my @origfiletagids=();
12581:         my $importedparts=0;
12582: 
12583: # Imported responseids would go here
12584:         my $importedresponses=0;
12585: #
12586: # Is this a recursive call for a library?
12587: #
12588: #	if (! exists($metacache{$uri})) {
12589: #	    $metacache{$uri}={};
12590: #	}
12591: 	my $cachetime = 60*60;
12592:         if ($liburi) {
12593: 	    $liburi=&declutter($liburi);
12594:             $filename=$liburi;
12595:         } else {
12596: 	    &devalidate_cache_new('meta',$uri);
12597: 	    undef(%metaentry);
12598: 	}
12599:         my %metathesekeys=();
12600:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12601: 	my $metastring;
12602: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12603: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12604: 	    $metastring = 
12605: 		&Apache::lonnet::ssi_body($which,
12606: 					  ('grade_target' => 'meta'));
12607: 	    $cachetime = 1; # only want this cached in the child not long term
12608: 	} elsif (($uri !~ m -^(editupload)/-) && 
12609:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12610: 	    my $file=&filelocation('',&clutter($filename));
12611: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12612: 	    $metastring=&getfile($file);
12613: 	}
12614:         my $parser=HTML::LCParser->new(\$metastring);
12615:         my $token;
12616:         undef %metathesekeys;
12617:         while ($token=$parser->get_token) {
12618: 	    if ($token->[0] eq 'S') {
12619: 		if (defined($token->[2]->{'package'})) {
12620: #
12621: # This is a package - get package info
12622: #
12623: 		    my $package=$token->[2]->{'package'};
12624: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12625: 		    if (defined($token->[2]->{'id'})) { 
12626: 			$keyroot.='_'.$token->[2]->{'id'}; 
12627: 		    }
12628: 		    if ($metaentry{':packages'}) {
12629: 			$metaentry{':packages'}.=','.$package.$keyroot;
12630: 		    } else {
12631: 			$metaentry{':packages'}=$package.$keyroot;
12632: 		    }
12633: 		    foreach my $pack_entry (keys(%packagetab)) {
12634: 			my $part=$keyroot;
12635: 			$part=~s/^\_//;
12636: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12637: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12638: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12639: 			    # ignore package.tab specified default values
12640:                             # here &package_tab_default() will fetch those
12641: 			    if ($subp eq 'default') { next; }
12642: 			    my $value=$packagetab{$pack_entry};
12643: 			    my $unikey;
12644: 			    if ($pack =~ /_0$/) {
12645: 				$unikey='parameter_0_'.$name;
12646: 				$part=0;
12647: 			    } else {
12648: 				$unikey='parameter'.$keyroot.'_'.$name;
12649: 			    }
12650: 			    if ($subp eq 'display') {
12651: 				$value.=' [Part: '.$part.']';
12652: 			    }
12653: 			    $metaentry{':'.$unikey.'.part'}=$part;
12654: 			    $metathesekeys{$unikey}=1;
12655: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12656: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12657: 			    }
12658: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12659: 				$metaentry{':'.$unikey}=
12660: 				    $metaentry{':'.$unikey.'.default'};
12661: 			    }
12662: 			}
12663: 		    }
12664: 		} else {
12665: #
12666: # This is not a package - some other kind of start tag
12667: #
12668: 		    my $entry=$token->[1];
12669: 		    my $unikey='';
12670: 
12671: 		    if ($entry eq 'import') {
12672: #
12673: # Importing a library here
12674: #
12675:                         my $location=$parser->get_text('/import');
12676:                         my $dir=$filename;
12677:                         $dir=~s|[^/]*$||;
12678:                         $location=&filelocation($dir,$location);
12679: 
12680:                         my $importid=$token->[2]->{'id'};
12681:                         my $importmode=$token->[2]->{'importmode'};
12682: #
12683: # Check metadata for imported file to
12684: # see if it contained response items
12685: #
12686:                         my ($origfile,@libfilekeys);
12687:                         my %currmetaentry = %metaentry;
12688:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12689:                                                            $depthcount+1));
12690:                         if (grep(/^responseorder$/,@libfilekeys)) {
12691:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12692:                                                              undef,$depthcount+1);
12693:                             if ($libresponseorder ne '') {
12694:                                 if ($#origfiletagids<0) {
12695:                                     undef(%importedrespids);
12696:                                     undef(%importedpartids);
12697:                                 }
12698:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12699:                                 if (@respids) {
12700:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12701:                                 }
12702:                                 if ($importedrespids{$importid} ne '') {
12703:                                     $importedresponses = 1;
12704: # We need to get the original file and the imported file to get the response order correct
12705: # Load and inspect original file
12706:                                     if ($#origfiletagids<0) {
12707:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12708:                                         $origfile=&getfile($origfilelocation);
12709:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12710:                                     }
12711:                                 }
12712:                             }
12713:                         }
12714: # Do not overwrite contents of %metaentry hash for resource itself with 
12715: # hash populated for imported library file
12716:                         %metaentry = %currmetaentry;
12717:                         undef(%currmetaentry);
12718:                         if ($importmode eq 'part') {
12719: # Import as part(s)
12720:                            $importedparts=1;
12721: # We need to get the original file and the imported file to get the part order correct
12722: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12723: # Load and inspect original file if we didn't do that already
12724:                            if ($#origfiletagids<0) {
12725:                                undef(%importedrespids);
12726:                                undef(%importedpartids);
12727:                                if ($origfile eq '') {
12728:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12729:                                    $origfile=&getfile($origfilelocation);
12730:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12731:                                }
12732:                            }
12733:                            my @impfilepartids;
12734: # If <partorder> tag is included in metadata for the imported file
12735: # get the parts in the imported file from that.
12736:                            if (grep(/^partorder$/,@libfilekeys)) {
12737:                                %currmetaentry = %metaentry;
12738:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12739:                                                             $depthcount+1);
12740:                                %metaentry = %currmetaentry;
12741:                                undef(%currmetaentry);
12742:                                if ($libpartorder ne '') {
12743:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12744:                                }
12745:                            } else {
12746: # If no <partorder> tag available, load and inspect imported file
12747:                                my $impfile=&getfile($location);
12748:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12749:                            }
12750:                            if ($#impfilepartids>=0) {
12751: # This problem had parts
12752:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12753:                            } else {
12754: # Importing by turning a single problem into a problem part
12755: # It gets the import-tags ID as part-ID
12756:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12757:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12758:                            }
12759:                         } else {
12760: # Import as problem or as normal import
12761:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12762:                             unless ($importmode eq 'problem') {
12763: # Normal import
12764:                                 if (defined($token->[2]->{'id'})) {
12765:                                     $unikey.='_'.$token->[2]->{'id'};
12766:                                 }
12767:                             }
12768: # Check metadata for imported file to
12769: # see if it contained parts
12770:                             if (grep(/^partorder$/,@libfilekeys)) {
12771:                                 %currmetaentry = %metaentry;
12772:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12773:                                                              $depthcount+1);
12774:                                 %metaentry = %currmetaentry;
12775:                                 undef(%currmetaentry);
12776:                                 if ($libpartorder ne '') {
12777:                                     $importedparts = 1;
12778:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12779:                                 }
12780:                             }
12781:                         }
12782: 			if ($depthcount<20) {
12783: 			    my $metadata = 
12784: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12785: 					  $depthcount+1);
12786: 			    foreach my $meta (split(',',$metadata)) {
12787: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12788: 				$metathesekeys{$meta}=1;
12789: 			    }
12790:                         }
12791: 		    } else {
12792: #
12793: # Not importing, some other kind of non-package, non-library start tag
12794: # 
12795:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12796:                         if (defined($token->[2]->{'id'})) {
12797:                             $unikey.='_'.$token->[2]->{'id'};
12798:                         }
12799: 			if (defined($token->[2]->{'name'})) { 
12800: 			    $unikey.='_'.$token->[2]->{'name'}; 
12801: 			}
12802: 			$metathesekeys{$unikey}=1;
12803: 			foreach my $param (@{$token->[3]}) {
12804: 			    $metaentry{':'.$unikey.'.'.$param} =
12805: 				$token->[2]->{$param};
12806: 			}
12807: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12808: 			my $default=$metaentry{':'.$unikey.'.default'};
12809: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12810: 		 # only ws inside the tag, and not in default, so use default
12811: 		 # as value
12812: 			    $metaentry{':'.$unikey}=$default;
12813: 			} elsif ( $internaltext =~ /\S/ ) {
12814: 		  # something interesting inside the tag
12815: 			    $metaentry{':'.$unikey}=$internaltext;
12816: 			} else {
12817: 		  # no interesting values, don't set a default
12818: 			}
12819: # end of not-a-package not-a-library import
12820: 		    }
12821: # end of not-a-package start tag
12822: 		}
12823: # the next is the end of "start tag"
12824: 	    }
12825: 	}
12826: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12827: 	$extension = lc($extension);
12828: 	if ($extension eq 'htm') { $extension='html'; }
12829: 
12830: 	foreach my $key (keys(%packagetab)) {
12831: 	    #no specific packages #how's our extension
12832: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12833: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12834: 					 \%metathesekeys);
12835: 	}
12836: 
12837: 	if (!exists($metaentry{':packages'})
12838: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12839: 	    foreach my $key (keys(%packagetab)) {
12840: 		#no specific packages well let's get default then
12841: 		if ($key!~/^default&/) { next; }
12842: 		&metadata_create_package_def($uri,$key,'default',
12843: 					     \%metathesekeys);
12844: 	    }
12845: 	}
12846: # are there custom rights to evaluate
12847: 	if ($metaentry{':copyright'} eq 'custom') {
12848: 
12849:     #
12850:     # Importing a rights file here
12851:     #
12852: 	    unless ($depthcount) {
12853: 		my $location=$metaentry{':customdistributionfile'};
12854: 		my $dir=$filename;
12855: 		$dir=~s|[^/]*$||;
12856: 		$location=&filelocation($dir,$location);
12857: 		my $rights_metadata =
12858: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12859: 			      $depthcount+1);
12860: 		foreach my $rights (split(',',$rights_metadata)) {
12861: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12862: 		    $metathesekeys{$rights}=1;
12863: 		}
12864: 	    }
12865: 	}
12866: 	# uniqifiy package listing
12867: 	my %seen;
12868: 	my @uniq_packages =
12869: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12870: 	$metaentry{':packages'} = join(',',@uniq_packages);
12871: 
12872:         if (($importedresponses) || ($importedparts)) {
12873:             if ($importedparts) {
12874: # We had imported parts and need to rebuild partorder
12875:                 $metaentry{':partorder'}='';
12876:                 $metathesekeys{'partorder'}=1;
12877:             }
12878:             if ($importedresponses) {
12879: # We had imported responses and need to rebuil responseorder
12880:                 $metaentry{':responseorder'}='';
12881:                 $metathesekeys{'responseorder'}=1;
12882:             }
12883:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12884:                 my $origid = $origfiletagids[$index+1];
12885:                 if ($origfiletagids[$index] eq 'part') {
12886: # Original part, part of the problem
12887:                     if ($importedparts) {
12888:                         $metaentry{':partorder'}.=','.$origid;
12889:                     }
12890:                 } elsif ($origfiletagids[$index] eq 'import') {
12891:                     if ($importedparts) {
12892: # We have imported parts at this position
12893:                         if ($importedpartids{$origid} ne '') {
12894:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12895:                         }
12896:                     }
12897:                     if ($importedresponses) {
12898: # We have imported responses at this position
12899:                         if ($importedrespids{$origid} ne '') {
12900:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12901:                         }
12902:                     }
12903:                 } else {
12904: # Original response item, part of the problem
12905:                     if ($importedresponses) {
12906:                         $metaentry{':responseorder'}.=','.$origid;
12907:                     }
12908:                 }
12909:             }
12910:             if ($importedparts) {
12911:                 $metaentry{':partorder'}=~s/^\,//;
12912:             }
12913:             if ($importedresponses) {
12914:                 $metaentry{':responseorder'}=~s/^\,//;
12915:             }
12916:         }
12917: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12918: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12919: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12920:         unless ($liburi) {
12921: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12922:         }
12923: # this is the end of "was not already recently cached
12924:     }
12925:     return $metaentry{':'.$what};
12926: }
12927: 
12928: sub metadata_create_package_def {
12929:     my ($uri,$key,$package,$metathesekeys)=@_;
12930:     my ($pack,$name,$subp)=split(/\&/,$key);
12931:     if ($subp eq 'default') { next; }
12932:     
12933:     if (defined($metaentry{':packages'})) {
12934: 	$metaentry{':packages'}.=','.$package;
12935:     } else {
12936: 	$metaentry{':packages'}=$package;
12937:     }
12938:     my $value=$packagetab{$key};
12939:     my $unikey;
12940:     $unikey='parameter_0_'.$name;
12941:     $metaentry{':'.$unikey.'.part'}=0;
12942:     $$metathesekeys{$unikey}=1;
12943:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12944: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12945:     }
12946:     if (defined($metaentry{':'.$unikey.'.default'})) {
12947: 	$metaentry{':'.$unikey}=
12948: 	    $metaentry{':'.$unikey.'.default'};
12949:     }
12950: }
12951: 
12952: sub metadata_generate_part0 {
12953:     my ($metadata,$metacache,$uri) = @_;
12954:     my %allnames;
12955:     foreach my $metakey (keys(%$metadata)) {
12956: 	if ($metakey=~/^parameter\_(.*)/) {
12957: 	  my $part=$$metacache{':'.$metakey.'.part'};
12958: 	  my $name=$$metacache{':'.$metakey.'.name'};
12959: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12960: 	    $allnames{$name}=$part;
12961: 	  }
12962: 	}
12963:     }
12964:     foreach my $name (keys(%allnames)) {
12965:       $$metadata{"parameter_0_$name"}=1;
12966:       my $key=":parameter_0_$name";
12967:       $$metacache{"$key.part"}='0';
12968:       $$metacache{"$key.name"}=$name;
12969:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12970: 					   $allnames{$name}.'_'.$name.
12971: 					   '.type'};
12972:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12973: 			     '.display'};
12974:       my $expr='[Part: '.$allnames{$name}.']';
12975:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12976:       $$metacache{"$key.display"}=$olddis;
12977:     }
12978: }
12979: 
12980: # ------------------------------------------------------ Devalidate title cache
12981: 
12982: sub devalidate_title_cache {
12983:     my ($url)=@_;
12984:     if (!$env{'request.course.id'}) { return; }
12985:     my $symb=&symbread($url);
12986:     if (!$symb) { return; }
12987:     my $key=$env{'request.course.id'}."\0".$symb;
12988:     &devalidate_cache_new('title',$key);
12989: }
12990: 
12991: # ------------------------------------------------- Get the title of a course
12992: 
12993: sub current_course_title {
12994:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12995: }
12996: # ------------------------------------------------- Get the title of a resource
12997: 
12998: sub gettitle {
12999:     my $urlsymb=shift;
13000:     my $symb=&symbread($urlsymb);
13001:     if ($symb) {
13002: 	my $key=$env{'request.course.id'}."\0".$symb;
13003: 	my ($result,$cached)=&is_cached_new('title',$key);
13004: 	if (defined($cached)) { 
13005: 	    return $result;
13006: 	}
13007: 	my ($map,$resid,$url)=&decode_symb($symb);
13008: 	my $title='';
13009: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13010: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13011: 	} else {
13012: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13013: 		    &GDBM_READER(),0640)) {
13014: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13015: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13016: 		untie(%bighash);
13017: 	    }
13018: 	}
13019: 	$title=~s/\&colon\;/\:/gs;
13020: 	if ($title) {
13021: # Remember both $symb and $title for dynamic metadata
13022:             $accesshash{$symb.'___crstitle'}=$title;
13023:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13024: # Cache this title and then return it
13025: 	    return &do_cache_new('title',$key,$title,600);
13026: 	}
13027: 	$urlsymb=$url;
13028:     }
13029:     my $title=&metadata($urlsymb,'title');
13030:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13031:     return $title;
13032: }
13033: 
13034: sub get_slot {
13035:     my ($which,$cnum,$cdom)=@_;
13036:     if (!$cnum || !$cdom) {
13037: 	(undef,my $courseid)=&whichuser();
13038: 	$cdom=$env{'course.'.$courseid.'.domain'};
13039: 	$cnum=$env{'course.'.$courseid.'.num'};
13040:     }
13041:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13042:     my %slotinfo;
13043:     if (exists($remembered{$key})) {
13044: 	$slotinfo{$which} = $remembered{$key};
13045:     } else {
13046: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13047: 	&Apache::lonhomework::showhash(%slotinfo);
13048: 	my ($tmp)=keys(%slotinfo);
13049: 	if ($tmp=~/^error:/) { return (); }
13050: 	$remembered{$key} = $slotinfo{$which};
13051:     }
13052:     if (ref($slotinfo{$which}) eq 'HASH') {
13053: 	return %{$slotinfo{$which}};
13054:     }
13055:     return $slotinfo{$which};
13056: }
13057: 
13058: sub get_reservable_slots {
13059:     my ($cnum,$cdom,$uname,$udom) = @_;
13060:     my $now = time;
13061:     my $reservable_info;
13062:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13063:     if (exists($remembered{$key})) {
13064:         $reservable_info = $remembered{$key};
13065:     } else {
13066:         my %resv;
13067:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13068:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13069:         $reservable_info = \%resv;
13070:         $remembered{$key} = $reservable_info;
13071:     }
13072:     return $reservable_info;
13073: }
13074: 
13075: sub get_course_slots {
13076:     my ($cnum,$cdom) = @_;
13077:     my $hashid=$cnum.':'.$cdom;
13078:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13079:     if (defined($cached)) {
13080:         if (ref($result) eq 'HASH') {
13081:             return %{$result};
13082:         }
13083:     } else {
13084:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13085:         my ($tmp) = keys(%slots);
13086:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13087:             &do_cache_new('allslots',$hashid,\%slots,600);
13088:             return %slots;
13089:         }
13090:     }
13091:     return;
13092: }
13093: 
13094: sub devalidate_slots_cache {
13095:     my ($cnum,$cdom)=@_;
13096:     my $hashid=$cnum.':'.$cdom;
13097:     &devalidate_cache_new('allslots',$hashid);
13098: }
13099: 
13100: sub get_coursechange {
13101:     my ($cdom,$cnum) = @_;
13102:     if ($cdom eq '' || $cnum eq '') {
13103:         return unless ($env{'request.course.id'});
13104:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13105:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13106:     }
13107:     my $hashid=$cdom.'_'.$cnum;
13108:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13109:     if ((defined($cached)) && ($change ne '')) {
13110:         return $change;
13111:     } else {
13112:         my %crshash;
13113:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13114:         if ($crshash{'internal.contentchange'} eq '') {
13115:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13116:             if ($change eq '') {
13117:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13118:                 $change = $crshash{'internal.created'};
13119:             }
13120:         } else {
13121:             $change = $crshash{'internal.contentchange'};
13122:         }
13123:         my $cachetime = 600;
13124:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13125:     }
13126:     return $change;
13127: }
13128: 
13129: sub devalidate_coursechange_cache {
13130:     my ($cnum,$cdom)=@_;
13131:     my $hashid=$cnum.':'.$cdom;
13132:     &devalidate_cache_new('crschange',$hashid);
13133: }
13134: 
13135: # ------------------------------------------------- Update symbolic store links
13136: 
13137: sub symblist {
13138:     my ($mapname,%newhash)=@_;
13139:     $mapname=&deversion(&declutter($mapname));
13140:     my %hash;
13141:     if (($env{'request.course.fn'}) && (%newhash)) {
13142:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13143:                       &GDBM_WRCREAT(),0640)) {
13144: 	    foreach my $url (keys(%newhash)) {
13145: 		next if ($url eq 'last_known'
13146: 			 && $env{'form.no_update_last_known'});
13147: 		$hash{declutter($url)}=&encode_symb($mapname,
13148: 						    $newhash{$url}->[1],
13149: 						    $newhash{$url}->[0]);
13150:             }
13151:             if (untie(%hash)) {
13152: 		return 'ok';
13153:             }
13154:         }
13155:     }
13156:     return 'error';
13157: }
13158: 
13159: # --------------------------------------------------------------- Verify a symb
13160: 
13161: sub symbverify {
13162:     my ($symb,$thisurl,$encstate)=@_;
13163:     my $thisfn=$thisurl;
13164:     $thisfn=&declutter($thisfn);
13165: # direct jump to resource in page or to a sequence - will construct own symbs
13166:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13167: # check URL part
13168:     my ($map,$resid,$url)=&decode_symb($symb);
13169: 
13170:     unless ($url eq $thisfn) { return 0; }
13171: 
13172:     $symb=&symbclean($symb);
13173:     $thisurl=&deversion($thisurl);
13174:     $thisfn=&deversion($thisfn);
13175: 
13176:     my %bighash;
13177:     my $okay=0;
13178: 
13179:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13180:                             &GDBM_READER(),0640)) {
13181:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13182:             $thisurl =~ s/\?.+$//;
13183:             if ($map =~ m{^uploaded/.+\.page$}) {
13184:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13185:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13186:             }
13187:         }
13188:         my $ids;
13189:         if ($map =~ m{^uploaded/.+\.page$}) {
13190:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13191:         } else {
13192:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13193:         }
13194:         unless ($ids) {
13195:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13196:             $ids=$bighash{$idkey};
13197:         }
13198:         if ($ids) {
13199: # ------------------------------------------------------------------- Has ID(s)
13200:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13201:                 $symb =~ s/\?.+$//;
13202:             }
13203: 	    foreach my $id (split(/\,/,$ids)) {
13204: 	       my ($mapid,$resid)=split(/\./,$id);
13205:                if (
13206:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13207:    eq $symb) {
13208:                    if (ref($encstate)) {
13209:                        $$encstate = $bighash{'encrypted_'.$id};
13210:                    }
13211: 		   if (($env{'request.role.adv'}) ||
13212: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13213:                        ($thisurl eq '/adm/navmaps')) {
13214: 		       $okay=1;
13215:                        last;
13216: 		   }
13217: 	       }
13218: 	   }
13219:         }
13220: 	untie(%bighash);
13221:     }
13222:     return $okay;
13223: }
13224: 
13225: # --------------------------------------------------------------- Clean-up symb
13226: 
13227: sub symbclean {
13228:     my $symb=shift;
13229:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13230: # remove version from map
13231:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13232: 
13233: # remove version from URL
13234:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13235: 
13236: # remove wrapper
13237: 
13238:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13239:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13240:     return $symb;
13241: }
13242: 
13243: # ---------------------------------------------- Split symb to find map and url
13244: 
13245: sub encode_symb {
13246:     my ($map,$resid,$url)=@_;
13247:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13248: }
13249: 
13250: sub decode_symb {
13251:     my $symb=shift;
13252:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13253:     my ($map,$resid,$url)=split(/___/,$symb);
13254:     return (&fixversion($map),$resid,&fixversion($url));
13255: }
13256: 
13257: sub fixversion {
13258:     my $fn=shift;
13259:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13260:     my %bighash;
13261:     my $uri=&clutter($fn);
13262:     my $key=$env{'request.course.id'}.'_'.$uri;
13263: # is this cached?
13264:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13265:     if (defined($cached)) { return $result; }
13266: # unfortunately not cached, or expired
13267:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13268: 	    &GDBM_READER(),0640)) {
13269:  	if ($bighash{'version_'.$uri}) {
13270:  	    my $version=$bighash{'version_'.$uri};
13271:  	    unless (($version eq 'mostrecent') || 
13272: 		    ($version==&getversion($uri))) {
13273:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13274:  	    }
13275:  	}
13276:  	untie %bighash;
13277:     }
13278:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13279: }
13280: 
13281: sub deversion {
13282:     my $url=shift;
13283:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13284:     return $url;
13285: }
13286: 
13287: # ------------------------------------------------------ Return symb list entry
13288: 
13289: sub symbread {
13290:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
13291:     my $cache_str='request.symbread.cached.'.$thisfn;
13292:     if (defined($env{$cache_str})) {
13293:         if ($ignorecachednull) {
13294:             return $env{$cache_str} unless ($env{$cache_str} eq '');
13295:         } else {
13296:             return $env{$cache_str};
13297:         }
13298:     }
13299: # no filename provided? try from environment
13300:     unless ($thisfn) {
13301:         if ($env{'request.symb'}) {
13302: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
13303: 	}
13304: 	$thisfn=$env{'request.filename'};
13305:     }
13306:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13307: # is that filename actually a symb? Verify, clean, and return
13308:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13309: 	if (&symbverify($thisfn,$1)) {
13310: 	    return $env{$cache_str}=&symbclean($thisfn);
13311: 	}
13312:     }
13313:     $thisfn=declutter($thisfn);
13314:     my %hash;
13315:     my %bighash;
13316:     my $syval='';
13317:     if (($env{'request.course.fn'}) && ($thisfn)) {
13318:         my $targetfn = $thisfn;
13319:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13320:             $targetfn = 'adm/wrapper/'.$thisfn;
13321:         }
13322: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13323: 	    $targetfn=$1;
13324: 	}
13325:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13326:                       &GDBM_READER(),0640)) {
13327: 	    $syval=$hash{$targetfn};
13328:             untie(%hash);
13329:         }
13330: # ---------------------------------------------------------- There was an entry
13331:         if ($syval) {
13332: 	    #unless ($syval=~/\_\d+$/) {
13333: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13334: 		    #&appenv({'request.ambiguous' => $thisfn});
13335: 		    #return $env{$cache_str}='';
13336: 		#}    
13337: 		#$syval.=$1;
13338: 	    #}
13339:         } else {
13340: # ------------------------------------------------------- Was not in symb table
13341:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13342:                             &GDBM_READER(),0640)) {
13343: # ---------------------------------------------- Get ID(s) for current resource
13344:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13345:               unless ($ids) { 
13346:                  $ids=$bighash{'ids_/'.$thisfn};
13347:               }
13348:               unless ($ids) {
13349: # alias?
13350: 		  $ids=$bighash{'mapalias_'.$thisfn};
13351:               }
13352:               if ($ids) {
13353: # ------------------------------------------------------------------- Has ID(s)
13354:                  my @possibilities=split(/\,/,$ids);
13355:                  if ($#possibilities==0) {
13356: # ----------------------------------------------- There is only one possibility
13357: 		     my ($mapid,$resid)=split(/\./,$ids);
13358: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13359: 						    $resid,$thisfn);
13360:                      if (ref($possibles) eq 'HASH') {
13361:                          $possibles->{$syval} = 1;    
13362:                      }
13363:                      if ($checkforblock) {
13364:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
13365:                          if (@blockers) {
13366:                              $syval = '';
13367:                              return;
13368:                          }
13369:                      }
13370:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13371: # ------------------------------------------ There is more than one possibility
13372:                      my $realpossible=0;
13373:                      foreach my $id (@possibilities) {
13374: 			 my $file=$bighash{'src_'.$id};
13375:                          my $canaccess;
13376:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13377:                              $canaccess = 1;
13378:                          } else { 
13379:                              $canaccess = &allowed('bre',$file);
13380:                          }
13381:                          if ($canaccess) {
13382:          		     my ($mapid,$resid)=split(/\./,$id);
13383:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13384:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13385: 						             $resid,$thisfn);
13386:                                  if (ref($possibles) eq 'HASH') {
13387:                                      $possibles->{$syval} = 1;
13388:                                  }
13389:                                  if ($checkforblock) {
13390:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
13391:                                      unless (@blockers > 0) {
13392:                                          $syval = $poss_syval;
13393:                                          $realpossible++;
13394:                                      }
13395:                                  } else {
13396:                                      $syval = $poss_syval;
13397:                                      $realpossible++;
13398:                                  }
13399:                              }
13400: 			 }
13401:                      }
13402: 		     if ($realpossible!=1) { $syval=''; }
13403:                  } else {
13404:                      $syval='';
13405:                  }
13406: 	      }
13407:               untie(%bighash);
13408:            }
13409:         }
13410:         if ($syval) {
13411: 	    return $env{$cache_str}=$syval;
13412:         }
13413:     }
13414:     &appenv({'request.ambiguous' => $thisfn});
13415:     return $env{$cache_str}='';
13416: }
13417: 
13418: # ---------------------------------------------------------- Return random seed
13419: 
13420: sub numval {
13421:     my $txt=shift;
13422:     $txt=~tr/A-J/0-9/;
13423:     $txt=~tr/a-j/0-9/;
13424:     $txt=~tr/K-T/0-9/;
13425:     $txt=~tr/k-t/0-9/;
13426:     $txt=~tr/U-Z/0-5/;
13427:     $txt=~tr/u-z/0-5/;
13428:     $txt=~s/\D//g;
13429:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13430:     return int($txt);
13431: }
13432: 
13433: sub numval2 {
13434:     my $txt=shift;
13435:     $txt=~tr/A-J/0-9/;
13436:     $txt=~tr/a-j/0-9/;
13437:     $txt=~tr/K-T/0-9/;
13438:     $txt=~tr/k-t/0-9/;
13439:     $txt=~tr/U-Z/0-5/;
13440:     $txt=~tr/u-z/0-5/;
13441:     $txt=~s/\D//g;
13442:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13443:     my $total;
13444:     foreach my $val (@txts) { $total+=$val; }
13445:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13446:     return int($total);
13447: }
13448: 
13449: sub numval3 {
13450:     use integer;
13451:     my $txt=shift;
13452:     $txt=~tr/A-J/0-9/;
13453:     $txt=~tr/a-j/0-9/;
13454:     $txt=~tr/K-T/0-9/;
13455:     $txt=~tr/k-t/0-9/;
13456:     $txt=~tr/U-Z/0-5/;
13457:     $txt=~tr/u-z/0-5/;
13458:     $txt=~s/\D//g;
13459:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13460:     my $total;
13461:     foreach my $val (@txts) { $total+=$val; }
13462:     if ($_64bit) { $total=(($total<<32)>>32); }
13463:     return $total;
13464: }
13465: 
13466: sub digest {
13467:     my ($data)=@_;
13468:     my $digest=&Digest::MD5::md5($data);
13469:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13470:     my ($e,$f);
13471:     {
13472:         use integer;
13473:         $e=($a+$b);
13474:         $f=($c+$d);
13475:         if ($_64bit) {
13476:             $e=(($e<<32)>>32);
13477:             $f=(($f<<32)>>32);
13478:         }
13479:     }
13480:     if (wantarray) {
13481: 	return ($e,$f);
13482:     } else {
13483: 	my $g;
13484: 	{
13485: 	    use integer;
13486: 	    $g=($e+$f);
13487: 	    if ($_64bit) {
13488: 		$g=(($g<<32)>>32);
13489: 	    }
13490: 	}
13491: 	return $g;
13492:     }
13493: }
13494: 
13495: sub latest_rnd_algorithm_id {
13496:     return '64bit5';
13497: }
13498: 
13499: sub get_rand_alg {
13500:     my ($courseid)=@_;
13501:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13502:     if ($courseid) {
13503: 	return $env{"course.$courseid.rndseed"};
13504:     }
13505:     return &latest_rnd_algorithm_id();
13506: }
13507: 
13508: sub validCODE {
13509:     my ($CODE)=@_;
13510:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13511:     return 0;
13512: }
13513: 
13514: sub getCODE {
13515:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13516:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13517: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13518: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13519: 	return $Apache::lonhomework::history{'resource.CODE'};
13520:     }
13521:     return undef;
13522: }
13523: #
13524: #  Determines the random seed for a specific context:
13525: #
13526: # parameters:
13527: #   symb      - in course context the symb for the seed.
13528: #   course_id - The course id of the form domain_coursenum.
13529: #   domain    - Domain for the user.
13530: #   course    - Course for the user.
13531: #   cenv      - environment of the course.
13532: #
13533: # NOTE:
13534: #   All parameters are picked out of the environment if missing
13535: #   or not defined.
13536: #   If a symb cannot be determined the current time is used instead.
13537: #
13538: #  For a given well defined symb, courside, domain, username,
13539: #  and course environment, the seed is reproducible.
13540: #
13541: sub rndseed {
13542:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13543:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13544:     if (!defined($symb)) {
13545: 	unless ($symb=$wsymb) { return time; }
13546:     }
13547:     if (!defined $courseid) { 
13548: 	$courseid=$wcourseid; 
13549:     }
13550:     if (!defined $domain) { $domain=$wdomain; }
13551:     if (!defined $username) { $username=$wusername }
13552: 
13553:     my $which;
13554:     if (defined($cenv->{'rndseed'})) {
13555: 	$which = $cenv->{'rndseed'};
13556:     } else {
13557: 	$which =&get_rand_alg($courseid);
13558:     }
13559:     if (defined(&getCODE())) {
13560: 
13561: 	if ($which eq '64bit5') {
13562: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13563: 	} elsif ($which eq '64bit4') {
13564: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13565: 	} else {
13566: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13567: 	}
13568:     } elsif ($which eq '64bit5') {
13569: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13570:     } elsif ($which eq '64bit4') {
13571: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13572:     } elsif ($which eq '64bit3') {
13573: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13574:     } elsif ($which eq '64bit2') {
13575: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13576:     } elsif ($which eq '64bit') {
13577: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13578:     }
13579:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13580: }
13581: 
13582: sub rndseed_32bit {
13583:     my ($symb,$courseid,$domain,$username)=@_;
13584:     {
13585: 	use integer;
13586: 	my $symbchck=unpack("%32C*",$symb) << 27;
13587: 	my $symbseed=numval($symb) << 22;
13588: 	my $namechck=unpack("%32C*",$username) << 17;
13589: 	my $nameseed=numval($username) << 12;
13590: 	my $domainseed=unpack("%32C*",$domain) << 7;
13591: 	my $courseseed=unpack("%32C*",$courseid);
13592: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13593: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13594: 	#&logthis("rndseed :$num:$symb");
13595: 	if ($_64bit) { $num=(($num<<32)>>32); }
13596: 	return $num;
13597:     }
13598: }
13599: 
13600: sub rndseed_64bit {
13601:     my ($symb,$courseid,$domain,$username)=@_;
13602:     {
13603: 	use integer;
13604: 	my $symbchck=unpack("%32S*",$symb) << 21;
13605: 	my $symbseed=numval($symb) << 10;
13606: 	my $namechck=unpack("%32S*",$username);
13607: 	
13608: 	my $nameseed=numval($username) << 21;
13609: 	my $domainseed=unpack("%32S*",$domain) << 10;
13610: 	my $courseseed=unpack("%32S*",$courseid);
13611: 	
13612: 	my $num1=$symbchck+$symbseed+$namechck;
13613: 	my $num2=$nameseed+$domainseed+$courseseed;
13614: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13615: 	#&logthis("rndseed :$num:$symb");
13616: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13617: 	return "$num1,$num2";
13618:     }
13619: }
13620: 
13621: sub rndseed_64bit2 {
13622:     my ($symb,$courseid,$domain,$username)=@_;
13623:     {
13624: 	use integer;
13625: 	# strings need to be an even # of cahracters long, it it is odd the
13626:         # last characters gets thrown away
13627: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13628: 	my $symbseed=numval($symb) << 10;
13629: 	my $namechck=unpack("%32S*",$username.' ');
13630: 	
13631: 	my $nameseed=numval($username) << 21;
13632: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13633: 	my $courseseed=unpack("%32S*",$courseid.' ');
13634: 	
13635: 	my $num1=$symbchck+$symbseed+$namechck;
13636: 	my $num2=$nameseed+$domainseed+$courseseed;
13637: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13638: 	#&logthis("rndseed :$num:$symb");
13639: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13640: 	return "$num1,$num2";
13641:     }
13642: }
13643: 
13644: sub rndseed_64bit3 {
13645:     my ($symb,$courseid,$domain,$username)=@_;
13646:     {
13647: 	use integer;
13648: 	# strings need to be an even # of cahracters long, it it is odd the
13649:         # last characters gets thrown away
13650: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13651: 	my $symbseed=numval2($symb) << 10;
13652: 	my $namechck=unpack("%32S*",$username.' ');
13653: 	
13654: 	my $nameseed=numval2($username) << 21;
13655: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13656: 	my $courseseed=unpack("%32S*",$courseid.' ');
13657: 	
13658: 	my $num1=$symbchck+$symbseed+$namechck;
13659: 	my $num2=$nameseed+$domainseed+$courseseed;
13660: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13661: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13662: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13663: 	
13664: 	return "$num1:$num2";
13665:     }
13666: }
13667: 
13668: sub rndseed_64bit4 {
13669:     my ($symb,$courseid,$domain,$username)=@_;
13670:     {
13671: 	use integer;
13672: 	# strings need to be an even # of cahracters long, it it is odd the
13673:         # last characters gets thrown away
13674: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13675: 	my $symbseed=numval3($symb) << 10;
13676: 	my $namechck=unpack("%32S*",$username.' ');
13677: 	
13678: 	my $nameseed=numval3($username) << 21;
13679: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13680: 	my $courseseed=unpack("%32S*",$courseid.' ');
13681: 	
13682: 	my $num1=$symbchck+$symbseed+$namechck;
13683: 	my $num2=$nameseed+$domainseed+$courseseed;
13684: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13685: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13686: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13687: 	
13688: 	return "$num1:$num2";
13689:     }
13690: }
13691: 
13692: sub rndseed_64bit5 {
13693:     my ($symb,$courseid,$domain,$username)=@_;
13694:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13695:     return "$num1:$num2";
13696: }
13697: 
13698: sub rndseed_CODE_64bit {
13699:     my ($symb,$courseid,$domain,$username)=@_;
13700:     {
13701: 	use integer;
13702: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13703: 	my $symbseed=numval2($symb);
13704: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13705: 	my $CODEseed=numval(&getCODE());
13706: 	my $courseseed=unpack("%32S*",$courseid.' ');
13707: 	my $num1=$symbseed+$CODEchck;
13708: 	my $num2=$CODEseed+$courseseed+$symbchck;
13709: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13710: 	#&logthis("rndseed :$num1:$num2:$symb");
13711: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13712: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13713: 	return "$num1:$num2";
13714:     }
13715: }
13716: 
13717: sub rndseed_CODE_64bit4 {
13718:     my ($symb,$courseid,$domain,$username)=@_;
13719:     {
13720: 	use integer;
13721: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13722: 	my $symbseed=numval3($symb);
13723: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13724: 	my $CODEseed=numval3(&getCODE());
13725: 	my $courseseed=unpack("%32S*",$courseid.' ');
13726: 	my $num1=$symbseed+$CODEchck;
13727: 	my $num2=$CODEseed+$courseseed+$symbchck;
13728: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13729: 	#&logthis("rndseed :$num1:$num2:$symb");
13730: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13731: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13732: 	return "$num1:$num2";
13733:     }
13734: }
13735: 
13736: sub rndseed_CODE_64bit5 {
13737:     my ($symb,$courseid,$domain,$username)=@_;
13738:     my $code = &getCODE();
13739:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13740:     return "$num1:$num2";
13741: }
13742: 
13743: sub setup_random_from_rndseed {
13744:     my ($rndseed)=@_;
13745:     if ($rndseed =~/([,:])/) {
13746:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13747:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13748:             &Math::Random::random_set_seed_from_phrase($rndseed);
13749:         } else {
13750:             &Math::Random::random_set_seed($num1,$num2);
13751:         }
13752:     } else {
13753: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13754:     }
13755: }
13756: 
13757: sub latest_receipt_algorithm_id {
13758:     return 'receipt3';
13759: }
13760: 
13761: sub recunique {
13762:     my $fucourseid=shift;
13763:     my $unique;
13764:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13765: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13766: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13767:     } else {
13768: 	$unique=$perlvar{'lonReceipt'};
13769:     }
13770:     return unpack("%32C*",$unique);
13771: }
13772: 
13773: sub recprefix {
13774:     my $fucourseid=shift;
13775:     my $prefix;
13776:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13777: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13778: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13779:     } else {
13780: 	$prefix=$perlvar{'lonHostID'};
13781:     }
13782:     return unpack("%32C*",$prefix);
13783: }
13784: 
13785: sub ireceipt {
13786:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13787: 
13788:     my $return =&recprefix($fucourseid).'-';
13789: 
13790:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13791: 	$env{'request.state'} eq 'construct') {
13792: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13793: 	return $return;
13794:     }
13795: 
13796:     my $cuname=unpack("%32C*",$funame);
13797:     my $cudom=unpack("%32C*",$fudom);
13798:     my $cucourseid=unpack("%32C*",$fucourseid);
13799:     my $cusymb=unpack("%32C*",$fusymb);
13800:     my $cunique=&recunique($fucourseid);
13801:     my $cpart=unpack("%32S*",$part);
13802:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13803: 
13804: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13805: 			       
13806: 	$return.= ($cunique%$cuname+
13807: 		   $cunique%$cudom+
13808: 		   $cusymb%$cuname+
13809: 		   $cusymb%$cudom+
13810: 		   $cucourseid%$cuname+
13811: 		   $cucourseid%$cudom+
13812: 		   $cpart%$cuname+
13813: 		   $cpart%$cudom);
13814:     } else {
13815: 	$return.= ($cunique%$cuname+
13816: 		   $cunique%$cudom+
13817: 		   $cusymb%$cuname+
13818: 		   $cusymb%$cudom+
13819: 		   $cucourseid%$cuname+
13820: 		   $cucourseid%$cudom);
13821:     }
13822:     return $return;
13823: }
13824: 
13825: sub receipt {
13826:     my ($part)=@_;
13827:     my ($symb,$courseid,$domain,$name) = &whichuser();
13828:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13829: }
13830: 
13831: sub whichuser {
13832:     my ($passedsymb)=@_;
13833:     my ($symb,$courseid,$domain,$name,$publicuser);
13834:     if (defined($env{'form.grade_symb'})) {
13835: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13836: 	my $allowed=&allowed('vgr',$tmp_courseid);
13837: 	if (!$allowed &&
13838: 	    exists($env{'request.course.sec'}) &&
13839: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13840: 	    $allowed=&allowed('vgr',$tmp_courseid.
13841: 			      '/'.$env{'request.course.sec'});
13842: 	}
13843: 	if ($allowed) {
13844: 	    ($symb)=&get_env_multiple('form.grade_symb');
13845: 	    $courseid=$tmp_courseid;
13846: 	    ($domain)=&get_env_multiple('form.grade_domain');
13847: 	    ($name)=&get_env_multiple('form.grade_username');
13848: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13849: 	}
13850:     }
13851:     if (!$passedsymb) {
13852: 	$symb=&symbread();
13853:     } else {
13854: 	$symb=$passedsymb;
13855:     }
13856:     $courseid=$env{'request.course.id'};
13857:     $domain=$env{'user.domain'};
13858:     $name=$env{'user.name'};
13859:     if ($name eq 'public' && $domain eq 'public') {
13860: 	if (!defined($env{'form.username'})) {
13861: 	    $env{'form.username'}.=time.rand(10000000);
13862: 	}
13863: 	$name.=$env{'form.username'};
13864:     }
13865:     return ($symb,$courseid,$domain,$name,$publicuser);
13866: 
13867: }
13868: 
13869: # ------------------------------------------------------------ Serves up a file
13870: # returns either the contents of the file or 
13871: # -1 if the file doesn't exist
13872: #
13873: # if the target is a file that was uploaded via DOCS, 
13874: # a check will be made to see if a current copy exists on the local server,
13875: # if it does this will be served, otherwise a copy will be retrieved from
13876: # the home server for the course and stored in /home/httpd/html/userfiles on
13877: # the local server.   
13878: 
13879: sub getfile {
13880:     my ($file) = @_;
13881:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13882:     &repcopy($file);
13883:     return &readfile($file);
13884: }
13885: 
13886: sub repcopy_userfile {
13887:     my ($file)=@_;
13888:     my $londocroot = $perlvar{'lonDocRoot'};
13889:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13890:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13891:     my ($cdom,$cnum,$filename) = 
13892: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13893:     my $uri="/uploaded/$cdom/$cnum/$filename";
13894:     if (-e "$file") {
13895: # we already have a local copy, check it out
13896: 	my @fileinfo = stat($file);
13897: 	my $rtncode;
13898: 	my $info;
13899: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13900: 	if ($lwpresp ne 'ok') {
13901: # there is no such file anymore, even though we had a local copy
13902: 	    if ($rtncode eq '404') {
13903: 		unlink($file);
13904: 	    }
13905: 	    return -1;
13906: 	}
13907: 	if ($info < $fileinfo[9]) {
13908: # nice, the file we have is up-to-date, just say okay
13909: 	    return 'ok';
13910: 	} else {
13911: # the file is outdated, get rid of it
13912: 	    unlink($file);
13913: 	}
13914:     }
13915: # one way or the other, at this point, we don't have the file
13916: # construct the correct path for the file
13917:     my @parts = ($cdom,$cnum); 
13918:     if ($filename =~ m|^(.+)/[^/]+$|) {
13919: 	push @parts, split(/\//,$1);
13920:     }
13921:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13922:     foreach my $part (@parts) {
13923: 	$path .= '/'.$part;
13924: 	if (!-e $path) {
13925: 	    mkdir($path,0770);
13926: 	}
13927:     }
13928: # now the path exists for sure
13929: # get a user agent
13930:     my $transferfile=$file.'.in.transfer';
13931: # FIXME: this should flock
13932:     if (-e $transferfile) { return 'ok'; }
13933:     my $request;
13934:     $uri=~s/^\///;
13935:     my $homeserver = &homeserver($cnum,$cdom);
13936:     my $hostname = &hostname($homeserver);
13937:     my $protocol = $protocol{$homeserver};
13938:     $protocol = 'http' if ($protocol ne 'https');
13939:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13940:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13941: # did it work?
13942:     if ($response->is_error()) {
13943: 	unlink($transferfile);
13944: 	&logthis("Userfile repcopy failed for $uri");
13945: 	return -1;
13946:     }
13947: # worked, rename the transfer file
13948:     rename($transferfile,$file);
13949:     return 'ok';
13950: }
13951: 
13952: sub tokenwrapper {
13953:     my $uri=shift;
13954:     $uri=~s|^https?\://([^/]+)||;
13955:     $uri=~s|^/||;
13956:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13957:     my $token=$1;
13958:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13959:     if ($udom && $uname && $file) {
13960: 	$file=~s|(\?\.*)*$||;
13961:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13962:         my $homeserver = &homeserver($uname,$udom);
13963:         my $hostname = &hostname($homeserver);
13964:         my $protocol = $protocol{$homeserver};
13965:         $protocol = 'http' if ($protocol ne 'https');
13966:         return $protocol.'://'.$hostname.'/'.$uri.
13967:                (($uri=~/\?/)?'&':'?').'token='.$token.
13968:                                '&tokenissued='.$perlvar{'lonHostID'};
13969:     } else {
13970:         return '/adm/notfound.html';
13971:     }
13972: }
13973: 
13974: # call with reqtype HEAD: get last modification time
13975: # call with reqtype GET: get the file contents
13976: # Do not call this with reqtype GET for large files! It loads everything into memory
13977: #
13978: sub getuploaded {
13979:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13980:     $uri=~s/^\///;
13981:     my $homeserver = &homeserver($cnum,$cdom);
13982:     my $hostname = &hostname($homeserver);
13983:     my $protocol = $protocol{$homeserver};
13984:     $protocol = 'http' if ($protocol ne 'https');
13985:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13986:     my $request=new HTTP::Request($reqtype,$uri);
13987:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13988:     $$rtncode = $response->code;
13989:     if (! $response->is_success()) {
13990: 	return 'failed';
13991:     }      
13992:     if ($reqtype eq 'HEAD') {
13993: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13994:     } elsif ($reqtype eq 'GET') {
13995: 	$$info = $response->content;
13996:     }
13997:     return 'ok';
13998: }
13999: 
14000: sub readfile {
14001:     my $file = shift;
14002:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14003:     my $fh;
14004:     open($fh,"<",$file);
14005:     my $a='';
14006:     while (my $line = <$fh>) { $a .= $line; }
14007:     return $a;
14008: }
14009: 
14010: sub filelocation {
14011:     my ($dir,$file) = @_;
14012:     my $location;
14013:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14014: 
14015:     if ($file =~ m-^/adm/-) {
14016: 	$file=~s-^/adm/wrapper/-/-;
14017: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14018:     }
14019: 
14020:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14021:         $location = $file;
14022:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14023:         my ($udom,$uname,$filename)=
14024:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14025:         my $home=&homeserver($uname,$udom);
14026:         my $is_me=0;
14027:         my @ids=&current_machine_ids();
14028:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14029:         if ($is_me) {
14030:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14031:         } else {
14032:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14033:   	      $udom.'/'.$uname.'/'.$filename;
14034:         }
14035:     } elsif ($file =~ m-^/adm/-) {
14036: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14037:     } else {
14038:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14039:         $file=~s:^/(res|priv)/:/:;
14040:         my $space=$1;
14041:         if ( !( $file =~ m:^/:) ) {
14042:             $location = $dir. '/'.$file;
14043:         } else {
14044:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14045:         }
14046:     }
14047:     $location=~s://+:/:g; # remove duplicate /
14048:     while ($location=~m{/\.\./}) {
14049: 	if ($location =~ m{/[^/]+/\.\./}) {
14050: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14051: 	} else {
14052: 	    $location=~ s{/\.\./}{/}g;
14053: 	}
14054:     } #remove dir/..
14055:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14056:     return $location;
14057: }
14058: 
14059: sub hreflocation {
14060:     my ($dir,$file)=@_;
14061:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14062: 	$file=filelocation($dir,$file);
14063:     } elsif ($file=~m-^/adm/-) {
14064: 	$file=~s-^/adm/wrapper/-/-;
14065: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14066:     }
14067:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14068: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14069:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14070: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14071: 	        {/uploaded/$1/$2/}x;
14072:     }
14073:     if ($file=~ m{^/userfiles/}) {
14074: 	$file =~ s{^/userfiles/}{/uploaded/};
14075:     }
14076:     return $file;
14077: }
14078: 
14079: 
14080: 
14081: 
14082: 
14083: sub current_machine_domains {
14084:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14085: }
14086: 
14087: sub machine_domains {
14088:     my ($hostname) = @_;
14089:     my @domains;
14090:     my %hostname = &all_hostnames();
14091:     while( my($id, $name) = each(%hostname)) {
14092: #	&logthis("-$id-$name-$hostname-");
14093: 	if ($hostname eq $name) {
14094: 	    push(@domains,&host_domain($id));
14095: 	}
14096:     }
14097:     return @domains;
14098: }
14099: 
14100: sub current_machine_ids {
14101:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14102: }
14103: 
14104: sub machine_ids {
14105:     my ($hostname) = @_;
14106:     $hostname ||= &hostname($perlvar{'lonHostID'});
14107:     my @ids;
14108:     my %name_to_host = &all_names();
14109:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14110: 	return @{ $name_to_host{$hostname} };
14111:     }
14112:     return;
14113: }
14114: 
14115: sub additional_machine_domains {
14116:     my @domains;
14117:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14118:     while( my $line = <$fh>) {
14119:         $line =~ s/\s//g;
14120:         push(@domains,$line);
14121:     }
14122:     return @domains;
14123: }
14124: 
14125: sub default_login_domain {
14126:     my $domain = $perlvar{'lonDefDomain'};
14127:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14128:     foreach my $posdom (&current_machine_domains(),
14129:                         &additional_machine_domains()) {
14130:         if (lc($posdom) eq lc($testdomain)) {
14131:             $domain=$posdom;
14132:             last;
14133:         }
14134:     }
14135:     return $domain;
14136: }
14137: 
14138: sub shared_institution {
14139:     my ($dom) = @_;
14140:     my $same_intdom;
14141:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
14142:     if ($hostintdom ne '') {
14143:         my %iphost = &get_iphost();
14144:         my $primary_id = &domain($dom,'primary');
14145:         my $primary_ip = &get_host_ip($primary_id);
14146:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14147:             foreach my $id (@{$iphost{$primary_ip}}) {
14148:                 my $intdom = &internet_dom($id);
14149:                 if ($intdom eq $hostintdom) {
14150:                     $same_intdom = 1;
14151:                     last;
14152:                 }
14153:             }
14154:         }
14155:     }
14156:     return $same_intdom;
14157: }
14158: 
14159: sub uses_sts {
14160:     my ($ignore_cache) = @_;
14161:     my $lonhost = $perlvar{'lonHostID'};
14162:     my $hostname = &hostname($lonhost);
14163:     my $sts_on;
14164:     if ($protocol{$lonhost} eq 'https') {
14165:         my $cachetime = 12*3600;
14166:         if (!$ignore_cache) {
14167:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14168:             if (defined($cached)) {
14169:                 return $sts_on;
14170:             }
14171:         }
14172:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14173:         my $request=new HTTP::Request('HEAD',$url);
14174:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14175:         if ($response->is_success) {
14176:             my $has_sts = $response->header('Strict-Transport-Security');
14177:             if ($has_sts eq '') {
14178:                 $sts_on = 0;
14179:             } else {
14180:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14181:                     my $maxage = $1;
14182:                     if ($maxage) {
14183:                         $sts_on = 1;
14184:                     } else {
14185:                         $sts_on = 0;
14186:                     }
14187:                 } else {
14188:                     $sts_on = 0;
14189:                 }
14190:             }
14191:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14192:         }
14193:     }
14194:     return;
14195: }
14196: 
14197: # ------------------------------------------------------------- Declutters URLs
14198: 
14199: sub declutter {
14200:     my $thisfn=shift;
14201:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14202:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14203:         $thisfn=~s{^/home/httpd/html}{};
14204:     }
14205:     $thisfn=~s/^\///;
14206:     $thisfn=~s|^adm/wrapper/||;
14207:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14208:     $thisfn=~s/^res\///;
14209:     $thisfn=~s/^priv\///;
14210:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14211:         $thisfn=~s/\?.+$//;
14212:     }
14213:     return $thisfn;
14214: }
14215: 
14216: # ------------------------------------------------------------- Clutter up URLs
14217: 
14218: sub clutter {
14219:     my $thisfn='/'.&declutter(shift);
14220:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14221: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14222:        $thisfn='/res'.$thisfn; 
14223:     }
14224:     if ($thisfn !~m|^/adm|) {
14225: 	if ($thisfn =~ m|^/ext/|) {
14226: 	    $thisfn='/adm/wrapper'.$thisfn;
14227: 	} else {
14228: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14229: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14230: 	    if ($embstyle eq 'ssi'
14231: 		|| ($embstyle eq 'hdn')
14232: 		|| ($embstyle eq 'rat')
14233: 		|| ($embstyle eq 'prv')
14234: 		|| ($embstyle eq 'ign')) {
14235: 		#do nothing with these
14236: 	    } elsif (($embstyle eq 'img') 
14237: 		|| ($embstyle eq 'emb')
14238: 		|| ($embstyle eq 'wrp')) {
14239: 		$thisfn='/adm/wrapper'.$thisfn;
14240: 	    } elsif ($embstyle eq 'unk'
14241: 		     && $thisfn!~/\.(sequence|page)$/) {
14242: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14243: 	    } else {
14244: #		&logthis("Got a blank emb style");
14245: 	    }
14246: 	}
14247:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14248:         $thisfn='/adm/wrapper'.$thisfn;
14249:     }
14250:     return $thisfn;
14251: }
14252: 
14253: sub clutter_with_no_wrapper {
14254:     my $uri = &clutter(shift);
14255:     if ($uri =~ m-^/adm/-) {
14256: 	$uri =~ s-^/adm/wrapper/-/-;
14257: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14258:     }
14259:     return $uri;
14260: }
14261: 
14262: sub freeze_escape {
14263:     my ($value)=@_;
14264:     if (ref($value)) {
14265: 	$value=&nfreeze($value);
14266: 	return '__FROZEN__'.&escape($value);
14267:     }
14268:     return &escape($value);
14269: }
14270: 
14271: 
14272: sub thaw_unescape {
14273:     my ($value)=@_;
14274:     if ($value =~ /^__FROZEN__/) {
14275: 	substr($value,0,10,undef);
14276: 	$value=&unescape($value);
14277: 	return &thaw($value);
14278:     }
14279:     return &unescape($value);
14280: }
14281: 
14282: sub correct_line_ends {
14283:     my ($result)=@_;
14284:     $$result =~s/\r\n/\n/mg;
14285:     $$result =~s/\r/\n/mg;
14286: }
14287: # ================================================================ Main Program
14288: 
14289: sub goodbye {
14290:    &logthis("Starting Shut down");
14291: #not converted to using infrastruture and probably shouldn't be
14292:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14293: #converted
14294: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14295:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14296: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14297: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14298: #1.1 only
14299: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14300: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14301: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14302: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14303:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14304:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14305:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14306:    &flushcourselogs();
14307:    &logthis("Shutting down");
14308: }
14309: 
14310: sub get_dns {
14311:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14312:     if (!$ignore_cache) {
14313: 	my ($content,$cached)=
14314: 	    &Apache::lonnet::is_cached_new('dns',$url);
14315: 	if ($cached) {
14316: 	    &$func($content,$hashref);
14317: 	    return;
14318: 	}
14319:     }
14320: 
14321:     my %alldns;
14322:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14323:         foreach my $dns (<$config>) {
14324: 	    next if ($dns !~ /^\^(\S*)/x);
14325:             my $line = $1;
14326:             my ($host,$protocol) = split(/:/,$line);
14327:             if ($protocol ne 'https') {
14328:                 $protocol = 'http';
14329:             }
14330: 	    $alldns{$host} = $protocol;
14331:         }
14332:         close($config);
14333:     }
14334:     while (%alldns) {
14335: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14336: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14337:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14338:         delete($alldns{$dns});
14339: 	next if ($response->is_error());
14340:         if ($url eq '/adm/dns/loncapaCRL') {
14341:             return &$func($response);
14342:         } else {
14343: 	    my @content = split("\n",$response->content);
14344: 	    unless ($nocache) {
14345: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14346: 	    }
14347: 	    &$func(\@content,$hashref);
14348:             return;
14349:         }
14350:     }
14351:     my $which = (split('/',$url,4))[3];
14352:     if ($which eq 'loncapaCRL') {
14353:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14354:         if (-e $diskfile) {
14355:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14356:         } else {
14357:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14358:         }
14359:     } else {
14360:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14361:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14362:             my @content = <$config>;
14363:             close($config);
14364:             &$func(\@content,$hashref);
14365:         }
14366:     }
14367:     return;
14368: }
14369: 
14370: # ------------------------------------------------------Get DNS checksums file
14371: sub parse_dns_checksums_tab {
14372:     my ($lines,$hashref) = @_;
14373:     my $lonhost = $perlvar{'lonHostID'};
14374:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14375:     my $loncaparev = &get_server_loncaparev($machine_dom);
14376:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14377:     my $webconfdir = '/etc/httpd/conf';
14378:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14379:         $webconfdir = '/etc/apache2';
14380:     } elsif ($distro =~ /^sles(\d+)$/) {
14381:         if ($1 >= 10) {
14382:             $webconfdir = '/etc/apache2';
14383:         }
14384:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14385:         if ($1 >= 10.0) {
14386:             $webconfdir = '/etc/apache2';
14387:         }
14388:     }
14389:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14390:     my (%chksum,%revnum);
14391:     if (ref($lines) eq 'ARRAY') {
14392:         chomp(@{$lines});
14393:         my $version = shift(@{$lines});
14394:         if ($version eq $release) {  
14395:             foreach my $line (@{$lines}) {
14396:                 my ($file,$version,$shasum) = split(/,/,$line);
14397:                 if ($file =~ m{^/etc/httpd/conf}) {
14398:                     if ($webconfdir eq '/etc/apache2') {
14399:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14400:                     }
14401:                 }
14402:                 $chksum{$file} = $shasum;
14403:                 $revnum{$file} = $version;
14404:             }
14405:             if (ref($hashref) eq 'HASH') {
14406:                 %{$hashref} = (
14407:                                 sums     => \%chksum,
14408:                                 versions => \%revnum,
14409:                               );
14410:             }
14411:         }
14412:     }
14413:     return;
14414: }
14415: 
14416: sub fetch_dns_checksums {
14417:     my %checksums;
14418:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14419:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14420:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14421:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14422:              \%checksums);
14423:     return \%checksums;
14424: }
14425: 
14426: sub fetch_crl_pemfile {
14427:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14428: }
14429: 
14430: sub save_crl_pem {
14431:     my ($response) = @_;
14432:     my ($msg,$hadchanges);
14433:     if (ref($response)) {
14434:         my $now = time;
14435:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14436:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14437:         if (open(my $fh,'>',"$tmpcrl")) {
14438:             print $fh $response->content;
14439:             close($fh);
14440:             if (-e $lonca) {
14441:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14442:                     my $check = <PIPE>;
14443:                     close(PIPE);
14444:                     chomp($check);
14445:                     if ($check eq 'verify OK') {
14446:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14447:                         my $backup;
14448:                         if (-e $dest) {
14449:                             if (&File::Copy::move($dest,"$dest.bak")) {
14450:                                 $backup = 'ok';
14451:                             }
14452:                         }
14453:                         if (&File::Copy::move($tmpcrl,$dest)) {
14454:                             $msg = 'ok';
14455:                             if ($backup) {
14456:                                 my (%oldnums,%newnums);
14457:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14458:                                     while (<PIPE>) {
14459:                                         $oldnums{(split(/:/))[1]} = 1;
14460:                                     }
14461:                                     close(PIPE);
14462:                                 }
14463:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14464:                                     while(<PIPE>) {
14465:                                         $newnums{(split(/:/))[1]} = 1;
14466:                                     }
14467:                                     close(PIPE);
14468:                                 }
14469:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14470:                                     unless (exists($oldnums{$key})) {
14471:                                         $hadchanges = 1;
14472:                                         last;
14473:                                     }
14474:                                 }
14475:                                 unless ($hadchanges) {
14476:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14477:                                         unless (exists($newnums{$key})) {
14478:                                             $hadchanges = 1;
14479:                                             last;
14480:                                         }
14481:                                     }
14482:                                 }
14483:                             }
14484:                         }
14485:                     } else {
14486:                         unlink($tmpcrl);
14487:                     }
14488:                 } else {
14489:                     unlink($tmpcrl);
14490:                 }
14491:             } else {
14492:                 unlink($tmpcrl);
14493:             }
14494:         }
14495:     }
14496:     return ($msg,$hadchanges);
14497: }
14498: 
14499: # ------------------------------------------------------------ Read domain file
14500: {
14501:     my $loaded;
14502:     my %domain;
14503: 
14504:     sub parse_domain_tab {
14505: 	my ($lines) = @_;
14506: 	foreach my $line (@$lines) {
14507: 	    next if ($line =~ /^(\#|\s*$ )/x);
14508: 
14509: 	    chomp($line);
14510: 	    my ($name,@elements) = split(/:/,$line,9);
14511: 	    my %this_domain;
14512: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14513: 			       'lang_def', 'city', 'longi', 'lati',
14514: 			       'primary') {
14515: 		$this_domain{$field} = shift(@elements);
14516: 	    }
14517: 	    $domain{$name} = \%this_domain;
14518: 	}
14519:     }
14520: 
14521:     sub reset_domain_info {
14522: 	undef($loaded);
14523: 	undef(%domain);
14524:     }
14525: 
14526:     sub load_domain_tab {
14527: 	my ($ignore_cache,$nocache) = @_;
14528: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14529: 	my $fh;
14530: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14531: 	    my @lines = <$fh>;
14532: 	    &parse_domain_tab(\@lines);
14533: 	}
14534: 	close($fh);
14535: 	$loaded = 1;
14536:     }
14537: 
14538:     sub domain {
14539: 	&load_domain_tab() if (!$loaded);
14540: 
14541: 	my ($name,$what) = @_;
14542: 	return if ( !exists($domain{$name}) );
14543: 
14544: 	if (!$what) {
14545: 	    return $domain{$name}{'description'};
14546: 	}
14547: 	return $domain{$name}{$what};
14548:     }
14549: 
14550:     sub domain_info {
14551:         &load_domain_tab() if (!$loaded);
14552:         return %domain;
14553:     }
14554: 
14555: }
14556: 
14557: 
14558: # ------------------------------------------------------------- Read hosts file
14559: {
14560:     my %hostname;
14561:     my %hostdom;
14562:     my %libserv;
14563:     my $loaded;
14564:     my %name_to_host;
14565:     my %internetdom;
14566:     my %LC_dns_serv;
14567: 
14568:     sub parse_hosts_tab {
14569: 	my ($file) = @_;
14570: 	foreach my $configline (@$file) {
14571: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14572:             chomp($configline);
14573: 	    if ($configline =~ /^\^/) {
14574:                 if ($configline =~ /^\^([\w.\-]+)/) {
14575:                     $LC_dns_serv{$1} = 1;
14576:                 }
14577:                 next;
14578:             }
14579: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14580: 	    $name=~s/\s//g;
14581: 	    if ($id && $domain && $role && $name) {
14582:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14583:                     my $curr = $hostname{$id};
14584:                     my $skip;
14585:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14586:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14587:                             $skip = 1;
14588:                         } else {
14589:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14590:                         }
14591:                     }
14592:                     unless ($skip) {
14593:                         push(@{$name_to_host{$name}},$id);
14594:                     }
14595:                 } else {
14596:                     push(@{$name_to_host{$name}},$id);
14597:                 }
14598: 		$hostname{$id}=$name;
14599: 		$hostdom{$id}=$domain;
14600: 		if ($role eq 'library') { $libserv{$id}=$name; }
14601:                 if (defined($protocol)) {
14602:                     if ($protocol eq 'https') {
14603:                         $protocol{$id} = $protocol;
14604:                     } else {
14605:                         $protocol{$id} = 'http'; 
14606:                     }
14607:                 } else {
14608:                     $protocol{$id} = 'http';
14609:                 }
14610:                 if (defined($intdom)) {
14611:                     $internetdom{$id} = $intdom;
14612:                 }
14613: 	    }
14614: 	}
14615:     }
14616:     
14617:     sub reset_hosts_info {
14618: 	&purge_remembered();
14619: 	&reset_domain_info();
14620: 	&reset_hosts_ip_info();
14621:         undef(%internetdom);
14622: 	undef(%name_to_host);
14623: 	undef(%hostname);
14624: 	undef(%hostdom);
14625: 	undef(%libserv);
14626: 	undef($loaded);
14627:     }
14628: 
14629:     sub load_hosts_tab {
14630: 	my ($ignore_cache,$nocache) = @_;
14631: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14632: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14633: 	my @config = <$config>;
14634: 	&parse_hosts_tab(\@config);
14635: 	close($config);
14636: 	$loaded=1;
14637:     }
14638: 
14639:     sub hostname {
14640: 	&load_hosts_tab() if (!$loaded);
14641: 
14642: 	my ($lonid) = @_;
14643: 	return $hostname{$lonid};
14644:     }
14645: 
14646:     sub all_hostnames {
14647: 	&load_hosts_tab() if (!$loaded);
14648: 
14649: 	return %hostname;
14650:     }
14651: 
14652:     sub all_names {
14653:         my ($ignore_cache,$nocache) = @_;
14654: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14655: 
14656: 	return %name_to_host;
14657:     }
14658: 
14659:     sub all_host_domain {
14660:         &load_hosts_tab() if (!$loaded);
14661:         return %hostdom;
14662:     }
14663: 
14664:     sub all_host_intdom {
14665:         &load_hosts_tab() if (!$loaded);
14666:         return %internetdom;
14667:     }
14668: 
14669:     sub is_library {
14670: 	&load_hosts_tab() if (!$loaded);
14671: 
14672: 	return exists($libserv{$_[0]});
14673:     }
14674: 
14675:     sub all_library {
14676: 	&load_hosts_tab() if (!$loaded);
14677: 
14678: 	return %libserv;
14679:     }
14680: 
14681:     sub unique_library {
14682: 	#2x reverse removes all hostnames that appear more than once
14683:         my %unique = reverse &all_library();
14684:         return reverse %unique;
14685:     }
14686: 
14687:     sub get_servers {
14688: 	&load_hosts_tab() if (!$loaded);
14689: 
14690: 	my ($domain,$type) = @_;
14691: 	my %possible_hosts = ($type eq 'library') ? %libserv
14692: 	                                          : %hostname;
14693: 	my %result;
14694: 	if (ref($domain) eq 'ARRAY') {
14695: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14696: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14697: 		    $result{$host} = $hostname;
14698: 		}
14699: 	    }
14700: 	} else {
14701: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14702: 		if ($hostdom{$host} eq $domain) {
14703: 		    $result{$host} = $hostname;
14704: 		}
14705: 	    }
14706: 	}
14707: 	return %result;
14708:     }
14709: 
14710:     sub get_unique_servers {
14711:         my %unique = reverse &get_servers(@_);
14712: 	return reverse %unique;
14713:     }
14714: 
14715:     sub host_domain {
14716: 	&load_hosts_tab() if (!$loaded);
14717: 
14718: 	my ($lonid) = @_;
14719: 	return $hostdom{$lonid};
14720:     }
14721: 
14722:     sub all_domains {
14723: 	&load_hosts_tab() if (!$loaded);
14724: 
14725: 	my %seen;
14726: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14727: 	return @uniq;
14728:     }
14729: 
14730:     sub internet_dom {
14731:         &load_hosts_tab() if (!$loaded);
14732: 
14733:         my ($lonid) = @_;
14734:         return $internetdom{$lonid};
14735:     }
14736: 
14737:     sub is_LC_dns {
14738:         &load_hosts_tab() if (!$loaded);
14739: 
14740:         my ($hostname) = @_;
14741:         return exists($LC_dns_serv{$hostname});
14742:     }
14743: 
14744: }
14745: 
14746: { 
14747:     my %iphost;
14748:     my %name_to_ip;
14749:     my %lonid_to_ip;
14750: 
14751:     sub get_hosts_from_ip {
14752: 	my ($ip) = @_;
14753: 	my %iphosts = &get_iphost();
14754: 	if (ref($iphosts{$ip})) {
14755: 	    return @{$iphosts{$ip}};
14756: 	}
14757: 	return;
14758:     }
14759:     
14760:     sub reset_hosts_ip_info {
14761: 	undef(%iphost);
14762: 	undef(%name_to_ip);
14763: 	undef(%lonid_to_ip);
14764:     }
14765: 
14766:     sub get_host_ip {
14767: 	my ($lonid) = @_;
14768: 	if (exists($lonid_to_ip{$lonid})) {
14769: 	    return $lonid_to_ip{$lonid};
14770: 	}
14771: 	my $name=&hostname($lonid);
14772:    	my $ip = gethostbyname($name);
14773: 	return if (!$ip || length($ip) ne 4);
14774: 	$ip=inet_ntoa($ip);
14775: 	$name_to_ip{$name}   = $ip;
14776: 	$lonid_to_ip{$lonid} = $ip;
14777: 	return $ip;
14778:     }
14779:     
14780:     sub get_iphost {
14781: 	my ($ignore_cache,$nocache) = @_;
14782: 
14783: 	if (!$ignore_cache) {
14784: 	    if (%iphost) {
14785: 		return %iphost;
14786: 	    }
14787: 	    my ($ip_info,$cached)=
14788: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14789: 	    if ($cached) {
14790: 		%iphost      = %{$ip_info->[0]};
14791: 		%name_to_ip  = %{$ip_info->[1]};
14792: 		%lonid_to_ip = %{$ip_info->[2]};
14793: 		return %iphost;
14794: 	    }
14795: 	}
14796: 
14797: 	# get yesterday's info for fallback
14798: 	my %old_name_to_ip;
14799: 	my ($ip_info,$cached)=
14800: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14801: 	if ($cached) {
14802: 	    %old_name_to_ip = %{$ip_info->[1]};
14803: 	}
14804: 
14805: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14806: 	foreach my $name (keys(%name_to_host)) {
14807: 	    my $ip;
14808: 	    if (!exists($name_to_ip{$name})) {
14809: 		$ip = gethostbyname($name);
14810: 		if (!$ip || length($ip) ne 4) {
14811: 		    if (defined($old_name_to_ip{$name})) {
14812: 			$ip = $old_name_to_ip{$name};
14813: 			&logthis("Can't find $name defaulting to old $ip");
14814: 		    } else {
14815: 			&logthis("Name $name no IP found");
14816: 			next;
14817: 		    }
14818: 		} else {
14819: 		    $ip=inet_ntoa($ip);
14820: 		}
14821: 		$name_to_ip{$name} = $ip;
14822: 	    } else {
14823: 		$ip = $name_to_ip{$name};
14824: 	    }
14825: 	    foreach my $id (@{ $name_to_host{$name} }) {
14826: 		$lonid_to_ip{$id} = $ip;
14827: 	    }
14828: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14829: 	}
14830:         unless ($nocache) {
14831: 	    &do_cache_new('iphost','iphost',
14832: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14833: 		          48*60*60);
14834:         }
14835: 
14836: 	return %iphost;
14837:     }
14838: 
14839:     #
14840:     #  Given a DNS returns the loncapa host name for that DNS 
14841:     # 
14842:     sub host_from_dns {
14843:         my ($dns) = @_;
14844:         my @hosts;
14845:         my $ip;
14846: 
14847:         if (exists($name_to_ip{$dns})) {
14848:             $ip = $name_to_ip{$dns};
14849:         }
14850:         if (!$ip) {
14851:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14852:             if (length($ip) == 4) { 
14853: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14854:             }
14855:         }
14856:         if ($ip) {
14857: 	    @hosts = get_hosts_from_ip($ip);
14858: 	    return $hosts[0];
14859:         }
14860:         return undef;
14861:     }
14862: 
14863:     sub get_internet_names {
14864:         my ($lonid) = @_;
14865:         return if ($lonid eq '');
14866:         my ($idnref,$cached)=
14867:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14868:         if ($cached) {
14869:             return $idnref;
14870:         }
14871:         my $ip = &get_host_ip($lonid);
14872:         my @hosts = &get_hosts_from_ip($ip);
14873:         my %iphost = &get_iphost();
14874:         my (@idns,%seen);
14875:         foreach my $id (@hosts) {
14876:             my $dom = &host_domain($id);
14877:             my $prim_id = &domain($dom,'primary');
14878:             my $prim_ip = &get_host_ip($prim_id);
14879:             next if ($seen{$prim_ip});
14880:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14881:                 foreach my $id (@{$iphost{$prim_ip}}) {
14882:                     my $intdom = &internet_dom($id);
14883:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14884:                         push(@idns,$intdom);
14885:                     }
14886:                 }
14887:             }
14888:             $seen{$prim_ip} = 1;
14889:         }
14890:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14891:     }
14892: 
14893: }
14894: 
14895: sub all_loncaparevs {
14896:     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);
14897: }
14898: 
14899: # ---------------------------------------------------------- Read loncaparev table
14900: {
14901:     sub load_loncaparevs { 
14902:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14903:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14904:                 while (my $configline=<$config>) {
14905:                     chomp($configline);
14906:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14907:                     $loncaparevs{$hostid}=$loncaparev;
14908:                 }
14909:                 close($config);
14910:             }
14911:         }
14912:     }
14913: }
14914: 
14915: # ---------------------------------------------------------- Read serverhostID table
14916: {
14917:     sub load_serverhomeIDs {
14918:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14919:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14920:                 while (my $configline=<$config>) {
14921:                     chomp($configline);
14922:                     my ($name,$id)=split(/:/,$configline);
14923:                     $serverhomeIDs{$name}=$id;
14924:                 }
14925:                 close($config);
14926:             }
14927:         }
14928:     }
14929: }
14930: 
14931: 
14932: BEGIN {
14933: 
14934: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14935:     unless ($readit) {
14936: {
14937:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14938:     %perlvar = (%perlvar,%{$configvars});
14939: }
14940: 
14941: 
14942: # ------------------------------------------------------ Read spare server file
14943: {
14944:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14945: 
14946:     while (my $configline=<$config>) {
14947:        chomp($configline);
14948:        if ($configline) {
14949: 	   my ($host,$type) = split(':',$configline,2);
14950: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14951: 	   push(@{ $spareid{$type} }, $host);
14952:        }
14953:     }
14954:     close($config);
14955: }
14956: # ------------------------------------------------------------ Read permissions
14957: {
14958:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14959: 
14960:     while (my $configline=<$config>) {
14961: 	chomp($configline);
14962: 	if ($configline) {
14963: 	    my ($role,$perm)=split(/ /,$configline);
14964: 	    if ($perm ne '') { $pr{$role}=$perm; }
14965: 	}
14966:     }
14967:     close($config);
14968: }
14969: 
14970: # -------------------------------------------- Read plain texts for permissions
14971: {
14972:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14973: 
14974:     while (my $configline=<$config>) {
14975: 	chomp($configline);
14976: 	if ($configline) {
14977: 	    my ($short,@plain)=split(/:/,$configline);
14978:             %{$prp{$short}} = ();
14979: 	    if (@plain > 0) {
14980:                 $prp{$short}{'std'} = $plain[0];
14981:                 for (my $i=1; $i<@plain; $i++) {
14982:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14983:                 }
14984:             }
14985: 	}
14986:     }
14987:     close($config);
14988: }
14989: 
14990: # ---------------------------------------------------------- Read package table
14991: {
14992:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14993: 
14994:     while (my $configline=<$config>) {
14995: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14996: 	chomp($configline);
14997: 	my ($short,$plain)=split(/:/,$configline);
14998: 	my ($pack,$name)=split(/\&/,$short);
14999: 	if ($plain ne '') {
15000: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15001: 	    $packagetab{$short}=$plain; 
15002: 	}
15003:     }
15004:     close($config);
15005: }
15006: 
15007: # ---------------------------------------------------------- Read loncaparev table
15008: 
15009: &load_loncaparevs();
15010: 
15011: # ---------------------------------------------------------- Read serverhostID table
15012: 
15013: &load_serverhomeIDs();
15014: 
15015: # ---------------------------------------------------------- Read releaseslist XML
15016: {
15017:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15018:     if (-e $file) {
15019:         my $parser = HTML::LCParser->new($file);
15020:         while (my $token = $parser->get_token()) {
15021:             if ($token->[0] eq 'S') {
15022:                 my $item = $token->[1];
15023:                 my $name = $token->[2]{'name'};
15024:                 my $value = $token->[2]{'value'};
15025:                 my $valuematch = $token->[2]{'valuematch'};
15026:                 my $namematch = $token->[2]{'namematch'};
15027:                 if ($item eq 'parameter') {
15028:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15029:                         my $release = $parser->get_text();
15030:                         $release =~ s/(^\s*|\s*$ )//gx;
15031:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15032:                     }
15033:                 } elsif ($item ne '' && $name ne '') {
15034:                     my $release = $parser->get_text();
15035:                     $release =~ s/(^\s*|\s*$ )//gx;
15036:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15037:                 }
15038:             }
15039:         }
15040:     }
15041: }
15042: 
15043: # ---------------------------------------------------------- Read managers table
15044: {
15045:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15046:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15047:             while (my $configline=<$config>) {
15048:                 chomp($configline);
15049:                 next if ($configline =~ /^\#/);
15050:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15051:                     $managerstab{$configline} = 1;
15052:                 }
15053:             }
15054:             close($config);
15055:         }
15056:     }
15057: }
15058: 
15059: # ------------- set up temporary directory
15060: {
15061:     $tmpdir = LONCAPA::tempdir();
15062: 
15063: }
15064: 
15065: # ------------- set default texengine (domain default overrides this)
15066: {
15067:     $deftex = LONCAPA::texengine();
15068: }
15069: 
15070: # ------------- set default minimum length for passwords for internal auth users
15071: {
15072:     $passwdmin = LONCAPA::passwd_min();
15073: }
15074: 
15075: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15076: 				'compress_threshold'=> 20_000,
15077:  			        });
15078: 
15079: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15080: $dumpcount=0;
15081: $locknum=0;
15082: 
15083: &logtouch();
15084: &logthis('<font color="yellow">INFO: Read configuration</font>');
15085: $readit=1;
15086:     {
15087: 	use integer;
15088: 	my $test=(2**32)+1;
15089: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15090: 	&logthis(" Detected 64bit platform ($_64bit)");
15091:     }
15092: }
15093: }
15094: 
15095: 1;
15096: __END__
15097: 
15098: =pod
15099: 
15100: =head1 NAME
15101: 
15102: Apache::lonnet - Subroutines to ask questions about things in the network.
15103: 
15104: =head1 SYNOPSIS
15105: 
15106: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15107: 
15108:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15109: 
15110: Common parameters:
15111: 
15112: =over 4
15113: 
15114: =item *
15115: 
15116: $uname : an internal username (if $cname expecting a course Id specifically)
15117: 
15118: =item *
15119: 
15120: $udom : a domain (if $cdom expecting a course's domain specifically)
15121: 
15122: =item *
15123: 
15124: $symb : a resource instance identifier
15125: 
15126: =item *
15127: 
15128: $namespace : the name of a .db file that contains the data needed or
15129: being set.
15130: 
15131: =back
15132: 
15133: =head1 OVERVIEW
15134: 
15135: lonnet provides subroutines which interact with the
15136: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15137: about classes, users, and resources.
15138: 
15139: For many of these objects you can also use this to store data about
15140: them or modify them in various ways.
15141: 
15142: =head2 Symbs
15143: 
15144: To identify a specific instance of a resource, LON-CAPA uses symbols
15145: or "symbs"X<symb>. These identifiers are built from the URL of the
15146: map, the resource number of the resource in the map, and the URL of
15147: the resource itself. The latter is somewhat redundant, but might help
15148: if maps change.
15149: 
15150: An example is
15151: 
15152:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15153: 
15154: The respective map entry is
15155: 
15156:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15157:   title="Problem 2">
15158:  </resource>
15159: 
15160: Symbs are used by the random number generator, as well as to store and
15161: restore data specific to a certain instance of for example a problem.
15162: 
15163: =head2 Storing And Retrieving Data
15164: 
15165: X<store()>X<cstore()>X<restore()>Three of the most important functions
15166: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15167: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15168: is is the non-critical message twin of cstore. These functions are for
15169: handlers to store a perl hash to a user's permanent data space in an
15170: easy manner, and to retrieve it again on another call. It is expected
15171: that a handler would use this once at the beginning to retrieve data,
15172: and then again once at the end to send only the new data back.
15173: 
15174: The data is stored in the user's data directory on the user's
15175: homeserver under the ID of the course.
15176: 
15177: The hash that is returned by restore will have all of the previous
15178: value for all of the elements of the hash.
15179: 
15180: Example:
15181: 
15182:  #creating a hash
15183:  my %hash;
15184:  $hash{'foo'}='bar';
15185: 
15186:  #storing it
15187:  &Apache::lonnet::cstore(\%hash);
15188: 
15189:  #changing a value
15190:  $hash{'foo'}='notbar';
15191: 
15192:  #adding a new value
15193:  $hash{'bar'}='foo';
15194:  &Apache::lonnet::cstore(\%hash);
15195: 
15196:  #retrieving the hash
15197:  my %history=&Apache::lonnet::restore();
15198: 
15199:  #print the hash
15200:  foreach my $key (sort(keys(%history))) {
15201:    print("\%history{$key} = $history{$key}");
15202:  }
15203: 
15204: Will print out:
15205: 
15206:  %history{1:foo} = bar
15207:  %history{1:keys} = foo:timestamp
15208:  %history{1:timestamp} = 990455579
15209:  %history{2:bar} = foo
15210:  %history{2:foo} = notbar
15211:  %history{2:keys} = foo:bar:timestamp
15212:  %history{2:timestamp} = 990455580
15213:  %history{bar} = foo
15214:  %history{foo} = notbar
15215:  %history{timestamp} = 990455580
15216:  %history{version} = 2
15217: 
15218: Note that the special hash entries C<keys>, C<version> and
15219: C<timestamp> were added to the hash. C<version> will be equal to the
15220: total number of versions of the data that have been stored. The
15221: C<timestamp> attribute will be the UNIX time the hash was
15222: stored. C<keys> is available in every historical section to list which
15223: keys were added or changed at a specific historical revision of a
15224: hash.
15225: 
15226: B<Warning>: do not store the hash that restore returns directly. This
15227: will cause a mess since it will restore the historical keys as if the
15228: were new keys. I.E. 1:foo will become 1:1:foo etc.
15229: 
15230: Calling convention:
15231: 
15232:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15233:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15234: 
15235: For more detailed information, see lonnet specific documentation.
15236: 
15237: =head1 RETURN MESSAGES
15238: 
15239: =over 4
15240: 
15241: =item * B<con_lost>: unable to contact remote host
15242: 
15243: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15244: when the connection is brought back up
15245: 
15246: =item * B<con_failed>: unable to contact remote host and unable to save message
15247: for later delivery
15248: 
15249: =item * B<error:>: an error a occurred, a description of the error follows the :
15250: 
15251: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15252: that was requested
15253: 
15254: =back
15255: 
15256: =head1 PUBLIC SUBROUTINES
15257: 
15258: =head2 Session Environment Functions
15259: 
15260: =over 4
15261: 
15262: =item * 
15263: X<appenv()>
15264: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15265: the user envirnoment file, and will be restored for each access this
15266: user makes during this session, also modifies the %env for the current
15267: process. Optional rolesarrayref - if defined contains a reference to an array
15268: of roles which are exempt from the restriction on modifying user.role entries 
15269: in the user's environment.db and in %env.    
15270: 
15271: =item *
15272: X<delenv()>
15273: B<delenv($delthis,$regexp)>: removes all items from the session
15274: environment file that begin with $delthis. If the 
15275: optional second arg - $regexp - is true, $delthis is treated as a 
15276: regular expression, otherwise \Q$delthis\E is used. 
15277: The values are also deleted from the current processes %env.
15278: 
15279: =item * get_env_multiple($name) 
15280: 
15281: gets $name from the %env hash, it seemlessly handles the cases where multiple
15282: values may be defined and end up as an array ref.
15283: 
15284: returns an array of values
15285: 
15286: =back
15287: 
15288: =head2 User Information
15289: 
15290: =over 4
15291: 
15292: =item *
15293: X<queryauthenticate()>
15294: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15295: authentication scheme
15296: 
15297: =item *
15298: X<authenticate()>
15299: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15300: authenticate user from domain's lib servers (first use the current
15301: one). C<$upass> should be the users password.
15302: $checkdefauth is optional (value is 1 if a check should be made to
15303:    authenticate user using default authentication method, and allow
15304:    account creation if username does not have account in the domain).
15305: $clientcancheckhost is optional (value is 1 if checking whether the
15306:    server can host will occur on the client side in lonauth.pm).   
15307: 
15308: =item *
15309: X<homeserver()>
15310: B<homeserver($uname,$udom)>: find the server which has
15311: the user's directory and files (there must be only one), this caches
15312: the answer, and also caches if there is a borken connection.
15313: 
15314: =item *
15315: X<idget()>
15316: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15317: a list of student/employee IDs or clicker IDs
15318: (student/employee IDs are a unique resource in a domain, there must be 
15319: only 1 ID per username, and only 1 username per ID in a specific domain).
15320: clickerIDs are not necessarily unique, as students might share clickers.
15321: (returns hash: id=>name,id=>name)
15322: 
15323: =item *
15324: X<idrget()>
15325: B<idrget($udom,@unames)>: find the IDs behind a list of
15326: usernames (returns hash: name=>id,name=>id)
15327: 
15328: =item *
15329: X<idput()>
15330: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15331: names and associated student/employee IDs or clicker IDs.
15332: 
15333: =item *
15334: X<iddel()>
15335: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15336: student/employee ID or clicker ID username look-ups from domain.
15337: The homeserver ($uhome) and namespace ($namespace) are optional.
15338: If no $uhome is provided, it will be determined usig &homeserver()
15339: for each user.  If no $namespace is provided, the default is ids.
15340: 
15341: =item *
15342: X<updateclickers()>
15343: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15344: clicker ID-to-username look-ups in clickers.db on library server.
15345: Permitted actions are add or del (i.e., add or delete). The 
15346: clickers.db contains clickerID as keys (escaped), and each corresponding
15347: value is an escaped comma-separated list of usernames (for whom the
15348: library server is the homeserver), who registered that particular ID.
15349: If $critical is true, the update will be sent via &critical, otherwise
15350: &reply() will be used.
15351: 
15352: =item *
15353: X<rolesinit()>
15354: B<rolesinit($udom,$username)>: get user privileges.
15355: returns user role, first access and timer interval hashes
15356: 
15357: =item *
15358: X<privileged()>
15359: B<privileged($username,$domain)>: returns a true if user has a
15360: privileged and active role (i.e. su or dc), false otherwise.
15361: 
15362: =item *
15363: X<getsection()>
15364: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15365: course $cname, return section name/number or '' for "not in course"
15366: and '-1' for "no section"
15367: 
15368: =item *
15369: X<userenvironment()>
15370: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15371: passed in @what from the requested user's environment, returns a hash
15372: 
15373: =item * 
15374: X<userlog_query()>
15375: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15376: activity.log file. %filters defines filters applied when parsing the
15377: log file. These can be start or end timestamps, or the type of action
15378: - log to look for Login or Logout events, check for Checkin or
15379: Checkout, role for role selection. The response is in the form
15380: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15381: escaped strings of the action recorded in the activity.log file.
15382: 
15383: =back
15384: 
15385: =head2 User Roles
15386: 
15387: =over 4
15388: 
15389: =item *
15390: 
15391: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15392: returns codes for allowed actions.
15393: 
15394: The first argument is required, all others are optional.
15395: 
15396: $priv is the privilege being checked.
15397: $uri contains additional information about what is being checked for access (e.g.,
15398: URL, course ID etc.). 
15399: $symb is the unique resource instance identifier in a course; if needed,
15400: but not provided, it will be retrieved via a call to &symbread(). 
15401: $role is the role for which a priv is being checked (only used if priv is evb). 
15402: $clientip is the user's IP address (only used when checking for access to portfolio 
15403: files).
15404: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15405: prevents recursive calls to &allowed.
15406: 
15407:  F: full access
15408:  U,I,K: authentication modes (cxx only)
15409:  '': forbidden
15410:  1: user needs to choose course
15411:  2: browse allowed
15412:  A: passphrase authentication needed
15413:  B: access temporarily blocked because of a blocking event in a course.
15414:  D: access blocked because access is required via session initiated via deep-link 
15415: 
15416: =item *
15417: 
15418: constructaccess($url,$setpriv) : check for access to construction space URL
15419: 
15420: See if the owner domain and name in the URL match those in the
15421: expected environment.  If so, return three element list
15422: ($ownername,$ownerdomain,$ownerhome).
15423: 
15424: Otherwise return the null string.
15425: 
15426: If second argument 'setpriv' is true, it assigns the privileges,
15427: and returns the same three element list, unless the owner has
15428: blocked "ad hoc" Domain Coordinator access to the Author Space,
15429: in which case the null string is returned.
15430: 
15431: =item *
15432: 
15433: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15434: define a custom role rolename set privileges in format of lonTabs/roles.tab
15435: for system, domain, and course level. $uname and $udom are optional (current
15436: user's username and domain will be used when either of $uname or $udom are absent.
15437: 
15438: =item *
15439: 
15440: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15441: (rolesplain.tab); plain text explanation of a user role term.
15442: $type is Course (default) or Community.
15443: If $forcedefault evaluates to true, text returned will be default 
15444: text for $type. Otherwise, if this is a course, the text returned 
15445: will be a custom name for the role (if defined in the course's 
15446: environment).  If no custom name is defined the default is returned.
15447:    
15448: =item *
15449: 
15450: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15451: All arguments are optional. Returns a hash of a roles, either for
15452: co-author/assistant author roles for a user's Construction Space
15453: (default), or if $context is 'userroles', roles for the user himself,
15454: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15455: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15456: For each key, value is set to colon-separated start and end times for
15457: the role.  If no username and domain are specified, will default to
15458: current user/domain. Types, roles, and roledoms are references to arrays
15459: of role statuses (active, future or previous), roles 
15460: (e.g., cc,in, st etc.) and domains of the roles which can be used
15461: to restrict the list of roles reported. If no array ref is 
15462: provided for types, will default to return only active roles.
15463: 
15464: =item *
15465: 
15466: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15467: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15468: 
15469: Additional optional arguments are: $type (if role checking is to be restricted 
15470: to certain user status types -- previous (expired roles), active (currently
15471: available roles) or future (roles available in the future), and
15472: $hideprivileged -- if true will not report course roles for users who
15473: have active Domain Coordinator role in course's domain or in additional
15474: domains (specified in 'Domains to check for privileged users' in course
15475: environment -- set via:  Course Settings -> Classlists and staff listing).
15476: 
15477: =item *
15478: 
15479: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15480: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15481: $possdomains and $possroles are optional array refs -- to domains to check and
15482: roles to check.  If $possdomains is not specified, a dump will be done of the
15483: users' roles.db to check for a dc or su role in any domain. This can be
15484: time consuming if &privileged is called repeatedly (e.g., when displaying a
15485: classlist), so in such cases, supplying a $possdomains array is preferred, as
15486: this then allows &privileged_by_domain() to be used, which caches the identity
15487: of privileged users, eliminating the need for repeated calls to &dump().
15488: 
15489: =item *
15490: 
15491: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15492: where the outer hash keys are domains specified in the $possdomains array ref,
15493: next inner hash keys are privileged roles specified in the $roles array ref,
15494: and the innermost hash contains key = value pairs for username:domain = end:start
15495: for active or future "privileged" users with that role in that domain. To avoid
15496: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15497: innerhash are cached using priv_$role and $dom as the identifiers.
15498: 
15499: =back
15500: 
15501: =head2 User Modification
15502: 
15503: =over 4
15504: 
15505: =item *
15506: 
15507: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15508: user for the level given by URL.  Optional start and end dates (leave empty
15509: string or zero for "no date")
15510: 
15511: =item *
15512: 
15513: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15514: change a users, password, possible return values are: ok,
15515: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15516: refused
15517: 
15518: =item *
15519: 
15520: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15521: 
15522: =item *
15523: 
15524: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15525:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15526: 
15527: will update user information (firstname,middlename,lastname,generation,
15528: permanentemail), and if forceid is true, student/employee ID also.
15529: A user's institutional affiliation(s) can also be updated.
15530: User information fields will not be overwritten with empty entries 
15531: unless the field is included in the $candelete array reference.
15532: This array is included when a single user is modified via "Manage Users",
15533: or when Autoupdate.pl is run by cron in a domain.
15534: 
15535: =item *
15536: 
15537: modifystudent
15538: 
15539: modify a student's enrollment and identification information.
15540: The course id is resolved based on the current user's environment.  
15541: This means the invoking user must be a course coordinator or otherwise
15542: associated with a course.
15543: 
15544: This call is essentially a wrapper for lonnet::modifyuser and
15545: lonnet::modify_student_enrollment
15546: 
15547: Inputs: 
15548: 
15549: =over 4
15550: 
15551: =item B<$udom> Student's loncapa domain
15552: 
15553: =item B<$uname> Student's loncapa login name
15554: 
15555: =item B<$uid> Student/Employee ID
15556: 
15557: =item B<$umode> Student's authentication mode
15558: 
15559: =item B<$upass> Student's password
15560: 
15561: =item B<$first> Student's first name
15562: 
15563: =item B<$middle> Student's middle name
15564: 
15565: =item B<$last> Student's last name
15566: 
15567: =item B<$gene> Student's generation
15568: 
15569: =item B<$usec> Student's section in course
15570: 
15571: =item B<$end> Unix time of the roles expiration
15572: 
15573: =item B<$start> Unix time of the roles start date
15574: 
15575: =item B<$forceid> If defined, allow $uid to be changed
15576: 
15577: =item B<$desiredhome> server to use as home server for student
15578: 
15579: =item B<$email> Student's permanent e-mail address
15580: 
15581: =item B<$type> Type of enrollment (auto or manual)
15582: 
15583: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15584: 
15585: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15586: 
15587: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15588: 
15589: =item B<$context> role change context (shown in User Management Logs display in a course)
15590: 
15591: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15592: 
15593: =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.
15594: 
15595: =back
15596: 
15597: =item *
15598: 
15599: modify_student_enrollment
15600: 
15601: Change a student's enrollment status in a class.  The environment variable
15602: 'role.request.course' must be defined for this function to proceed.
15603: 
15604: Inputs:
15605: 
15606: =over 4
15607: 
15608: =item $udom, student's domain
15609: 
15610: =item $uname, student's name
15611: 
15612: =item $uid, student's user id
15613: 
15614: =item $first, student's first name
15615: 
15616: =item $middle
15617: 
15618: =item $last
15619: 
15620: =item $gene
15621: 
15622: =item $usec
15623: 
15624: =item $end
15625: 
15626: =item $start
15627: 
15628: =item $type
15629: 
15630: =item $locktype
15631: 
15632: =item $cid
15633: 
15634: =item $selfenroll
15635: 
15636: =item $context
15637: 
15638: =item $credits, number of credits student will earn from this class
15639: 
15640: =item $instsec, institutional course section code for student
15641: 
15642: =back
15643: 
15644: 
15645: =item *
15646: 
15647: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15648: custom role; give a custom role to a user for the level given by URL.  Specify
15649: name and domain of role author, and role name
15650: 
15651: =item *
15652: 
15653: revokerole($udom,$uname,$url,$role) : revoke a role for url
15654: 
15655: =item *
15656: 
15657: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15658: 
15659: =back
15660: 
15661: =head2 Course Infomation
15662: 
15663: =over 4
15664: 
15665: =item *
15666: 
15667: coursedescription($courseid,$options) : returns a hash of information about the
15668: specified course id, including all environment settings for the
15669: course, the description of the course will be in the hash under the
15670: key 'description'
15671: 
15672: $options is an optional parameter that if supplied is a hash reference that controls
15673: what how this function works.  It has the following key/values:
15674: 
15675: =over 4
15676: 
15677: =item freshen_cache
15678: 
15679: If defined, and the environment cache for the course is valid, it is 
15680: returned in the returned hash.
15681: 
15682: =item one_time
15683: 
15684: If defined, the last cache time is set to _now_
15685: 
15686: =item user
15687: 
15688: If defined, the supplied username is used instead of the current user.
15689: 
15690: 
15691: =back
15692: 
15693: =item *
15694: 
15695: resdata($name,$domain,$type,@which) : request for current parameter
15696: setting for a specific $type, where $type is either 'course' or 'user',
15697: @what should be a list of parameters to ask about. This routine caches
15698: answers for 10 minutes.
15699: 
15700: =item *
15701: 
15702: get_courseresdata($courseid, $domain) : dump the entire course resource
15703: data base, returning a hash that is keyed by the resource name and has
15704: values that are the resource value.  I believe that the timestamps and
15705: versions are also returned.
15706: 
15707: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15708: supplemental content area. This routine caches the number of files for 
15709: 10 minutes.
15710: 
15711: =back
15712: 
15713: =head2 Course Modification
15714: 
15715: =over 4
15716: 
15717: =item *
15718: 
15719: writecoursepref($courseid,%prefs) : write preferences (environment
15720: database) for a course
15721: 
15722: =item *
15723: 
15724: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15725: 
15726: =item *
15727: 
15728: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15729: 
15730: =item *
15731: 
15732: is_course($courseid), is_course($cdom, $cnum)
15733: 
15734: Accepts either a combined $courseid (in the form of domain_courseid) or the
15735: two component version $cdom, $cnum. It checks if the specified course exists.
15736: 
15737: Returns:
15738:     undef if the course doesn't exist, otherwise
15739:     in scalar context the combined courseid.
15740:     in list context the two components of the course identifier, domain and 
15741:     courseid.    
15742: 
15743: =back
15744: 
15745: =head2 Bubblesheet Configuration
15746: 
15747: =over 4
15748: 
15749: =item *
15750: 
15751: get_scantron_config($which)
15752: 
15753: $which - the name of the configuration to parse from the file.
15754: 
15755: Parses and returns the bubblesheet configuration line selected as a
15756: hash of configuration file fields.
15757: 
15758: 
15759: Returns:
15760:     If the named configuration is not in the file, an empty
15761:     hash is returned.
15762: 
15763:     a hash with the fields
15764:       name         - internal name for the this configuration setup
15765:       description  - text to display to operator that describes this config
15766:       CODElocation - if 0 or the string 'none'
15767:                           - no CODE exists for this config
15768:                      if -1 || the string 'letter'
15769:                           - a CODE exists for this config and is
15770:                             a string of letters
15771:                      Unsupported value (but planned for future support)
15772:                           if a positive integer
15773:                                - The CODE exists as the first n items from
15774:                                  the question section of the form
15775:                           if the string 'number'
15776:                                - The CODE exists for this config and is
15777:                                  a string of numbers
15778:       CODEstart   - (only matter if a CODE exists) column in the line where
15779:                      the CODE starts
15780:       CODElength  - length of the CODE
15781:       IDstart     - column where the student/employee ID starts
15782:       IDlength    - length of the student/employee ID info
15783:       Qstart      - column where the information from the bubbled
15784:                     'questions' start
15785:       Qlength     - number of columns comprising a single bubble line from
15786:                     the sheet. (usually either 1 or 10)
15787:       Qon         - either a single character representing the character used
15788:                     to signal a bubble was chosen in the positional setup, or
15789:                     the string 'letter' if the letter of the chosen bubble is
15790:                     in the final, or 'number' if a number representing the
15791:                     chosen bubble is in the file (1->A 0->J)
15792:       Qoff        - the character used to represent that a bubble was
15793:                     left blank
15794:       PaperID     - if the scanning process generates a unique number for each
15795:                     sheet scanned the column that this ID number starts in
15796:       PaperIDlength - number of columns that comprise the unique ID number
15797:                       for the sheet of paper
15798:       FirstName   - column that the first name starts in
15799:       FirstNameLength - number of columns that the first name spans
15800:       LastName    - column that the last name starts in
15801:       LastNameLength - number of columns that the last name spans
15802:       BubblesPerRow - number of bubbles available in each row used to
15803:                       bubble an answer. (If not specified, 10 assumed).
15804: 
15805: 
15806: =item *
15807: 
15808: get_scantronformat_file($cdom)
15809: 
15810: $cdom - the course's domain (optional); if not supplied, uses
15811: domain for current $env{'request.course.id'}.
15812: 
15813: Returns an array containing lines from the scantron format file for
15814: the domain of the course.
15815: 
15816: If a url for a custom.tab file is listed in domain's configuration.db,
15817: lines are from this file.
15818: 
15819: Otherwise, if a default.tab has been published in RES space by the
15820: domainconfig user, lines are from this file.
15821: 
15822: Otherwise, fall back to getting lines from the legacy file on the
15823: local server:  /home/httpd/lonTabs/default_scantronformat.tab
15824: 
15825: =back
15826: 
15827: =head2 Resource Subroutines
15828: 
15829: =over 4
15830: 
15831: =item *
15832: 
15833: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15834: 
15835: =item *
15836: 
15837: repcopy($filename) : subscribes to the requested file, and attempts to
15838: replicate from the owning library server, Might return
15839: 'unavailable', 'not_found', 'forbidden', 'ok', or
15840: 'bad_request', also attempts to grab the metadata for the
15841: resource. Expects the local filesystem pathname
15842: (/home/httpd/html/res/....)
15843: 
15844: =back
15845: 
15846: =head2 Resource Information
15847: 
15848: =over 4
15849: 
15850: =item *
15851: 
15852: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15853: and returns the value of a variety of different possible values,
15854: $varname should be a request string, and the other parameters can be
15855: used to specify who and what one is asking about. Ordinarily, $cid 
15856: does not need to be specified, as it is retrived from 
15857: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15858: within lonuserstate::loadmap() when initializing a course, before
15859: $env{'request.course.id'} has been set, so it needs to be provided
15860: in that one case.
15861: 
15862: Possible values for $varname are environment.lastname (or other item
15863: from the envirnment hash), user.name (or someother aspect about the
15864: user), resource.0.maxtries (or some other part and parameter of a
15865: resource)
15866: 
15867: =item *
15868: 
15869: directcondval($number) : get current value of a condition; reads from a state
15870: string
15871: 
15872: =item *
15873: 
15874: condval($condidx) : value of condition index based on state
15875: 
15876: =item *
15877: 
15878: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15879: resource's metadata, $what should be either a specific key, or either
15880: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15881: packages that this resource currently uses, the last 3 arguments are 
15882: only used internally for recursive metadata.
15883: 
15884: the toolsymb is only used where the uri is for an external tool (for which
15885: the uri as well as the symb are guaranteed to be unique).
15886: 
15887: this function automatically caches all requests except any made recursively
15888: to retrieve a list of metadata keys for an imported library file ($liburi is 
15889: defined).
15890: 
15891: =item *
15892: 
15893: metadata_query($query,$custom,$customshow) : make a metadata query against the
15894: network of library servers; returns file handle of where SQL and regex results
15895: will be stored for query
15896: 
15897: =item *
15898: 
15899: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15900: return symbolic list entry (all arguments optional). 
15901: 
15902: Args: filename is the filename (including path) for the file for which a symb 
15903: is required; donotrecurse, if true will prevent calls to allowed() being made 
15904: to check access status if more than one resource was found in the bighash 
15905: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15906: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15907: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15908: cause possible symbs to be checked to determine if they are subject to content
15909: blocking, if so they will not be included as possible symbs; possibles is a
15910: ref to a hash, which, as a side effect, will be populated with all possible 
15911: symbs (content blocking not tested).
15912:  
15913: returns the data handle
15914: 
15915: =item *
15916: 
15917: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15918: and is a possible symb for the URL in $thisfn, and if is an encrypted
15919: resource that the user accessed using /enc/ returns a 1 on success, 0
15920: on failure, user must be in a course, as it assumes the existence of
15921: the course initial hash, and uses $env('request.course.id'}.  The third
15922: arg is an optional reference to a scalar.  If this arg is passed in the 
15923: call to symbverify, it will be set to 1 if the symb has been set to be 
15924: encrypted; otherwise it will be null.  
15925: 
15926: =item *
15927: 
15928: symbclean($symb) : removes versions numbers from a symb, returns the
15929: cleaned symb
15930: 
15931: =item *
15932: 
15933: is_on_map($uri) : checks if the $uri is somewhere on the current
15934: course map, user must be in a course for it to work.
15935: 
15936: =item *
15937: 
15938: numval($salt) : return random seed value (addend for rndseed)
15939: 
15940: =item *
15941: 
15942: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15943: a random seed, all arguments are optional, if they aren't sent it uses the
15944: environment to derive them. Note: if symb isn't sent and it can't get one
15945: from &symbread it will use the current time as its return value
15946: 
15947: =item *
15948: 
15949: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15950: unfakeable, receipt
15951: 
15952: =item *
15953: 
15954: receipt() : API to ireceipt working off of env values; given out to users
15955: 
15956: =item *
15957: 
15958: countacc($url) : count the number of accesses to a given URL
15959: 
15960: =item *
15961: 
15962: 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
15963: 
15964: =item *
15965: 
15966: 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)
15967: 
15968: =item *
15969: 
15970: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15971: 
15972: =item *
15973: 
15974: devalidate($symb) : devalidate temporary spreadsheet calculations,
15975: forcing spreadsheet to reevaluate the resource scores next time.
15976: 
15977: =item * 
15978: 
15979: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15980: when viewing in course context.
15981: 
15982:  input: six args -- filename (decluttered), course number, course domain,
15983:                     url, symb (if registered) and group (if this is a 
15984:                     group item -- e.g., bulletin board, group page etc.).
15985: 
15986:  output: array of five scalars --
15987:          $cfile -- url for file editing if editable on current server
15988:          $home -- homeserver of resource (i.e., for author if published,
15989:                                           or course if uploaded.).
15990:          $switchserver --  1 if server switch will be needed.
15991:          $forceedit -- 1 if icon/link should be to go to edit mode 
15992:          $forceview -- 1 if icon/link should be to go to view mode
15993: 
15994: =item *
15995: 
15996: is_course_upload($file,$cnum,$cdom)
15997: 
15998: Used in course context to determine if current file was uploaded to 
15999: the course (i.e., would be found in /userfiles/docs on the course's 
16000: homeserver.
16001: 
16002:   input: 3 args -- filename (decluttered), course number and course domain.
16003:   output: boolean -- 1 if file was uploaded.
16004: 
16005: =back
16006: 
16007: =head2 Storing/Retreiving Data
16008: 
16009: =over 4
16010: 
16011: =item *
16012: 
16013: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16014: permanently for this url; hashref needs to be given and should be a \%hashname;
16015: the remaining args aren't required and if they aren't passed or are '' they will
16016: be derived from the env (with the exception of $laststore, which is an 
16017: optional arg used when a user's submission is stored in grading).
16018: $laststore is $version=$timestamp, where $version is the most recent version
16019: number retrieved for the corresponding $symb in the $namespace db file, and
16020: $timestamp is the timestamp for that transaction (UNIX time).
16021: $laststore is currently only passed when cstore() is called by 
16022: structuretags::finalize_storage().
16023: 
16024: =item *
16025: 
16026: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16027: but uses critical subroutine
16028: 
16029: =item *
16030: 
16031: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16032: all args are optional
16033: 
16034: =item *
16035: 
16036: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16037: dumps the complete (or key matching regexp) namespace into a hash
16038: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16039: normally &store()ed into
16040: 
16041: $range should be either an integer '100' (give me the first 100
16042:                                            matching records)
16043:               or be  two integers sperated by a - with no spaces
16044:                  '30-50' (give me the 30th through the 50th matching
16045:                           records)
16046: 
16047: 
16048: =item *
16049: 
16050: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16051: replaces a &store() version of data with a replacement set of data
16052: for a particular resource in a namespace passed in the $storehash hash 
16053: reference. If $tolog is true, the transaction is logged in the courselog
16054: with an action=PUTSTORE.
16055: 
16056: =item *
16057: 
16058: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16059: works very similar to store/cstore, but all data is stored in a
16060: temporary location and can be reset using tmpreset, $storehash should
16061: be a hash reference, returns nothing on success
16062: 
16063: =item *
16064: 
16065: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16066: similar to restore, but all data is stored in a temporary location and
16067: can be reset using tmpreset. Returns a hash of values on success,
16068: error string otherwise.
16069: 
16070: =item *
16071: 
16072: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16073: deltes all keys for $symb form the temporary storage hash.
16074: 
16075: =item *
16076: 
16077: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16078: reference filled in from namesp ($udom and $uname are optional)
16079: 
16080: =item *
16081: 
16082: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16083: namesp ($udom and $uname are optional)
16084: 
16085: =item *
16086: 
16087: dump($namespace,$udom,$uname,$regexp,$range) : 
16088: dumps the complete (or key matching regexp) namespace into a hash
16089: ($udom, $uname, $regexp, $range are optional)
16090: 
16091: $range should be either an integer '100' (give me the first 100
16092:                                            matching records)
16093:               or be  two integers sperated by a - with no spaces
16094:                  '30-50' (give me the 30th through the 50th matching
16095:                           records)
16096: =item *
16097: 
16098: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16099: $store can be a scalar, an array reference, or if the amount to be 
16100: incremented is > 1, a hash reference.
16101: 
16102: ($udom and $uname are optional)
16103: 
16104: =item *
16105: 
16106: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16107: ($udom and $uname are optional)
16108: 
16109: =item *
16110: 
16111: cput($namespace,$storehash,$udom,$uname) : critical put
16112: ($udom and $uname are optional)
16113: 
16114: =item *
16115: 
16116: newput($namespace,$storehash,$udom,$uname) :
16117: 
16118: Attempts to store the items in the $storehash, but only if they don't
16119: currently exist, if this succeeds you can be certain that you have 
16120: successfully created a new key value pair in the $namespace db.
16121: 
16122: 
16123: Args:
16124:  $namespace: name of database to store values to
16125:  $storehash: hashref to store to the db
16126:  $udom: (optional) domain of user containing the db
16127:  $uname: (optional) name of user caontaining the db
16128: 
16129: Returns:
16130:  'ok' -> succeeded in storing all keys of $storehash
16131:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16132:                         least <key> already existed in the db (other
16133:                         requested keys may also already exist)
16134:  'error: <msg>' -> unable to tie the DB or other error occurred
16135:  'con_lost' -> unable to contact request server
16136:  'refused' -> action was not allowed by remote machine
16137: 
16138: 
16139: =item *
16140: 
16141: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16142: reference filled in from namesp (encrypts the return communication)
16143: ($udom and $uname are optional)
16144: 
16145: =item *
16146: 
16147: log($udom,$name,$home,$message) : write to permanent log for user; use
16148: critical subroutine
16149: 
16150: =item *
16151: 
16152: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16153: array reference filled in from namespace found in domain level on either
16154: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16155: 
16156: =item *
16157: 
16158: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16159: domain level either on specified domain server ($uhome) or primary domain 
16160: server ($udom and $uhome are optional)
16161: 
16162: =item * 
16163: 
16164: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16165: for: authentication, language, quotas, timezone, date locale, and portal URL in
16166: the target domain.
16167: 
16168: May also include additional key => value pairs for the following groups:
16169: 
16170: =over
16171: 
16172: =item
16173: disk quotas (MB allocated by default to portfolios and authoring spaces).
16174: 
16175: =over
16176: 
16177: =item defaultquota, authorquota
16178: 
16179: =back
16180: 
16181: =item
16182: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16183: portfolio for users).
16184: 
16185: =over
16186: 
16187: =item
16188: aboutme, blog, webdav, portfolio
16189: 
16190: =back
16191: 
16192: =item
16193: requestcourses: ability to request courses, and how requests are processed.
16194: 
16195: =over
16196: 
16197: =item
16198: official, unofficial, community, textbook, placement
16199: 
16200: =back
16201: 
16202: =item
16203: inststatus: types of institutional affiliation, and order in which they are displayed.
16204: 
16205: =over
16206: 
16207: =item
16208: inststatustypes, inststatusorder, inststatusguest
16209: 
16210: =back
16211: 
16212: =item
16213: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16214: for course's uploaded content.
16215: 
16216: =over
16217: 
16218: =item
16219: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16220: communityquota, textbookquota, placementquota
16221: 
16222: =back
16223: 
16224: =item
16225: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16226: on your servers.
16227: 
16228: =over
16229: 
16230: =item 
16231: remotesessions, hostedsessions
16232: 
16233: =back
16234: 
16235: =back
16236: 
16237: In cases where a domain coordinator has never used the "Set Domain Configuration"
16238: utility to create a configuration.db file on a domain's primary library server 
16239: only the following domain defaults: auth_def, auth_arg_def, lang_def
16240: -- corresponding values are authentication type (internal, krb4, krb5,
16241: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16242: will be available. Values are retrieved from cache (if current), unless the
16243: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16244: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16245: 
16246: Typical usage:
16247: 
16248: %domdefaults = &get_domain_defaults($target_domain);
16249: 
16250: =back
16251: 
16252: =head2 Network Status Functions
16253: 
16254: =over 4
16255: 
16256: =item *
16257: 
16258: dirlist() : return directory list based on URI (first arg).
16259: 
16260: Inputs: 1 required, 5 optional.
16261: 
16262: =over
16263: 
16264: =item 
16265: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16266: 
16267: =item
16268: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16269: 
16270: =item
16271: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16272: 
16273: =item
16274: $getpropath - boolean: 1 if prepend path using &propath(). 
16275: 
16276: =item
16277: $getuserdir - boolean: 1 if prepend path for "userfiles".
16278: 
16279: =item 
16280: $alternateRoot - path to prepend in place of path from $uri.
16281: 
16282: =back
16283: 
16284: Returns: Array of up to two items.
16285: 
16286: =over
16287: 
16288: a reference to an array of files/subdirectories
16289: 
16290: =over
16291: 
16292: Each element in the array of files/subdirectories is a & separated list of
16293: item name and the result of running stat on the item.  If dirlist was requested
16294: for a file instead of a directory, the item name will be ''. For a directory 
16295: listing, if the item is a metadata file, the element will end &N&M 
16296: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16297: default copyright set (1).  
16298: 
16299: =back
16300: 
16301: a scalar containing error condition (if encountered).
16302: 
16303: =over
16304: 
16305: =item 
16306: no_host (no homeserver identified for $username:$domain).
16307: 
16308: =item 
16309: no_such_host (server contacted for listing not identified as valid host).
16310: 
16311: =item 
16312: con_lost (connection to remote server failed).
16313: 
16314: =item 
16315: refused (invalid $username:$domain received on lond side).
16316: 
16317: =item 
16318: no_such_dir (directory at specified path on lond side does not exist). 
16319: 
16320: =item 
16321: empty (directory at specified path on lond side is empty).
16322: 
16323: =over
16324: 
16325: This is currently not encountered because the &ls3, &ls2, 
16326: &ls (_handler) routines on the lond side do not filter out
16327: . and .. from a directory listing. 
16328: 
16329: =back
16330: 
16331: =back
16332: 
16333: =back
16334: 
16335: =item *
16336: 
16337: spareserver() : find server with least workload from spare.tab
16338: 
16339: 
16340: =item *
16341: 
16342: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16343: if there is no corresponding loncapa host.
16344: 
16345: =back
16346: 
16347: 
16348: =head2 Apache Request
16349: 
16350: =over 4
16351: 
16352: =item *
16353: 
16354: ssi($url,%hash) : server side include, does a complete request cycle on url to
16355: localhost, posts hash
16356: 
16357: =back
16358: 
16359: =head2 Data to String to Data
16360: 
16361: =over 4
16362: 
16363: =item *
16364: 
16365: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16366: and '&' separators, supports elements that are arrayrefs and hashrefs
16367: 
16368: =item *
16369: 
16370: hashref2str($hashref) : convert a hashref into a string complete with
16371: escaping and '=' and '&' separators, supports elements that are
16372: arrayrefs and hashrefs
16373: 
16374: =item *
16375: 
16376: arrayref2str($arrayref) : convert an arrayref into a string complete
16377: with escaping and '&' separators, supports elements that are arrayrefs
16378: and hashrefs
16379: 
16380: =item *
16381: 
16382: str2hash($string) : convert string to hash using unescaping and
16383: splitting on '=' and '&', supports elements that are arrayrefs and
16384: hashrefs
16385: 
16386: =item *
16387: 
16388: str2array($string) : convert string to hash using unescaping and
16389: splitting on '&', supports elements that are arrayrefs and hashrefs
16390: 
16391: =back
16392: 
16393: =head2 Logging Routines
16394: 
16395: 
16396: These routines allow one to make log messages in the lonnet.log and
16397: lonnet.perm logfiles.
16398: 
16399: =over 4
16400: 
16401: =item *
16402: 
16403: logtouch() : make sure the logfile, lonnet.log, exists
16404: 
16405: =item *
16406: 
16407: logthis() : append message to the normal lonnet.log file, it gets
16408: preiodically rolled over and deleted.
16409: 
16410: =item *
16411: 
16412: logperm() : append a permanent message to lonnet.perm.log, this log
16413: file never gets deleted by any automated portion of the system, only
16414: messages of critical importance should go in here.
16415: 
16416: 
16417: =back
16418: 
16419: =head2 General File Helper Routines
16420: 
16421: =over 4
16422: 
16423: =item *
16424: 
16425: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16426: (a) files in /uploaded
16427:   (i) If a local copy of the file exists - 
16428:       compares modification date of local copy with last-modified date for 
16429:       definitive version stored on home server for course. If local copy is 
16430:       stale, requests a new version from the home server and stores it. 
16431:       If the original has been removed from the home server, then local copy 
16432:       is unlinked.
16433:   (ii) If local copy does not exist -
16434:       requests the file from the home server and stores it. 
16435:   
16436:   If $caller is 'uploadrep':  
16437:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16438:     for request for files originally uploaded via DOCS. 
16439:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16440:   
16441:   Otherwise:
16442:      This indicates a call from the content generation phase of the request.
16443:      -  returns the entire contents of the file or -1.
16444:      
16445: (b) files in /res
16446:    - returns the entire contents of a file or -1; 
16447:    it properly subscribes to and replicates the file if neccessary.
16448: 
16449: 
16450: =item *
16451: 
16452: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16453:                   reference
16454: 
16455: returns either a stat() list of data about the file or an empty list
16456: if the file doesn't exist or couldn't find out about it (connection
16457: problems or user unknown)
16458: 
16459: =item *
16460: 
16461: filelocation($dir,$file) : returns file system location of a file
16462: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16463: directory that relative $file lookups are to looked in ($dir of /a/dir
16464: and a file of ../bob will become /a/bob)
16465: 
16466: =item *
16467: 
16468: hreflocation($dir,$file) : returns file system location or a URL; same as
16469: filelocation except for hrefs
16470: 
16471: =item *
16472: 
16473: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16474: also removes beginning /home/httpd/html unless /priv/ follows it.
16475: 
16476: =back
16477: 
16478: =head2 Usererfile file routines (/uploaded*)
16479: 
16480: =over 4
16481: 
16482: =item *
16483: 
16484: userfileupload(): main rotine for putting a file in a user or course's
16485:                   filespace, arguments are,
16486: 
16487:  formname - required - this is the name of the element in $env where the
16488:            filename, and the contents of the file to create/modifed exist
16489:            the filename is in $env{'form.'.$formname.'.filename'} and the
16490:            contents of the file is located in $env{'form.'.$formname}
16491:  context - if coursedoc, store the file in the course of the active role
16492:              of the current user; 
16493:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16494:            if 'canceloverwrite': delete file in tmp/overwrites directory
16495:  subdir - required - subdirectory to put the file in under ../userfiles/
16496:          if undefined, it will be placed in "unknown"
16497: 
16498:  (This routine calls clean_filename() to remove any dangerous
16499:  characters from the filename, and then calls finuserfileupload() to
16500:  complete the transaction)
16501: 
16502:  returns either the url of the uploaded file (/uploaded/....) if successful
16503:  and /adm/notfound.html if unsuccessful
16504: 
16505: =item *
16506: 
16507: clean_filename(): routine for cleaing a filename up for storage in
16508:                  userfile space, argument is:
16509: 
16510:  filename - proposed filename
16511: 
16512: returns: the new clean filename
16513: 
16514: =item *
16515: 
16516: finishuserfileupload(): routine that creates and sends the file to
16517: userspace, probably shouldn't be called directly
16518: 
16519:   docuname: username or courseid of destination for the file
16520:   docudom: domain of user/course of destination for the file
16521:   formname: same as for userfileupload()
16522:   fname: filename (including subdirectories) for the file
16523:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16524:           if hashref, and context is scantron, will convert csv format to standard format
16525:   allfiles: reference to hash used to store objects found by parser
16526:   codebase: reference to hash used for codebases of java objects found by parser
16527:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16528:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16529:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16530:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16531:   context: if 'overwrite', will move the uploaded file from its temporary location to
16532:             userfiles to facilitate overwriting a previously uploaded file with same name.
16533:   mimetype: reference to scalar to accommodate mime type determined
16534:             from File::MMagic if $parser = parse.
16535: 
16536:  returns either the url of the uploaded file (/uploaded/....) if successful
16537:  and /adm/notfound.html if unsuccessful (or an error message if context 
16538:  was 'overwrite').
16539:  
16540: 
16541: =item *
16542: 
16543: renameuserfile(): renames an existing userfile to a new name
16544: 
16545:   Args:
16546:    docuname: username or courseid of destination for the file
16547:    docudom: domain of user/course of destination for the file
16548:    old: current file name (including any subdirs under userfiles)
16549:    new: desired file name (including any subdirs under userfiles)
16550: 
16551: =item *
16552: 
16553: mkdiruserfile(): creates a directory is a userfiles dir
16554: 
16555:   Args:
16556:    docuname: username or courseid of destination for the file
16557:    docudom: domain of user/course of destination for the file
16558:    dir: dir to create (including any subdirs under userfiles)
16559: 
16560: =item *
16561: 
16562: removeuserfile(): removes a file that exists in userfiles
16563: 
16564:   Args:
16565:    docuname: username or courseid of destination for the file
16566:    docudom: domain of user/course of destination for the file
16567:    fname: filname to delete (including any subdirs under userfiles)
16568: 
16569: =item *
16570: 
16571: removeuploadedurl(): convience function for removeuserfile()
16572: 
16573:   Args:
16574:    url:  a full /uploaded/... url to delete
16575: 
16576: =item * 
16577: 
16578: get_portfile_permissions():
16579:   Args:
16580:     domain: domain of user or course contain the portfolio files
16581:     user: name of user or num of course contain the portfolio files
16582:   Returns:
16583:     hashref of a dump of the proper file_permissions.db
16584:    
16585: 
16586: =item * 
16587: 
16588: get_access_controls():
16589: 
16590: Args:
16591:   current_permissions: the hash ref returned from get_portfile_permissions()
16592:   group: (optional) the group you want the files associated with
16593:   file: (optional) the file you want access info on
16594: 
16595: Returns:
16596:     a hash (keys are file names) of hashes containing
16597:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16598:         values are XML containing access control settings (see below) 
16599: 
16600: Internal notes:
16601: 
16602:  access controls are stored in file_permissions.db as key=value pairs.
16603:     key -> path to file/file_name\0uniqueID:scope_end_start
16604:         where scope -> public,guest,course,group,domains or users.
16605:               end -> UNIX time for end of access (0 -> no end date)
16606:               start -> UNIX time for start of access
16607: 
16608:     value -> XML description of access control
16609:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16610:             <start></start>
16611:             <end></end>
16612: 
16613:             <password></password>  for scope type = guest
16614: 
16615:             <domain></domain>     for scope type = course or group
16616:             <number></number>
16617:             <roles id="">
16618:              <role></role>
16619:              <access></access>
16620:              <section></section>
16621:              <group></group>
16622:             </roles>
16623: 
16624:             <dom></dom>         for scope type = domains
16625: 
16626:             <users>             for scope type = users
16627:              <user>
16628:               <uname></uname>
16629:               <udom></udom>
16630:              </user>
16631:             </users>
16632:            </scope> 
16633:               
16634:  Access data is also aggregated for each file in an additional key=value pair:
16635:  key -> path to file/file_name\0accesscontrol 
16636:  value -> reference to hash
16637:           hash contains key = value pairs
16638:           where key = uniqueID:scope_end_start
16639:                 value = UNIX time record was last updated
16640: 
16641:           Used to improve speed of look-ups of access controls for each file.  
16642:  
16643:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16644: 
16645: =item *
16646: 
16647: modify_access_controls():
16648: 
16649: Modifies access controls for a portfolio file
16650: Args
16651: 1. file name
16652: 2. reference to hash of required changes,
16653: 3. domain
16654: 4. username
16655:   where domain,username are the domain of the portfolio owner 
16656:   (either a user or a course) 
16657: 
16658: Returns:
16659: 1. result of additions or updates ('ok' or 'error', with error message). 
16660: 2. result of deletions ('ok' or 'error', with error message).
16661: 3. reference to hash of any new or updated access controls.
16662: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16663:    key = integer (inbound ID)
16664:    value = uniqueID
16665: 
16666: =item *
16667: 
16668: get_timebased_id():
16669: 
16670: Attempts to get a unique timestamp-based suffix for use with items added to a 
16671: course via the Course Editor (e.g., folders, composite pages, 
16672: group bulletin boards).
16673: 
16674: Args: (first three required; six others optional)
16675: 
16676: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16677:    docssequence, or name of group
16678: 
16679: 2. keyid (alphanumeric): name of temporary locking key in hash,
16680:    e.g., num, boardids
16681: 
16682: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16683:    file will be named nohist_namespace.db
16684: 
16685: 4. cdom: domain of course; default is current course domain from %env
16686: 
16687: 5. cnum: course number; default is current course number from %env
16688: 
16689: 6. idtype: set to concat if an additional digit is to be appended to the 
16690:    unix timestamp to form the suffix, if the plain timestamp is already
16691:    in use.  Default is to not do this, but simply increment the unix 
16692:    timestamp by 1 until a unique key is obtained.
16693: 
16694: 7. who: holder of locking key; defaults to user:domain for user.
16695: 
16696: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16697:    retrying); default is 3.
16698: 
16699: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16700: 
16701: Returns:
16702: 
16703: 1. suffix obtained (numeric)
16704: 
16705: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16706: 
16707: 3. error: contains (localized) error message if an error occurred.
16708: 
16709: 
16710: =back
16711: 
16712: =head2 HTTP Helper Routines
16713: 
16714: =over 4
16715: 
16716: =item *
16717: 
16718: escape() : unpack non-word characters into CGI-compatible hex codes
16719: 
16720: =item *
16721: 
16722: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16723: 
16724: =back
16725: 
16726: =head1 PRIVATE SUBROUTINES
16727: 
16728: =head2 Underlying communication routines (Shouldn't call)
16729: 
16730: =over 4
16731: 
16732: =item *
16733: 
16734: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16735: 
16736: =item *
16737: 
16738: reply() : uses subreply to send a message to remote machine, logs all failures
16739: 
16740: =item *
16741: 
16742: critical() : passes a critical message to another server; if cannot
16743: get through then place message in connection buffer directory and
16744: returns con_delayed, if incapable of saving message, returns
16745: con_failed
16746: 
16747: =item *
16748: 
16749: reconlonc() : tries to reconnect lonc client processes.
16750: 
16751: =back
16752: 
16753: =head2 Resource Access Logging
16754: 
16755: =over 4
16756: 
16757: =item *
16758: 
16759: flushcourselogs() : flush (save) buffer logs and access logs
16760: 
16761: =item *
16762: 
16763: courselog($what) : save message for course in hash
16764: 
16765: =item *
16766: 
16767: courseacclog($what) : save message for course using &courselog().  Perform
16768: special processing for specific resource types (problems, exams, quizzes, etc).
16769: 
16770: =item *
16771: 
16772: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16773: as a PerlChildExitHandler
16774: 
16775: =back
16776: 
16777: =head2 Other
16778: 
16779: =over 4
16780: 
16781: =item *
16782: 
16783: symblist($mapname,%newhash) : update symbolic storage links
16784: 
16785: =back
16786: 
16787: =cut
16788: 

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